the type field for a store is the type of the pointer, not the value.
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 using namespace llvm;
24
25 BitcodeReader::~BitcodeReader() {
26   delete Buffer;
27 }
28
29
30 /// ConvertToString - Convert a string from a record into an std::string, return
31 /// true on failure.
32 template<typename StrTy>
33 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
34                             StrTy &Result) {
35   if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
36     return true;
37   
38   for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
39     Result += (char)Record[Idx+i+1];
40   return false;
41 }
42
43 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
44   switch (Val) {
45   default: // Map unknown/new linkages to external
46   case 0: return GlobalValue::ExternalLinkage;
47   case 1: return GlobalValue::WeakLinkage;
48   case 2: return GlobalValue::AppendingLinkage;
49   case 3: return GlobalValue::InternalLinkage;
50   case 4: return GlobalValue::LinkOnceLinkage;
51   case 5: return GlobalValue::DLLImportLinkage;
52   case 6: return GlobalValue::DLLExportLinkage;
53   case 7: return GlobalValue::ExternalWeakLinkage;
54   }
55 }
56
57 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
58   switch (Val) {
59   default: // Map unknown visibilities to default.
60   case 0: return GlobalValue::DefaultVisibility;
61   case 1: return GlobalValue::HiddenVisibility;
62   case 2: return GlobalValue::ProtectedVisibility;
63   }
64 }
65
66 static int GetDecodedCastOpcode(unsigned Val) {
67   switch (Val) {
68   default: return -1;
69   case bitc::CAST_TRUNC   : return Instruction::Trunc;
70   case bitc::CAST_ZEXT    : return Instruction::ZExt;
71   case bitc::CAST_SEXT    : return Instruction::SExt;
72   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
73   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
74   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
75   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
76   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
77   case bitc::CAST_FPEXT   : return Instruction::FPExt;
78   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
79   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
80   case bitc::CAST_BITCAST : return Instruction::BitCast;
81   }
82 }
83 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
84   switch (Val) {
85   default: return -1;
86   case bitc::BINOP_ADD:  return Instruction::Add;
87   case bitc::BINOP_SUB:  return Instruction::Sub;
88   case bitc::BINOP_MUL:  return Instruction::Mul;
89   case bitc::BINOP_UDIV: return Instruction::UDiv;
90   case bitc::BINOP_SDIV:
91     return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
92   case bitc::BINOP_UREM: return Instruction::URem;
93   case bitc::BINOP_SREM:
94     return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
95   case bitc::BINOP_SHL:  return Instruction::Shl;
96   case bitc::BINOP_LSHR: return Instruction::LShr;
97   case bitc::BINOP_ASHR: return Instruction::AShr;
98   case bitc::BINOP_AND:  return Instruction::And;
99   case bitc::BINOP_OR:   return Instruction::Or;
100   case bitc::BINOP_XOR:  return Instruction::Xor;
101   }
102 }
103
104
105 namespace {
106   /// @brief A class for maintaining the slot number definition
107   /// as a placeholder for the actual definition for forward constants defs.
108   class ConstantPlaceHolder : public ConstantExpr {
109     ConstantPlaceHolder();                       // DO NOT IMPLEMENT
110     void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
111   public:
112     Use Op;
113     ConstantPlaceHolder(const Type *Ty)
114       : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
115         Op(UndefValue::get(Type::Int32Ty), this) {
116     }
117   };
118 }
119
120 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
121                                                     const Type *Ty) {
122   if (Idx >= size()) {
123     // Insert a bunch of null values.
124     Uses.resize(Idx+1);
125     OperandList = &Uses[0];
126     NumOperands = Idx+1;
127   }
128
129   if (Value *V = Uses[Idx]) {
130     assert(Ty == V->getType() && "Type mismatch in constant table!");
131     return cast<Constant>(V);
132   }
133
134   // Create and return a placeholder, which will later be RAUW'd.
135   Constant *C = new ConstantPlaceHolder(Ty);
136   Uses[Idx].init(C, this);
137   return C;
138 }
139
140 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
141   if (Idx >= size()) {
142     // Insert a bunch of null values.
143     Uses.resize(Idx+1);
144     OperandList = &Uses[0];
145     NumOperands = Idx+1;
146   }
147   
148   if (Value *V = Uses[Idx]) {
149     assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
150     return V;
151   }
152   
153   // No type specified, must be invalid reference.
154   if (Ty == 0) return 0;
155   
156   // Create and return a placeholder, which will later be RAUW'd.
157   Value *V = new Argument(Ty);
158   Uses[Idx].init(V, this);
159   return V;
160 }
161
162
163 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
164   // If the TypeID is in range, return it.
165   if (ID < TypeList.size())
166     return TypeList[ID].get();
167   if (!isTypeTable) return 0;
168   
169   // The type table allows forward references.  Push as many Opaque types as
170   // needed to get up to ID.
171   while (TypeList.size() <= ID)
172     TypeList.push_back(OpaqueType::get());
173   return TypeList.back().get();
174 }
175
176 bool BitcodeReader::ParseTypeTable() {
177   if (Stream.EnterSubBlock())
178     return Error("Malformed block record");
179   
180   if (!TypeList.empty())
181     return Error("Multiple TYPE_BLOCKs found!");
182
183   SmallVector<uint64_t, 64> Record;
184   unsigned NumRecords = 0;
185
186   // Read all the records for this type table.
187   while (1) {
188     unsigned Code = Stream.ReadCode();
189     if (Code == bitc::END_BLOCK) {
190       if (NumRecords != TypeList.size())
191         return Error("Invalid type forward reference in TYPE_BLOCK");
192       if (Stream.ReadBlockEnd())
193         return Error("Error at end of type table block");
194       return false;
195     }
196     
197     if (Code == bitc::ENTER_SUBBLOCK) {
198       // No known subblocks, always skip them.
199       Stream.ReadSubBlockID();
200       if (Stream.SkipBlock())
201         return Error("Malformed block record");
202       continue;
203     }
204     
205     if (Code == bitc::DEFINE_ABBREV) {
206       Stream.ReadAbbrevRecord();
207       continue;
208     }
209     
210     // Read a record.
211     Record.clear();
212     const Type *ResultTy = 0;
213     switch (Stream.ReadRecord(Code, Record)) {
214     default:  // Default behavior: unknown type.
215       ResultTy = 0;
216       break;
217     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
218       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
219       // type list.  This allows us to reserve space.
220       if (Record.size() < 1)
221         return Error("Invalid TYPE_CODE_NUMENTRY record");
222       TypeList.reserve(Record[0]);
223       continue;
224     case bitc::TYPE_CODE_META:      // TYPE_CODE_META: [metacode]...
225       // No metadata supported yet.
226       if (Record.size() < 1)
227         return Error("Invalid TYPE_CODE_META record");
228       continue;
229       
230     case bitc::TYPE_CODE_VOID:      // VOID
231       ResultTy = Type::VoidTy;
232       break;
233     case bitc::TYPE_CODE_FLOAT:     // FLOAT
234       ResultTy = Type::FloatTy;
235       break;
236     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
237       ResultTy = Type::DoubleTy;
238       break;
239     case bitc::TYPE_CODE_LABEL:     // LABEL
240       ResultTy = Type::LabelTy;
241       break;
242     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
243       ResultTy = 0;
244       break;
245     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
246       if (Record.size() < 1)
247         return Error("Invalid Integer type record");
248       
249       ResultTy = IntegerType::get(Record[0]);
250       break;
251     case bitc::TYPE_CODE_POINTER:   // POINTER: [pointee type]
252       if (Record.size() < 1)
253         return Error("Invalid POINTER type record");
254       ResultTy = PointerType::get(getTypeByID(Record[0], true));
255       break;
256     case bitc::TYPE_CODE_FUNCTION: {
257       // FUNCTION: [vararg, retty, #pararms, paramty N]
258       if (Record.size() < 3 || Record.size() < Record[2]+3)
259         return Error("Invalid FUNCTION type record");
260       std::vector<const Type*> ArgTys;
261       for (unsigned i = 0, e = Record[2]; i != e; ++i)
262         ArgTys.push_back(getTypeByID(Record[3+i], true));
263       
264       // FIXME: PARAM TYS.
265       ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
266                                    Record[0]);
267       break;
268     }
269     case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, #elts, eltty x N]
270       if (Record.size() < 2 || Record.size() < Record[1]+2)
271         return Error("Invalid STRUCT type record");
272       std::vector<const Type*> EltTys;
273       for (unsigned i = 0, e = Record[1]; i != e; ++i)
274         EltTys.push_back(getTypeByID(Record[2+i], true));
275       ResultTy = StructType::get(EltTys, Record[0]);
276       break;
277     }
278     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
279       if (Record.size() < 2)
280         return Error("Invalid ARRAY type record");
281       ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
282       break;
283     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
284       if (Record.size() < 2)
285         return Error("Invalid VECTOR type record");
286       ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
287       break;
288     }
289     
290     if (NumRecords == TypeList.size()) {
291       // If this is a new type slot, just append it.
292       TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
293       ++NumRecords;
294     } else if (ResultTy == 0) {
295       // Otherwise, this was forward referenced, so an opaque type was created,
296       // but the result type is actually just an opaque.  Leave the one we
297       // created previously.
298       ++NumRecords;
299     } else {
300       // Otherwise, this was forward referenced, so an opaque type was created.
301       // Resolve the opaque type to the real type now.
302       assert(NumRecords < TypeList.size() && "Typelist imbalance");
303       const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
304      
305       // Don't directly push the new type on the Tab. Instead we want to replace
306       // the opaque type we previously inserted with the new concrete value. The
307       // refinement from the abstract (opaque) type to the new type causes all
308       // uses of the abstract type to use the concrete type (NewTy). This will
309       // also cause the opaque type to be deleted.
310       const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
311       
312       // This should have replaced the old opaque type with the new type in the
313       // value table... or with a preexisting type that was already in the
314       // system.  Let's just make sure it did.
315       assert(TypeList[NumRecords-1].get() != OldTy &&
316              "refineAbstractType didn't work!");
317     }
318   }
319 }
320
321
322 bool BitcodeReader::ParseTypeSymbolTable() {
323   if (Stream.EnterSubBlock())
324     return Error("Malformed block record");
325   
326   SmallVector<uint64_t, 64> Record;
327   
328   // Read all the records for this type table.
329   std::string TypeName;
330   while (1) {
331     unsigned Code = Stream.ReadCode();
332     if (Code == bitc::END_BLOCK) {
333       if (Stream.ReadBlockEnd())
334         return Error("Error at end of type symbol table block");
335       return false;
336     }
337     
338     if (Code == bitc::ENTER_SUBBLOCK) {
339       // No known subblocks, always skip them.
340       Stream.ReadSubBlockID();
341       if (Stream.SkipBlock())
342         return Error("Malformed block record");
343       continue;
344     }
345     
346     if (Code == bitc::DEFINE_ABBREV) {
347       Stream.ReadAbbrevRecord();
348       continue;
349     }
350     
351     // Read a record.
352     Record.clear();
353     switch (Stream.ReadRecord(Code, Record)) {
354     default:  // Default behavior: unknown type.
355       break;
356     case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namelen, namechar x N]
357       if (ConvertToString(Record, 1, TypeName))
358         return Error("Invalid TST_ENTRY record");
359       unsigned TypeID = Record[0];
360       if (TypeID >= TypeList.size())
361         return Error("Invalid Type ID in TST_ENTRY record");
362
363       TheModule->addTypeName(TypeName, TypeList[TypeID].get());
364       TypeName.clear();
365       break;
366     }
367   }
368 }
369
370 bool BitcodeReader::ParseValueSymbolTable() {
371   if (Stream.EnterSubBlock())
372     return Error("Malformed block record");
373
374   SmallVector<uint64_t, 64> Record;
375   
376   // Read all the records for this value table.
377   SmallString<128> ValueName;
378   while (1) {
379     unsigned Code = Stream.ReadCode();
380     if (Code == bitc::END_BLOCK) {
381       if (Stream.ReadBlockEnd())
382         return Error("Error at end of value symbol table block");
383       return false;
384     }    
385     if (Code == bitc::ENTER_SUBBLOCK) {
386       // No known subblocks, always skip them.
387       Stream.ReadSubBlockID();
388       if (Stream.SkipBlock())
389         return Error("Malformed block record");
390       continue;
391     }
392     
393     if (Code == bitc::DEFINE_ABBREV) {
394       Stream.ReadAbbrevRecord();
395       continue;
396     }
397     
398     // Read a record.
399     Record.clear();
400     switch (Stream.ReadRecord(Code, Record)) {
401     default:  // Default behavior: unknown type.
402       break;
403     case bitc::VST_CODE_ENTRY:    // VST_ENTRY: [valueid, namelen, namechar x N]
404       if (ConvertToString(Record, 1, ValueName))
405         return Error("Invalid TST_ENTRY record");
406       unsigned ValueID = Record[0];
407       if (ValueID >= ValueList.size())
408         return Error("Invalid Value ID in VST_ENTRY record");
409       Value *V = ValueList[ValueID];
410       
411       V->setName(&ValueName[0], ValueName.size());
412       ValueName.clear();
413       break;
414     case bitc::VST_CODE_BBENTRY:
415       if (ConvertToString(Record, 1, ValueName))
416         return Error("Invalid VST_BBENTRY record");
417       BasicBlock *BB = getBasicBlock(Record[0]);
418       if (BB == 0)
419         return Error("Invalid BB ID in VST_BBENTRY record");
420       
421       BB->setName(&ValueName[0], ValueName.size());
422       ValueName.clear();
423       break;
424     }
425   }
426 }
427
428 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
429 /// the LSB for dense VBR encoding.
430 static uint64_t DecodeSignRotatedValue(uint64_t V) {
431   if ((V & 1) == 0)
432     return V >> 1;
433   if (V != 1) 
434     return -(V >> 1);
435   // There is no such thing as -0 with integers.  "-0" really means MININT.
436   return 1ULL << 63;
437 }
438
439 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
440 /// values and aliases that we can.
441 bool BitcodeReader::ResolveGlobalAndAliasInits() {
442   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
443   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
444   
445   GlobalInitWorklist.swap(GlobalInits);
446   AliasInitWorklist.swap(AliasInits);
447
448   while (!GlobalInitWorklist.empty()) {
449     unsigned ValID = GlobalInitWorklist.back().second;
450     if (ValID >= ValueList.size()) {
451       // Not ready to resolve this yet, it requires something later in the file.
452       GlobalInits.push_back(GlobalInitWorklist.back());
453     } else {
454       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
455         GlobalInitWorklist.back().first->setInitializer(C);
456       else
457         return Error("Global variable initializer is not a constant!");
458     }
459     GlobalInitWorklist.pop_back(); 
460   }
461
462   while (!AliasInitWorklist.empty()) {
463     unsigned ValID = AliasInitWorklist.back().second;
464     if (ValID >= ValueList.size()) {
465       AliasInits.push_back(AliasInitWorklist.back());
466     } else {
467       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
468         AliasInitWorklist.back().first->setAliasee(C);
469       else
470         return Error("Alias initializer is not a constant!");
471     }
472     AliasInitWorklist.pop_back(); 
473   }
474   return false;
475 }
476
477
478 bool BitcodeReader::ParseConstants() {
479   if (Stream.EnterSubBlock())
480     return Error("Malformed block record");
481
482   SmallVector<uint64_t, 64> Record;
483   
484   // Read all the records for this value table.
485   const Type *CurTy = Type::Int32Ty;
486   unsigned NextCstNo = ValueList.size();
487   while (1) {
488     unsigned Code = Stream.ReadCode();
489     if (Code == bitc::END_BLOCK) {
490       if (NextCstNo != ValueList.size())
491         return Error("Invalid constant reference!");
492       
493       if (Stream.ReadBlockEnd())
494         return Error("Error at end of constants block");
495       return false;
496     }
497     
498     if (Code == bitc::ENTER_SUBBLOCK) {
499       // No known subblocks, always skip them.
500       Stream.ReadSubBlockID();
501       if (Stream.SkipBlock())
502         return Error("Malformed block record");
503       continue;
504     }
505     
506     if (Code == bitc::DEFINE_ABBREV) {
507       Stream.ReadAbbrevRecord();
508       continue;
509     }
510     
511     // Read a record.
512     Record.clear();
513     Value *V = 0;
514     switch (Stream.ReadRecord(Code, Record)) {
515     default:  // Default behavior: unknown constant
516     case bitc::CST_CODE_UNDEF:     // UNDEF
517       V = UndefValue::get(CurTy);
518       break;
519     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
520       if (Record.empty())
521         return Error("Malformed CST_SETTYPE record");
522       if (Record[0] >= TypeList.size())
523         return Error("Invalid Type ID in CST_SETTYPE record");
524       CurTy = TypeList[Record[0]];
525       continue;  // Skip the ValueList manipulation.
526     case bitc::CST_CODE_NULL:      // NULL
527       V = Constant::getNullValue(CurTy);
528       break;
529     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
530       if (!isa<IntegerType>(CurTy) || Record.empty())
531         return Error("Invalid CST_INTEGER record");
532       V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
533       break;
534     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
535       if (!isa<IntegerType>(CurTy) || Record.empty() ||
536           Record.size() < Record[0]+1)
537         return Error("Invalid WIDE_INTEGER record");
538       
539       unsigned NumWords = Record[0];
540       SmallVector<uint64_t, 8> Words;
541       Words.resize(NumWords);
542       for (unsigned i = 0; i != NumWords; ++i)
543         Words[i] = DecodeSignRotatedValue(Record[i+1]);
544       V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
545                                  NumWords, &Words[0]));
546       break;
547     }
548     case bitc::CST_CODE_FLOAT:     // FLOAT: [fpval]
549       if (Record.empty())
550         return Error("Invalid FLOAT record");
551       if (CurTy == Type::FloatTy)
552         V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
553       else if (CurTy == Type::DoubleTy)
554         V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
555       else
556         V = UndefValue::get(CurTy);
557       break;
558       
559     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
560       if (Record.empty() || Record.size() < Record[0]+1)
561         return Error("Invalid CST_AGGREGATE record");
562       
563       unsigned Size = Record[0];
564       std::vector<Constant*> Elts;
565       
566       if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
567         for (unsigned i = 0; i != Size; ++i)
568           Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
569                                                      STy->getElementType(i)));
570         V = ConstantStruct::get(STy, Elts);
571       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
572         const Type *EltTy = ATy->getElementType();
573         for (unsigned i = 0; i != Size; ++i)
574           Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
575         V = ConstantArray::get(ATy, Elts);
576       } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
577         const Type *EltTy = VTy->getElementType();
578         for (unsigned i = 0; i != Size; ++i)
579           Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
580         V = ConstantVector::get(Elts);
581       } else {
582         V = UndefValue::get(CurTy);
583       }
584       break;
585     }
586
587     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
588       if (Record.size() < 3) return Error("Invalid CE_BINOP record");
589       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
590       if (Opc < 0) {
591         V = UndefValue::get(CurTy);  // Unknown binop.
592       } else {
593         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
594         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
595         V = ConstantExpr::get(Opc, LHS, RHS);
596       }
597       break;
598     }  
599     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
600       if (Record.size() < 3) return Error("Invalid CE_CAST record");
601       int Opc = GetDecodedCastOpcode(Record[0]);
602       if (Opc < 0) {
603         V = UndefValue::get(CurTy);  // Unknown cast.
604       } else {
605         const Type *OpTy = getTypeByID(Record[1]);
606         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
607         V = ConstantExpr::getCast(Opc, Op, CurTy);
608       }
609       break;
610     }  
611     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
612       if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
613       SmallVector<Constant*, 16> Elts;
614       for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
615         const Type *ElTy = getTypeByID(Record[i]);
616         if (!ElTy) return Error("Invalid CE_GEP record");
617         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
618       }
619       V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
620       break;
621     }
622     case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
623       if (Record.size() < 3) return Error("Invalid CE_SELECT record");
624       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
625                                                               Type::Int1Ty),
626                                   ValueList.getConstantFwdRef(Record[1],CurTy),
627                                   ValueList.getConstantFwdRef(Record[2],CurTy));
628       break;
629     case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
630       if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
631       const VectorType *OpTy = 
632         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
633       if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
634       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
635       Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
636                                                   OpTy->getElementType());
637       V = ConstantExpr::getExtractElement(Op0, Op1);
638       break;
639     }
640     case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
641       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
642       if (Record.size() < 3 || OpTy == 0)
643         return Error("Invalid CE_INSERTELT record");
644       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
645       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
646                                                   OpTy->getElementType());
647       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
648       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
649       break;
650     }
651     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
652       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
653       if (Record.size() < 3 || OpTy == 0)
654         return Error("Invalid CE_INSERTELT record");
655       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
656       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
657       const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
658       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
659       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
660       break;
661     }
662     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
663       if (Record.size() < 4) return Error("Invalid CE_CMP record");
664       const Type *OpTy = getTypeByID(Record[0]);
665       if (OpTy == 0) return Error("Invalid CE_CMP record");
666       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
667       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
668
669       if (OpTy->isFloatingPoint())
670         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
671       else
672         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
673       break;
674     }
675     }
676     
677     ValueList.AssignValue(V, NextCstNo);
678     ++NextCstNo;
679   }
680 }
681
682 /// RememberAndSkipFunctionBody - When we see the block for a function body,
683 /// remember where it is and then skip it.  This lets us lazily deserialize the
684 /// functions.
685 bool BitcodeReader::RememberAndSkipFunctionBody() {
686   // Get the function we are talking about.
687   if (FunctionsWithBodies.empty())
688     return Error("Insufficient function protos");
689   
690   Function *Fn = FunctionsWithBodies.back();
691   FunctionsWithBodies.pop_back();
692   
693   // Save the current stream state.
694   uint64_t CurBit = Stream.GetCurrentBitNo();
695   DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
696   
697   // Set the functions linkage to GhostLinkage so we know it is lazily
698   // deserialized.
699   Fn->setLinkage(GlobalValue::GhostLinkage);
700   
701   // Skip over the function block for now.
702   if (Stream.SkipBlock())
703     return Error("Malformed block record");
704   return false;
705 }
706
707 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
708   // Reject multiple MODULE_BLOCK's in a single bitstream.
709   if (TheModule)
710     return Error("Multiple MODULE_BLOCKs in same stream");
711   
712   if (Stream.EnterSubBlock())
713     return Error("Malformed block record");
714
715   // Otherwise, create the module.
716   TheModule = new Module(ModuleID);
717   
718   SmallVector<uint64_t, 64> Record;
719   std::vector<std::string> SectionTable;
720
721   // Read all the records for this module.
722   while (!Stream.AtEndOfStream()) {
723     unsigned Code = Stream.ReadCode();
724     if (Code == bitc::END_BLOCK) {
725       if (Stream.ReadBlockEnd())
726         return Error("Error at end of module block");
727
728       // Patch the initializers for globals and aliases up.
729       ResolveGlobalAndAliasInits();
730       if (!GlobalInits.empty() || !AliasInits.empty())
731         return Error("Malformed global initializer set");
732       if (!FunctionsWithBodies.empty())
733         return Error("Too few function bodies found");
734
735       // Force deallocation of memory for these vectors to favor the client that
736       // want lazy deserialization.
737       std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
738       std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
739       std::vector<Function*>().swap(FunctionsWithBodies);
740       return false;
741     }
742     
743     if (Code == bitc::ENTER_SUBBLOCK) {
744       switch (Stream.ReadSubBlockID()) {
745       default:  // Skip unknown content.
746         if (Stream.SkipBlock())
747           return Error("Malformed block record");
748         break;
749       case bitc::TYPE_BLOCK_ID:
750         if (ParseTypeTable())
751           return true;
752         break;
753       case bitc::TYPE_SYMTAB_BLOCK_ID:
754         if (ParseTypeSymbolTable())
755           return true;
756         break;
757       case bitc::VALUE_SYMTAB_BLOCK_ID:
758         if (ParseValueSymbolTable())
759           return true;
760         break;
761       case bitc::CONSTANTS_BLOCK_ID:
762         if (ParseConstants() || ResolveGlobalAndAliasInits())
763           return true;
764         break;
765       case bitc::FUNCTION_BLOCK_ID:
766         // If this is the first function body we've seen, reverse the
767         // FunctionsWithBodies list.
768         if (!HasReversedFunctionsWithBodies) {
769           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
770           HasReversedFunctionsWithBodies = true;
771         }
772         
773         if (RememberAndSkipFunctionBody())
774           return true;
775         break;
776       }
777       continue;
778     }
779     
780     if (Code == bitc::DEFINE_ABBREV) {
781       Stream.ReadAbbrevRecord();
782       continue;
783     }
784     
785     // Read a record.
786     switch (Stream.ReadRecord(Code, Record)) {
787     default: break;  // Default behavior, ignore unknown content.
788     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
789       if (Record.size() < 1)
790         return Error("Malformed MODULE_CODE_VERSION");
791       // Only version #0 is supported so far.
792       if (Record[0] != 0)
793         return Error("Unknown bitstream version!");
794       break;
795     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strlen, strchr x N]
796       std::string S;
797       if (ConvertToString(Record, 0, S))
798         return Error("Invalid MODULE_CODE_TRIPLE record");
799       TheModule->setTargetTriple(S);
800       break;
801     }
802     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strlen, strchr x N]
803       std::string S;
804       if (ConvertToString(Record, 0, S))
805         return Error("Invalid MODULE_CODE_DATALAYOUT record");
806       TheModule->setDataLayout(S);
807       break;
808     }
809     case bitc::MODULE_CODE_ASM: {  // ASM: [strlen, strchr x N]
810       std::string S;
811       if (ConvertToString(Record, 0, S))
812         return Error("Invalid MODULE_CODE_ASM record");
813       TheModule->setModuleInlineAsm(S);
814       break;
815     }
816     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strlen, strchr x N]
817       std::string S;
818       if (ConvertToString(Record, 0, S))
819         return Error("Invalid MODULE_CODE_DEPLIB record");
820       TheModule->addLibrary(S);
821       break;
822     }
823     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strlen, strchr x N]
824       std::string S;
825       if (ConvertToString(Record, 0, S))
826         return Error("Invalid MODULE_CODE_SECTIONNAME record");
827       SectionTable.push_back(S);
828       break;
829     }
830     // GLOBALVAR: [type, isconst, initid, 
831     //             linkage, alignment, section, visibility, threadlocal]
832     case bitc::MODULE_CODE_GLOBALVAR: {
833       if (Record.size() < 6)
834         return Error("Invalid MODULE_CODE_GLOBALVAR record");
835       const Type *Ty = getTypeByID(Record[0]);
836       if (!isa<PointerType>(Ty))
837         return Error("Global not a pointer type!");
838       Ty = cast<PointerType>(Ty)->getElementType();
839       
840       bool isConstant = Record[1];
841       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
842       unsigned Alignment = (1 << Record[4]) >> 1;
843       std::string Section;
844       if (Record[5]) {
845         if (Record[5]-1 >= SectionTable.size())
846           return Error("Invalid section ID");
847         Section = SectionTable[Record[5]-1];
848       }
849       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
850       if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
851       bool isThreadLocal = false;
852       if (Record.size() >= 7) isThreadLocal = Record[7];
853
854       GlobalVariable *NewGV =
855         new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
856       NewGV->setAlignment(Alignment);
857       if (!Section.empty())
858         NewGV->setSection(Section);
859       NewGV->setVisibility(Visibility);
860       NewGV->setThreadLocal(isThreadLocal);
861       
862       ValueList.push_back(NewGV);
863       
864       // Remember which value to use for the global initializer.
865       if (unsigned InitID = Record[2])
866         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
867       break;
868     }
869     // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
870     //             visibility]
871     case bitc::MODULE_CODE_FUNCTION: {
872       if (Record.size() < 7)
873         return Error("Invalid MODULE_CODE_FUNCTION record");
874       const Type *Ty = getTypeByID(Record[0]);
875       if (!isa<PointerType>(Ty))
876         return Error("Function not a pointer type!");
877       const FunctionType *FTy =
878         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
879       if (!FTy)
880         return Error("Function not a pointer to function type!");
881
882       Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
883                                     "", TheModule);
884
885       Func->setCallingConv(Record[1]);
886       bool isProto = Record[2];
887       Func->setLinkage(GetDecodedLinkage(Record[3]));
888       Func->setAlignment((1 << Record[4]) >> 1);
889       if (Record[5]) {
890         if (Record[5]-1 >= SectionTable.size())
891           return Error("Invalid section ID");
892         Func->setSection(SectionTable[Record[5]-1]);
893       }
894       Func->setVisibility(GetDecodedVisibility(Record[6]));
895       
896       ValueList.push_back(Func);
897       
898       // If this is a function with a body, remember the prototype we are
899       // creating now, so that we can match up the body with them later.
900       if (!isProto)
901         FunctionsWithBodies.push_back(Func);
902       break;
903     }
904     // ALIAS: [alias type, aliasee val#, linkage]
905     case bitc::MODULE_CODE_ALIAS: {
906       if (Record.size() < 3)
907         return Error("Invalid MODULE_ALIAS record");
908       const Type *Ty = getTypeByID(Record[0]);
909       if (!isa<PointerType>(Ty))
910         return Error("Function not a pointer type!");
911       
912       GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
913                                            "", 0, TheModule);
914       ValueList.push_back(NewGA);
915       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
916       break;
917     }
918     /// MODULE_CODE_PURGEVALS: [numvals]
919     case bitc::MODULE_CODE_PURGEVALS:
920       // Trim down the value list to the specified size.
921       if (Record.size() < 1 || Record[0] > ValueList.size())
922         return Error("Invalid MODULE_PURGEVALS record");
923       ValueList.shrinkTo(Record[0]);
924       break;
925     }
926     Record.clear();
927   }
928   
929   return Error("Premature end of bitstream");
930 }
931
932
933 bool BitcodeReader::ParseBitcode() {
934   TheModule = 0;
935   
936   if (Buffer->getBufferSize() & 3)
937     return Error("Bitcode stream should be a multiple of 4 bytes in length");
938   
939   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
940   Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
941   
942   // Sniff for the signature.
943   if (Stream.Read(8) != 'B' ||
944       Stream.Read(8) != 'C' ||
945       Stream.Read(4) != 0x0 ||
946       Stream.Read(4) != 0xC ||
947       Stream.Read(4) != 0xE ||
948       Stream.Read(4) != 0xD)
949     return Error("Invalid bitcode signature");
950   
951   // We expect a number of well-defined blocks, though we don't necessarily
952   // need to understand them all.
953   while (!Stream.AtEndOfStream()) {
954     unsigned Code = Stream.ReadCode();
955     
956     if (Code != bitc::ENTER_SUBBLOCK)
957       return Error("Invalid record at top-level");
958     
959     unsigned BlockID = Stream.ReadSubBlockID();
960     
961     // We only know the MODULE subblock ID.
962     if (BlockID == bitc::MODULE_BLOCK_ID) {
963       if (ParseModule(Buffer->getBufferIdentifier()))
964         return true;
965     } else if (Stream.SkipBlock()) {
966       return Error("Malformed block record");
967     }
968   }
969   
970   return false;
971 }
972
973
974 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
975   // If it already is material, ignore the request.
976   if (!F->hasNotBeenReadFromBytecode()) return false;
977
978   DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII = 
979     DeferredFunctionInfo.find(F);
980   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
981   
982   // Move the bit stream to the saved position of the deferred function body and
983   // restore the real linkage type for the function.
984   Stream.JumpToBit(DFII->second.first);
985   F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
986   DeferredFunctionInfo.erase(DFII);
987   
988   if (ParseFunctionBody(F)) {
989     if (ErrInfo) *ErrInfo = ErrorString;
990     return true;
991   }
992   
993   return false;
994 }
995
996 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
997   DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I = 
998     DeferredFunctionInfo.begin();
999   while (!DeferredFunctionInfo.empty()) {
1000     Function *F = (*I++).first;
1001     assert(F->hasNotBeenReadFromBytecode() &&
1002            "Deserialized function found in map!");
1003     if (materializeFunction(F, ErrInfo))
1004       return 0;
1005   }
1006   return TheModule;
1007 }
1008
1009
1010 /// ParseFunctionBody - Lazily parse the specified function body block.
1011 bool BitcodeReader::ParseFunctionBody(Function *F) {
1012   if (Stream.EnterSubBlock())
1013     return Error("Malformed block record");
1014   
1015   unsigned ModuleValueListSize = ValueList.size();
1016   
1017   // Add all the function arguments to the value table.
1018   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1019     ValueList.push_back(I);
1020   
1021   unsigned NextValueNo = ValueList.size();
1022   BasicBlock *CurBB = 0;
1023   unsigned CurBBNo = 0;
1024
1025   // Read all the records.
1026   SmallVector<uint64_t, 64> Record;
1027   while (1) {
1028     unsigned Code = Stream.ReadCode();
1029     if (Code == bitc::END_BLOCK) {
1030       if (Stream.ReadBlockEnd())
1031         return Error("Error at end of function block");
1032       break;
1033     }
1034     
1035     if (Code == bitc::ENTER_SUBBLOCK) {
1036       switch (Stream.ReadSubBlockID()) {
1037       default:  // Skip unknown content.
1038         if (Stream.SkipBlock())
1039           return Error("Malformed block record");
1040         break;
1041       case bitc::CONSTANTS_BLOCK_ID:
1042         if (ParseConstants()) return true;
1043         NextValueNo = ValueList.size();
1044         break;
1045       case bitc::VALUE_SYMTAB_BLOCK_ID:
1046         if (ParseValueSymbolTable()) return true;
1047         break;
1048       }
1049       continue;
1050     }
1051     
1052     if (Code == bitc::DEFINE_ABBREV) {
1053       Stream.ReadAbbrevRecord();
1054       continue;
1055     }
1056     
1057     // Read a record.
1058     Record.clear();
1059     Instruction *I = 0;
1060     switch (Stream.ReadRecord(Code, Record)) {
1061     default: // Default behavior: reject
1062       return Error("Unknown instruction");
1063     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1064       if (Record.size() < 1 || Record[0] == 0)
1065         return Error("Invalid DECLAREBLOCKS record");
1066       // Create all the basic blocks for the function.
1067       FunctionBBs.resize(Record[0]);
1068       for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1069         FunctionBBs[i] = new BasicBlock("", F);
1070       CurBB = FunctionBBs[0];
1071       continue;
1072       
1073     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opcode, ty, opval, opval]
1074       if (Record.size() < 4) return Error("Invalid BINOP record");
1075       const Type *Ty = getTypeByID(Record[1]);
1076       int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
1077       Value *LHS = getFnValueByID(Record[2], Ty);
1078       Value *RHS = getFnValueByID(Record[3], Ty);
1079       if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
1080          return Error("Invalid BINOP record");
1081       I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1082       break;
1083     }
1084     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opcode, ty, opty, opval]
1085       if (Record.size() < 4) return Error("Invalid CAST record");
1086       int Opc = GetDecodedCastOpcode(Record[0]);
1087       const Type *ResTy = getTypeByID(Record[1]);
1088       const Type *OpTy = getTypeByID(Record[2]);
1089       Value *Op = getFnValueByID(Record[3], OpTy);
1090       if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
1091         return Error("Invalid CAST record");
1092       I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1093       break;
1094     }
1095     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n, n x operands]
1096       if (Record.size() < 2 || (Record.size() & 1))
1097         return Error("Invalid GEP record");
1098       const Type *OpTy = getTypeByID(Record[0]);
1099       Value *Op = getFnValueByID(Record[1], OpTy);
1100       if (OpTy == 0 || Op == 0)
1101         return Error("Invalid GEP record");
1102
1103       SmallVector<Value*, 16> GEPIdx;
1104       for (unsigned i = 1, e = Record.size()/2; i != e; ++i) {
1105         const Type *IdxTy = getTypeByID(Record[i*2]);
1106         Value *Idx = getFnValueByID(Record[i*2+1], IdxTy);
1107         if (IdxTy == 0 || Idx == 0)
1108           return Error("Invalid GEP record");
1109         GEPIdx.push_back(Idx);
1110       }
1111
1112       I = new GetElementPtrInst(Op, &GEPIdx[0], GEPIdx.size());
1113       break;
1114     }
1115       
1116     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [ty, opval, opval, opval]
1117       if (Record.size() < 4) return Error("Invalid SELECT record");
1118       const Type *Ty = getTypeByID(Record[0]);
1119       Value *Cond = getFnValueByID(Record[1], Type::Int1Ty);
1120       Value *LHS = getFnValueByID(Record[2], Ty);
1121       Value *RHS = getFnValueByID(Record[3], Ty);
1122       if (Ty == 0 || Cond == 0 || LHS == 0 || RHS == 0)
1123         return Error("Invalid SELECT record");
1124       I = new SelectInst(Cond, LHS, RHS);
1125       break;
1126     }
1127       
1128     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1129       if (Record.size() < 3) return Error("Invalid EXTRACTELT record");
1130       const Type *OpTy = getTypeByID(Record[0]);
1131       Value *Vec = getFnValueByID(Record[1], OpTy);
1132       Value *Idx = getFnValueByID(Record[2], Type::Int32Ty);
1133       if (OpTy == 0 || Vec == 0 || Idx == 0)
1134         return Error("Invalid EXTRACTELT record");
1135       I = new ExtractElementInst(Vec, Idx);
1136       break;
1137     }
1138       
1139     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1140       if (Record.size() < 4) return Error("Invalid INSERTELT record");
1141       const VectorType *OpTy = 
1142         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1143       if (OpTy == 0) return Error("Invalid INSERTELT record");
1144       Value *Vec = getFnValueByID(Record[1], OpTy);
1145       Value *Elt = getFnValueByID(Record[2], OpTy->getElementType());
1146       Value *Idx = getFnValueByID(Record[3], Type::Int32Ty);
1147       if (Vec == 0 || Elt == 0 || Idx == 0)
1148         return Error("Invalid INSERTELT record");
1149       I = new InsertElementInst(Vec, Elt, Idx);
1150       break;
1151     }
1152       
1153     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [ty,opval,opval,opval]
1154       if (Record.size() < 4) return Error("Invalid SHUFFLEVEC record");
1155       const VectorType *OpTy = 
1156         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1157       if (OpTy == 0) return Error("Invalid SHUFFLEVEC record");
1158       Value *Vec1 = getFnValueByID(Record[1], OpTy);
1159       Value *Vec2 = getFnValueByID(Record[2], OpTy);
1160       Value *Mask = getFnValueByID(Record[3],
1161                                    VectorType::get(Type::Int32Ty,
1162                                                    OpTy->getNumElements()));
1163       if (Vec1 == 0 || Vec2 == 0 || Mask == 0)
1164         return Error("Invalid SHUFFLEVEC record");
1165       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1166       break;
1167     }
1168       
1169     case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1170       if (Record.size() < 4) return Error("Invalid CMP record");
1171       const Type *OpTy = getTypeByID(Record[0]);
1172       Value *LHS = getFnValueByID(Record[1], OpTy);
1173       Value *RHS = getFnValueByID(Record[2], OpTy);
1174       if (OpTy == 0 || LHS == 0 || RHS == 0)
1175         return Error("Invalid CMP record");
1176       if (OpTy->isFPOrFPVector())
1177         I = new FCmpInst((FCmpInst::Predicate)Record[3], LHS, RHS);
1178       else
1179         I = new ICmpInst((ICmpInst::Predicate)Record[3], LHS, RHS);
1180       break;
1181     }
1182     
1183     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1184       if (Record.size() == 0) {
1185         I = new ReturnInst();
1186         break;
1187       }
1188       if (Record.size() == 2) {
1189         const Type *OpTy = getTypeByID(Record[0]);
1190         Value *Op = getFnValueByID(Record[1], OpTy);
1191         if (!OpTy || !Op)
1192           return Error("Invalid RET record");
1193         I = new ReturnInst(Op);
1194         break;
1195       }
1196       return Error("Invalid RET record");
1197     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1198       if (Record.size() != 1 && Record.size() != 3)
1199         return Error("Invalid BR record");
1200       BasicBlock *TrueDest = getBasicBlock(Record[0]);
1201       if (TrueDest == 0)
1202         return Error("Invalid BR record");
1203
1204       if (Record.size() == 1)
1205         I = new BranchInst(TrueDest);
1206       else {
1207         BasicBlock *FalseDest = getBasicBlock(Record[1]);
1208         Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1209         if (FalseDest == 0 || Cond == 0)
1210           return Error("Invalid BR record");
1211         I = new BranchInst(TrueDest, FalseDest, Cond);
1212       }
1213       break;
1214     }
1215     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1216       if (Record.size() < 3 || (Record.size() & 1) == 0)
1217         return Error("Invalid SWITCH record");
1218       const Type *OpTy = getTypeByID(Record[0]);
1219       Value *Cond = getFnValueByID(Record[1], OpTy);
1220       BasicBlock *Default = getBasicBlock(Record[2]);
1221       if (OpTy == 0 || Cond == 0 || Default == 0)
1222         return Error("Invalid SWITCH record");
1223       unsigned NumCases = (Record.size()-3)/2;
1224       SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1225       for (unsigned i = 0, e = NumCases; i != e; ++i) {
1226         ConstantInt *CaseVal = 
1227           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1228         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1229         if (CaseVal == 0 || DestBB == 0) {
1230           delete SI;
1231           return Error("Invalid SWITCH record!");
1232         }
1233         SI->addCase(CaseVal, DestBB);
1234       }
1235       I = SI;
1236       break;
1237     }
1238       
1239     case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [fnty, op0,op1,op2, ...]
1240       if (Record.size() < 4)
1241         return Error("Invalid INVOKE record");
1242       const PointerType *CalleeTy =
1243         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1244       Value *Callee = getFnValueByID(Record[1], CalleeTy);
1245       BasicBlock *NormalBB = getBasicBlock(Record[2]);
1246       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1247       if (CalleeTy == 0 || Callee == 0 || NormalBB == 0 || UnwindBB == 0)
1248         return Error("Invalid INVOKE record");
1249       
1250       const FunctionType *FTy =
1251         dyn_cast<FunctionType>(CalleeTy->getElementType());
1252
1253       // Check that the right number of fixed parameters are here.
1254       if (FTy == 0 || Record.size() < 4+FTy->getNumParams())
1255         return Error("Invalid INVOKE record");
1256
1257       SmallVector<Value*, 16> Ops;
1258       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1259         Ops.push_back(getFnValueByID(Record[4+i], FTy->getParamType(4+i)));
1260         if (Ops.back() == 0)
1261           return Error("Invalid INVOKE record");
1262       }
1263       
1264       unsigned FirstVarargParam = 4+FTy->getNumParams();
1265       if (FTy->isVarArg()) {
1266         // Read type/value pairs for varargs params.
1267         if ((Record.size()-FirstVarargParam) & 1)
1268           return Error("Invalid INVOKE record");
1269         
1270         for (unsigned i = FirstVarargParam, e = Record.size(); i != e; i += 2) {
1271           const Type *ArgTy = getTypeByID(Record[i]);
1272           Ops.push_back(getFnValueByID(Record[i+1], ArgTy));
1273           if (Ops.back() == 0 || ArgTy == 0)
1274             return Error("Invalid INVOKE record");
1275         }
1276       } else {
1277         if (Record.size() != FirstVarargParam)
1278           return Error("Invalid INVOKE record");
1279       }
1280       
1281       I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
1282       break;
1283     }
1284     case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1285       I = new UnwindInst();
1286       break;
1287     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1288       I = new UnreachableInst();
1289       break;
1290     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, #ops, val0,bb0, ...]
1291       if (Record.size() < 2 || Record.size() < 2+Record[1] || (Record[1]&1))
1292         return Error("Invalid PHI record");
1293       const Type *Ty = getTypeByID(Record[0]);
1294       if (!Ty) return Error("Invalid PHI record");
1295       
1296       PHINode *PN = new PHINode(Ty);
1297       PN->reserveOperandSpace(Record[1]);
1298       
1299       for (unsigned i = 0, e = Record[1]; i != e; i += 2) {
1300         Value *V = getFnValueByID(Record[2+i], Ty);
1301         BasicBlock *BB = getBasicBlock(Record[3+i]);
1302         if (!V || !BB) return Error("Invalid PHI record");
1303         PN->addIncoming(V, BB);
1304       }
1305       I = PN;
1306       break;
1307     }
1308       
1309     case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1310       if (Record.size() < 3)
1311         return Error("Invalid MALLOC record");
1312       const PointerType *Ty =
1313         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1314       Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1315       unsigned Align = Record[2];
1316       if (!Ty || !Size) return Error("Invalid MALLOC record");
1317       I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1318       break;
1319     }
1320     case bitc::FUNC_CODE_INST_FREE: { // FREE: [opty, op]
1321       if (Record.size() < 2)
1322         return Error("Invalid FREE record");
1323       const Type *OpTy = getTypeByID(Record[0]);
1324       Value *Op = getFnValueByID(Record[1], OpTy);
1325       if (!OpTy || !Op)
1326         return Error("Invalid FREE record");
1327       I = new FreeInst(Op);
1328       break;
1329     }
1330     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1331       if (Record.size() < 3)
1332         return Error("Invalid ALLOCA record");
1333       const PointerType *Ty =
1334         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1335       Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1336       unsigned Align = Record[2];
1337       if (!Ty || !Size) return Error("Invalid ALLOCA record");
1338       I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1339       break;
1340     }
1341     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1342       if (Record.size() < 4)
1343         return Error("Invalid LOAD record");
1344       const Type *OpTy = getTypeByID(Record[0]);
1345       Value *Op = getFnValueByID(Record[1], OpTy);
1346       if (!OpTy || !Op)
1347         return Error("Invalid LOAD record");
1348       I = new LoadInst(Op, "", Record[3], (1 << Record[2]) >> 1);
1349       break;
1350     }
1351     case bitc::FUNC_CODE_INST_STORE: { // STORE:[ptrty,val,ptr, align, vol]
1352       if (Record.size() < 5)
1353         return Error("Invalid LOAD record");
1354       const PointerType *OpTy = 
1355         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1356       Value *Op = getFnValueByID(Record[1], OpTy ? OpTy->getElementType() : 0);
1357       Value *Ptr = getFnValueByID(Record[2], OpTy);
1358       if (!OpTy || !Op || !Ptr)
1359         return Error("Invalid STORE record");
1360       I = new StoreInst(Op, Ptr, (1 << Record[3]) >> 1, Record[4]);
1361       break;
1362     }
1363     case bitc::FUNC_CODE_INST_CALL: { // CALL: [fnty, fnid, arg0, arg1...]
1364       if (Record.size() < 2)
1365         return Error("Invalid CALL record");
1366       const PointerType *OpTy = 
1367         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1368       const FunctionType *FTy = 0;
1369       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1370       Value *Callee = getFnValueByID(Record[1], OpTy);
1371       if (!FTy || !Callee || Record.size() < FTy->getNumParams()+2)
1372         return Error("Invalid CALL record");
1373       
1374       SmallVector<Value*, 16> Args;
1375       // Read the fixed params.
1376       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
1377         Args.push_back(getFnValueByID(Record[i+2], FTy->getParamType(i)));
1378         if (Args.back() == 0) return Error("Invalid CALL record");
1379       }
1380       
1381       
1382       // Read type/value pairs for varargs params.
1383       unsigned NextArg = FTy->getNumParams()+2;
1384       if (!FTy->isVarArg()) {
1385         if (NextArg != Record.size())
1386           return Error("Invalid CALL record");
1387       } else {
1388         if ((Record.size()-NextArg) & 1)
1389           return Error("Invalid CALL record");
1390         for (unsigned e = Record.size(); NextArg != e; NextArg += 2) {
1391           Args.push_back(getFnValueByID(Record[NextArg+1], 
1392                                         getTypeByID(Record[NextArg])));
1393           if (Args.back() == 0) return Error("Invalid CALL record");
1394         }
1395       }
1396       
1397       I = new CallInst(Callee, &Args[0], Args.size());
1398       break;
1399     }
1400     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1401       if (Record.size() < 3)
1402         return Error("Invalid VAARG record");
1403       const Type *OpTy = getTypeByID(Record[0]);
1404       Value *Op = getFnValueByID(Record[1], OpTy);
1405       const Type *ResTy = getTypeByID(Record[2]);
1406       if (!OpTy || !Op || !ResTy)
1407         return Error("Invalid VAARG record");
1408       I = new VAArgInst(Op, ResTy);
1409       break;
1410     }
1411     }
1412
1413     // Add instruction to end of current BB.  If there is no current BB, reject
1414     // this file.
1415     if (CurBB == 0) {
1416       delete I;
1417       return Error("Invalid instruction with no BB");
1418     }
1419     CurBB->getInstList().push_back(I);
1420     
1421     // If this was a terminator instruction, move to the next block.
1422     if (isa<TerminatorInst>(I)) {
1423       ++CurBBNo;
1424       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1425     }
1426     
1427     // Non-void values get registered in the value table for future use.
1428     if (I && I->getType() != Type::VoidTy)
1429       ValueList.AssignValue(I, NextValueNo++);
1430   }
1431   
1432   // Check the function list for unresolved values.
1433   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1434     if (A->getParent() == 0) {
1435       // We found at least one unresolved value.  Nuke them all to avoid leaks.
1436       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1437         if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1438           A->replaceAllUsesWith(UndefValue::get(A->getType()));
1439           delete A;
1440         }
1441       }
1442     }
1443     return Error("Never resolved value found in function!");
1444   }
1445   
1446   // Trim the value list down to the size it was before we parsed this function.
1447   ValueList.shrinkTo(ModuleValueListSize);
1448   std::vector<BasicBlock*>().swap(FunctionBBs);
1449   
1450   return false;
1451 }
1452
1453
1454 //===----------------------------------------------------------------------===//
1455 // External interface
1456 //===----------------------------------------------------------------------===//
1457
1458 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1459 ///
1460 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1461                                                std::string *ErrMsg) {
1462   BitcodeReader *R = new BitcodeReader(Buffer);
1463   if (R->ParseBitcode()) {
1464     if (ErrMsg)
1465       *ErrMsg = R->getErrorString();
1466     
1467     // Don't let the BitcodeReader dtor delete 'Buffer'.
1468     R->releaseMemoryBuffer();
1469     delete R;
1470     return 0;
1471   }
1472   return R;
1473 }
1474
1475 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1476 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1477 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1478   BitcodeReader *R;
1479   R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1480   if (!R) return 0;
1481   
1482   // Read the whole module, get a pointer to it, tell ModuleProvider not to
1483   // delete it when its dtor is run.
1484   Module *M = R->releaseModule(ErrMsg);
1485   
1486   // Don't let the BitcodeReader dtor delete 'Buffer'.
1487   R->releaseMemoryBuffer();
1488   delete R;
1489   return M;
1490 }