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