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