For PR950:
[oota-llvm.git] / lib / Bytecode / Reader / Reader.cpp
1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/Bytecode/Reader.h
11 //
12 // Note that this library should be as fast as possible, reentrant, and
13 // threadsafe!!
14 //
15 // TODO: Allow passing in an option to ignore the symbol table
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "Reader.h"
20 #include "llvm/Bytecode/BytecodeHandler.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/SymbolTable.h"
27 #include "llvm/Bytecode/Format.h"
28 #include "llvm/Config/alloca.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/Compressor.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include <sstream>
34 #include <algorithm>
35 using namespace llvm;
36
37 namespace {
38   /// @brief A class for maintaining the slot number definition
39   /// as a placeholder for the actual definition for forward constants defs.
40   class ConstantPlaceHolder : public ConstantExpr {
41     ConstantPlaceHolder();                       // DO NOT IMPLEMENT
42     void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
43   public:
44     Use Op;
45     ConstantPlaceHolder(const Type *Ty)
46       : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
47         Op(UndefValue::get(Type::Int32Ty), this) {
48     }
49   };
50 }
51
52 // Provide some details on error
53 inline void BytecodeReader::error(const std::string& err) {
54   ErrorMsg = err + " (Vers=" + itostr(RevisionNum) + ", Pos=" 
55     + itostr(At-MemStart) + ")";
56   longjmp(context,1);
57 }
58
59 //===----------------------------------------------------------------------===//
60 // Bytecode Reading Methods
61 //===----------------------------------------------------------------------===//
62
63 /// Determine if the current block being read contains any more data.
64 inline bool BytecodeReader::moreInBlock() {
65   return At < BlockEnd;
66 }
67
68 /// Throw an error if we've read past the end of the current block
69 inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
70   if (At > BlockEnd)
71     error(std::string("Attempt to read past the end of ") + block_name +
72           " block.");
73 }
74
75 /// Read a whole unsigned integer
76 inline unsigned BytecodeReader::read_uint() {
77   if (At+4 > BlockEnd)
78     error("Ran out of data reading uint!");
79   At += 4;
80   return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
81 }
82
83 /// Read a variable-bit-rate encoded unsigned integer
84 inline unsigned BytecodeReader::read_vbr_uint() {
85   unsigned Shift = 0;
86   unsigned Result = 0;
87   BufPtr Save = At;
88
89   do {
90     if (At == BlockEnd)
91       error("Ran out of data reading vbr_uint!");
92     Result |= (unsigned)((*At++) & 0x7F) << Shift;
93     Shift += 7;
94   } while (At[-1] & 0x80);
95   if (Handler) Handler->handleVBR32(At-Save);
96   return Result;
97 }
98
99 /// Read a variable-bit-rate encoded unsigned 64-bit integer.
100 inline uint64_t BytecodeReader::read_vbr_uint64() {
101   unsigned Shift = 0;
102   uint64_t Result = 0;
103   BufPtr Save = At;
104
105   do {
106     if (At == BlockEnd)
107       error("Ran out of data reading vbr_uint64!");
108     Result |= (uint64_t)((*At++) & 0x7F) << Shift;
109     Shift += 7;
110   } while (At[-1] & 0x80);
111   if (Handler) Handler->handleVBR64(At-Save);
112   return Result;
113 }
114
115 /// Read a variable-bit-rate encoded signed 64-bit integer.
116 inline int64_t BytecodeReader::read_vbr_int64() {
117   uint64_t R = read_vbr_uint64();
118   if (R & 1) {
119     if (R != 1)
120       return -(int64_t)(R >> 1);
121     else   // There is no such thing as -0 with integers.  "-0" really means
122            // 0x8000000000000000.
123       return 1LL << 63;
124   } else
125     return  (int64_t)(R >> 1);
126 }
127
128 /// Read a pascal-style string (length followed by text)
129 inline std::string BytecodeReader::read_str() {
130   unsigned Size = read_vbr_uint();
131   const unsigned char *OldAt = At;
132   At += Size;
133   if (At > BlockEnd)             // Size invalid?
134     error("Ran out of data reading a string!");
135   return std::string((char*)OldAt, Size);
136 }
137
138 /// Read an arbitrary block of data
139 inline void BytecodeReader::read_data(void *Ptr, void *End) {
140   unsigned char *Start = (unsigned char *)Ptr;
141   unsigned Amount = (unsigned char *)End - Start;
142   if (At+Amount > BlockEnd)
143     error("Ran out of data!");
144   std::copy(At, At+Amount, Start);
145   At += Amount;
146 }
147
148 /// Read a float value in little-endian order
149 inline void BytecodeReader::read_float(float& FloatVal) {
150   /// FIXME: This isn't optimal, it has size problems on some platforms
151   /// where FP is not IEEE.
152   FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
153   At+=sizeof(uint32_t);
154 }
155
156 /// Read a double value in little-endian order
157 inline void BytecodeReader::read_double(double& DoubleVal) {
158   /// FIXME: This isn't optimal, it has size problems on some platforms
159   /// where FP is not IEEE.
160   DoubleVal = BitsToDouble((uint64_t(At[0]) <<  0) | (uint64_t(At[1]) << 8) |
161                            (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
162                            (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
163                            (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
164   At+=sizeof(uint64_t);
165 }
166
167 /// Read a block header and obtain its type and size
168 inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
169   Size = read_uint(); // Read the header
170   Type = Size & 0x1F; // mask low order five bits to get type
171   Size >>= 5;         // high order 27 bits is the size
172   BlockStart = At;
173   if (At + Size > BlockEnd)
174     error("Attempt to size a block past end of memory");
175   BlockEnd = At + Size;
176   if (Handler) Handler->handleBlock(Type, BlockStart, Size);
177 }
178
179 //===----------------------------------------------------------------------===//
180 // IR Lookup Methods
181 //===----------------------------------------------------------------------===//
182
183 /// Determine if a type id has an implicit null value
184 inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
185   return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
186 }
187
188 /// Obtain a type given a typeid and account for things like compaction tables,
189 /// function level vs module level, and the offsetting for the primitive types.
190 const Type *BytecodeReader::getType(unsigned ID) {
191   if (ID < Type::FirstDerivedTyID)
192     if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
193       return T;   // Asked for a primitive type...
194
195   // Otherwise, derived types need offset...
196   ID -= Type::FirstDerivedTyID;
197
198   if (!CompactionTypes.empty()) {
199     if (ID >= CompactionTypes.size())
200       error("Type ID out of range for compaction table!");
201     return CompactionTypes[ID].first;
202   }
203
204   // Is it a module-level type?
205   if (ID < ModuleTypes.size())
206     return ModuleTypes[ID].get();
207
208   // Nope, is it a function-level type?
209   ID -= ModuleTypes.size();
210   if (ID < FunctionTypes.size())
211     return FunctionTypes[ID].get();
212
213   error("Illegal type reference!");
214   return Type::VoidTy;
215 }
216
217 /// This method just saves some coding. It uses read_vbr_uint to read in a 
218 /// type id, errors that its not the type type, and then calls getType to 
219 /// return the type value.
220 inline const Type* BytecodeReader::readType() {
221   return getType(read_vbr_uint());
222 }
223
224 /// Get the slot number associated with a type accounting for primitive
225 /// types, compaction tables, and function level vs module level.
226 unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
227   if (Ty->isPrimitiveType())
228     return Ty->getTypeID();
229
230   // Scan the compaction table for the type if needed.
231   if (!CompactionTypes.empty()) {
232     for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
233       if (CompactionTypes[i].first == Ty)
234         return Type::FirstDerivedTyID + i;
235
236     error("Couldn't find type specified in compaction table!");
237   }
238
239   // Check the function level types first...
240   TypeListTy::iterator I = std::find(FunctionTypes.begin(),
241                                      FunctionTypes.end(), Ty);
242
243   if (I != FunctionTypes.end())
244     return Type::FirstDerivedTyID + ModuleTypes.size() +
245            (&*I - &FunctionTypes[0]);
246
247   // If we don't have our cache yet, build it now.
248   if (ModuleTypeIDCache.empty()) {
249     unsigned N = 0;
250     ModuleTypeIDCache.reserve(ModuleTypes.size());
251     for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
252          I != E; ++I, ++N)
253       ModuleTypeIDCache.push_back(std::make_pair(*I, N));
254     
255     std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
256   }
257   
258   // Binary search the cache for the entry.
259   std::vector<std::pair<const Type*, unsigned> >::iterator IT =
260     std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
261                      std::make_pair(Ty, 0U));
262   if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
263     error("Didn't find type in ModuleTypes.");
264     
265   return Type::FirstDerivedTyID + IT->second;
266 }
267
268 /// This is just like getType, but when a compaction table is in use, it is
269 /// ignored.  It also ignores function level types.
270 /// @see getType
271 const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
272   if (Slot < Type::FirstDerivedTyID) {
273     const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
274     if (!Ty)
275       error("Not a primitive type ID?");
276     return Ty;
277   }
278   Slot -= Type::FirstDerivedTyID;
279   if (Slot >= ModuleTypes.size())
280     error("Illegal compaction table type reference!");
281   return ModuleTypes[Slot];
282 }
283
284 /// This is just like getTypeSlot, but when a compaction table is in use, it
285 /// is ignored. It also ignores function level types.
286 unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
287   if (Ty->isPrimitiveType())
288     return Ty->getTypeID();
289   
290   // If we don't have our cache yet, build it now.
291   if (ModuleTypeIDCache.empty()) {
292     unsigned N = 0;
293     ModuleTypeIDCache.reserve(ModuleTypes.size());
294     for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
295          I != E; ++I, ++N)
296       ModuleTypeIDCache.push_back(std::make_pair(*I, N));
297     
298     std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
299   }
300   
301   // Binary search the cache for the entry.
302   std::vector<std::pair<const Type*, unsigned> >::iterator IT =
303     std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
304                      std::make_pair(Ty, 0U));
305   if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
306     error("Didn't find type in ModuleTypes.");
307   
308   return Type::FirstDerivedTyID + IT->second;
309 }
310
311 /// Retrieve a value of a given type and slot number, possibly creating
312 /// it if it doesn't already exist.
313 Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
314   assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
315   unsigned Num = oNum;
316
317   // If there is a compaction table active, it defines the low-level numbers.
318   // If not, the module values define the low-level numbers.
319   if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
320     if (Num < CompactionValues[type].size())
321       return CompactionValues[type][Num];
322     Num -= CompactionValues[type].size();
323   } else {
324     // By default, the global type id is the type id passed in
325     unsigned GlobalTyID = type;
326
327     // If the type plane was compactified, figure out the global type ID by
328     // adding the derived type ids and the distance.
329     if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
330       GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
331
332     if (hasImplicitNull(GlobalTyID)) {
333       const Type *Ty = getType(type);
334       if (!isa<OpaqueType>(Ty)) {
335         if (Num == 0)
336           return Constant::getNullValue(Ty);
337         --Num;
338       }
339     }
340
341     if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
342       if (Num < ModuleValues[GlobalTyID]->size())
343         return ModuleValues[GlobalTyID]->getOperand(Num);
344       Num -= ModuleValues[GlobalTyID]->size();
345     }
346   }
347
348   if (FunctionValues.size() > type &&
349       FunctionValues[type] &&
350       Num < FunctionValues[type]->size())
351     return FunctionValues[type]->getOperand(Num);
352
353   if (!Create) return 0;  // Do not create a placeholder?
354
355   // Did we already create a place holder?
356   std::pair<unsigned,unsigned> KeyValue(type, oNum);
357   ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
358   if (I != ForwardReferences.end() && I->first == KeyValue)
359     return I->second;   // We have already created this placeholder
360
361   // If the type exists (it should)
362   if (const Type* Ty = getType(type)) {
363     // Create the place holder
364     Value *Val = new Argument(Ty);
365     ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
366     return Val;
367   }
368   error("Can't create placeholder for value of type slot #" + utostr(type));
369   return 0; // just silence warning, error calls longjmp
370 }
371
372 /// This is just like getValue, but when a compaction table is in use, it
373 /// is ignored.  Also, no forward references or other fancy features are
374 /// supported.
375 Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
376   if (SlotNo == 0)
377     return Constant::getNullValue(getType(TyID));
378
379   if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
380     TyID -= Type::FirstDerivedTyID;
381     if (TyID >= CompactionTypes.size())
382       error("Type ID out of range for compaction table!");
383     TyID = CompactionTypes[TyID].second;
384   }
385
386   --SlotNo;
387
388   if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
389       SlotNo >= ModuleValues[TyID]->size()) {
390     if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
391       error("Corrupt compaction table entry!"
392             + utostr(TyID) + ", " + utostr(SlotNo) + ": "
393             + utostr(ModuleValues.size()));
394     else
395       error("Corrupt compaction table entry!"
396             + utostr(TyID) + ", " + utostr(SlotNo) + ": "
397             + utostr(ModuleValues.size()) + ", "
398             + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
399             + ", "
400             + utostr(ModuleValues[TyID]->size()));
401   }
402   return ModuleValues[TyID]->getOperand(SlotNo);
403 }
404
405 /// Just like getValue, except that it returns a null pointer
406 /// only on error.  It always returns a constant (meaning that if the value is
407 /// defined, but is not a constant, that is an error).  If the specified
408 /// constant hasn't been parsed yet, a placeholder is defined and used.
409 /// Later, after the real value is parsed, the placeholder is eliminated.
410 Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
411   if (Value *V = getValue(TypeSlot, Slot, false))
412     if (Constant *C = dyn_cast<Constant>(V))
413       return C;   // If we already have the value parsed, just return it
414     else
415       error("Value for slot " + utostr(Slot) +
416             " is expected to be a constant!");
417
418   std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
419   ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
420
421   if (I != ConstantFwdRefs.end() && I->first == Key) {
422     return I->second;
423   } else {
424     // Create a placeholder for the constant reference and
425     // keep track of the fact that we have a forward ref to recycle it
426     Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
427
428     // Keep track of the fact that we have a forward ref to recycle it
429     ConstantFwdRefs.insert(I, std::make_pair(Key, C));
430     return C;
431   }
432 }
433
434 //===----------------------------------------------------------------------===//
435 // IR Construction Methods
436 //===----------------------------------------------------------------------===//
437
438 /// As values are created, they are inserted into the appropriate place
439 /// with this method. The ValueTable argument must be one of ModuleValues
440 /// or FunctionValues data members of this class.
441 unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
442                                       ValueTable &ValueTab) {
443   if (ValueTab.size() <= type)
444     ValueTab.resize(type+1);
445
446   if (!ValueTab[type]) ValueTab[type] = new ValueList();
447
448   ValueTab[type]->push_back(Val);
449
450   bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
451   return ValueTab[type]->size()-1 + HasOffset;
452 }
453
454 /// Insert the arguments of a function as new values in the reader.
455 void BytecodeReader::insertArguments(Function* F) {
456   const FunctionType *FT = F->getFunctionType();
457   Function::arg_iterator AI = F->arg_begin();
458   for (FunctionType::param_iterator It = FT->param_begin();
459        It != FT->param_end(); ++It, ++AI)
460     insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
461 }
462
463 //===----------------------------------------------------------------------===//
464 // Bytecode Parsing Methods
465 //===----------------------------------------------------------------------===//
466
467 /// This method parses a single instruction. The instruction is
468 /// inserted at the end of the \p BB provided. The arguments of
469 /// the instruction are provided in the \p Oprnds vector.
470 void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
471                                       BasicBlock* BB) {
472   BufPtr SaveAt = At;
473
474   // Clear instruction data
475   Oprnds.clear();
476   unsigned iType = 0;
477   unsigned Opcode = 0;
478   unsigned Op = read_uint();
479
480   // bits   Instruction format:        Common to all formats
481   // --------------------------
482   // 01-00: Opcode type, fixed to 1.
483   // 07-02: Opcode
484   Opcode    = (Op >> 2) & 63;
485   Oprnds.resize((Op >> 0) & 03);
486
487   // Extract the operands
488   switch (Oprnds.size()) {
489   case 1:
490     // bits   Instruction format:
491     // --------------------------
492     // 19-08: Resulting type plane
493     // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
494     //
495     iType   = (Op >>  8) & 4095;
496     Oprnds[0] = (Op >> 20) & 4095;
497     if (Oprnds[0] == 4095)    // Handle special encoding for 0 operands...
498       Oprnds.resize(0);
499     break;
500   case 2:
501     // bits   Instruction format:
502     // --------------------------
503     // 15-08: Resulting type plane
504     // 23-16: Operand #1
505     // 31-24: Operand #2
506     //
507     iType   = (Op >>  8) & 255;
508     Oprnds[0] = (Op >> 16) & 255;
509     Oprnds[1] = (Op >> 24) & 255;
510     break;
511   case 3:
512     // bits   Instruction format:
513     // --------------------------
514     // 13-08: Resulting type plane
515     // 19-14: Operand #1
516     // 25-20: Operand #2
517     // 31-26: Operand #3
518     //
519     iType   = (Op >>  8) & 63;
520     Oprnds[0] = (Op >> 14) & 63;
521     Oprnds[1] = (Op >> 20) & 63;
522     Oprnds[2] = (Op >> 26) & 63;
523     break;
524   case 0:
525     At -= 4;  // Hrm, try this again...
526     Opcode = read_vbr_uint();
527     Opcode >>= 2;
528     iType = read_vbr_uint();
529
530     unsigned NumOprnds = read_vbr_uint();
531     Oprnds.resize(NumOprnds);
532
533     if (NumOprnds == 0)
534       error("Zero-argument instruction found; this is invalid.");
535
536     for (unsigned i = 0; i != NumOprnds; ++i)
537       Oprnds[i] = read_vbr_uint();
538     break;
539   }
540
541   const Type *InstTy = getType(iType);
542
543   // Make the necessary adjustments for dealing with backwards compatibility
544   // of opcodes.
545   Instruction* Result = 0;
546
547   // We have enough info to inform the handler now.
548   if (Handler) 
549     Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
550
551   // First, handle the easy binary operators case
552   if (Opcode >= Instruction::BinaryOpsBegin &&
553       Opcode <  Instruction::BinaryOpsEnd  && Oprnds.size() == 2) {
554     Result = BinaryOperator::create(Instruction::BinaryOps(Opcode),
555                                     getValue(iType, Oprnds[0]),
556                                     getValue(iType, Oprnds[1]));
557   } else {
558     // Indicate that we don't think this is a call instruction (yet).
559     // Process based on the Opcode read
560     switch (Opcode) {
561     default: // There was an error, this shouldn't happen.
562       if (Result == 0)
563         error("Illegal instruction read!");
564       break;
565     case Instruction::VAArg:
566       if (Oprnds.size() != 2)
567         error("Invalid VAArg instruction!");
568       Result = new VAArgInst(getValue(iType, Oprnds[0]),
569                              getType(Oprnds[1]));
570       break;
571     case Instruction::ExtractElement: {
572       if (Oprnds.size() != 2)
573         error("Invalid extractelement instruction!");
574       Value *V1 = getValue(iType, Oprnds[0]);
575       Value *V2 = getValue(Type::Int32TyID, Oprnds[1]);
576       
577       if (!ExtractElementInst::isValidOperands(V1, V2))
578         error("Invalid extractelement instruction!");
579
580       Result = new ExtractElementInst(V1, V2);
581       break;
582     }
583     case Instruction::InsertElement: {
584       const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
585       if (!PackedTy || Oprnds.size() != 3)
586         error("Invalid insertelement instruction!");
587       
588       Value *V1 = getValue(iType, Oprnds[0]);
589       Value *V2 = getValue(getTypeSlot(PackedTy->getElementType()),Oprnds[1]);
590       Value *V3 = getValue(Type::Int32TyID, Oprnds[2]);
591         
592       if (!InsertElementInst::isValidOperands(V1, V2, V3))
593         error("Invalid insertelement instruction!");
594       Result = new InsertElementInst(V1, V2, V3);
595       break;
596     }
597     case Instruction::ShuffleVector: {
598       const PackedType *PackedTy = dyn_cast<PackedType>(InstTy);
599       if (!PackedTy || Oprnds.size() != 3)
600         error("Invalid shufflevector instruction!");
601       Value *V1 = getValue(iType, Oprnds[0]);
602       Value *V2 = getValue(iType, Oprnds[1]);
603       const PackedType *EltTy = 
604         PackedType::get(Type::Int32Ty, PackedTy->getNumElements());
605       Value *V3 = getValue(getTypeSlot(EltTy), Oprnds[2]);
606       if (!ShuffleVectorInst::isValidOperands(V1, V2, V3))
607         error("Invalid shufflevector instruction!");
608       Result = new ShuffleVectorInst(V1, V2, V3);
609       break;
610     }
611     case Instruction::Trunc:
612       if (Oprnds.size() != 2)
613         error("Invalid cast instruction!");
614       Result = new TruncInst(getValue(iType, Oprnds[0]), 
615                              getType(Oprnds[1]));
616       break;
617     case Instruction::ZExt:
618       if (Oprnds.size() != 2)
619         error("Invalid cast instruction!");
620       Result = new ZExtInst(getValue(iType, Oprnds[0]), 
621                             getType(Oprnds[1]));
622       break;
623     case Instruction::SExt:
624       if (Oprnds.size() != 2)
625         error("Invalid Cast instruction!");
626       Result = new SExtInst(getValue(iType, Oprnds[0]),
627                             getType(Oprnds[1]));
628       break;
629     case Instruction::FPTrunc:
630       if (Oprnds.size() != 2)
631         error("Invalid cast instruction!");
632       Result = new FPTruncInst(getValue(iType, Oprnds[0]), 
633                                getType(Oprnds[1]));
634       break;
635     case Instruction::FPExt:
636       if (Oprnds.size() != 2)
637         error("Invalid cast instruction!");
638       Result = new FPExtInst(getValue(iType, Oprnds[0]), 
639                              getType(Oprnds[1]));
640       break;
641     case Instruction::UIToFP:
642       if (Oprnds.size() != 2)
643         error("Invalid cast instruction!");
644       Result = new UIToFPInst(getValue(iType, Oprnds[0]), 
645                               getType(Oprnds[1]));
646       break;
647     case Instruction::SIToFP:
648       if (Oprnds.size() != 2)
649         error("Invalid cast instruction!");
650       Result = new SIToFPInst(getValue(iType, Oprnds[0]), 
651                               getType(Oprnds[1]));
652       break;
653     case Instruction::FPToUI:
654       if (Oprnds.size() != 2)
655         error("Invalid cast instruction!");
656       Result = new FPToUIInst(getValue(iType, Oprnds[0]), 
657                               getType(Oprnds[1]));
658       break;
659     case Instruction::FPToSI:
660       if (Oprnds.size() != 2)
661         error("Invalid cast instruction!");
662       Result = new FPToSIInst(getValue(iType, Oprnds[0]), 
663                               getType(Oprnds[1]));
664       break;
665     case Instruction::IntToPtr:
666       if (Oprnds.size() != 2)
667         error("Invalid cast instruction!");
668       Result = new IntToPtrInst(getValue(iType, Oprnds[0]), 
669                                 getType(Oprnds[1]));
670       break;
671     case Instruction::PtrToInt:
672       if (Oprnds.size() != 2)
673         error("Invalid cast instruction!");
674       Result = new PtrToIntInst(getValue(iType, Oprnds[0]), 
675                                 getType(Oprnds[1]));
676       break;
677     case Instruction::BitCast:
678       if (Oprnds.size() != 2)
679         error("Invalid cast instruction!");
680       Result = new BitCastInst(getValue(iType, Oprnds[0]),
681                                getType(Oprnds[1]));
682       break;
683     case Instruction::Select:
684       if (Oprnds.size() != 3)
685         error("Invalid Select instruction!");
686       Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
687                               getValue(iType, Oprnds[1]),
688                               getValue(iType, Oprnds[2]));
689       break;
690     case Instruction::PHI: {
691       if (Oprnds.size() == 0 || (Oprnds.size() & 1))
692         error("Invalid phi node encountered!");
693
694       PHINode *PN = new PHINode(InstTy);
695       PN->reserveOperandSpace(Oprnds.size());
696       for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
697         PN->addIncoming(
698           getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
699       Result = PN;
700       break;
701     }
702     case Instruction::ICmp:
703     case Instruction::FCmp:
704       if (Oprnds.size() != 3)
705         error("Cmp instructions requires 3 operands");
706       // These instructions encode the comparison predicate as the 3rd operand.
707       Result = CmpInst::create(Instruction::OtherOps(Opcode),
708           static_cast<unsigned short>(Oprnds[2]),
709           getValue(iType, Oprnds[0]), getValue(iType, Oprnds[1]));
710       break;
711     case Instruction::Shl:
712     case Instruction::LShr:
713     case Instruction::AShr:
714       Result = new ShiftInst(Instruction::OtherOps(Opcode),
715                              getValue(iType, Oprnds[0]),
716                              getValue(Type::Int8TyID, Oprnds[1]));
717       break;
718     case Instruction::Ret:
719       if (Oprnds.size() == 0)
720         Result = new ReturnInst();
721       else if (Oprnds.size() == 1)
722         Result = new ReturnInst(getValue(iType, Oprnds[0]));
723       else
724         error("Unrecognized instruction!");
725       break;
726
727     case Instruction::Br:
728       if (Oprnds.size() == 1)
729         Result = new BranchInst(getBasicBlock(Oprnds[0]));
730       else if (Oprnds.size() == 3)
731         Result = new BranchInst(getBasicBlock(Oprnds[0]),
732             getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
733       else
734         error("Invalid number of operands for a 'br' instruction!");
735       break;
736     case Instruction::Switch: {
737       if (Oprnds.size() & 1)
738         error("Switch statement with odd number of arguments!");
739
740       SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
741                                      getBasicBlock(Oprnds[1]),
742                                      Oprnds.size()/2-1);
743       for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
744         I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
745                    getBasicBlock(Oprnds[i+1]));
746       Result = I;
747       break;
748     }
749     case 58:                   // Call with extra operand for calling conv
750     case 59:                   // tail call, Fast CC
751     case 60:                   // normal call, Fast CC
752     case 61:                   // tail call, C Calling Conv
753     case Instruction::Call: {  // Normal Call, C Calling Convention
754       if (Oprnds.size() == 0)
755         error("Invalid call instruction encountered!");
756       Value *F = getValue(iType, Oprnds[0]);
757
758       unsigned CallingConv = CallingConv::C;
759       bool isTailCall = false;
760
761       if (Opcode == 61 || Opcode == 59)
762         isTailCall = true;
763       
764       if (Opcode == 58) {
765         isTailCall = Oprnds.back() & 1;
766         CallingConv = Oprnds.back() >> 1;
767         Oprnds.pop_back();
768       } else if (Opcode == 59 || Opcode == 60) {
769         CallingConv = CallingConv::Fast;
770       }
771       
772       // Check to make sure we have a pointer to function type
773       const PointerType *PTy = dyn_cast<PointerType>(F->getType());
774       if (PTy == 0) error("Call to non function pointer value!");
775       const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
776       if (FTy == 0) error("Call to non function pointer value!");
777
778       std::vector<Value *> Params;
779       if (!FTy->isVarArg()) {
780         FunctionType::param_iterator It = FTy->param_begin();
781
782         for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
783           if (It == FTy->param_end())
784             error("Invalid call instruction!");
785           Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
786         }
787         if (It != FTy->param_end())
788           error("Invalid call instruction!");
789       } else {
790         Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
791
792         unsigned FirstVariableOperand;
793         if (Oprnds.size() < FTy->getNumParams())
794           error("Call instruction missing operands!");
795
796         // Read all of the fixed arguments
797         for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
798           Params.push_back(
799             getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
800
801         FirstVariableOperand = FTy->getNumParams();
802
803         if ((Oprnds.size()-FirstVariableOperand) & 1)
804           error("Invalid call instruction!");   // Must be pairs of type/value
805
806         for (unsigned i = FirstVariableOperand, e = Oprnds.size();
807              i != e; i += 2)
808           Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
809       }
810
811       Result = new CallInst(F, Params);
812       if (isTailCall) cast<CallInst>(Result)->setTailCall();
813       if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
814       break;
815     }
816     case Instruction::Invoke: {  // Invoke C CC
817       if (Oprnds.size() < 3)
818         error("Invalid invoke instruction!");
819       Value *F = getValue(iType, Oprnds[0]);
820
821       // Check to make sure we have a pointer to function type
822       const PointerType *PTy = dyn_cast<PointerType>(F->getType());
823       if (PTy == 0)
824         error("Invoke to non function pointer value!");
825       const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
826       if (FTy == 0)
827         error("Invoke to non function pointer value!");
828
829       std::vector<Value *> Params;
830       BasicBlock *Normal, *Except;
831       unsigned CallingConv = Oprnds.back();
832       Oprnds.pop_back();
833
834       if (!FTy->isVarArg()) {
835         Normal = getBasicBlock(Oprnds[1]);
836         Except = getBasicBlock(Oprnds[2]);
837
838         FunctionType::param_iterator It = FTy->param_begin();
839         for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
840           if (It == FTy->param_end())
841             error("Invalid invoke instruction!");
842           Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
843         }
844         if (It != FTy->param_end())
845           error("Invalid invoke instruction!");
846       } else {
847         Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
848
849         Normal = getBasicBlock(Oprnds[0]);
850         Except = getBasicBlock(Oprnds[1]);
851
852         unsigned FirstVariableArgument = FTy->getNumParams()+2;
853         for (unsigned i = 2; i != FirstVariableArgument; ++i)
854           Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
855                                     Oprnds[i]));
856
857         // Must be type/value pairs. If not, error out.
858         if (Oprnds.size()-FirstVariableArgument & 1) 
859           error("Invalid invoke instruction!");
860
861         for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
862           Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
863       }
864
865       Result = new InvokeInst(F, Normal, Except, Params);
866       if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
867       break;
868     }
869     case Instruction::Malloc: {
870       unsigned Align = 0;
871       if (Oprnds.size() == 2)
872         Align = (1 << Oprnds[1]) >> 1;
873       else if (Oprnds.size() > 2)
874         error("Invalid malloc instruction!");
875       if (!isa<PointerType>(InstTy))
876         error("Invalid malloc instruction!");
877
878       Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
879                               getValue(Type::Int32TyID, Oprnds[0]), Align);
880       break;
881     }
882     case Instruction::Alloca: {
883       unsigned Align = 0;
884       if (Oprnds.size() == 2)
885         Align = (1 << Oprnds[1]) >> 1;
886       else if (Oprnds.size() > 2)
887         error("Invalid alloca instruction!");
888       if (!isa<PointerType>(InstTy))
889         error("Invalid alloca instruction!");
890
891       Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
892                               getValue(Type::Int32TyID, Oprnds[0]), Align);
893       break;
894     }
895     case Instruction::Free:
896       if (!isa<PointerType>(InstTy))
897         error("Invalid free instruction!");
898       Result = new FreeInst(getValue(iType, Oprnds[0]));
899       break;
900     case Instruction::GetElementPtr: {
901       if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
902         error("Invalid getelementptr instruction!");
903
904       std::vector<Value*> Idx;
905
906       const Type *NextTy = InstTy;
907       for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
908         const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
909         if (!TopTy)
910           error("Invalid getelementptr instruction!");
911
912         unsigned ValIdx = Oprnds[i];
913         unsigned IdxTy = 0;
914         // Struct indices are always uints, sequential type indices can be 
915         // any of the 32 or 64-bit integer types.  The actual choice of 
916         // type is encoded in the low bit of the slot number.
917         if (isa<StructType>(TopTy))
918           IdxTy = Type::Int32TyID;
919         else {
920           switch (ValIdx & 1) {
921           default:
922           case 0: IdxTy = Type::Int32TyID; break;
923           case 1: IdxTy = Type::Int64TyID; break;
924           }
925           ValIdx >>= 1;
926         }
927         Idx.push_back(getValue(IdxTy, ValIdx));
928         NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
929       }
930
931       Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
932       break;
933     }
934     case 62:   // volatile load
935     case Instruction::Load:
936       if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
937         error("Invalid load instruction!");
938       Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
939       break;
940     case 63:   // volatile store
941     case Instruction::Store: {
942       if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
943         error("Invalid store instruction!");
944
945       Value *Ptr = getValue(iType, Oprnds[1]);
946       const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
947       Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
948                              Opcode == 63);
949       break;
950     }
951     case Instruction::Unwind:
952       if (Oprnds.size() != 0) error("Invalid unwind instruction!");
953       Result = new UnwindInst();
954       break;
955     case Instruction::Unreachable:
956       if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
957       Result = new UnreachableInst();
958       break;
959     }  // end switch(Opcode)
960   } // end if !Result
961
962   BB->getInstList().push_back(Result);
963
964   unsigned TypeSlot;
965   if (Result->getType() == InstTy)
966     TypeSlot = iType;
967   else
968     TypeSlot = getTypeSlot(Result->getType());
969
970   insertValue(Result, TypeSlot, FunctionValues);
971 }
972
973 /// Get a particular numbered basic block, which might be a forward reference.
974 /// This works together with ParseInstructionList to handle these forward 
975 /// references in a clean manner.  This function is used when constructing 
976 /// phi, br, switch, and other instructions that reference basic blocks. 
977 /// Blocks are numbered sequentially as they appear in the function.
978 BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
979   // Make sure there is room in the table...
980   if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
981
982   // First check to see if this is a backwards reference, i.e. this block
983   // has already been created, or if the forward reference has already
984   // been created.
985   if (ParsedBasicBlocks[ID])
986     return ParsedBasicBlocks[ID];
987
988   // Otherwise, the basic block has not yet been created.  Do so and add it to
989   // the ParsedBasicBlocks list.
990   return ParsedBasicBlocks[ID] = new BasicBlock();
991 }
992
993 /// Parse all of the BasicBlock's & Instruction's in the body of a function.
994 /// In post 1.0 bytecode files, we no longer emit basic block individually,
995 /// in order to avoid per-basic-block overhead.
996 /// @returns the number of basic blocks encountered.
997 unsigned BytecodeReader::ParseInstructionList(Function* F) {
998   unsigned BlockNo = 0;
999   std::vector<unsigned> Args;
1000
1001   while (moreInBlock()) {
1002     if (Handler) Handler->handleBasicBlockBegin(BlockNo);
1003     BasicBlock *BB;
1004     if (ParsedBasicBlocks.size() == BlockNo)
1005       ParsedBasicBlocks.push_back(BB = new BasicBlock());
1006     else if (ParsedBasicBlocks[BlockNo] == 0)
1007       BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1008     else
1009       BB = ParsedBasicBlocks[BlockNo];
1010     ++BlockNo;
1011     F->getBasicBlockList().push_back(BB);
1012
1013     // Read instructions into this basic block until we get to a terminator
1014     while (moreInBlock() && !BB->getTerminator())
1015       ParseInstruction(Args, BB);
1016
1017     if (!BB->getTerminator())
1018       error("Non-terminated basic block found!");
1019
1020     if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
1021   }
1022
1023   return BlockNo;
1024 }
1025
1026 /// Parse a symbol table. This works for both module level and function
1027 /// level symbol tables.  For function level symbol tables, the CurrentFunction
1028 /// parameter must be non-zero and the ST parameter must correspond to
1029 /// CurrentFunction's symbol table. For Module level symbol tables, the
1030 /// CurrentFunction argument must be zero.
1031 void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
1032                                       SymbolTable *ST) {
1033   if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
1034
1035   // Allow efficient basic block lookup by number.
1036   std::vector<BasicBlock*> BBMap;
1037   if (CurrentFunction)
1038     for (Function::iterator I = CurrentFunction->begin(),
1039            E = CurrentFunction->end(); I != E; ++I)
1040       BBMap.push_back(I);
1041
1042   // Symtab block header: [num entries]
1043   unsigned NumEntries = read_vbr_uint();
1044   for (unsigned i = 0; i < NumEntries; ++i) {
1045     // Symtab entry: [def slot #][name]
1046     unsigned slot = read_vbr_uint();
1047     std::string Name = read_str();
1048     const Type* T = getType(slot);
1049     ST->insert(Name, T);
1050   }
1051
1052   while (moreInBlock()) {
1053     // Symtab block header: [num entries][type id number]
1054     unsigned NumEntries = read_vbr_uint();
1055     unsigned Typ = read_vbr_uint();
1056
1057     for (unsigned i = 0; i != NumEntries; ++i) {
1058       // Symtab entry: [def slot #][name]
1059       unsigned slot = read_vbr_uint();
1060       std::string Name = read_str();
1061       Value *V = 0;
1062       if (Typ == Type::LabelTyID) {
1063         if (slot < BBMap.size())
1064           V = BBMap[slot];
1065       } else {
1066         V = getValue(Typ, slot, false); // Find mapping...
1067       }
1068       if (V == 0)
1069         error("Failed value look-up for name '" + Name + "'");
1070       V->setName(Name);
1071     }
1072   }
1073   checkPastBlockEnd("Symbol Table");
1074   if (Handler) Handler->handleSymbolTableEnd();
1075 }
1076
1077 /// Read in the types portion of a compaction table.
1078 void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
1079   for (unsigned i = 0; i != NumEntries; ++i) {
1080     unsigned TypeSlot = read_vbr_uint();
1081     const Type *Typ = getGlobalTableType(TypeSlot);
1082     CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
1083     if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
1084   }
1085 }
1086
1087 /// Parse a compaction table.
1088 void BytecodeReader::ParseCompactionTable() {
1089
1090   // Notify handler that we're beginning a compaction table.
1091   if (Handler) Handler->handleCompactionTableBegin();
1092
1093   // Get the types for the compaction table.
1094   unsigned NumEntries = read_vbr_uint();
1095   ParseCompactionTypes(NumEntries);
1096
1097   // Compaction tables live in separate blocks so we have to loop
1098   // until we've read the whole thing.
1099   while (moreInBlock()) {
1100     // Read the number of Value* entries in the compaction table
1101     unsigned NumEntries = read_vbr_uint();
1102     unsigned Ty = 0;
1103
1104     // Decode the type from value read in. Most compaction table
1105     // planes will have one or two entries in them. If that's the
1106     // case then the length is encoded in the bottom two bits and
1107     // the higher bits encode the type. This saves another VBR value.
1108     if ((NumEntries & 3) == 3) {
1109       // In this case, both low-order bits are set (value 3). This
1110       // is a signal that the typeid follows.
1111       NumEntries >>= 2;
1112       Ty = read_vbr_uint();
1113     } else {
1114       // In this case, the low-order bits specify the number of entries
1115       // and the high order bits specify the type.
1116       Ty = NumEntries >> 2;
1117       NumEntries &= 3;
1118     }
1119
1120     // Make sure we have enough room for the plane.
1121     if (Ty >= CompactionValues.size())
1122       CompactionValues.resize(Ty+1);
1123
1124     // Make sure the plane is empty or we have some kind of error.
1125     if (!CompactionValues[Ty].empty())
1126       error("Compaction table plane contains multiple entries!");
1127
1128     // Notify handler about the plane.
1129     if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
1130
1131     // Push the implicit zero.
1132     CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
1133
1134     // Read in each of the entries, put them in the compaction table
1135     // and notify the handler that we have a new compaction table value.
1136     for (unsigned i = 0; i != NumEntries; ++i) {
1137       unsigned ValSlot = read_vbr_uint();
1138       Value *V = getGlobalTableValue(Ty, ValSlot);
1139       CompactionValues[Ty].push_back(V);
1140       if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
1141     }
1142   }
1143   // Notify handler that the compaction table is done.
1144   if (Handler) Handler->handleCompactionTableEnd();
1145 }
1146
1147 // Parse a single type. The typeid is read in first. If its a primitive type
1148 // then nothing else needs to be read, we know how to instantiate it. If its
1149 // a derived type, then additional data is read to fill out the type
1150 // definition.
1151 const Type *BytecodeReader::ParseType() {
1152   unsigned PrimType = read_vbr_uint();
1153   const Type *Result = 0;
1154   if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1155     return Result;
1156
1157   switch (PrimType) {
1158   case Type::FunctionTyID: {
1159     const Type *RetType = readType();
1160     unsigned RetAttr = read_vbr_uint();
1161
1162     unsigned NumParams = read_vbr_uint();
1163
1164     std::vector<const Type*> Params;
1165     std::vector<FunctionType::ParameterAttributes> Attrs;
1166     Attrs.push_back(FunctionType::ParameterAttributes(RetAttr));
1167     while (NumParams--) {
1168       Params.push_back(readType());
1169       if (Params.back() != Type::VoidTy)
1170         Attrs.push_back(FunctionType::ParameterAttributes(read_vbr_uint()));
1171     }
1172
1173     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1174     if (isVarArg) Params.pop_back();
1175
1176     Result = FunctionType::get(RetType, Params, isVarArg, Attrs);
1177     break;
1178   }
1179   case Type::ArrayTyID: {
1180     const Type *ElementType = readType();
1181     unsigned NumElements = read_vbr_uint();
1182     Result =  ArrayType::get(ElementType, NumElements);
1183     break;
1184   }
1185   case Type::PackedTyID: {
1186     const Type *ElementType = readType();
1187     unsigned NumElements = read_vbr_uint();
1188     Result =  PackedType::get(ElementType, NumElements);
1189     break;
1190   }
1191   case Type::StructTyID: {
1192     std::vector<const Type*> Elements;
1193     unsigned Typ = read_vbr_uint();
1194     while (Typ) {         // List is terminated by void/0 typeid
1195       Elements.push_back(getType(Typ));
1196       Typ = read_vbr_uint();
1197     }
1198
1199     Result = StructType::get(Elements, false);
1200     break;
1201   }
1202   case Type::BC_ONLY_PackedStructTyID: {
1203     std::vector<const Type*> Elements;
1204     unsigned Typ = read_vbr_uint();
1205     while (Typ) {         // List is terminated by void/0 typeid
1206       Elements.push_back(getType(Typ));
1207       Typ = read_vbr_uint();
1208     }
1209
1210     Result = StructType::get(Elements, true);
1211     break;
1212   }
1213   case Type::PointerTyID: {
1214     Result = PointerType::get(readType());
1215     break;
1216   }
1217
1218   case Type::OpaqueTyID: {
1219     Result = OpaqueType::get();
1220     break;
1221   }
1222
1223   default:
1224     error("Don't know how to deserialize primitive type " + utostr(PrimType));
1225     break;
1226   }
1227   if (Handler) Handler->handleType(Result);
1228   return Result;
1229 }
1230
1231 // ParseTypes - We have to use this weird code to handle recursive
1232 // types.  We know that recursive types will only reference the current slab of
1233 // values in the type plane, but they can forward reference types before they
1234 // have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1235 // be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
1236 // this ugly problem, we pessimistically insert an opaque type for each type we
1237 // are about to read.  This means that forward references will resolve to
1238 // something and when we reread the type later, we can replace the opaque type
1239 // with a new resolved concrete type.
1240 //
1241 void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
1242   assert(Tab.size() == 0 && "should not have read type constants in before!");
1243
1244   // Insert a bunch of opaque types to be resolved later...
1245   Tab.reserve(NumEntries);
1246   for (unsigned i = 0; i != NumEntries; ++i)
1247     Tab.push_back(OpaqueType::get());
1248
1249   if (Handler)
1250     Handler->handleTypeList(NumEntries);
1251
1252   // If we are about to resolve types, make sure the type cache is clear.
1253   if (NumEntries)
1254     ModuleTypeIDCache.clear();
1255   
1256   // Loop through reading all of the types.  Forward types will make use of the
1257   // opaque types just inserted.
1258   //
1259   for (unsigned i = 0; i != NumEntries; ++i) {
1260     const Type* NewTy = ParseType();
1261     const Type* OldTy = Tab[i].get();
1262     if (NewTy == 0)
1263       error("Couldn't parse type!");
1264
1265     // Don't directly push the new type on the Tab. Instead we want to replace
1266     // the opaque type we previously inserted with the new concrete value. This
1267     // approach helps with forward references to types. The refinement from the
1268     // abstract (opaque) type to the new type causes all uses of the abstract
1269     // type to use the concrete type (NewTy). This will also cause the opaque
1270     // type to be deleted.
1271     cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1272
1273     // This should have replaced the old opaque type with the new type in the
1274     // value table... or with a preexisting type that was already in the system.
1275     // Let's just make sure it did.
1276     assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1277   }
1278 }
1279
1280 /// Parse a single constant value
1281 Value *BytecodeReader::ParseConstantPoolValue(unsigned TypeID) {
1282   // We must check for a ConstantExpr before switching by type because
1283   // a ConstantExpr can be of any type, and has no explicit value.
1284   //
1285   // 0 if not expr; numArgs if is expr
1286   unsigned isExprNumArgs = read_vbr_uint();
1287
1288   if (isExprNumArgs) {
1289     // 'undef' is encoded with 'exprnumargs' == 1.
1290     if (isExprNumArgs == 1)
1291       return UndefValue::get(getType(TypeID));
1292
1293     // Inline asm is encoded with exprnumargs == ~0U.
1294     if (isExprNumArgs == ~0U) {
1295       std::string AsmStr = read_str();
1296       std::string ConstraintStr = read_str();
1297       unsigned Flags = read_vbr_uint();
1298       
1299       const PointerType *PTy = dyn_cast<PointerType>(getType(TypeID));
1300       const FunctionType *FTy = 
1301         PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
1302
1303       if (!FTy || !InlineAsm::Verify(FTy, ConstraintStr))
1304         error("Invalid constraints for inline asm");
1305       if (Flags & ~1U)
1306         error("Invalid flags for inline asm");
1307       bool HasSideEffects = Flags & 1;
1308       return InlineAsm::get(FTy, AsmStr, ConstraintStr, HasSideEffects);
1309     }
1310     
1311     --isExprNumArgs;
1312
1313     // FIXME: Encoding of constant exprs could be much more compact!
1314     std::vector<Constant*> ArgVec;
1315     ArgVec.reserve(isExprNumArgs);
1316     unsigned Opcode = read_vbr_uint();
1317
1318     // Read the slot number and types of each of the arguments
1319     for (unsigned i = 0; i != isExprNumArgs; ++i) {
1320       unsigned ArgValSlot = read_vbr_uint();
1321       unsigned ArgTypeSlot = read_vbr_uint();
1322
1323       // Get the arg value from its slot if it exists, otherwise a placeholder
1324       ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1325     }
1326
1327     // Construct a ConstantExpr of the appropriate kind
1328     if (isExprNumArgs == 1) {           // All one-operand expressions
1329       if (!Instruction::isCast(Opcode))
1330         error("Only cast instruction has one argument for ConstantExpr");
1331
1332       Constant *Result = ConstantExpr::getCast(Opcode, ArgVec[0], 
1333                                                getType(TypeID));
1334       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1335       return Result;
1336     } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1337       std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1338       Constant *Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
1339       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1340       return Result;
1341     } else if (Opcode == Instruction::Select) {
1342       if (ArgVec.size() != 3)
1343         error("Select instruction must have three arguments.");
1344       Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
1345                                                  ArgVec[2]);
1346       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1347       return Result;
1348     } else if (Opcode == Instruction::ExtractElement) {
1349       if (ArgVec.size() != 2 ||
1350           !ExtractElementInst::isValidOperands(ArgVec[0], ArgVec[1]))
1351         error("Invalid extractelement constand expr arguments");
1352       Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1353       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1354       return Result;
1355     } else if (Opcode == Instruction::InsertElement) {
1356       if (ArgVec.size() != 3 ||
1357           !InsertElementInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1358         error("Invalid insertelement constand expr arguments");
1359         
1360       Constant *Result = 
1361         ConstantExpr::getInsertElement(ArgVec[0], ArgVec[1], ArgVec[2]);
1362       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1363       return Result;
1364     } else if (Opcode == Instruction::ShuffleVector) {
1365       if (ArgVec.size() != 3 ||
1366           !ShuffleVectorInst::isValidOperands(ArgVec[0], ArgVec[1], ArgVec[2]))
1367         error("Invalid shufflevector constant expr arguments.");
1368       Constant *Result = 
1369         ConstantExpr::getShuffleVector(ArgVec[0], ArgVec[1], ArgVec[2]);
1370       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1371       return Result;
1372     } else if (Opcode == Instruction::ICmp) {
1373       if (ArgVec.size() != 2) 
1374         error("Invalid ICmp constant expr arguments.");
1375       unsigned predicate = read_vbr_uint();
1376       Constant *Result = ConstantExpr::getICmp(predicate, ArgVec[0], ArgVec[1]);
1377       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1378       return Result;
1379     } else if (Opcode == Instruction::FCmp) {
1380       if (ArgVec.size() != 2) 
1381         error("Invalid FCmp constant expr arguments.");
1382       unsigned predicate = read_vbr_uint();
1383       Constant *Result = ConstantExpr::getFCmp(predicate, ArgVec[0], ArgVec[1]);
1384       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1385       return Result;
1386     } else {                            // All other 2-operand expressions
1387       Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1388       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1389       return Result;
1390     }
1391   }
1392
1393   // Ok, not an ConstantExpr.  We now know how to read the given type...
1394   const Type *Ty = getType(TypeID);
1395   Constant *Result = 0;
1396   switch (Ty->getTypeID()) {
1397   case Type::BoolTyID: {
1398     unsigned Val = read_vbr_uint();
1399     if (Val != 0 && Val != 1)
1400       error("Invalid boolean value read.");
1401     Result = ConstantBool::get(Val == 1);
1402     if (Handler) Handler->handleConstantValue(Result);
1403     break;
1404   }
1405
1406   case Type::Int8TyID:   // Unsigned integer types...
1407   case Type::Int16TyID:
1408   case Type::Int32TyID: {
1409     unsigned Val = read_vbr_uint();
1410     if (!ConstantInt::isValueValidForType(Ty, uint64_t(Val)))
1411       error("Invalid unsigned byte/short/int read.");
1412     Result = ConstantInt::get(Ty, Val);
1413     if (Handler) Handler->handleConstantValue(Result);
1414     break;
1415   }
1416
1417   case Type::Int64TyID: {
1418     uint64_t Val = read_vbr_uint64();
1419     if (!ConstantInt::isValueValidForType(Ty, Val))
1420       error("Invalid constant integer read.");
1421     Result = ConstantInt::get(Ty, Val);
1422     if (Handler) Handler->handleConstantValue(Result);
1423     break;
1424   }
1425   case Type::FloatTyID: {
1426     float Val;
1427     read_float(Val);
1428     Result = ConstantFP::get(Ty, Val);
1429     if (Handler) Handler->handleConstantValue(Result);
1430     break;
1431   }
1432
1433   case Type::DoubleTyID: {
1434     double Val;
1435     read_double(Val);
1436     Result = ConstantFP::get(Ty, Val);
1437     if (Handler) Handler->handleConstantValue(Result);
1438     break;
1439   }
1440
1441   case Type::ArrayTyID: {
1442     const ArrayType *AT = cast<ArrayType>(Ty);
1443     unsigned NumElements = AT->getNumElements();
1444     unsigned TypeSlot = getTypeSlot(AT->getElementType());
1445     std::vector<Constant*> Elements;
1446     Elements.reserve(NumElements);
1447     while (NumElements--)     // Read all of the elements of the constant.
1448       Elements.push_back(getConstantValue(TypeSlot,
1449                                           read_vbr_uint()));
1450     Result = ConstantArray::get(AT, Elements);
1451     if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
1452     break;
1453   }
1454
1455   case Type::StructTyID: {
1456     const StructType *ST = cast<StructType>(Ty);
1457
1458     std::vector<Constant *> Elements;
1459     Elements.reserve(ST->getNumElements());
1460     for (unsigned i = 0; i != ST->getNumElements(); ++i)
1461       Elements.push_back(getConstantValue(ST->getElementType(i),
1462                                           read_vbr_uint()));
1463
1464     Result = ConstantStruct::get(ST, Elements);
1465     if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
1466     break;
1467   }
1468
1469   case Type::PackedTyID: {
1470     const PackedType *PT = cast<PackedType>(Ty);
1471     unsigned NumElements = PT->getNumElements();
1472     unsigned TypeSlot = getTypeSlot(PT->getElementType());
1473     std::vector<Constant*> Elements;
1474     Elements.reserve(NumElements);
1475     while (NumElements--)     // Read all of the elements of the constant.
1476       Elements.push_back(getConstantValue(TypeSlot,
1477                                           read_vbr_uint()));
1478     Result = ConstantPacked::get(PT, Elements);
1479     if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1480     break;
1481   }
1482
1483   case Type::PointerTyID: {  // ConstantPointerRef value (backwards compat).
1484     const PointerType *PT = cast<PointerType>(Ty);
1485     unsigned Slot = read_vbr_uint();
1486
1487     // Check to see if we have already read this global variable...
1488     Value *Val = getValue(TypeID, Slot, false);
1489     if (Val) {
1490       GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1491       if (!GV) error("GlobalValue not in ValueTable!");
1492       if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1493       return GV;
1494     } else {
1495       error("Forward references are not allowed here.");
1496     }
1497   }
1498
1499   default:
1500     error("Don't know how to deserialize constant value of type '" +
1501                       Ty->getDescription());
1502     break;
1503   }
1504   
1505   // Check that we didn't read a null constant if they are implicit for this
1506   // type plane.  Do not do this check for constantexprs, as they may be folded
1507   // to a null value in a way that isn't predicted when a .bc file is initially
1508   // produced.
1509   assert((!isa<Constant>(Result) || !cast<Constant>(Result)->isNullValue()) ||
1510          !hasImplicitNull(TypeID) &&
1511          "Cannot read null values from bytecode!");
1512   return Result;
1513 }
1514
1515 /// Resolve references for constants. This function resolves the forward
1516 /// referenced constants in the ConstantFwdRefs map. It uses the
1517 /// replaceAllUsesWith method of Value class to substitute the placeholder
1518 /// instance with the actual instance.
1519 void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1520                                                  unsigned Slot) {
1521   ConstantRefsType::iterator I =
1522     ConstantFwdRefs.find(std::make_pair(Typ, Slot));
1523   if (I == ConstantFwdRefs.end()) return;   // Never forward referenced?
1524
1525   Value *PH = I->second;   // Get the placeholder...
1526   PH->replaceAllUsesWith(NewV);
1527   delete PH;                               // Delete the old placeholder
1528   ConstantFwdRefs.erase(I);                // Remove the map entry for it
1529 }
1530
1531 /// Parse the constant strings section.
1532 void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1533   for (; NumEntries; --NumEntries) {
1534     unsigned Typ = read_vbr_uint();
1535     const Type *Ty = getType(Typ);
1536     if (!isa<ArrayType>(Ty))
1537       error("String constant data invalid!");
1538
1539     const ArrayType *ATy = cast<ArrayType>(Ty);
1540     if (ATy->getElementType() != Type::Int8Ty &&
1541         ATy->getElementType() != Type::Int8Ty)
1542       error("String constant data invalid!");
1543
1544     // Read character data.  The type tells us how long the string is.
1545     char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
1546     read_data(Data, Data+ATy->getNumElements());
1547
1548     std::vector<Constant*> Elements(ATy->getNumElements());
1549     const Type* ElemType = ATy->getElementType();
1550     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1551       Elements[i] = ConstantInt::get(ElemType, (unsigned char)Data[i]);
1552
1553     // Create the constant, inserting it as needed.
1554     Constant *C = ConstantArray::get(ATy, Elements);
1555     unsigned Slot = insertValue(C, Typ, Tab);
1556     ResolveReferencesToConstant(C, Typ, Slot);
1557     if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
1558   }
1559 }
1560
1561 /// Parse the constant pool.
1562 void BytecodeReader::ParseConstantPool(ValueTable &Tab,
1563                                        TypeListTy &TypeTab,
1564                                        bool isFunction) {
1565   if (Handler) Handler->handleGlobalConstantsBegin();
1566
1567   /// In LLVM 1.3 Type does not derive from Value so the types
1568   /// do not occupy a plane. Consequently, we read the types
1569   /// first in the constant pool.
1570   if (isFunction) {
1571     unsigned NumEntries = read_vbr_uint();
1572     ParseTypes(TypeTab, NumEntries);
1573   }
1574
1575   while (moreInBlock()) {
1576     unsigned NumEntries = read_vbr_uint();
1577     unsigned Typ = read_vbr_uint();
1578
1579     if (Typ == Type::VoidTyID) {
1580       /// Use of Type::VoidTyID is a misnomer. It actually means
1581       /// that the following plane is constant strings
1582       assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1583       ParseStringConstants(NumEntries, Tab);
1584     } else {
1585       for (unsigned i = 0; i < NumEntries; ++i) {
1586         Value *V = ParseConstantPoolValue(Typ);
1587         assert(V && "ParseConstantPoolValue returned NULL!");
1588         unsigned Slot = insertValue(V, Typ, Tab);
1589
1590         // If we are reading a function constant table, make sure that we adjust
1591         // the slot number to be the real global constant number.
1592         //
1593         if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1594             ModuleValues[Typ])
1595           Slot += ModuleValues[Typ]->size();
1596         if (Constant *C = dyn_cast<Constant>(V))
1597           ResolveReferencesToConstant(C, Typ, Slot);
1598       }
1599     }
1600   }
1601
1602   // After we have finished parsing the constant pool, we had better not have
1603   // any dangling references left.
1604   if (!ConstantFwdRefs.empty()) {
1605     ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
1606     Constant* missingConst = I->second;
1607     error(utostr(ConstantFwdRefs.size()) +
1608           " unresolved constant reference exist. First one is '" +
1609           missingConst->getName() + "' of type '" +
1610           missingConst->getType()->getDescription() + "'.");
1611   }
1612
1613   checkPastBlockEnd("Constant Pool");
1614   if (Handler) Handler->handleGlobalConstantsEnd();
1615 }
1616
1617 /// Parse the contents of a function. Note that this function can be
1618 /// called lazily by materializeFunction
1619 /// @see materializeFunction
1620 void BytecodeReader::ParseFunctionBody(Function* F) {
1621
1622   unsigned FuncSize = BlockEnd - At;
1623   GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1624
1625   unsigned LinkageType = read_vbr_uint();
1626   switch (LinkageType) {
1627   case 0: Linkage = GlobalValue::ExternalLinkage; break;
1628   case 1: Linkage = GlobalValue::WeakLinkage; break;
1629   case 2: Linkage = GlobalValue::AppendingLinkage; break;
1630   case 3: Linkage = GlobalValue::InternalLinkage; break;
1631   case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1632   case 5: Linkage = GlobalValue::DLLImportLinkage; break;
1633   case 6: Linkage = GlobalValue::DLLExportLinkage; break;
1634   case 7: Linkage = GlobalValue::ExternalWeakLinkage; break;
1635   default:
1636     error("Invalid linkage type for Function.");
1637     Linkage = GlobalValue::InternalLinkage;
1638     break;
1639   }
1640
1641   F->setLinkage(Linkage);
1642   if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1643
1644   // Keep track of how many basic blocks we have read in...
1645   unsigned BlockNum = 0;
1646   bool InsertedArguments = false;
1647
1648   BufPtr MyEnd = BlockEnd;
1649   while (At < MyEnd) {
1650     unsigned Type, Size;
1651     BufPtr OldAt = At;
1652     read_block(Type, Size);
1653
1654     switch (Type) {
1655     case BytecodeFormat::ConstantPoolBlockID:
1656       if (!InsertedArguments) {
1657         // Insert arguments into the value table before we parse the first basic
1658         // block in the function, but after we potentially read in the
1659         // compaction table.
1660         insertArguments(F);
1661         InsertedArguments = true;
1662       }
1663
1664       ParseConstantPool(FunctionValues, FunctionTypes, true);
1665       break;
1666
1667     case BytecodeFormat::CompactionTableBlockID:
1668       ParseCompactionTable();
1669       break;
1670
1671     case BytecodeFormat::InstructionListBlockID: {
1672       // Insert arguments into the value table before we parse the instruction
1673       // list for the function, but after we potentially read in the compaction
1674       // table.
1675       if (!InsertedArguments) {
1676         insertArguments(F);
1677         InsertedArguments = true;
1678       }
1679
1680       if (BlockNum)
1681         error("Already parsed basic blocks!");
1682       BlockNum = ParseInstructionList(F);
1683       break;
1684     }
1685
1686     case BytecodeFormat::SymbolTableBlockID:
1687       ParseSymbolTable(F, &F->getSymbolTable());
1688       break;
1689
1690     default:
1691       At += Size;
1692       if (OldAt > At)
1693         error("Wrapped around reading bytecode.");
1694       break;
1695     }
1696     BlockEnd = MyEnd;
1697   }
1698
1699   // Make sure there were no references to non-existant basic blocks.
1700   if (BlockNum != ParsedBasicBlocks.size())
1701     error("Illegal basic block operand reference");
1702
1703   ParsedBasicBlocks.clear();
1704
1705   // Resolve forward references.  Replace any uses of a forward reference value
1706   // with the real value.
1707   while (!ForwardReferences.empty()) {
1708     std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1709       I = ForwardReferences.begin();
1710     Value *V = getValue(I->first.first, I->first.second, false);
1711     Value *PlaceHolder = I->second;
1712     PlaceHolder->replaceAllUsesWith(V);
1713     ForwardReferences.erase(I);
1714     delete PlaceHolder;
1715   }
1716
1717   // Clear out function-level types...
1718   FunctionTypes.clear();
1719   CompactionTypes.clear();
1720   CompactionValues.clear();
1721   freeTable(FunctionValues);
1722
1723   if (Handler) Handler->handleFunctionEnd(F);
1724 }
1725
1726 /// This function parses LLVM functions lazily. It obtains the type of the
1727 /// function and records where the body of the function is in the bytecode
1728 /// buffer. The caller can then use the ParseNextFunction and
1729 /// ParseAllFunctionBodies to get handler events for the functions.
1730 void BytecodeReader::ParseFunctionLazily() {
1731   if (FunctionSignatureList.empty())
1732     error("FunctionSignatureList empty!");
1733
1734   Function *Func = FunctionSignatureList.back();
1735   FunctionSignatureList.pop_back();
1736
1737   // Save the information for future reading of the function
1738   LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1739
1740   // This function has a body but it's not loaded so it appears `External'.
1741   // Mark it as a `Ghost' instead to notify the users that it has a body.
1742   Func->setLinkage(GlobalValue::GhostLinkage);
1743
1744   // Pretend we've `parsed' this function
1745   At = BlockEnd;
1746 }
1747
1748 /// The ParserFunction method lazily parses one function. Use this method to
1749 /// casue the parser to parse a specific function in the module. Note that
1750 /// this will remove the function from what is to be included by
1751 /// ParseAllFunctionBodies.
1752 /// @see ParseAllFunctionBodies
1753 /// @see ParseBytecode
1754 bool BytecodeReader::ParseFunction(Function* Func, std::string* ErrMsg) {
1755
1756   if (setjmp(context)) {
1757     // Set caller's error message, if requested
1758     if (ErrMsg)
1759       *ErrMsg = ErrorMsg;
1760     // Indicate an error occurred
1761     return true;
1762   }
1763
1764   // Find {start, end} pointers and slot in the map. If not there, we're done.
1765   LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1766
1767   // Make sure we found it
1768   if (Fi == LazyFunctionLoadMap.end()) {
1769     error("Unrecognized function of type " + Func->getType()->getDescription());
1770     return true;
1771   }
1772
1773   BlockStart = At = Fi->second.Buf;
1774   BlockEnd = Fi->second.EndBuf;
1775   assert(Fi->first == Func && "Found wrong function?");
1776
1777   LazyFunctionLoadMap.erase(Fi);
1778
1779   this->ParseFunctionBody(Func);
1780   return false;
1781 }
1782
1783 /// The ParseAllFunctionBodies method parses through all the previously
1784 /// unparsed functions in the bytecode file. If you want to completely parse
1785 /// a bytecode file, this method should be called after Parsebytecode because
1786 /// Parsebytecode only records the locations in the bytecode file of where
1787 /// the function definitions are located. This function uses that information
1788 /// to materialize the functions.
1789 /// @see ParseBytecode
1790 bool BytecodeReader::ParseAllFunctionBodies(std::string* ErrMsg) {
1791   if (setjmp(context)) {
1792     // Set caller's error message, if requested
1793     if (ErrMsg)
1794       *ErrMsg = ErrorMsg;
1795     // Indicate an error occurred
1796     return true;
1797   }
1798
1799   LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1800   LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1801
1802   while (Fi != Fe) {
1803     Function* Func = Fi->first;
1804     BlockStart = At = Fi->second.Buf;
1805     BlockEnd = Fi->second.EndBuf;
1806     ParseFunctionBody(Func);
1807     ++Fi;
1808   }
1809   LazyFunctionLoadMap.clear();
1810   return false;
1811 }
1812
1813 /// Parse the global type list
1814 void BytecodeReader::ParseGlobalTypes() {
1815   // Read the number of types
1816   unsigned NumEntries = read_vbr_uint();
1817   ParseTypes(ModuleTypes, NumEntries);
1818 }
1819
1820 /// Parse the Global info (types, global vars, constants)
1821 void BytecodeReader::ParseModuleGlobalInfo() {
1822
1823   if (Handler) Handler->handleModuleGlobalsBegin();
1824
1825   // SectionID - If a global has an explicit section specified, this map
1826   // remembers the ID until we can translate it into a string.
1827   std::map<GlobalValue*, unsigned> SectionID;
1828   
1829   // Read global variables...
1830   unsigned VarType = read_vbr_uint();
1831   while (VarType != Type::VoidTyID) { // List is terminated by Void
1832     // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1833     // Linkage, bit4+ = slot#
1834     unsigned SlotNo = VarType >> 5;
1835     unsigned LinkageID = (VarType >> 2) & 7;
1836     bool isConstant = VarType & 1;
1837     bool hasInitializer = (VarType & 2) != 0;
1838     unsigned Alignment = 0;
1839     unsigned GlobalSectionID = 0;
1840     
1841     // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1842     if (LinkageID == 3 && !hasInitializer) {
1843       unsigned ExtWord = read_vbr_uint();
1844       // The extension word has this format: bit 0 = has initializer, bit 1-3 =
1845       // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
1846       hasInitializer = ExtWord & 1;
1847       LinkageID = (ExtWord >> 1) & 7;
1848       Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
1849       
1850       if (ExtWord & (1 << 9))  // Has a section ID.
1851         GlobalSectionID = read_vbr_uint();
1852     }
1853
1854     GlobalValue::LinkageTypes Linkage;
1855     switch (LinkageID) {
1856     case 0: Linkage = GlobalValue::ExternalLinkage;  break;
1857     case 1: Linkage = GlobalValue::WeakLinkage;      break;
1858     case 2: Linkage = GlobalValue::AppendingLinkage; break;
1859     case 3: Linkage = GlobalValue::InternalLinkage;  break;
1860     case 4: Linkage = GlobalValue::LinkOnceLinkage;  break;
1861     case 5: Linkage = GlobalValue::DLLImportLinkage;  break;
1862     case 6: Linkage = GlobalValue::DLLExportLinkage;  break;
1863     case 7: Linkage = GlobalValue::ExternalWeakLinkage;  break;
1864     default:
1865       error("Unknown linkage type: " + utostr(LinkageID));
1866       Linkage = GlobalValue::InternalLinkage;
1867       break;
1868     }
1869
1870     const Type *Ty = getType(SlotNo);
1871     if (!Ty)
1872       error("Global has no type! SlotNo=" + utostr(SlotNo));
1873
1874     if (!isa<PointerType>(Ty))
1875       error("Global not a pointer type! Ty= " + Ty->getDescription());
1876
1877     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1878
1879     // Create the global variable...
1880     GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1881                                             0, "", TheModule);
1882     GV->setAlignment(Alignment);
1883     insertValue(GV, SlotNo, ModuleValues);
1884
1885     if (GlobalSectionID != 0)
1886       SectionID[GV] = GlobalSectionID;
1887
1888     unsigned initSlot = 0;
1889     if (hasInitializer) {
1890       initSlot = read_vbr_uint();
1891       GlobalInits.push_back(std::make_pair(GV, initSlot));
1892     }
1893
1894     // Notify handler about the global value.
1895     if (Handler)
1896       Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
1897
1898     // Get next item
1899     VarType = read_vbr_uint();
1900   }
1901
1902   // Read the function objects for all of the functions that are coming
1903   unsigned FnSignature = read_vbr_uint();
1904
1905   // List is terminated by VoidTy.
1906   while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1907     const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
1908     if (!isa<PointerType>(Ty) ||
1909         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1910       error("Function not a pointer to function type! Ty = " +
1911             Ty->getDescription());
1912     }
1913
1914     // We create functions by passing the underlying FunctionType to create...
1915     const FunctionType* FTy =
1916       cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1917
1918     // Insert the place holder.
1919     Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1920                                   "", TheModule);
1921
1922     insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
1923
1924     // Flags are not used yet.
1925     unsigned Flags = FnSignature & 31;
1926
1927     // Save this for later so we know type of lazily instantiated functions.
1928     // Note that known-external functions do not have FunctionInfo blocks, so we
1929     // do not add them to the FunctionSignatureList.
1930     if ((Flags & (1 << 4)) == 0)
1931       FunctionSignatureList.push_back(Func);
1932
1933     // Get the calling convention from the low bits.
1934     unsigned CC = Flags & 15;
1935     unsigned Alignment = 0;
1936     if (FnSignature & (1 << 31)) {  // Has extension word?
1937       unsigned ExtWord = read_vbr_uint();
1938       Alignment = (1 << (ExtWord & 31)) >> 1;
1939       CC |= ((ExtWord >> 5) & 15) << 4;
1940       
1941       if (ExtWord & (1 << 10))  // Has a section ID.
1942         SectionID[Func] = read_vbr_uint();
1943
1944       // Parse external declaration linkage
1945       switch ((ExtWord >> 11) & 3) {
1946        case 0: break;
1947        case 1: Func->setLinkage(Function::DLLImportLinkage); break;
1948        case 2: Func->setLinkage(Function::ExternalWeakLinkage); break;        
1949        default: assert(0 && "Unsupported external linkage");        
1950       }      
1951     }
1952     
1953     Func->setCallingConv(CC-1);
1954     Func->setAlignment(Alignment);
1955
1956     if (Handler) Handler->handleFunctionDeclaration(Func);
1957
1958     // Get the next function signature.
1959     FnSignature = read_vbr_uint();
1960   }
1961
1962   // Now that the function signature list is set up, reverse it so that we can
1963   // remove elements efficiently from the back of the vector.
1964   std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
1965
1966   /// SectionNames - This contains the list of section names encoded in the
1967   /// moduleinfoblock.  Functions and globals with an explicit section index
1968   /// into this to get their section name.
1969   std::vector<std::string> SectionNames;
1970   
1971   // Read in the dependent library information.
1972   unsigned num_dep_libs = read_vbr_uint();
1973   std::string dep_lib;
1974   while (num_dep_libs--) {
1975     dep_lib = read_str();
1976     TheModule->addLibrary(dep_lib);
1977     if (Handler)
1978       Handler->handleDependentLibrary(dep_lib);
1979   }
1980
1981   // Read target triple and place into the module.
1982   std::string triple = read_str();
1983   TheModule->setTargetTriple(triple);
1984   if (Handler)
1985     Handler->handleTargetTriple(triple);
1986   
1987   if (At != BlockEnd) {
1988     // If the file has section info in it, read the section names now.
1989     unsigned NumSections = read_vbr_uint();
1990     while (NumSections--)
1991       SectionNames.push_back(read_str());
1992   }
1993   
1994   // If the file has module-level inline asm, read it now.
1995   if (At != BlockEnd)
1996     TheModule->setModuleInlineAsm(read_str());
1997
1998   // If any globals are in specified sections, assign them now.
1999   for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2000        SectionID.end(); I != E; ++I)
2001     if (I->second) {
2002       if (I->second > SectionID.size())
2003         error("SectionID out of range for global!");
2004       I->first->setSection(SectionNames[I->second-1]);
2005     }
2006
2007   // This is for future proofing... in the future extra fields may be added that
2008   // we don't understand, so we transparently ignore them.
2009   //
2010   At = BlockEnd;
2011
2012   if (Handler) Handler->handleModuleGlobalsEnd();
2013 }
2014
2015 /// Parse the version information and decode it by setting flags on the
2016 /// Reader that enable backward compatibility of the reader.
2017 void BytecodeReader::ParseVersionInfo() {
2018   unsigned Version = read_vbr_uint();
2019
2020   // Unpack version number: low four bits are for flags, top bits = version
2021   Module::Endianness  Endianness;
2022   Module::PointerSize PointerSize;
2023   Endianness  = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2024   PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2025
2026   bool hasNoEndianness = Version & 4;
2027   bool hasNoPointerSize = Version & 8;
2028
2029   RevisionNum = Version >> 4;
2030
2031   // We don't provide backwards compatibility in the Reader any more. To
2032   // upgrade, the user should use llvm-upgrade.
2033   if (RevisionNum < 7)
2034     error("Bytecode formats < 7 are no longer supported. Use llvm-upgrade.");
2035
2036   if (hasNoEndianness) Endianness  = Module::AnyEndianness;
2037   if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
2038
2039   TheModule->setEndianness(Endianness);
2040   TheModule->setPointerSize(PointerSize);
2041
2042   if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
2043 }
2044
2045 /// Parse a whole module.
2046 void BytecodeReader::ParseModule() {
2047   unsigned Type, Size;
2048
2049   FunctionSignatureList.clear(); // Just in case...
2050
2051   // Read into instance variables...
2052   ParseVersionInfo();
2053
2054   bool SeenModuleGlobalInfo = false;
2055   bool SeenGlobalTypePlane = false;
2056   BufPtr MyEnd = BlockEnd;
2057   while (At < MyEnd) {
2058     BufPtr OldAt = At;
2059     read_block(Type, Size);
2060
2061     switch (Type) {
2062
2063     case BytecodeFormat::GlobalTypePlaneBlockID:
2064       if (SeenGlobalTypePlane)
2065         error("Two GlobalTypePlane Blocks Encountered!");
2066
2067       if (Size > 0)
2068         ParseGlobalTypes();
2069       SeenGlobalTypePlane = true;
2070       break;
2071
2072     case BytecodeFormat::ModuleGlobalInfoBlockID:
2073       if (SeenModuleGlobalInfo)
2074         error("Two ModuleGlobalInfo Blocks Encountered!");
2075       ParseModuleGlobalInfo();
2076       SeenModuleGlobalInfo = true;
2077       break;
2078
2079     case BytecodeFormat::ConstantPoolBlockID:
2080       ParseConstantPool(ModuleValues, ModuleTypes,false);
2081       break;
2082
2083     case BytecodeFormat::FunctionBlockID:
2084       ParseFunctionLazily();
2085       break;
2086
2087     case BytecodeFormat::SymbolTableBlockID:
2088       ParseSymbolTable(0, &TheModule->getSymbolTable());
2089       break;
2090
2091     default:
2092       At += Size;
2093       if (OldAt > At) {
2094         error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
2095       }
2096       break;
2097     }
2098     BlockEnd = MyEnd;
2099   }
2100
2101   // After the module constant pool has been read, we can safely initialize
2102   // global variables...
2103   while (!GlobalInits.empty()) {
2104     GlobalVariable *GV = GlobalInits.back().first;
2105     unsigned Slot = GlobalInits.back().second;
2106     GlobalInits.pop_back();
2107
2108     // Look up the initializer value...
2109     // FIXME: Preserve this type ID!
2110
2111     const llvm::PointerType* GVType = GV->getType();
2112     unsigned TypeSlot = getTypeSlot(GVType->getElementType());
2113     if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
2114       if (GV->hasInitializer())
2115         error("Global *already* has an initializer?!");
2116       if (Handler) Handler->handleGlobalInitializer(GV,CV);
2117       GV->setInitializer(CV);
2118     } else
2119       error("Cannot find initializer value.");
2120   }
2121
2122   if (!ConstantFwdRefs.empty())
2123     error("Use of undefined constants in a module");
2124
2125   /// Make sure we pulled them all out. If we didn't then there's a declaration
2126   /// but a missing body. That's not allowed.
2127   if (!FunctionSignatureList.empty())
2128     error("Function declared, but bytecode stream ended before definition");
2129 }
2130
2131 /// This function completely parses a bytecode buffer given by the \p Buf
2132 /// and \p Length parameters.
2133 bool BytecodeReader::ParseBytecode(volatile BufPtr Buf, unsigned Length,
2134                                    const std::string &ModuleID,
2135                                    std::string* ErrMsg) {
2136
2137   /// We handle errors by
2138   if (setjmp(context)) {
2139     // Cleanup after error
2140     if (Handler) Handler->handleError(ErrorMsg);
2141     freeState();
2142     delete TheModule;
2143     TheModule = 0;
2144     if (decompressedBlock != 0 ) {
2145       ::free(decompressedBlock);
2146       decompressedBlock = 0;
2147     }
2148     // Set caller's error message, if requested
2149     if (ErrMsg)
2150       *ErrMsg = ErrorMsg;
2151     // Indicate an error occurred
2152     return true;
2153   }
2154
2155   RevisionNum = 0;
2156   At = MemStart = BlockStart = Buf;
2157   MemEnd = BlockEnd = Buf + Length;
2158
2159   // Create the module
2160   TheModule = new Module(ModuleID);
2161
2162   if (Handler) Handler->handleStart(TheModule, Length);
2163
2164   // Read the four bytes of the signature.
2165   unsigned Sig = read_uint();
2166
2167   // If this is a compressed file
2168   if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2169
2170     // Invoke the decompression of the bytecode. Note that we have to skip the
2171     // file's magic number which is not part of the compressed block. Hence,
2172     // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2173     // member for retention until BytecodeReader is destructed.
2174     unsigned decompressedLength = Compressor::decompressToNewBuffer(
2175         (char*)Buf+4,Length-4,decompressedBlock);
2176
2177     // We must adjust the buffer pointers used by the bytecode reader to point
2178     // into the new decompressed block. After decompression, the
2179     // decompressedBlock will point to a contiguous memory area that has
2180     // the decompressed data.
2181     At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2182     MemEnd = BlockEnd = Buf + decompressedLength;
2183
2184   // else if this isn't a regular (uncompressed) bytecode file, then its
2185   // and error, generate that now.
2186   } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2187     error("Invalid bytecode signature: " + utohexstr(Sig));
2188   }
2189
2190   // Tell the handler we're starting a module
2191   if (Handler) Handler->handleModuleBegin(ModuleID);
2192
2193   // Get the module block and size and verify. This is handled specially
2194   // because the module block/size is always written in long format. Other
2195   // blocks are written in short format so the read_block method is used.
2196   unsigned Type, Size;
2197   Type = read_uint();
2198   Size = read_uint();
2199   if (Type != BytecodeFormat::ModuleBlockID) {
2200     error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2201           + utostr(Size));
2202   }
2203
2204   // It looks like the darwin ranlib program is broken, and adds trailing
2205   // garbage to the end of some bytecode files.  This hack allows the bc
2206   // reader to ignore trailing garbage on bytecode files.
2207   if (At + Size < MemEnd)
2208     MemEnd = BlockEnd = At+Size;
2209
2210   if (At + Size != MemEnd)
2211     error("Invalid Top Level Block Length! Type:" + utostr(Type)
2212           + ", Size:" + utostr(Size));
2213
2214   // Parse the module contents
2215   this->ParseModule();
2216
2217   // Check for missing functions
2218   if (hasFunctions())
2219     error("Function expected, but bytecode stream ended!");
2220
2221   // Tell the handler we're done with the module
2222   if (Handler)
2223     Handler->handleModuleEnd(ModuleID);
2224
2225   // Tell the handler we're finished the parse
2226   if (Handler) Handler->handleFinish();
2227
2228   return false;
2229
2230 }
2231
2232 //===----------------------------------------------------------------------===//
2233 //=== Default Implementations of Handler Methods
2234 //===----------------------------------------------------------------------===//
2235
2236 BytecodeHandler::~BytecodeHandler() {}
2237