IR, bitcode reader, bitcode writer, and asmparser changes to
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This header defines the BitcodeReader class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "BitcodeReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/AutoUpgrade.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/OperandTraits.h"
27 using namespace llvm;
28
29 void BitcodeReader::FreeState() {
30   delete Buffer;
31   Buffer = 0;
32   std::vector<PATypeHolder>().swap(TypeList);
33   ValueList.clear();
34   
35   std::vector<PAListPtr>().swap(ParamAttrs);
36   std::vector<BasicBlock*>().swap(FunctionBBs);
37   std::vector<Function*>().swap(FunctionsWithBodies);
38   DeferredFunctionInfo.clear();
39 }
40
41 //===----------------------------------------------------------------------===//
42 //  Helper functions to implement forward reference resolution, etc.
43 //===----------------------------------------------------------------------===//
44
45 /// ConvertToString - Convert a string from a record into an std::string, return
46 /// true on failure.
47 template<typename StrTy>
48 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
49                             StrTy &Result) {
50   if (Idx > Record.size())
51     return true;
52   
53   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
54     Result += (char)Record[i];
55   return false;
56 }
57
58 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
59   switch (Val) {
60   default: // Map unknown/new linkages to external
61   case 0: return GlobalValue::ExternalLinkage;
62   case 1: return GlobalValue::WeakLinkage;
63   case 2: return GlobalValue::AppendingLinkage;
64   case 3: return GlobalValue::InternalLinkage;
65   case 4: return GlobalValue::LinkOnceLinkage;
66   case 5: return GlobalValue::DLLImportLinkage;
67   case 6: return GlobalValue::DLLExportLinkage;
68   case 7: return GlobalValue::ExternalWeakLinkage;
69   case 8: return GlobalValue::CommonLinkage;
70   }
71 }
72
73 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
74   switch (Val) {
75   default: // Map unknown visibilities to default.
76   case 0: return GlobalValue::DefaultVisibility;
77   case 1: return GlobalValue::HiddenVisibility;
78   case 2: return GlobalValue::ProtectedVisibility;
79   }
80 }
81
82 static int GetDecodedCastOpcode(unsigned Val) {
83   switch (Val) {
84   default: return -1;
85   case bitc::CAST_TRUNC   : return Instruction::Trunc;
86   case bitc::CAST_ZEXT    : return Instruction::ZExt;
87   case bitc::CAST_SEXT    : return Instruction::SExt;
88   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
89   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
90   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
91   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
92   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
93   case bitc::CAST_FPEXT   : return Instruction::FPExt;
94   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
95   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
96   case bitc::CAST_BITCAST : return Instruction::BitCast;
97   }
98 }
99 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
100   switch (Val) {
101   default: return -1;
102   case bitc::BINOP_ADD:  return Instruction::Add;
103   case bitc::BINOP_SUB:  return Instruction::Sub;
104   case bitc::BINOP_MUL:  return Instruction::Mul;
105   case bitc::BINOP_UDIV: return Instruction::UDiv;
106   case bitc::BINOP_SDIV:
107     return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
108   case bitc::BINOP_UREM: return Instruction::URem;
109   case bitc::BINOP_SREM:
110     return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
111   case bitc::BINOP_SHL:  return Instruction::Shl;
112   case bitc::BINOP_LSHR: return Instruction::LShr;
113   case bitc::BINOP_ASHR: return Instruction::AShr;
114   case bitc::BINOP_AND:  return Instruction::And;
115   case bitc::BINOP_OR:   return Instruction::Or;
116   case bitc::BINOP_XOR:  return Instruction::Xor;
117   }
118 }
119
120 namespace llvm {
121 namespace {
122   /// @brief A class for maintaining the slot number definition
123   /// as a placeholder for the actual definition for forward constants defs.
124   class ConstantPlaceHolder : public ConstantExpr {
125     ConstantPlaceHolder();                       // DO NOT IMPLEMENT
126     void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
127   public:
128     // allocate space for exactly one operand
129     void *operator new(size_t s) {
130       return User::operator new(s, 1);
131     }
132     explicit ConstantPlaceHolder(const Type *Ty)
133       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
134       Op<0>() = UndefValue::get(Type::Int32Ty);
135     }
136     /// Provide fast operand accessors
137     DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
138   };
139 }
140
141
142   // FIXME: can we inherit this from ConstantExpr?
143 template <>
144 struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
145 };
146
147 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
148 }
149
150 void BitcodeReaderValueList::resize(unsigned Desired) {
151   if (Desired > Capacity) {
152     // Since we expect many values to come from the bitcode file we better
153     // allocate the double amount, so that the array size grows exponentially
154     // at each reallocation.  Also, add a small amount of 100 extra elements
155     // each time, to reallocate less frequently when the array is still small.
156     //
157     Capacity = Desired * 2 + 100;
158     Use *New = allocHungoffUses(Capacity);
159     Use *Old = OperandList;
160     unsigned Ops = getNumOperands();
161     for (int i(Ops - 1); i >= 0; --i)
162       New[i] = Old[i].get();
163     OperandList = New;
164     if (Old) Use::zap(Old, Old + Ops, true);
165   }
166 }
167
168 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
169                                                     const Type *Ty) {
170   if (Idx >= size()) {
171     // Insert a bunch of null values.
172     resize(Idx + 1);
173     NumOperands = Idx+1;
174   }
175
176   if (Value *V = OperandList[Idx]) {
177     assert(Ty == V->getType() && "Type mismatch in constant table!");
178     return cast<Constant>(V);
179   }
180
181   // Create and return a placeholder, which will later be RAUW'd.
182   Constant *C = new ConstantPlaceHolder(Ty);
183   OperandList[Idx] = C;
184   return C;
185 }
186
187 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
188   if (Idx >= size()) {
189     // Insert a bunch of null values.
190     resize(Idx + 1);
191     NumOperands = Idx+1;
192   }
193   
194   if (Value *V = OperandList[Idx]) {
195     assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
196     return V;
197   }
198   
199   // No type specified, must be invalid reference.
200   if (Ty == 0) return 0;
201   
202   // Create and return a placeholder, which will later be RAUW'd.
203   Value *V = new Argument(Ty);
204   OperandList[Idx] = V;
205   return V;
206 }
207
208
209 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
210   // If the TypeID is in range, return it.
211   if (ID < TypeList.size())
212     return TypeList[ID].get();
213   if (!isTypeTable) return 0;
214   
215   // The type table allows forward references.  Push as many Opaque types as
216   // needed to get up to ID.
217   while (TypeList.size() <= ID)
218     TypeList.push_back(OpaqueType::get());
219   return TypeList.back().get();
220 }
221
222 //===----------------------------------------------------------------------===//
223 //  Functions for parsing blocks from the bitcode file
224 //===----------------------------------------------------------------------===//
225
226 bool BitcodeReader::ParseParamAttrBlock() {
227   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
228     return Error("Malformed block record");
229   
230   if (!ParamAttrs.empty())
231     return Error("Multiple PARAMATTR blocks found!");
232   
233   SmallVector<uint64_t, 64> Record;
234   
235   SmallVector<ParamAttrsWithIndex, 8> Attrs;
236   
237   // Read all the records.
238   while (1) {
239     unsigned Code = Stream.ReadCode();
240     if (Code == bitc::END_BLOCK) {
241       if (Stream.ReadBlockEnd())
242         return Error("Error at end of PARAMATTR block");
243       return false;
244     }
245     
246     if (Code == bitc::ENTER_SUBBLOCK) {
247       // No known subblocks, always skip them.
248       Stream.ReadSubBlockID();
249       if (Stream.SkipBlock())
250         return Error("Malformed block record");
251       continue;
252     }
253     
254     if (Code == bitc::DEFINE_ABBREV) {
255       Stream.ReadAbbrevRecord();
256       continue;
257     }
258     
259     // Read a record.
260     Record.clear();
261     switch (Stream.ReadRecord(Code, Record)) {
262     default:  // Default behavior: ignore.
263       break;
264     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
265       if (Record.size() & 1)
266         return Error("Invalid ENTRY record");
267
268       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
269         if (Record[i+1] != ParamAttr::None)
270           Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
271       }
272
273       ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end()));
274       Attrs.clear();
275       break;
276     }
277     }
278   }
279 }
280
281
282 bool BitcodeReader::ParseTypeTable() {
283   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
284     return Error("Malformed block record");
285   
286   if (!TypeList.empty())
287     return Error("Multiple TYPE_BLOCKs found!");
288
289   SmallVector<uint64_t, 64> Record;
290   unsigned NumRecords = 0;
291
292   // Read all the records for this type table.
293   while (1) {
294     unsigned Code = Stream.ReadCode();
295     if (Code == bitc::END_BLOCK) {
296       if (NumRecords != TypeList.size())
297         return Error("Invalid type forward reference in TYPE_BLOCK");
298       if (Stream.ReadBlockEnd())
299         return Error("Error at end of type table block");
300       return false;
301     }
302     
303     if (Code == bitc::ENTER_SUBBLOCK) {
304       // No known subblocks, always skip them.
305       Stream.ReadSubBlockID();
306       if (Stream.SkipBlock())
307         return Error("Malformed block record");
308       continue;
309     }
310     
311     if (Code == bitc::DEFINE_ABBREV) {
312       Stream.ReadAbbrevRecord();
313       continue;
314     }
315     
316     // Read a record.
317     Record.clear();
318     const Type *ResultTy = 0;
319     switch (Stream.ReadRecord(Code, Record)) {
320     default:  // Default behavior: unknown type.
321       ResultTy = 0;
322       break;
323     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
324       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
325       // type list.  This allows us to reserve space.
326       if (Record.size() < 1)
327         return Error("Invalid TYPE_CODE_NUMENTRY record");
328       TypeList.reserve(Record[0]);
329       continue;
330     case bitc::TYPE_CODE_VOID:      // VOID
331       ResultTy = Type::VoidTy;
332       break;
333     case bitc::TYPE_CODE_FLOAT:     // FLOAT
334       ResultTy = Type::FloatTy;
335       break;
336     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
337       ResultTy = Type::DoubleTy;
338       break;
339     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
340       ResultTy = Type::X86_FP80Ty;
341       break;
342     case bitc::TYPE_CODE_FP128:     // FP128
343       ResultTy = Type::FP128Ty;
344       break;
345     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
346       ResultTy = Type::PPC_FP128Ty;
347       break;
348     case bitc::TYPE_CODE_LABEL:     // LABEL
349       ResultTy = Type::LabelTy;
350       break;
351     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
352       ResultTy = 0;
353       break;
354     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
355       if (Record.size() < 1)
356         return Error("Invalid Integer type record");
357       
358       ResultTy = IntegerType::get(Record[0]);
359       break;
360     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 
361                                     //          [pointee type, address space]
362       if (Record.size() < 1)
363         return Error("Invalid POINTER type record");
364       unsigned AddressSpace = 0;
365       if (Record.size() == 2)
366         AddressSpace = Record[1];
367       ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
368       break;
369     }
370     case bitc::TYPE_CODE_FUNCTION: {
371       // FIXME: attrid is dead, remove it in LLVM 3.0
372       // FUNCTION: [vararg, attrid, retty, paramty x N]
373       if (Record.size() < 3)
374         return Error("Invalid FUNCTION type record");
375       std::vector<const Type*> ArgTys;
376       for (unsigned i = 3, e = Record.size(); i != e; ++i)
377         ArgTys.push_back(getTypeByID(Record[i], true));
378       
379       ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
380                                    Record[0]);
381       break;
382     }
383     case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
384       if (Record.size() < 1)
385         return Error("Invalid STRUCT type record");
386       std::vector<const Type*> EltTys;
387       for (unsigned i = 1, e = Record.size(); i != e; ++i)
388         EltTys.push_back(getTypeByID(Record[i], true));
389       ResultTy = StructType::get(EltTys, Record[0]);
390       break;
391     }
392     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
393       if (Record.size() < 2)
394         return Error("Invalid ARRAY type record");
395       ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
396       break;
397     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
398       if (Record.size() < 2)
399         return Error("Invalid VECTOR type record");
400       ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
401       break;
402     }
403     
404     if (NumRecords == TypeList.size()) {
405       // If this is a new type slot, just append it.
406       TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
407       ++NumRecords;
408     } else if (ResultTy == 0) {
409       // Otherwise, this was forward referenced, so an opaque type was created,
410       // but the result type is actually just an opaque.  Leave the one we
411       // created previously.
412       ++NumRecords;
413     } else {
414       // Otherwise, this was forward referenced, so an opaque type was created.
415       // Resolve the opaque type to the real type now.
416       assert(NumRecords < TypeList.size() && "Typelist imbalance");
417       const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
418      
419       // Don't directly push the new type on the Tab. Instead we want to replace
420       // the opaque type we previously inserted with the new concrete value. The
421       // refinement from the abstract (opaque) type to the new type causes all
422       // uses of the abstract type to use the concrete type (NewTy). This will
423       // also cause the opaque type to be deleted.
424       const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
425       
426       // This should have replaced the old opaque type with the new type in the
427       // value table... or with a preexisting type that was already in the
428       // system.  Let's just make sure it did.
429       assert(TypeList[NumRecords-1].get() != OldTy &&
430              "refineAbstractType didn't work!");
431     }
432   }
433 }
434
435
436 bool BitcodeReader::ParseTypeSymbolTable() {
437   if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
438     return Error("Malformed block record");
439   
440   SmallVector<uint64_t, 64> Record;
441   
442   // Read all the records for this type table.
443   std::string TypeName;
444   while (1) {
445     unsigned Code = Stream.ReadCode();
446     if (Code == bitc::END_BLOCK) {
447       if (Stream.ReadBlockEnd())
448         return Error("Error at end of type symbol table block");
449       return false;
450     }
451     
452     if (Code == bitc::ENTER_SUBBLOCK) {
453       // No known subblocks, always skip them.
454       Stream.ReadSubBlockID();
455       if (Stream.SkipBlock())
456         return Error("Malformed block record");
457       continue;
458     }
459     
460     if (Code == bitc::DEFINE_ABBREV) {
461       Stream.ReadAbbrevRecord();
462       continue;
463     }
464     
465     // Read a record.
466     Record.clear();
467     switch (Stream.ReadRecord(Code, Record)) {
468     default:  // Default behavior: unknown type.
469       break;
470     case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
471       if (ConvertToString(Record, 1, TypeName))
472         return Error("Invalid TST_ENTRY record");
473       unsigned TypeID = Record[0];
474       if (TypeID >= TypeList.size())
475         return Error("Invalid Type ID in TST_ENTRY record");
476
477       TheModule->addTypeName(TypeName, TypeList[TypeID].get());
478       TypeName.clear();
479       break;
480     }
481   }
482 }
483
484 bool BitcodeReader::ParseValueSymbolTable() {
485   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
486     return Error("Malformed block record");
487
488   SmallVector<uint64_t, 64> Record;
489   
490   // Read all the records for this value table.
491   SmallString<128> ValueName;
492   while (1) {
493     unsigned Code = Stream.ReadCode();
494     if (Code == bitc::END_BLOCK) {
495       if (Stream.ReadBlockEnd())
496         return Error("Error at end of value symbol table block");
497       return false;
498     }    
499     if (Code == bitc::ENTER_SUBBLOCK) {
500       // No known subblocks, always skip them.
501       Stream.ReadSubBlockID();
502       if (Stream.SkipBlock())
503         return Error("Malformed block record");
504       continue;
505     }
506     
507     if (Code == bitc::DEFINE_ABBREV) {
508       Stream.ReadAbbrevRecord();
509       continue;
510     }
511     
512     // Read a record.
513     Record.clear();
514     switch (Stream.ReadRecord(Code, Record)) {
515     default:  // Default behavior: unknown type.
516       break;
517     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
518       if (ConvertToString(Record, 1, ValueName))
519         return Error("Invalid TST_ENTRY record");
520       unsigned ValueID = Record[0];
521       if (ValueID >= ValueList.size())
522         return Error("Invalid Value ID in VST_ENTRY record");
523       Value *V = ValueList[ValueID];
524       
525       V->setName(&ValueName[0], ValueName.size());
526       ValueName.clear();
527       break;
528     }
529     case bitc::VST_CODE_BBENTRY: {
530       if (ConvertToString(Record, 1, ValueName))
531         return Error("Invalid VST_BBENTRY record");
532       BasicBlock *BB = getBasicBlock(Record[0]);
533       if (BB == 0)
534         return Error("Invalid BB ID in VST_BBENTRY record");
535       
536       BB->setName(&ValueName[0], ValueName.size());
537       ValueName.clear();
538       break;
539     }
540     }
541   }
542 }
543
544 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
545 /// the LSB for dense VBR encoding.
546 static uint64_t DecodeSignRotatedValue(uint64_t V) {
547   if ((V & 1) == 0)
548     return V >> 1;
549   if (V != 1) 
550     return -(V >> 1);
551   // There is no such thing as -0 with integers.  "-0" really means MININT.
552   return 1ULL << 63;
553 }
554
555 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
556 /// values and aliases that we can.
557 bool BitcodeReader::ResolveGlobalAndAliasInits() {
558   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
559   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
560   
561   GlobalInitWorklist.swap(GlobalInits);
562   AliasInitWorklist.swap(AliasInits);
563
564   while (!GlobalInitWorklist.empty()) {
565     unsigned ValID = GlobalInitWorklist.back().second;
566     if (ValID >= ValueList.size()) {
567       // Not ready to resolve this yet, it requires something later in the file.
568       GlobalInits.push_back(GlobalInitWorklist.back());
569     } else {
570       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
571         GlobalInitWorklist.back().first->setInitializer(C);
572       else
573         return Error("Global variable initializer is not a constant!");
574     }
575     GlobalInitWorklist.pop_back(); 
576   }
577
578   while (!AliasInitWorklist.empty()) {
579     unsigned ValID = AliasInitWorklist.back().second;
580     if (ValID >= ValueList.size()) {
581       AliasInits.push_back(AliasInitWorklist.back());
582     } else {
583       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
584         AliasInitWorklist.back().first->setAliasee(C);
585       else
586         return Error("Alias initializer is not a constant!");
587     }
588     AliasInitWorklist.pop_back(); 
589   }
590   return false;
591 }
592
593
594 bool BitcodeReader::ParseConstants() {
595   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
596     return Error("Malformed block record");
597
598   SmallVector<uint64_t, 64> Record;
599   
600   // Read all the records for this value table.
601   const Type *CurTy = Type::Int32Ty;
602   unsigned NextCstNo = ValueList.size();
603   while (1) {
604     unsigned Code = Stream.ReadCode();
605     if (Code == bitc::END_BLOCK) {
606       if (NextCstNo != ValueList.size())
607         return Error("Invalid constant reference!");
608       
609       if (Stream.ReadBlockEnd())
610         return Error("Error at end of constants block");
611       return false;
612     }
613     
614     if (Code == bitc::ENTER_SUBBLOCK) {
615       // No known subblocks, always skip them.
616       Stream.ReadSubBlockID();
617       if (Stream.SkipBlock())
618         return Error("Malformed block record");
619       continue;
620     }
621     
622     if (Code == bitc::DEFINE_ABBREV) {
623       Stream.ReadAbbrevRecord();
624       continue;
625     }
626     
627     // Read a record.
628     Record.clear();
629     Value *V = 0;
630     switch (Stream.ReadRecord(Code, Record)) {
631     default:  // Default behavior: unknown constant
632     case bitc::CST_CODE_UNDEF:     // UNDEF
633       V = UndefValue::get(CurTy);
634       break;
635     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
636       if (Record.empty())
637         return Error("Malformed CST_SETTYPE record");
638       if (Record[0] >= TypeList.size())
639         return Error("Invalid Type ID in CST_SETTYPE record");
640       CurTy = TypeList[Record[0]];
641       continue;  // Skip the ValueList manipulation.
642     case bitc::CST_CODE_NULL:      // NULL
643       V = Constant::getNullValue(CurTy);
644       break;
645     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
646       if (!isa<IntegerType>(CurTy) || Record.empty())
647         return Error("Invalid CST_INTEGER record");
648       V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
649       break;
650     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
651       if (!isa<IntegerType>(CurTy) || Record.empty())
652         return Error("Invalid WIDE_INTEGER record");
653       
654       unsigned NumWords = Record.size();
655       SmallVector<uint64_t, 8> Words;
656       Words.resize(NumWords);
657       for (unsigned i = 0; i != NumWords; ++i)
658         Words[i] = DecodeSignRotatedValue(Record[i]);
659       V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
660                                  NumWords, &Words[0]));
661       break;
662     }
663     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
664       if (Record.empty())
665         return Error("Invalid FLOAT record");
666       if (CurTy == Type::FloatTy)
667         V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
668       else if (CurTy == Type::DoubleTy)
669         V = ConstantFP::get(APFloat(APInt(64, Record[0])));
670       else if (CurTy == Type::X86_FP80Ty)
671         V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0])));
672       else if (CurTy == Type::FP128Ty)
673         V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
674       else if (CurTy == Type::PPC_FP128Ty)
675         V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
676       else
677         V = UndefValue::get(CurTy);
678       break;
679     }
680       
681     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
682       if (Record.empty())
683         return Error("Invalid CST_AGGREGATE record");
684       
685       unsigned Size = Record.size();
686       std::vector<Constant*> Elts;
687       
688       if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
689         for (unsigned i = 0; i != Size; ++i)
690           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
691                                                      STy->getElementType(i)));
692         V = ConstantStruct::get(STy, Elts);
693       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
694         const Type *EltTy = ATy->getElementType();
695         for (unsigned i = 0; i != Size; ++i)
696           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
697         V = ConstantArray::get(ATy, Elts);
698       } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
699         const Type *EltTy = VTy->getElementType();
700         for (unsigned i = 0; i != Size; ++i)
701           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
702         V = ConstantVector::get(Elts);
703       } else {
704         V = UndefValue::get(CurTy);
705       }
706       break;
707     }
708     case bitc::CST_CODE_STRING: { // STRING: [values]
709       if (Record.empty())
710         return Error("Invalid CST_AGGREGATE record");
711
712       const ArrayType *ATy = cast<ArrayType>(CurTy);
713       const Type *EltTy = ATy->getElementType();
714       
715       unsigned Size = Record.size();
716       std::vector<Constant*> Elts;
717       for (unsigned i = 0; i != Size; ++i)
718         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
719       V = ConstantArray::get(ATy, Elts);
720       break;
721     }
722     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
723       if (Record.empty())
724         return Error("Invalid CST_AGGREGATE record");
725       
726       const ArrayType *ATy = cast<ArrayType>(CurTy);
727       const Type *EltTy = ATy->getElementType();
728       
729       unsigned Size = Record.size();
730       std::vector<Constant*> Elts;
731       for (unsigned i = 0; i != Size; ++i)
732         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
733       Elts.push_back(Constant::getNullValue(EltTy));
734       V = ConstantArray::get(ATy, Elts);
735       break;
736     }
737     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
738       if (Record.size() < 3) return Error("Invalid CE_BINOP record");
739       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
740       if (Opc < 0) {
741         V = UndefValue::get(CurTy);  // Unknown binop.
742       } else {
743         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
744         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
745         V = ConstantExpr::get(Opc, LHS, RHS);
746       }
747       break;
748     }  
749     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
750       if (Record.size() < 3) return Error("Invalid CE_CAST record");
751       int Opc = GetDecodedCastOpcode(Record[0]);
752       if (Opc < 0) {
753         V = UndefValue::get(CurTy);  // Unknown cast.
754       } else {
755         const Type *OpTy = getTypeByID(Record[1]);
756         if (!OpTy) return Error("Invalid CE_CAST record");
757         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
758         V = ConstantExpr::getCast(Opc, Op, CurTy);
759       }
760       break;
761     }  
762     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
763       if (Record.size() & 1) return Error("Invalid CE_GEP record");
764       SmallVector<Constant*, 16> Elts;
765       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
766         const Type *ElTy = getTypeByID(Record[i]);
767         if (!ElTy) return Error("Invalid CE_GEP record");
768         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
769       }
770       V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
771       break;
772     }
773     case bitc::CST_CODE_CE_EXTRACTVAL: {
774                                     // CE_EXTRACTVAL: [opty, opval, n x indices]
775       const Type *AggTy = getTypeByID(Record[0]);
776       if (!AggTy || !AggTy->isAggregateType())
777         return Error("Invalid CE_INSERTVAL record");
778       Constant *Agg = ValueList.getConstantFwdRef(Record[1], AggTy);
779       SmallVector<unsigned, 4> Indices;
780       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
781         uint64_t Index = Record[i];
782         if ((unsigned)Index != Index)
783           return Error("Invalid CE_EXTRACTVAL record");
784         Indices.push_back((unsigned)Index);
785       }
786       if (!ExtractValueInst::getIndexedType(AggTy,
787                                             Indices.begin(), Indices.end()))
788         return Error("Invalid CE_EXTRACTVAL record");
789       V = ConstantExpr::getExtractValue(Agg, &Indices[0], Indices.size());
790       break;
791     }
792     case bitc::CST_CODE_CE_INSERTVAL: {
793                         // CE_INSERTVAL: [opty, opval, opty, opval, n x indices]
794       const Type *AggTy = getTypeByID(Record[0]);
795       if (!AggTy || !AggTy->isAggregateType())
796         return Error("Invalid CE_INSERTVAL record");
797       Constant *Agg = ValueList.getConstantFwdRef(Record[1], AggTy);
798       const Type *ValTy = getTypeByID(Record[2]);
799       Constant *Val = ValueList.getConstantFwdRef(Record[2], ValTy);
800       SmallVector<unsigned, 4> Indices;
801       for (unsigned i = 4, e = Record.size(); i != e; ++i) {
802         uint64_t Index = Record[i];
803         if ((unsigned)Index != Index)
804           return Error("Invalid CE_INSERTVAL record");
805         Indices.push_back((unsigned)Index);
806       }
807       if (ExtractValueInst::getIndexedType(AggTy,
808                                            Indices.begin(),
809                                            Indices.end()) != ValTy)
810         return Error("Invalid CE_INSERTVAL record");
811       V = ConstantExpr::getInsertValue(Agg, Val, &Indices[0], Indices.size());
812       break;
813     }
814     case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
815       if (Record.size() < 3) return Error("Invalid CE_SELECT record");
816       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
817                                                               Type::Int1Ty),
818                                   ValueList.getConstantFwdRef(Record[1],CurTy),
819                                   ValueList.getConstantFwdRef(Record[2],CurTy));
820       break;
821     case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
822       if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
823       const VectorType *OpTy = 
824         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
825       if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
826       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
827       Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
828                                                   OpTy->getElementType());
829       V = ConstantExpr::getExtractElement(Op0, Op1);
830       break;
831     }
832     case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
833       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
834       if (Record.size() < 3 || OpTy == 0)
835         return Error("Invalid CE_INSERTELT record");
836       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
837       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
838                                                   OpTy->getElementType());
839       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
840       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
841       break;
842     }
843     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
844       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
845       if (Record.size() < 3 || OpTy == 0)
846         return Error("Invalid CE_INSERTELT record");
847       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
848       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
849       const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
850       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
851       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
852       break;
853     }
854     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
855       if (Record.size() < 4) return Error("Invalid CE_CMP record");
856       const Type *OpTy = getTypeByID(Record[0]);
857       if (OpTy == 0) return Error("Invalid CE_CMP record");
858       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
859       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
860
861       if (OpTy->isFloatingPoint())
862         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
863       else if (!isa<VectorType>(OpTy))
864         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
865       else if (OpTy->isFPOrFPVector())
866         V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
867       else
868         V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
869       break;
870     }
871     case bitc::CST_CODE_INLINEASM: {
872       if (Record.size() < 2) return Error("Invalid INLINEASM record");
873       std::string AsmStr, ConstrStr;
874       bool HasSideEffects = Record[0];
875       unsigned AsmStrSize = Record[1];
876       if (2+AsmStrSize >= Record.size())
877         return Error("Invalid INLINEASM record");
878       unsigned ConstStrSize = Record[2+AsmStrSize];
879       if (3+AsmStrSize+ConstStrSize > Record.size())
880         return Error("Invalid INLINEASM record");
881       
882       for (unsigned i = 0; i != AsmStrSize; ++i)
883         AsmStr += (char)Record[2+i];
884       for (unsigned i = 0; i != ConstStrSize; ++i)
885         ConstrStr += (char)Record[3+AsmStrSize+i];
886       const PointerType *PTy = cast<PointerType>(CurTy);
887       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
888                          AsmStr, ConstrStr, HasSideEffects);
889       break;
890     }
891     }
892     
893     ValueList.AssignValue(V, NextCstNo);
894     ++NextCstNo;
895   }
896 }
897
898 /// RememberAndSkipFunctionBody - When we see the block for a function body,
899 /// remember where it is and then skip it.  This lets us lazily deserialize the
900 /// functions.
901 bool BitcodeReader::RememberAndSkipFunctionBody() {
902   // Get the function we are talking about.
903   if (FunctionsWithBodies.empty())
904     return Error("Insufficient function protos");
905   
906   Function *Fn = FunctionsWithBodies.back();
907   FunctionsWithBodies.pop_back();
908   
909   // Save the current stream state.
910   uint64_t CurBit = Stream.GetCurrentBitNo();
911   DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
912   
913   // Set the functions linkage to GhostLinkage so we know it is lazily
914   // deserialized.
915   Fn->setLinkage(GlobalValue::GhostLinkage);
916   
917   // Skip over the function block for now.
918   if (Stream.SkipBlock())
919     return Error("Malformed block record");
920   return false;
921 }
922
923 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
924   // Reject multiple MODULE_BLOCK's in a single bitstream.
925   if (TheModule)
926     return Error("Multiple MODULE_BLOCKs in same stream");
927   
928   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
929     return Error("Malformed block record");
930
931   // Otherwise, create the module.
932   TheModule = new Module(ModuleID);
933   
934   SmallVector<uint64_t, 64> Record;
935   std::vector<std::string> SectionTable;
936   std::vector<std::string> CollectorTable;
937
938   // Read all the records for this module.
939   while (!Stream.AtEndOfStream()) {
940     unsigned Code = Stream.ReadCode();
941     if (Code == bitc::END_BLOCK) {
942       if (Stream.ReadBlockEnd())
943         return Error("Error at end of module block");
944
945       // Patch the initializers for globals and aliases up.
946       ResolveGlobalAndAliasInits();
947       if (!GlobalInits.empty() || !AliasInits.empty())
948         return Error("Malformed global initializer set");
949       if (!FunctionsWithBodies.empty())
950         return Error("Too few function bodies found");
951
952       // Look for intrinsic functions which need to be upgraded at some point
953       for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
954            FI != FE; ++FI) {
955         Function* NewFn;
956         if (UpgradeIntrinsicFunction(FI, NewFn))
957           UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
958       }
959
960       // Force deallocation of memory for these vectors to favor the client that
961       // want lazy deserialization.
962       std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
963       std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
964       std::vector<Function*>().swap(FunctionsWithBodies);
965       return false;
966     }
967     
968     if (Code == bitc::ENTER_SUBBLOCK) {
969       switch (Stream.ReadSubBlockID()) {
970       default:  // Skip unknown content.
971         if (Stream.SkipBlock())
972           return Error("Malformed block record");
973         break;
974       case bitc::BLOCKINFO_BLOCK_ID:
975         if (Stream.ReadBlockInfoBlock())
976           return Error("Malformed BlockInfoBlock");
977         break;
978       case bitc::PARAMATTR_BLOCK_ID:
979         if (ParseParamAttrBlock())
980           return true;
981         break;
982       case bitc::TYPE_BLOCK_ID:
983         if (ParseTypeTable())
984           return true;
985         break;
986       case bitc::TYPE_SYMTAB_BLOCK_ID:
987         if (ParseTypeSymbolTable())
988           return true;
989         break;
990       case bitc::VALUE_SYMTAB_BLOCK_ID:
991         if (ParseValueSymbolTable())
992           return true;
993         break;
994       case bitc::CONSTANTS_BLOCK_ID:
995         if (ParseConstants() || ResolveGlobalAndAliasInits())
996           return true;
997         break;
998       case bitc::FUNCTION_BLOCK_ID:
999         // If this is the first function body we've seen, reverse the
1000         // FunctionsWithBodies list.
1001         if (!HasReversedFunctionsWithBodies) {
1002           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1003           HasReversedFunctionsWithBodies = true;
1004         }
1005         
1006         if (RememberAndSkipFunctionBody())
1007           return true;
1008         break;
1009       }
1010       continue;
1011     }
1012     
1013     if (Code == bitc::DEFINE_ABBREV) {
1014       Stream.ReadAbbrevRecord();
1015       continue;
1016     }
1017     
1018     // Read a record.
1019     switch (Stream.ReadRecord(Code, Record)) {
1020     default: break;  // Default behavior, ignore unknown content.
1021     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1022       if (Record.size() < 1)
1023         return Error("Malformed MODULE_CODE_VERSION");
1024       // Only version #0 is supported so far.
1025       if (Record[0] != 0)
1026         return Error("Unknown bitstream version!");
1027       break;
1028     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1029       std::string S;
1030       if (ConvertToString(Record, 0, S))
1031         return Error("Invalid MODULE_CODE_TRIPLE record");
1032       TheModule->setTargetTriple(S);
1033       break;
1034     }
1035     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1036       std::string S;
1037       if (ConvertToString(Record, 0, S))
1038         return Error("Invalid MODULE_CODE_DATALAYOUT record");
1039       TheModule->setDataLayout(S);
1040       break;
1041     }
1042     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1043       std::string S;
1044       if (ConvertToString(Record, 0, S))
1045         return Error("Invalid MODULE_CODE_ASM record");
1046       TheModule->setModuleInlineAsm(S);
1047       break;
1048     }
1049     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1050       std::string S;
1051       if (ConvertToString(Record, 0, S))
1052         return Error("Invalid MODULE_CODE_DEPLIB record");
1053       TheModule->addLibrary(S);
1054       break;
1055     }
1056     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1057       std::string S;
1058       if (ConvertToString(Record, 0, S))
1059         return Error("Invalid MODULE_CODE_SECTIONNAME record");
1060       SectionTable.push_back(S);
1061       break;
1062     }
1063     case bitc::MODULE_CODE_COLLECTORNAME: {  // SECTIONNAME: [strchr x N]
1064       std::string S;
1065       if (ConvertToString(Record, 0, S))
1066         return Error("Invalid MODULE_CODE_COLLECTORNAME record");
1067       CollectorTable.push_back(S);
1068       break;
1069     }
1070     // GLOBALVAR: [pointer type, isconst, initid,
1071     //             linkage, alignment, section, visibility, threadlocal]
1072     case bitc::MODULE_CODE_GLOBALVAR: {
1073       if (Record.size() < 6)
1074         return Error("Invalid MODULE_CODE_GLOBALVAR record");
1075       const Type *Ty = getTypeByID(Record[0]);
1076       if (!isa<PointerType>(Ty))
1077         return Error("Global not a pointer type!");
1078       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1079       Ty = cast<PointerType>(Ty)->getElementType();
1080       
1081       bool isConstant = Record[1];
1082       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1083       unsigned Alignment = (1 << Record[4]) >> 1;
1084       std::string Section;
1085       if (Record[5]) {
1086         if (Record[5]-1 >= SectionTable.size())
1087           return Error("Invalid section ID");
1088         Section = SectionTable[Record[5]-1];
1089       }
1090       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1091       if (Record.size() > 6)
1092         Visibility = GetDecodedVisibility(Record[6]);
1093       bool isThreadLocal = false;
1094       if (Record.size() > 7)
1095         isThreadLocal = Record[7];
1096
1097       GlobalVariable *NewGV =
1098         new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule, 
1099                            isThreadLocal, AddressSpace);
1100       NewGV->setAlignment(Alignment);
1101       if (!Section.empty())
1102         NewGV->setSection(Section);
1103       NewGV->setVisibility(Visibility);
1104       NewGV->setThreadLocal(isThreadLocal);
1105       
1106       ValueList.push_back(NewGV);
1107       
1108       // Remember which value to use for the global initializer.
1109       if (unsigned InitID = Record[2])
1110         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1111       break;
1112     }
1113     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1114     //             alignment, section, visibility, collector]
1115     case bitc::MODULE_CODE_FUNCTION: {
1116       if (Record.size() < 8)
1117         return Error("Invalid MODULE_CODE_FUNCTION record");
1118       const Type *Ty = getTypeByID(Record[0]);
1119       if (!isa<PointerType>(Ty))
1120         return Error("Function not a pointer type!");
1121       const FunctionType *FTy =
1122         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1123       if (!FTy)
1124         return Error("Function not a pointer to function type!");
1125
1126       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1127                                         "", TheModule);
1128
1129       Func->setCallingConv(Record[1]);
1130       bool isProto = Record[2];
1131       Func->setLinkage(GetDecodedLinkage(Record[3]));
1132       Func->setParamAttrs(getParamAttrs(Record[4]));
1133       
1134       Func->setAlignment((1 << Record[5]) >> 1);
1135       if (Record[6]) {
1136         if (Record[6]-1 >= SectionTable.size())
1137           return Error("Invalid section ID");
1138         Func->setSection(SectionTable[Record[6]-1]);
1139       }
1140       Func->setVisibility(GetDecodedVisibility(Record[7]));
1141       if (Record.size() > 8 && Record[8]) {
1142         if (Record[8]-1 > CollectorTable.size())
1143           return Error("Invalid collector ID");
1144         Func->setCollector(CollectorTable[Record[8]-1].c_str());
1145       }
1146       
1147       ValueList.push_back(Func);
1148       
1149       // If this is a function with a body, remember the prototype we are
1150       // creating now, so that we can match up the body with them later.
1151       if (!isProto)
1152         FunctionsWithBodies.push_back(Func);
1153       break;
1154     }
1155     // ALIAS: [alias type, aliasee val#, linkage]
1156     // ALIAS: [alias type, aliasee val#, linkage, visibility]
1157     case bitc::MODULE_CODE_ALIAS: {
1158       if (Record.size() < 3)
1159         return Error("Invalid MODULE_ALIAS record");
1160       const Type *Ty = getTypeByID(Record[0]);
1161       if (!isa<PointerType>(Ty))
1162         return Error("Function not a pointer type!");
1163       
1164       GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1165                                            "", 0, TheModule);
1166       // Old bitcode files didn't have visibility field.
1167       if (Record.size() > 3)
1168         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1169       ValueList.push_back(NewGA);
1170       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1171       break;
1172     }
1173     /// MODULE_CODE_PURGEVALS: [numvals]
1174     case bitc::MODULE_CODE_PURGEVALS:
1175       // Trim down the value list to the specified size.
1176       if (Record.size() < 1 || Record[0] > ValueList.size())
1177         return Error("Invalid MODULE_PURGEVALS record");
1178       ValueList.shrinkTo(Record[0]);
1179       break;
1180     }
1181     Record.clear();
1182   }
1183   
1184   return Error("Premature end of bitstream");
1185 }
1186
1187
1188 bool BitcodeReader::ParseBitcode() {
1189   TheModule = 0;
1190   
1191   if (Buffer->getBufferSize() & 3)
1192     return Error("Bitcode stream should be a multiple of 4 bytes in length");
1193   
1194   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1195   Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1196   
1197   // Sniff for the signature.
1198   if (Stream.Read(8) != 'B' ||
1199       Stream.Read(8) != 'C' ||
1200       Stream.Read(4) != 0x0 ||
1201       Stream.Read(4) != 0xC ||
1202       Stream.Read(4) != 0xE ||
1203       Stream.Read(4) != 0xD)
1204     return Error("Invalid bitcode signature");
1205   
1206   // We expect a number of well-defined blocks, though we don't necessarily
1207   // need to understand them all.
1208   while (!Stream.AtEndOfStream()) {
1209     unsigned Code = Stream.ReadCode();
1210     
1211     if (Code != bitc::ENTER_SUBBLOCK)
1212       return Error("Invalid record at top-level");
1213     
1214     unsigned BlockID = Stream.ReadSubBlockID();
1215     
1216     // We only know the MODULE subblock ID.
1217     switch (BlockID) {
1218     case bitc::BLOCKINFO_BLOCK_ID:
1219       if (Stream.ReadBlockInfoBlock())
1220         return Error("Malformed BlockInfoBlock");
1221       break;
1222     case bitc::MODULE_BLOCK_ID:
1223       if (ParseModule(Buffer->getBufferIdentifier()))
1224         return true;
1225       break;
1226     default:
1227       if (Stream.SkipBlock())
1228         return Error("Malformed block record");
1229       break;
1230     }
1231   }
1232   
1233   return false;
1234 }
1235
1236
1237 /// ParseFunctionBody - Lazily parse the specified function body block.
1238 bool BitcodeReader::ParseFunctionBody(Function *F) {
1239   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1240     return Error("Malformed block record");
1241   
1242   unsigned ModuleValueListSize = ValueList.size();
1243   
1244   // Add all the function arguments to the value table.
1245   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1246     ValueList.push_back(I);
1247   
1248   unsigned NextValueNo = ValueList.size();
1249   BasicBlock *CurBB = 0;
1250   unsigned CurBBNo = 0;
1251
1252   // Read all the records.
1253   SmallVector<uint64_t, 64> Record;
1254   while (1) {
1255     unsigned Code = Stream.ReadCode();
1256     if (Code == bitc::END_BLOCK) {
1257       if (Stream.ReadBlockEnd())
1258         return Error("Error at end of function block");
1259       break;
1260     }
1261     
1262     if (Code == bitc::ENTER_SUBBLOCK) {
1263       switch (Stream.ReadSubBlockID()) {
1264       default:  // Skip unknown content.
1265         if (Stream.SkipBlock())
1266           return Error("Malformed block record");
1267         break;
1268       case bitc::CONSTANTS_BLOCK_ID:
1269         if (ParseConstants()) return true;
1270         NextValueNo = ValueList.size();
1271         break;
1272       case bitc::VALUE_SYMTAB_BLOCK_ID:
1273         if (ParseValueSymbolTable()) return true;
1274         break;
1275       }
1276       continue;
1277     }
1278     
1279     if (Code == bitc::DEFINE_ABBREV) {
1280       Stream.ReadAbbrevRecord();
1281       continue;
1282     }
1283     
1284     // Read a record.
1285     Record.clear();
1286     Instruction *I = 0;
1287     switch (Stream.ReadRecord(Code, Record)) {
1288     default: // Default behavior: reject
1289       return Error("Unknown instruction");
1290     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1291       if (Record.size() < 1 || Record[0] == 0)
1292         return Error("Invalid DECLAREBLOCKS record");
1293       // Create all the basic blocks for the function.
1294       FunctionBBs.resize(Record[0]);
1295       for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1296         FunctionBBs[i] = BasicBlock::Create("", F);
1297       CurBB = FunctionBBs[0];
1298       continue;
1299       
1300     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1301       unsigned OpNum = 0;
1302       Value *LHS, *RHS;
1303       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1304           getValue(Record, OpNum, LHS->getType(), RHS) ||
1305           OpNum+1 != Record.size())
1306         return Error("Invalid BINOP record");
1307       
1308       int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1309       if (Opc == -1) return Error("Invalid BINOP record");
1310       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1311       break;
1312     }
1313     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1314       unsigned OpNum = 0;
1315       Value *Op;
1316       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1317           OpNum+2 != Record.size())
1318         return Error("Invalid CAST record");
1319       
1320       const Type *ResTy = getTypeByID(Record[OpNum]);
1321       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1322       if (Opc == -1 || ResTy == 0)
1323         return Error("Invalid CAST record");
1324       I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1325       break;
1326     }
1327     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1328       unsigned OpNum = 0;
1329       Value *BasePtr;
1330       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1331         return Error("Invalid GEP record");
1332
1333       SmallVector<Value*, 16> GEPIdx;
1334       while (OpNum != Record.size()) {
1335         Value *Op;
1336         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1337           return Error("Invalid GEP record");
1338         GEPIdx.push_back(Op);
1339       }
1340
1341       I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1342       break;
1343     }
1344       
1345     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1346                                        // EXTRACTVAL: [opty, opval, n x indices]
1347       unsigned OpNum = 0;
1348       Value *Agg;
1349       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1350         return Error("Invalid EXTRACTVAL record");
1351
1352       SmallVector<unsigned, 4> EXTRACTVALIdx;
1353       for (unsigned RecSize = Record.size();
1354            OpNum != RecSize; ++OpNum) {
1355         uint64_t Index = Record[OpNum];
1356         if ((unsigned)Index != Index)
1357           return Error("Invalid EXTRACTVAL index");
1358         EXTRACTVALIdx.push_back((unsigned)Index);
1359       }
1360
1361       I = ExtractValueInst::Create(Agg,
1362                                    EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1363       break;
1364     }
1365       
1366     case bitc::FUNC_CODE_INST_INSERTVAL: {
1367                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
1368       unsigned OpNum = 0;
1369       Value *Agg;
1370       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1371         return Error("Invalid INSERTVAL record");
1372       Value *Val;
1373       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1374         return Error("Invalid INSERTVAL record");
1375
1376       SmallVector<unsigned, 4> INSERTVALIdx;
1377       for (unsigned RecSize = Record.size();
1378            OpNum != RecSize; ++OpNum) {
1379         uint64_t Index = Record[OpNum];
1380         if ((unsigned)Index != Index)
1381           return Error("Invalid INSERTVAL index");
1382         INSERTVALIdx.push_back((unsigned)Index);
1383       }
1384
1385       I = InsertValueInst::Create(Agg, Val,
1386                                   INSERTVALIdx.begin(), INSERTVALIdx.end());
1387       break;
1388     }
1389       
1390     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1391       unsigned OpNum = 0;
1392       Value *TrueVal, *FalseVal, *Cond;
1393       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1394           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1395           getValue(Record, OpNum, Type::Int1Ty, Cond))
1396         return Error("Invalid SELECT record");
1397       
1398       I = SelectInst::Create(Cond, TrueVal, FalseVal);
1399       break;
1400     }
1401       
1402     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1403       unsigned OpNum = 0;
1404       Value *Vec, *Idx;
1405       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1406           getValue(Record, OpNum, Type::Int32Ty, Idx))
1407         return Error("Invalid EXTRACTELT record");
1408       I = new ExtractElementInst(Vec, Idx);
1409       break;
1410     }
1411       
1412     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1413       unsigned OpNum = 0;
1414       Value *Vec, *Elt, *Idx;
1415       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1416           getValue(Record, OpNum, 
1417                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1418           getValue(Record, OpNum, Type::Int32Ty, Idx))
1419         return Error("Invalid INSERTELT record");
1420       I = InsertElementInst::Create(Vec, Elt, Idx);
1421       break;
1422     }
1423       
1424     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1425       unsigned OpNum = 0;
1426       Value *Vec1, *Vec2, *Mask;
1427       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1428           getValue(Record, OpNum, Vec1->getType(), Vec2))
1429         return Error("Invalid SHUFFLEVEC record");
1430
1431       const Type *MaskTy =
1432         VectorType::get(Type::Int32Ty, 
1433                         cast<VectorType>(Vec1->getType())->getNumElements());
1434
1435       if (getValue(Record, OpNum, MaskTy, Mask))
1436         return Error("Invalid SHUFFLEVEC record");
1437       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1438       break;
1439     }
1440       
1441     case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1442       unsigned OpNum = 0;
1443       Value *LHS, *RHS;
1444       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1445           getValue(Record, OpNum, LHS->getType(), RHS) ||
1446           OpNum+1 != Record.size())
1447         return Error("Invalid CMP record");
1448       
1449       if (LHS->getType()->isFloatingPoint())
1450         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1451       else if (!isa<VectorType>(LHS->getType()))
1452         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1453       else if (LHS->getType()->isFPOrFPVector())
1454         I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1455       else
1456         I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1457       break;
1458     }
1459     case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1460       if (Record.size() != 2)
1461         return Error("Invalid GETRESULT record");
1462       unsigned OpNum = 0;
1463       Value *Op;
1464       getValueTypePair(Record, OpNum, NextValueNo, Op);
1465       unsigned Index = Record[1];
1466       I = new GetResultInst(Op, Index);
1467       break;
1468     }
1469     
1470     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1471       {
1472         unsigned Size = Record.size();
1473         if (Size == 0) {
1474           I = ReturnInst::Create();
1475           break;
1476         } else {
1477           unsigned OpNum = 0;
1478           SmallVector<Value *,4> Vs;
1479           do {
1480             Value *Op = NULL;
1481             if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1482               return Error("Invalid RET record");
1483             Vs.push_back(Op);
1484           } while(OpNum != Record.size());
1485
1486           // SmallVector Vs has at least one element.
1487           I = ReturnInst::Create(&Vs[0], Vs.size());
1488           break;
1489         }
1490       }
1491     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1492       if (Record.size() != 1 && Record.size() != 3)
1493         return Error("Invalid BR record");
1494       BasicBlock *TrueDest = getBasicBlock(Record[0]);
1495       if (TrueDest == 0)
1496         return Error("Invalid BR record");
1497
1498       if (Record.size() == 1)
1499         I = BranchInst::Create(TrueDest);
1500       else {
1501         BasicBlock *FalseDest = getBasicBlock(Record[1]);
1502         Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1503         if (FalseDest == 0 || Cond == 0)
1504           return Error("Invalid BR record");
1505         I = BranchInst::Create(TrueDest, FalseDest, Cond);
1506       }
1507       break;
1508     }
1509     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1510       if (Record.size() < 3 || (Record.size() & 1) == 0)
1511         return Error("Invalid SWITCH record");
1512       const Type *OpTy = getTypeByID(Record[0]);
1513       Value *Cond = getFnValueByID(Record[1], OpTy);
1514       BasicBlock *Default = getBasicBlock(Record[2]);
1515       if (OpTy == 0 || Cond == 0 || Default == 0)
1516         return Error("Invalid SWITCH record");
1517       unsigned NumCases = (Record.size()-3)/2;
1518       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1519       for (unsigned i = 0, e = NumCases; i != e; ++i) {
1520         ConstantInt *CaseVal = 
1521           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1522         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1523         if (CaseVal == 0 || DestBB == 0) {
1524           delete SI;
1525           return Error("Invalid SWITCH record!");
1526         }
1527         SI->addCase(CaseVal, DestBB);
1528       }
1529       I = SI;
1530       break;
1531     }
1532       
1533     case bitc::FUNC_CODE_INST_INVOKE: {
1534       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1535       if (Record.size() < 4) return Error("Invalid INVOKE record");
1536       PAListPtr PAL = getParamAttrs(Record[0]);
1537       unsigned CCInfo = Record[1];
1538       BasicBlock *NormalBB = getBasicBlock(Record[2]);
1539       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1540       
1541       unsigned OpNum = 4;
1542       Value *Callee;
1543       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1544         return Error("Invalid INVOKE record");
1545       
1546       const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1547       const FunctionType *FTy = !CalleeTy ? 0 :
1548         dyn_cast<FunctionType>(CalleeTy->getElementType());
1549
1550       // Check that the right number of fixed parameters are here.
1551       if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1552           Record.size() < OpNum+FTy->getNumParams())
1553         return Error("Invalid INVOKE record");
1554       
1555       SmallVector<Value*, 16> Ops;
1556       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1557         Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1558         if (Ops.back() == 0) return Error("Invalid INVOKE record");
1559       }
1560       
1561       if (!FTy->isVarArg()) {
1562         if (Record.size() != OpNum)
1563           return Error("Invalid INVOKE record");
1564       } else {
1565         // Read type/value pairs for varargs params.
1566         while (OpNum != Record.size()) {
1567           Value *Op;
1568           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1569             return Error("Invalid INVOKE record");
1570           Ops.push_back(Op);
1571         }
1572       }
1573       
1574       I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1575                              Ops.begin(), Ops.end());
1576       cast<InvokeInst>(I)->setCallingConv(CCInfo);
1577       cast<InvokeInst>(I)->setParamAttrs(PAL);
1578       break;
1579     }
1580     case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1581       I = new UnwindInst();
1582       break;
1583     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1584       I = new UnreachableInst();
1585       break;
1586     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1587       if (Record.size() < 1 || ((Record.size()-1)&1))
1588         return Error("Invalid PHI record");
1589       const Type *Ty = getTypeByID(Record[0]);
1590       if (!Ty) return Error("Invalid PHI record");
1591       
1592       PHINode *PN = PHINode::Create(Ty);
1593       PN->reserveOperandSpace((Record.size()-1)/2);
1594       
1595       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1596         Value *V = getFnValueByID(Record[1+i], Ty);
1597         BasicBlock *BB = getBasicBlock(Record[2+i]);
1598         if (!V || !BB) return Error("Invalid PHI record");
1599         PN->addIncoming(V, BB);
1600       }
1601       I = PN;
1602       break;
1603     }
1604       
1605     case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1606       if (Record.size() < 3)
1607         return Error("Invalid MALLOC record");
1608       const PointerType *Ty =
1609         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1610       Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1611       unsigned Align = Record[2];
1612       if (!Ty || !Size) return Error("Invalid MALLOC record");
1613       I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1614       break;
1615     }
1616     case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1617       unsigned OpNum = 0;
1618       Value *Op;
1619       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1620           OpNum != Record.size())
1621         return Error("Invalid FREE record");
1622       I = new FreeInst(Op);
1623       break;
1624     }
1625     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1626       if (Record.size() < 3)
1627         return Error("Invalid ALLOCA record");
1628       const PointerType *Ty =
1629         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1630       Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1631       unsigned Align = Record[2];
1632       if (!Ty || !Size) return Error("Invalid ALLOCA record");
1633       I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1634       break;
1635     }
1636     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1637       unsigned OpNum = 0;
1638       Value *Op;
1639       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1640           OpNum+2 != Record.size())
1641         return Error("Invalid LOAD record");
1642       
1643       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1644       break;
1645     }
1646     case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1647       unsigned OpNum = 0;
1648       Value *Val, *Ptr;
1649       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1650           getValue(Record, OpNum, 
1651                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1652           OpNum+2 != Record.size())
1653         return Error("Invalid STORE record");
1654       
1655       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1656       break;
1657     }
1658     case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1659       // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1660       unsigned OpNum = 0;
1661       Value *Val, *Ptr;
1662       if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1663           getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
1664           OpNum+2 != Record.size())
1665         return Error("Invalid STORE record");
1666       
1667       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1668       break;
1669     }
1670     case bitc::FUNC_CODE_INST_CALL: {
1671       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1672       if (Record.size() < 3)
1673         return Error("Invalid CALL record");
1674       
1675       PAListPtr PAL = getParamAttrs(Record[0]);
1676       unsigned CCInfo = Record[1];
1677       
1678       unsigned OpNum = 2;
1679       Value *Callee;
1680       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1681         return Error("Invalid CALL record");
1682       
1683       const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1684       const FunctionType *FTy = 0;
1685       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1686       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1687         return Error("Invalid CALL record");
1688       
1689       SmallVector<Value*, 16> Args;
1690       // Read the fixed params.
1691       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1692         if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1693           Args.push_back(getBasicBlock(Record[OpNum]));
1694         else
1695           Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1696         if (Args.back() == 0) return Error("Invalid CALL record");
1697       }
1698       
1699       // Read type/value pairs for varargs params.
1700       if (!FTy->isVarArg()) {
1701         if (OpNum != Record.size())
1702           return Error("Invalid CALL record");
1703       } else {
1704         while (OpNum != Record.size()) {
1705           Value *Op;
1706           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1707             return Error("Invalid CALL record");
1708           Args.push_back(Op);
1709         }
1710       }
1711       
1712       I = CallInst::Create(Callee, Args.begin(), Args.end());
1713       cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1714       cast<CallInst>(I)->setTailCall(CCInfo & 1);
1715       cast<CallInst>(I)->setParamAttrs(PAL);
1716       break;
1717     }
1718     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1719       if (Record.size() < 3)
1720         return Error("Invalid VAARG record");
1721       const Type *OpTy = getTypeByID(Record[0]);
1722       Value *Op = getFnValueByID(Record[1], OpTy);
1723       const Type *ResTy = getTypeByID(Record[2]);
1724       if (!OpTy || !Op || !ResTy)
1725         return Error("Invalid VAARG record");
1726       I = new VAArgInst(Op, ResTy);
1727       break;
1728     }
1729     }
1730
1731     // Add instruction to end of current BB.  If there is no current BB, reject
1732     // this file.
1733     if (CurBB == 0) {
1734       delete I;
1735       return Error("Invalid instruction with no BB");
1736     }
1737     CurBB->getInstList().push_back(I);
1738     
1739     // If this was a terminator instruction, move to the next block.
1740     if (isa<TerminatorInst>(I)) {
1741       ++CurBBNo;
1742       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1743     }
1744     
1745     // Non-void values get registered in the value table for future use.
1746     if (I && I->getType() != Type::VoidTy)
1747       ValueList.AssignValue(I, NextValueNo++);
1748   }
1749   
1750   // Check the function list for unresolved values.
1751   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1752     if (A->getParent() == 0) {
1753       // We found at least one unresolved value.  Nuke them all to avoid leaks.
1754       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1755         if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1756           A->replaceAllUsesWith(UndefValue::get(A->getType()));
1757           delete A;
1758         }
1759       }
1760       return Error("Never resolved value found in function!");
1761     }
1762   }
1763   
1764   // Trim the value list down to the size it was before we parsed this function.
1765   ValueList.shrinkTo(ModuleValueListSize);
1766   std::vector<BasicBlock*>().swap(FunctionBBs);
1767   
1768   return false;
1769 }
1770
1771 //===----------------------------------------------------------------------===//
1772 // ModuleProvider implementation
1773 //===----------------------------------------------------------------------===//
1774
1775
1776 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1777   // If it already is material, ignore the request.
1778   if (!F->hasNotBeenReadFromBitcode()) return false;
1779   
1780   DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII = 
1781     DeferredFunctionInfo.find(F);
1782   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1783   
1784   // Move the bit stream to the saved position of the deferred function body and
1785   // restore the real linkage type for the function.
1786   Stream.JumpToBit(DFII->second.first);
1787   F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1788   
1789   if (ParseFunctionBody(F)) {
1790     if (ErrInfo) *ErrInfo = ErrorString;
1791     return true;
1792   }
1793
1794   // Upgrade any old intrinsic calls in the function.
1795   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1796        E = UpgradedIntrinsics.end(); I != E; ++I) {
1797     if (I->first != I->second) {
1798       for (Value::use_iterator UI = I->first->use_begin(),
1799            UE = I->first->use_end(); UI != UE; ) {
1800         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1801           UpgradeIntrinsicCall(CI, I->second);
1802       }
1803     }
1804   }
1805   
1806   return false;
1807 }
1808
1809 void BitcodeReader::dematerializeFunction(Function *F) {
1810   // If this function isn't materialized, or if it is a proto, this is a noop.
1811   if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
1812     return;
1813   
1814   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1815   
1816   // Just forget the function body, we can remat it later.
1817   F->deleteBody();
1818   F->setLinkage(GlobalValue::GhostLinkage);
1819 }
1820
1821
1822 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1823   for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I = 
1824        DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1825        ++I) {
1826     Function *F = I->first;
1827     if (F->hasNotBeenReadFromBitcode() &&
1828         materializeFunction(F, ErrInfo))
1829       return 0;
1830   }
1831
1832   // Upgrade any intrinsic calls that slipped through (should not happen!) and 
1833   // delete the old functions to clean up. We can't do this unless the entire 
1834   // module is materialized because there could always be another function body 
1835   // with calls to the old function.
1836   for (std::vector<std::pair<Function*, Function*> >::iterator I =
1837        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1838     if (I->first != I->second) {
1839       for (Value::use_iterator UI = I->first->use_begin(),
1840            UE = I->first->use_end(); UI != UE; ) {
1841         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1842           UpgradeIntrinsicCall(CI, I->second);
1843       }
1844       ValueList.replaceUsesOfWith(I->first, I->second);
1845       I->first->eraseFromParent();
1846     }
1847   }
1848   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1849   
1850   return TheModule;
1851 }
1852
1853
1854 /// This method is provided by the parent ModuleProvde class and overriden
1855 /// here. It simply releases the module from its provided and frees up our
1856 /// state.
1857 /// @brief Release our hold on the generated module
1858 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1859   // Since we're losing control of this Module, we must hand it back complete
1860   Module *M = ModuleProvider::releaseModule(ErrInfo);
1861   FreeState();
1862   return M;
1863 }
1864
1865
1866 //===----------------------------------------------------------------------===//
1867 // External interface
1868 //===----------------------------------------------------------------------===//
1869
1870 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1871 ///
1872 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1873                                                std::string *ErrMsg) {
1874   BitcodeReader *R = new BitcodeReader(Buffer);
1875   if (R->ParseBitcode()) {
1876     if (ErrMsg)
1877       *ErrMsg = R->getErrorString();
1878     
1879     // Don't let the BitcodeReader dtor delete 'Buffer'.
1880     R->releaseMemoryBuffer();
1881     delete R;
1882     return 0;
1883   }
1884   return R;
1885 }
1886
1887 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1888 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1889 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1890   BitcodeReader *R;
1891   R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1892   if (!R) return 0;
1893   
1894   // Read in the entire module.
1895   Module *M = R->materializeModule(ErrMsg);
1896
1897   // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1898   // there was an error.
1899   R->releaseMemoryBuffer();
1900   
1901   // If there was no error, tell ModuleProvider not to delete it when its dtor
1902   // is run.
1903   if (M)
1904     M = R->releaseModule(ErrMsg);
1905   
1906   delete R;
1907   return M;
1908 }