963791f5d6c935c629ac294da5f98792f616af11
[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/IntrinsicInst.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/AutoUpgrade.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/OperandTraits.h"
28 using namespace llvm;
29
30 void BitcodeReader::FreeState() {
31   if (BufferOwned)
32     delete Buffer;
33   Buffer = 0;
34   std::vector<PATypeHolder>().swap(TypeList);
35   ValueList.clear();
36   MDValueList.clear();
37
38   std::vector<AttrListPtr>().swap(MAttributes);
39   std::vector<BasicBlock*>().swap(FunctionBBs);
40   std::vector<Function*>().swap(FunctionsWithBodies);
41   DeferredFunctionInfo.clear();
42   MDKindMap.clear();
43 }
44
45 //===----------------------------------------------------------------------===//
46 //  Helper functions to implement forward reference resolution, etc.
47 //===----------------------------------------------------------------------===//
48
49 /// ConvertToString - Convert a string from a record into an std::string, return
50 /// true on failure.
51 template<typename StrTy>
52 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
53                             StrTy &Result) {
54   if (Idx > Record.size())
55     return true;
56
57   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58     Result += (char)Record[i];
59   return false;
60 }
61
62 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
63   switch (Val) {
64   default: // Map unknown/new linkages to external
65   case 0:  return GlobalValue::ExternalLinkage;
66   case 1:  return GlobalValue::WeakAnyLinkage;
67   case 2:  return GlobalValue::AppendingLinkage;
68   case 3:  return GlobalValue::InternalLinkage;
69   case 4:  return GlobalValue::LinkOnceAnyLinkage;
70   case 5:  return GlobalValue::DLLImportLinkage;
71   case 6:  return GlobalValue::DLLExportLinkage;
72   case 7:  return GlobalValue::ExternalWeakLinkage;
73   case 8:  return GlobalValue::CommonLinkage;
74   case 9:  return GlobalValue::PrivateLinkage;
75   case 10: return GlobalValue::WeakODRLinkage;
76   case 11: return GlobalValue::LinkOnceODRLinkage;
77   case 12: return GlobalValue::AvailableExternallyLinkage;
78   case 13: return GlobalValue::LinkerPrivateLinkage;
79   case 14: return GlobalValue::LinkerPrivateWeakLinkage;
80   case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
81   }
82 }
83
84 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
85   switch (Val) {
86   default: // Map unknown visibilities to default.
87   case 0: return GlobalValue::DefaultVisibility;
88   case 1: return GlobalValue::HiddenVisibility;
89   case 2: return GlobalValue::ProtectedVisibility;
90   }
91 }
92
93 static int GetDecodedCastOpcode(unsigned Val) {
94   switch (Val) {
95   default: return -1;
96   case bitc::CAST_TRUNC   : return Instruction::Trunc;
97   case bitc::CAST_ZEXT    : return Instruction::ZExt;
98   case bitc::CAST_SEXT    : return Instruction::SExt;
99   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
100   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
101   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
102   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
103   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
104   case bitc::CAST_FPEXT   : return Instruction::FPExt;
105   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
106   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
107   case bitc::CAST_BITCAST : return Instruction::BitCast;
108   }
109 }
110 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
111   switch (Val) {
112   default: return -1;
113   case bitc::BINOP_ADD:
114     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
115   case bitc::BINOP_SUB:
116     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
117   case bitc::BINOP_MUL:
118     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
119   case bitc::BINOP_UDIV: return Instruction::UDiv;
120   case bitc::BINOP_SDIV:
121     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
122   case bitc::BINOP_UREM: return Instruction::URem;
123   case bitc::BINOP_SREM:
124     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
125   case bitc::BINOP_SHL:  return Instruction::Shl;
126   case bitc::BINOP_LSHR: return Instruction::LShr;
127   case bitc::BINOP_ASHR: return Instruction::AShr;
128   case bitc::BINOP_AND:  return Instruction::And;
129   case bitc::BINOP_OR:   return Instruction::Or;
130   case bitc::BINOP_XOR:  return Instruction::Xor;
131   }
132 }
133
134 namespace llvm {
135 namespace {
136   /// @brief A class for maintaining the slot number definition
137   /// as a placeholder for the actual definition for forward constants defs.
138   class ConstantPlaceHolder : public ConstantExpr {
139     void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
140   public:
141     // allocate space for exactly one operand
142     void *operator new(size_t s) {
143       return User::operator new(s, 1);
144     }
145     explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
146       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
147       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
148     }
149
150     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
151     //static inline bool classof(const ConstantPlaceHolder *) { return true; }
152     static bool classof(const Value *V) {
153       return isa<ConstantExpr>(V) &&
154              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
155     }
156
157
158     /// Provide fast operand accessors
159     //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
160   };
161 }
162
163 // FIXME: can we inherit this from ConstantExpr?
164 template <>
165 struct OperandTraits<ConstantPlaceHolder> :
166   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
167 };
168 }
169
170
171 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
172   if (Idx == size()) {
173     push_back(V);
174     return;
175   }
176
177   if (Idx >= size())
178     resize(Idx+1);
179
180   WeakVH &OldV = ValuePtrs[Idx];
181   if (OldV == 0) {
182     OldV = V;
183     return;
184   }
185
186   // Handle constants and non-constants (e.g. instrs) differently for
187   // efficiency.
188   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
189     ResolveConstants.push_back(std::make_pair(PHC, Idx));
190     OldV = V;
191   } else {
192     // If there was a forward reference to this value, replace it.
193     Value *PrevVal = OldV;
194     OldV->replaceAllUsesWith(V);
195     delete PrevVal;
196   }
197 }
198
199
200 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
201                                                     const Type *Ty) {
202   if (Idx >= size())
203     resize(Idx + 1);
204
205   if (Value *V = ValuePtrs[Idx]) {
206     assert(Ty == V->getType() && "Type mismatch in constant table!");
207     return cast<Constant>(V);
208   }
209
210   // Create and return a placeholder, which will later be RAUW'd.
211   Constant *C = new ConstantPlaceHolder(Ty, Context);
212   ValuePtrs[Idx] = C;
213   return C;
214 }
215
216 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
217   if (Idx >= size())
218     resize(Idx + 1);
219
220   if (Value *V = ValuePtrs[Idx]) {
221     assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
222     return V;
223   }
224
225   // No type specified, must be invalid reference.
226   if (Ty == 0) return 0;
227
228   // Create and return a placeholder, which will later be RAUW'd.
229   Value *V = new Argument(Ty);
230   ValuePtrs[Idx] = V;
231   return V;
232 }
233
234 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
235 /// resolves any forward references.  The idea behind this is that we sometimes
236 /// get constants (such as large arrays) which reference *many* forward ref
237 /// constants.  Replacing each of these causes a lot of thrashing when
238 /// building/reuniquing the constant.  Instead of doing this, we look at all the
239 /// uses and rewrite all the place holders at once for any constant that uses
240 /// a placeholder.
241 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
242   // Sort the values by-pointer so that they are efficient to look up with a
243   // binary search.
244   std::sort(ResolveConstants.begin(), ResolveConstants.end());
245
246   SmallVector<Constant*, 64> NewOps;
247
248   while (!ResolveConstants.empty()) {
249     Value *RealVal = operator[](ResolveConstants.back().second);
250     Constant *Placeholder = ResolveConstants.back().first;
251     ResolveConstants.pop_back();
252
253     // Loop over all users of the placeholder, updating them to reference the
254     // new value.  If they reference more than one placeholder, update them all
255     // at once.
256     while (!Placeholder->use_empty()) {
257       Value::use_iterator UI = Placeholder->use_begin();
258       User *U = *UI;
259
260       // If the using object isn't uniqued, just update the operands.  This
261       // handles instructions and initializers for global variables.
262       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
263         UI.getUse().set(RealVal);
264         continue;
265       }
266
267       // Otherwise, we have a constant that uses the placeholder.  Replace that
268       // constant with a new constant that has *all* placeholder uses updated.
269       Constant *UserC = cast<Constant>(U);
270       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
271            I != E; ++I) {
272         Value *NewOp;
273         if (!isa<ConstantPlaceHolder>(*I)) {
274           // Not a placeholder reference.
275           NewOp = *I;
276         } else if (*I == Placeholder) {
277           // Common case is that it just references this one placeholder.
278           NewOp = RealVal;
279         } else {
280           // Otherwise, look up the placeholder in ResolveConstants.
281           ResolveConstantsTy::iterator It =
282             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
283                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
284                                                             0));
285           assert(It != ResolveConstants.end() && It->first == *I);
286           NewOp = operator[](It->second);
287         }
288
289         NewOps.push_back(cast<Constant>(NewOp));
290       }
291
292       // Make the new constant.
293       Constant *NewC;
294       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
295         NewC = ConstantArray::get(UserCA->getType(), NewOps);
296       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
297         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
298       } else if (isa<ConstantVector>(UserC)) {
299         NewC = ConstantVector::get(NewOps);
300       } else {
301         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
302         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
303       }
304
305       UserC->replaceAllUsesWith(NewC);
306       UserC->destroyConstant();
307       NewOps.clear();
308     }
309
310     // Update all ValueHandles, they should be the only users at this point.
311     Placeholder->replaceAllUsesWith(RealVal);
312     delete Placeholder;
313   }
314 }
315
316 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
317   if (Idx == size()) {
318     push_back(V);
319     return;
320   }
321
322   if (Idx >= size())
323     resize(Idx+1);
324
325   WeakVH &OldV = MDValuePtrs[Idx];
326   if (OldV == 0) {
327     OldV = V;
328     return;
329   }
330
331   // If there was a forward reference to this value, replace it.
332   MDNode *PrevVal = cast<MDNode>(OldV);
333   OldV->replaceAllUsesWith(V);
334   MDNode::deleteTemporary(PrevVal);
335   // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
336   // value for Idx.
337   MDValuePtrs[Idx] = V;
338 }
339
340 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
341   if (Idx >= size())
342     resize(Idx + 1);
343
344   if (Value *V = MDValuePtrs[Idx]) {
345     assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
346     return V;
347   }
348
349   // Create and return a placeholder, which will later be RAUW'd.
350   Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
351   MDValuePtrs[Idx] = V;
352   return V;
353 }
354
355 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
356   // If the TypeID is in range, return it.
357   if (ID < TypeList.size())
358     return TypeList[ID].get();
359   if (!isTypeTable) return 0;
360
361   // The type table allows forward references.  Push as many Opaque types as
362   // needed to get up to ID.
363   while (TypeList.size() <= ID)
364     TypeList.push_back(OpaqueType::get(Context));
365   return TypeList.back().get();
366 }
367
368 //===----------------------------------------------------------------------===//
369 //  Functions for parsing blocks from the bitcode file
370 //===----------------------------------------------------------------------===//
371
372 bool BitcodeReader::ParseAttributeBlock() {
373   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
374     return Error("Malformed block record");
375
376   if (!MAttributes.empty())
377     return Error("Multiple PARAMATTR blocks found!");
378
379   SmallVector<uint64_t, 64> Record;
380
381   SmallVector<AttributeWithIndex, 8> Attrs;
382
383   // Read all the records.
384   while (1) {
385     unsigned Code = Stream.ReadCode();
386     if (Code == bitc::END_BLOCK) {
387       if (Stream.ReadBlockEnd())
388         return Error("Error at end of PARAMATTR block");
389       return false;
390     }
391
392     if (Code == bitc::ENTER_SUBBLOCK) {
393       // No known subblocks, always skip them.
394       Stream.ReadSubBlockID();
395       if (Stream.SkipBlock())
396         return Error("Malformed block record");
397       continue;
398     }
399
400     if (Code == bitc::DEFINE_ABBREV) {
401       Stream.ReadAbbrevRecord();
402       continue;
403     }
404
405     // Read a record.
406     Record.clear();
407     switch (Stream.ReadRecord(Code, Record)) {
408     default:  // Default behavior: ignore.
409       break;
410     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
411       if (Record.size() & 1)
412         return Error("Invalid ENTRY record");
413
414       // FIXME : Remove this autoupgrade code in LLVM 3.0.
415       // If Function attributes are using index 0 then transfer them
416       // to index ~0. Index 0 is used for return value attributes but used to be
417       // used for function attributes.
418       Attributes RetAttribute = Attribute::None;
419       Attributes FnAttribute = Attribute::None;
420       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
421         // FIXME: remove in LLVM 3.0
422         // The alignment is stored as a 16-bit raw value from bits 31--16.
423         // We shift the bits above 31 down by 11 bits.
424
425         unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
426         if (Alignment && !isPowerOf2_32(Alignment))
427           return Error("Alignment is not a power of two.");
428
429         Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
430         if (Alignment)
431           ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
432         ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
433         Record[i+1] = ReconstitutedAttr;
434
435         if (Record[i] == 0)
436           RetAttribute = Record[i+1];
437         else if (Record[i] == ~0U)
438           FnAttribute = Record[i+1];
439       }
440
441       unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
442                               Attribute::ReadOnly|Attribute::ReadNone);
443
444       if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
445           (RetAttribute & OldRetAttrs) != 0) {
446         if (FnAttribute == Attribute::None) { // add a slot so they get added.
447           Record.push_back(~0U);
448           Record.push_back(0);
449         }
450
451         FnAttribute  |= RetAttribute & OldRetAttrs;
452         RetAttribute &= ~OldRetAttrs;
453       }
454
455       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
456         if (Record[i] == 0) {
457           if (RetAttribute != Attribute::None)
458             Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
459         } else if (Record[i] == ~0U) {
460           if (FnAttribute != Attribute::None)
461             Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
462         } else if (Record[i+1] != Attribute::None)
463           Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
464       }
465
466       MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
467       Attrs.clear();
468       break;
469     }
470     }
471   }
472 }
473
474
475 bool BitcodeReader::ParseTypeTable() {
476   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
477     return Error("Malformed block record");
478
479   if (!TypeList.empty())
480     return Error("Multiple TYPE_BLOCKs found!");
481
482   SmallVector<uint64_t, 64> Record;
483   unsigned NumRecords = 0;
484
485   // Read all the records for this type table.
486   while (1) {
487     unsigned Code = Stream.ReadCode();
488     if (Code == bitc::END_BLOCK) {
489       if (NumRecords != TypeList.size())
490         return Error("Invalid type forward reference in TYPE_BLOCK");
491       if (Stream.ReadBlockEnd())
492         return Error("Error at end of type table block");
493       return false;
494     }
495
496     if (Code == bitc::ENTER_SUBBLOCK) {
497       // No known subblocks, always skip them.
498       Stream.ReadSubBlockID();
499       if (Stream.SkipBlock())
500         return Error("Malformed block record");
501       continue;
502     }
503
504     if (Code == bitc::DEFINE_ABBREV) {
505       Stream.ReadAbbrevRecord();
506       continue;
507     }
508
509     // Read a record.
510     Record.clear();
511     const Type *ResultTy = 0;
512     switch (Stream.ReadRecord(Code, Record)) {
513     default:  // Default behavior: unknown type.
514       ResultTy = 0;
515       break;
516     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
517       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
518       // type list.  This allows us to reserve space.
519       if (Record.size() < 1)
520         return Error("Invalid TYPE_CODE_NUMENTRY record");
521       TypeList.reserve(Record[0]);
522       continue;
523     case bitc::TYPE_CODE_VOID:      // VOID
524       ResultTy = Type::getVoidTy(Context);
525       break;
526     case bitc::TYPE_CODE_FLOAT:     // FLOAT
527       ResultTy = Type::getFloatTy(Context);
528       break;
529     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
530       ResultTy = Type::getDoubleTy(Context);
531       break;
532     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
533       ResultTy = Type::getX86_FP80Ty(Context);
534       break;
535     case bitc::TYPE_CODE_FP128:     // FP128
536       ResultTy = Type::getFP128Ty(Context);
537       break;
538     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
539       ResultTy = Type::getPPC_FP128Ty(Context);
540       break;
541     case bitc::TYPE_CODE_LABEL:     // LABEL
542       ResultTy = Type::getLabelTy(Context);
543       break;
544     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
545       ResultTy = 0;
546       break;
547     case bitc::TYPE_CODE_METADATA:  // METADATA
548       ResultTy = Type::getMetadataTy(Context);
549       break;
550     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
551       ResultTy = Type::getX86_MMXTy(Context);
552       break;
553     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
554       if (Record.size() < 1)
555         return Error("Invalid Integer type record");
556
557       ResultTy = IntegerType::get(Context, Record[0]);
558       break;
559     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
560                                     //          [pointee type, address space]
561       if (Record.size() < 1)
562         return Error("Invalid POINTER type record");
563       unsigned AddressSpace = 0;
564       if (Record.size() == 2)
565         AddressSpace = Record[1];
566       ResultTy = PointerType::get(getTypeByID(Record[0], true),
567                                         AddressSpace);
568       break;
569     }
570     case bitc::TYPE_CODE_FUNCTION: {
571       // FIXME: attrid is dead, remove it in LLVM 3.0
572       // FUNCTION: [vararg, attrid, retty, paramty x N]
573       if (Record.size() < 3)
574         return Error("Invalid FUNCTION type record");
575       std::vector<const Type*> ArgTys;
576       for (unsigned i = 3, e = Record.size(); i != e; ++i)
577         ArgTys.push_back(getTypeByID(Record[i], true));
578
579       ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
580                                    Record[0]);
581       break;
582     }
583     case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
584       if (Record.size() < 1)
585         return Error("Invalid STRUCT type record");
586       std::vector<const Type*> EltTys;
587       for (unsigned i = 1, e = Record.size(); i != e; ++i)
588         EltTys.push_back(getTypeByID(Record[i], true));
589       ResultTy = StructType::get(Context, EltTys, Record[0]);
590       break;
591     }
592     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
593       if (Record.size() < 2)
594         return Error("Invalid ARRAY type record");
595       ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
596       break;
597     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
598       if (Record.size() < 2)
599         return Error("Invalid VECTOR type record");
600       ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
601       break;
602     }
603
604     if (NumRecords == TypeList.size()) {
605       // If this is a new type slot, just append it.
606       TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
607       ++NumRecords;
608     } else if (ResultTy == 0) {
609       // Otherwise, this was forward referenced, so an opaque type was created,
610       // but the result type is actually just an opaque.  Leave the one we
611       // created previously.
612       ++NumRecords;
613     } else {
614       // Otherwise, this was forward referenced, so an opaque type was created.
615       // Resolve the opaque type to the real type now.
616       assert(NumRecords < TypeList.size() && "Typelist imbalance");
617       const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
618
619       // Don't directly push the new type on the Tab. Instead we want to replace
620       // the opaque type we previously inserted with the new concrete value. The
621       // refinement from the abstract (opaque) type to the new type causes all
622       // uses of the abstract type to use the concrete type (NewTy). This will
623       // also cause the opaque type to be deleted.
624       const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
625
626       // This should have replaced the old opaque type with the new type in the
627       // value table... or with a preexisting type that was already in the
628       // system.  Let's just make sure it did.
629       assert(TypeList[NumRecords-1].get() != OldTy &&
630              "refineAbstractType didn't work!");
631     }
632   }
633 }
634
635
636 bool BitcodeReader::ParseTypeSymbolTable() {
637   if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
638     return Error("Malformed block record");
639
640   SmallVector<uint64_t, 64> Record;
641
642   // Read all the records for this type table.
643   std::string TypeName;
644   while (1) {
645     unsigned Code = Stream.ReadCode();
646     if (Code == bitc::END_BLOCK) {
647       if (Stream.ReadBlockEnd())
648         return Error("Error at end of type symbol table block");
649       return false;
650     }
651
652     if (Code == bitc::ENTER_SUBBLOCK) {
653       // No known subblocks, always skip them.
654       Stream.ReadSubBlockID();
655       if (Stream.SkipBlock())
656         return Error("Malformed block record");
657       continue;
658     }
659
660     if (Code == bitc::DEFINE_ABBREV) {
661       Stream.ReadAbbrevRecord();
662       continue;
663     }
664
665     // Read a record.
666     Record.clear();
667     switch (Stream.ReadRecord(Code, Record)) {
668     default:  // Default behavior: unknown type.
669       break;
670     case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
671       if (ConvertToString(Record, 1, TypeName))
672         return Error("Invalid TST_ENTRY record");
673       unsigned TypeID = Record[0];
674       if (TypeID >= TypeList.size())
675         return Error("Invalid Type ID in TST_ENTRY record");
676
677       TheModule->addTypeName(TypeName, TypeList[TypeID].get());
678       TypeName.clear();
679       break;
680     }
681   }
682 }
683
684 bool BitcodeReader::ParseValueSymbolTable() {
685   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
686     return Error("Malformed block record");
687
688   SmallVector<uint64_t, 64> Record;
689
690   // Read all the records for this value table.
691   SmallString<128> ValueName;
692   while (1) {
693     unsigned Code = Stream.ReadCode();
694     if (Code == bitc::END_BLOCK) {
695       if (Stream.ReadBlockEnd())
696         return Error("Error at end of value symbol table block");
697       return false;
698     }
699     if (Code == bitc::ENTER_SUBBLOCK) {
700       // No known subblocks, always skip them.
701       Stream.ReadSubBlockID();
702       if (Stream.SkipBlock())
703         return Error("Malformed block record");
704       continue;
705     }
706
707     if (Code == bitc::DEFINE_ABBREV) {
708       Stream.ReadAbbrevRecord();
709       continue;
710     }
711
712     // Read a record.
713     Record.clear();
714     switch (Stream.ReadRecord(Code, Record)) {
715     default:  // Default behavior: unknown type.
716       break;
717     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
718       if (ConvertToString(Record, 1, ValueName))
719         return Error("Invalid VST_ENTRY record");
720       unsigned ValueID = Record[0];
721       if (ValueID >= ValueList.size())
722         return Error("Invalid Value ID in VST_ENTRY record");
723       Value *V = ValueList[ValueID];
724
725       V->setName(StringRef(ValueName.data(), ValueName.size()));
726       ValueName.clear();
727       break;
728     }
729     case bitc::VST_CODE_BBENTRY: {
730       if (ConvertToString(Record, 1, ValueName))
731         return Error("Invalid VST_BBENTRY record");
732       BasicBlock *BB = getBasicBlock(Record[0]);
733       if (BB == 0)
734         return Error("Invalid BB ID in VST_BBENTRY record");
735
736       BB->setName(StringRef(ValueName.data(), ValueName.size()));
737       ValueName.clear();
738       break;
739     }
740     }
741   }
742 }
743
744 bool BitcodeReader::ParseMetadata() {
745   unsigned NextMDValueNo = MDValueList.size();
746
747   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
748     return Error("Malformed block record");
749
750   SmallVector<uint64_t, 64> Record;
751
752   // Read all the records.
753   while (1) {
754     unsigned Code = Stream.ReadCode();
755     if (Code == bitc::END_BLOCK) {
756       if (Stream.ReadBlockEnd())
757         return Error("Error at end of PARAMATTR block");
758       return false;
759     }
760
761     if (Code == bitc::ENTER_SUBBLOCK) {
762       // No known subblocks, always skip them.
763       Stream.ReadSubBlockID();
764       if (Stream.SkipBlock())
765         return Error("Malformed block record");
766       continue;
767     }
768
769     if (Code == bitc::DEFINE_ABBREV) {
770       Stream.ReadAbbrevRecord();
771       continue;
772     }
773
774     bool IsFunctionLocal = false;
775     // Read a record.
776     Record.clear();
777     Code = Stream.ReadRecord(Code, Record);
778     switch (Code) {
779     default:  // Default behavior: ignore.
780       break;
781     case bitc::METADATA_NAME: {
782       // Read named of the named metadata.
783       unsigned NameLength = Record.size();
784       SmallString<8> Name;
785       Name.resize(NameLength);
786       for (unsigned i = 0; i != NameLength; ++i)
787         Name[i] = Record[i];
788       Record.clear();
789       Code = Stream.ReadCode();
790
791       // METADATA_NAME is always followed by METADATA_NAMED_NODE.
792       unsigned NextBitCode = Stream.ReadRecord(Code, Record);
793       assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
794
795       // Read named metadata elements.
796       unsigned Size = Record.size();
797       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
798       for (unsigned i = 0; i != Size; ++i) {
799         MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
800         if (MD == 0)
801           return Error("Malformed metadata record");
802         NMD->addOperand(MD);
803       }
804       break;
805     }
806     case bitc::METADATA_FN_NODE:
807       IsFunctionLocal = true;
808       // fall-through
809     case bitc::METADATA_NODE: {
810       if (Record.size() % 2 == 1)
811         return Error("Invalid METADATA_NODE record");
812
813       unsigned Size = Record.size();
814       SmallVector<Value*, 8> Elts;
815       for (unsigned i = 0; i != Size; i += 2) {
816         const Type *Ty = getTypeByID(Record[i]);
817         if (!Ty) return Error("Invalid METADATA_NODE record");
818         if (Ty->isMetadataTy())
819           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
820         else if (!Ty->isVoidTy())
821           Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
822         else
823           Elts.push_back(NULL);
824       }
825       Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
826       IsFunctionLocal = false;
827       MDValueList.AssignValue(V, NextMDValueNo++);
828       break;
829     }
830     case bitc::METADATA_STRING: {
831       unsigned MDStringLength = Record.size();
832       SmallString<8> String;
833       String.resize(MDStringLength);
834       for (unsigned i = 0; i != MDStringLength; ++i)
835         String[i] = Record[i];
836       Value *V = MDString::get(Context,
837                                StringRef(String.data(), String.size()));
838       MDValueList.AssignValue(V, NextMDValueNo++);
839       break;
840     }
841     case bitc::METADATA_KIND: {
842       unsigned RecordLength = Record.size();
843       if (Record.empty() || RecordLength < 2)
844         return Error("Invalid METADATA_KIND record");
845       SmallString<8> Name;
846       Name.resize(RecordLength-1);
847       unsigned Kind = Record[0];
848       for (unsigned i = 1; i != RecordLength; ++i)
849         Name[i-1] = Record[i];
850       
851       unsigned NewKind = TheModule->getMDKindID(Name.str());
852       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
853         return Error("Conflicting METADATA_KIND records");
854       break;
855     }
856     }
857   }
858 }
859
860 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
861 /// the LSB for dense VBR encoding.
862 static uint64_t DecodeSignRotatedValue(uint64_t V) {
863   if ((V & 1) == 0)
864     return V >> 1;
865   if (V != 1)
866     return -(V >> 1);
867   // There is no such thing as -0 with integers.  "-0" really means MININT.
868   return 1ULL << 63;
869 }
870
871 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
872 /// values and aliases that we can.
873 bool BitcodeReader::ResolveGlobalAndAliasInits() {
874   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
875   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
876
877   GlobalInitWorklist.swap(GlobalInits);
878   AliasInitWorklist.swap(AliasInits);
879
880   while (!GlobalInitWorklist.empty()) {
881     unsigned ValID = GlobalInitWorklist.back().second;
882     if (ValID >= ValueList.size()) {
883       // Not ready to resolve this yet, it requires something later in the file.
884       GlobalInits.push_back(GlobalInitWorklist.back());
885     } else {
886       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
887         GlobalInitWorklist.back().first->setInitializer(C);
888       else
889         return Error("Global variable initializer is not a constant!");
890     }
891     GlobalInitWorklist.pop_back();
892   }
893
894   while (!AliasInitWorklist.empty()) {
895     unsigned ValID = AliasInitWorklist.back().second;
896     if (ValID >= ValueList.size()) {
897       AliasInits.push_back(AliasInitWorklist.back());
898     } else {
899       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
900         AliasInitWorklist.back().first->setAliasee(C);
901       else
902         return Error("Alias initializer is not a constant!");
903     }
904     AliasInitWorklist.pop_back();
905   }
906   return false;
907 }
908
909 bool BitcodeReader::ParseConstants() {
910   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
911     return Error("Malformed block record");
912
913   SmallVector<uint64_t, 64> Record;
914
915   // Read all the records for this value table.
916   const Type *CurTy = Type::getInt32Ty(Context);
917   unsigned NextCstNo = ValueList.size();
918   while (1) {
919     unsigned Code = Stream.ReadCode();
920     if (Code == bitc::END_BLOCK)
921       break;
922
923     if (Code == bitc::ENTER_SUBBLOCK) {
924       // No known subblocks, always skip them.
925       Stream.ReadSubBlockID();
926       if (Stream.SkipBlock())
927         return Error("Malformed block record");
928       continue;
929     }
930
931     if (Code == bitc::DEFINE_ABBREV) {
932       Stream.ReadAbbrevRecord();
933       continue;
934     }
935
936     // Read a record.
937     Record.clear();
938     Value *V = 0;
939     unsigned BitCode = Stream.ReadRecord(Code, Record);
940     switch (BitCode) {
941     default:  // Default behavior: unknown constant
942     case bitc::CST_CODE_UNDEF:     // UNDEF
943       V = UndefValue::get(CurTy);
944       break;
945     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
946       if (Record.empty())
947         return Error("Malformed CST_SETTYPE record");
948       if (Record[0] >= TypeList.size())
949         return Error("Invalid Type ID in CST_SETTYPE record");
950       CurTy = TypeList[Record[0]];
951       continue;  // Skip the ValueList manipulation.
952     case bitc::CST_CODE_NULL:      // NULL
953       V = Constant::getNullValue(CurTy);
954       break;
955     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
956       if (!CurTy->isIntegerTy() || Record.empty())
957         return Error("Invalid CST_INTEGER record");
958       V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
959       break;
960     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
961       if (!CurTy->isIntegerTy() || Record.empty())
962         return Error("Invalid WIDE_INTEGER record");
963
964       unsigned NumWords = Record.size();
965       SmallVector<uint64_t, 8> Words;
966       Words.resize(NumWords);
967       for (unsigned i = 0; i != NumWords; ++i)
968         Words[i] = DecodeSignRotatedValue(Record[i]);
969       V = ConstantInt::get(Context,
970                            APInt(cast<IntegerType>(CurTy)->getBitWidth(),
971                            NumWords, &Words[0]));
972       break;
973     }
974     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
975       if (Record.empty())
976         return Error("Invalid FLOAT record");
977       if (CurTy->isFloatTy())
978         V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
979       else if (CurTy->isDoubleTy())
980         V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
981       else if (CurTy->isX86_FP80Ty()) {
982         // Bits are not stored the same way as a normal i80 APInt, compensate.
983         uint64_t Rearrange[2];
984         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
985         Rearrange[1] = Record[0] >> 48;
986         V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
987       } else if (CurTy->isFP128Ty())
988         V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
989       else if (CurTy->isPPC_FP128Ty())
990         V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
991       else
992         V = UndefValue::get(CurTy);
993       break;
994     }
995
996     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
997       if (Record.empty())
998         return Error("Invalid CST_AGGREGATE record");
999
1000       unsigned Size = Record.size();
1001       std::vector<Constant*> Elts;
1002
1003       if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
1004         for (unsigned i = 0; i != Size; ++i)
1005           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1006                                                      STy->getElementType(i)));
1007         V = ConstantStruct::get(STy, Elts);
1008       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1009         const Type *EltTy = ATy->getElementType();
1010         for (unsigned i = 0; i != Size; ++i)
1011           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1012         V = ConstantArray::get(ATy, Elts);
1013       } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1014         const Type *EltTy = VTy->getElementType();
1015         for (unsigned i = 0; i != Size; ++i)
1016           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1017         V = ConstantVector::get(Elts);
1018       } else {
1019         V = UndefValue::get(CurTy);
1020       }
1021       break;
1022     }
1023     case bitc::CST_CODE_STRING: { // STRING: [values]
1024       if (Record.empty())
1025         return Error("Invalid CST_AGGREGATE record");
1026
1027       const ArrayType *ATy = cast<ArrayType>(CurTy);
1028       const Type *EltTy = ATy->getElementType();
1029
1030       unsigned Size = Record.size();
1031       std::vector<Constant*> Elts;
1032       for (unsigned i = 0; i != Size; ++i)
1033         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1034       V = ConstantArray::get(ATy, Elts);
1035       break;
1036     }
1037     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1038       if (Record.empty())
1039         return Error("Invalid CST_AGGREGATE record");
1040
1041       const ArrayType *ATy = cast<ArrayType>(CurTy);
1042       const Type *EltTy = ATy->getElementType();
1043
1044       unsigned Size = Record.size();
1045       std::vector<Constant*> Elts;
1046       for (unsigned i = 0; i != Size; ++i)
1047         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1048       Elts.push_back(Constant::getNullValue(EltTy));
1049       V = ConstantArray::get(ATy, Elts);
1050       break;
1051     }
1052     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1053       if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1054       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1055       if (Opc < 0) {
1056         V = UndefValue::get(CurTy);  // Unknown binop.
1057       } else {
1058         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1059         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1060         unsigned Flags = 0;
1061         if (Record.size() >= 4) {
1062           if (Opc == Instruction::Add ||
1063               Opc == Instruction::Sub ||
1064               Opc == Instruction::Mul ||
1065               Opc == Instruction::Shl) {
1066             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1067               Flags |= OverflowingBinaryOperator::NoSignedWrap;
1068             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1069               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1070           } else if (Opc == Instruction::SDiv ||
1071                      Opc == Instruction::UDiv ||
1072                      Opc == Instruction::LShr ||
1073                      Opc == Instruction::AShr) {
1074             if (Record[3] & (1 << bitc::PEO_EXACT))
1075               Flags |= SDivOperator::IsExact;
1076           }
1077         }
1078         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1079       }
1080       break;
1081     }
1082     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1083       if (Record.size() < 3) return Error("Invalid CE_CAST record");
1084       int Opc = GetDecodedCastOpcode(Record[0]);
1085       if (Opc < 0) {
1086         V = UndefValue::get(CurTy);  // Unknown cast.
1087       } else {
1088         const Type *OpTy = getTypeByID(Record[1]);
1089         if (!OpTy) return Error("Invalid CE_CAST record");
1090         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1091         V = ConstantExpr::getCast(Opc, Op, CurTy);
1092       }
1093       break;
1094     }
1095     case bitc::CST_CODE_CE_INBOUNDS_GEP:
1096     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1097       if (Record.size() & 1) return Error("Invalid CE_GEP record");
1098       SmallVector<Constant*, 16> Elts;
1099       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1100         const Type *ElTy = getTypeByID(Record[i]);
1101         if (!ElTy) return Error("Invalid CE_GEP record");
1102         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1103       }
1104       if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1105         V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
1106                                                    Elts.size()-1);
1107       else
1108         V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
1109                                            Elts.size()-1);
1110       break;
1111     }
1112     case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
1113       if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1114       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1115                                                               Type::getInt1Ty(Context)),
1116                                   ValueList.getConstantFwdRef(Record[1],CurTy),
1117                                   ValueList.getConstantFwdRef(Record[2],CurTy));
1118       break;
1119     case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1120       if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1121       const VectorType *OpTy =
1122         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1123       if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1124       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1125       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1126       V = ConstantExpr::getExtractElement(Op0, Op1);
1127       break;
1128     }
1129     case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1130       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1131       if (Record.size() < 3 || OpTy == 0)
1132         return Error("Invalid CE_INSERTELT record");
1133       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1134       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1135                                                   OpTy->getElementType());
1136       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1137       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1138       break;
1139     }
1140     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1141       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1142       if (Record.size() < 3 || OpTy == 0)
1143         return Error("Invalid CE_SHUFFLEVEC record");
1144       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1145       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1146       const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1147                                                  OpTy->getNumElements());
1148       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1149       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1150       break;
1151     }
1152     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1153       const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1154       const VectorType *OpTy =
1155         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1156       if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1157         return Error("Invalid CE_SHUFVEC_EX record");
1158       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1159       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1160       const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1161                                                  RTy->getNumElements());
1162       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1163       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1164       break;
1165     }
1166     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1167       if (Record.size() < 4) return Error("Invalid CE_CMP record");
1168       const Type *OpTy = getTypeByID(Record[0]);
1169       if (OpTy == 0) return Error("Invalid CE_CMP record");
1170       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1171       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1172
1173       if (OpTy->isFPOrFPVectorTy())
1174         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1175       else
1176         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1177       break;
1178     }
1179     case bitc::CST_CODE_INLINEASM: {
1180       if (Record.size() < 2) return Error("Invalid INLINEASM record");
1181       std::string AsmStr, ConstrStr;
1182       bool HasSideEffects = Record[0] & 1;
1183       bool IsAlignStack = Record[0] >> 1;
1184       unsigned AsmStrSize = Record[1];
1185       if (2+AsmStrSize >= Record.size())
1186         return Error("Invalid INLINEASM record");
1187       unsigned ConstStrSize = Record[2+AsmStrSize];
1188       if (3+AsmStrSize+ConstStrSize > Record.size())
1189         return Error("Invalid INLINEASM record");
1190
1191       for (unsigned i = 0; i != AsmStrSize; ++i)
1192         AsmStr += (char)Record[2+i];
1193       for (unsigned i = 0; i != ConstStrSize; ++i)
1194         ConstrStr += (char)Record[3+AsmStrSize+i];
1195       const PointerType *PTy = cast<PointerType>(CurTy);
1196       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1197                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1198       break;
1199     }
1200     case bitc::CST_CODE_BLOCKADDRESS:{
1201       if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1202       const Type *FnTy = getTypeByID(Record[0]);
1203       if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1204       Function *Fn =
1205         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1206       if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1207       
1208       GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1209                                                   Type::getInt8Ty(Context),
1210                                             false, GlobalValue::InternalLinkage,
1211                                                   0, "");
1212       BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1213       V = FwdRef;
1214       break;
1215     }  
1216     }
1217
1218     ValueList.AssignValue(V, NextCstNo);
1219     ++NextCstNo;
1220   }
1221
1222   if (NextCstNo != ValueList.size())
1223     return Error("Invalid constant reference!");
1224
1225   if (Stream.ReadBlockEnd())
1226     return Error("Error at end of constants block");
1227
1228   // Once all the constants have been read, go through and resolve forward
1229   // references.
1230   ValueList.ResolveConstantForwardRefs();
1231   return false;
1232 }
1233
1234 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1235 /// remember where it is and then skip it.  This lets us lazily deserialize the
1236 /// functions.
1237 bool BitcodeReader::RememberAndSkipFunctionBody() {
1238   // Get the function we are talking about.
1239   if (FunctionsWithBodies.empty())
1240     return Error("Insufficient function protos");
1241
1242   Function *Fn = FunctionsWithBodies.back();
1243   FunctionsWithBodies.pop_back();
1244
1245   // Save the current stream state.
1246   uint64_t CurBit = Stream.GetCurrentBitNo();
1247   DeferredFunctionInfo[Fn] = CurBit;
1248
1249   // Skip over the function block for now.
1250   if (Stream.SkipBlock())
1251     return Error("Malformed block record");
1252   return false;
1253 }
1254
1255 bool BitcodeReader::ParseModule() {
1256   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1257     return Error("Malformed block record");
1258
1259   SmallVector<uint64_t, 64> Record;
1260   std::vector<std::string> SectionTable;
1261   std::vector<std::string> GCTable;
1262
1263   // Read all the records for this module.
1264   while (!Stream.AtEndOfStream()) {
1265     unsigned Code = Stream.ReadCode();
1266     if (Code == bitc::END_BLOCK) {
1267       if (Stream.ReadBlockEnd())
1268         return Error("Error at end of module block");
1269
1270       // Patch the initializers for globals and aliases up.
1271       ResolveGlobalAndAliasInits();
1272       if (!GlobalInits.empty() || !AliasInits.empty())
1273         return Error("Malformed global initializer set");
1274       if (!FunctionsWithBodies.empty())
1275         return Error("Too few function bodies found");
1276
1277       // Look for intrinsic functions which need to be upgraded at some point
1278       for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1279            FI != FE; ++FI) {
1280         Function* NewFn;
1281         if (UpgradeIntrinsicFunction(FI, NewFn))
1282           UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1283       }
1284
1285       // Look for global variables which need to be renamed.
1286       for (Module::global_iterator
1287              GI = TheModule->global_begin(), GE = TheModule->global_end();
1288            GI != GE; ++GI)
1289         UpgradeGlobalVariable(GI);
1290
1291       // Force deallocation of memory for these vectors to favor the client that
1292       // want lazy deserialization.
1293       std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1294       std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1295       std::vector<Function*>().swap(FunctionsWithBodies);
1296       return false;
1297     }
1298
1299     if (Code == bitc::ENTER_SUBBLOCK) {
1300       switch (Stream.ReadSubBlockID()) {
1301       default:  // Skip unknown content.
1302         if (Stream.SkipBlock())
1303           return Error("Malformed block record");
1304         break;
1305       case bitc::BLOCKINFO_BLOCK_ID:
1306         if (Stream.ReadBlockInfoBlock())
1307           return Error("Malformed BlockInfoBlock");
1308         break;
1309       case bitc::PARAMATTR_BLOCK_ID:
1310         if (ParseAttributeBlock())
1311           return true;
1312         break;
1313       case bitc::TYPE_BLOCK_ID:
1314         if (ParseTypeTable())
1315           return true;
1316         break;
1317       case bitc::TYPE_SYMTAB_BLOCK_ID:
1318         if (ParseTypeSymbolTable())
1319           return true;
1320         break;
1321       case bitc::VALUE_SYMTAB_BLOCK_ID:
1322         if (ParseValueSymbolTable())
1323           return true;
1324         break;
1325       case bitc::CONSTANTS_BLOCK_ID:
1326         if (ParseConstants() || ResolveGlobalAndAliasInits())
1327           return true;
1328         break;
1329       case bitc::METADATA_BLOCK_ID:
1330         if (ParseMetadata())
1331           return true;
1332         break;
1333       case bitc::FUNCTION_BLOCK_ID:
1334         // If this is the first function body we've seen, reverse the
1335         // FunctionsWithBodies list.
1336         if (!HasReversedFunctionsWithBodies) {
1337           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1338           HasReversedFunctionsWithBodies = true;
1339         }
1340
1341         if (RememberAndSkipFunctionBody())
1342           return true;
1343         break;
1344       }
1345       continue;
1346     }
1347
1348     if (Code == bitc::DEFINE_ABBREV) {
1349       Stream.ReadAbbrevRecord();
1350       continue;
1351     }
1352
1353     // Read a record.
1354     switch (Stream.ReadRecord(Code, Record)) {
1355     default: break;  // Default behavior, ignore unknown content.
1356     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1357       if (Record.size() < 1)
1358         return Error("Malformed MODULE_CODE_VERSION");
1359       // Only version #0 is supported so far.
1360       if (Record[0] != 0)
1361         return Error("Unknown bitstream version!");
1362       break;
1363     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1364       std::string S;
1365       if (ConvertToString(Record, 0, S))
1366         return Error("Invalid MODULE_CODE_TRIPLE record");
1367       TheModule->setTargetTriple(S);
1368       break;
1369     }
1370     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1371       std::string S;
1372       if (ConvertToString(Record, 0, S))
1373         return Error("Invalid MODULE_CODE_DATALAYOUT record");
1374       TheModule->setDataLayout(S);
1375       break;
1376     }
1377     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1378       std::string S;
1379       if (ConvertToString(Record, 0, S))
1380         return Error("Invalid MODULE_CODE_ASM record");
1381       TheModule->setModuleInlineAsm(S);
1382       break;
1383     }
1384     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1385       std::string S;
1386       if (ConvertToString(Record, 0, S))
1387         return Error("Invalid MODULE_CODE_DEPLIB record");
1388       TheModule->addLibrary(S);
1389       break;
1390     }
1391     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1392       std::string S;
1393       if (ConvertToString(Record, 0, S))
1394         return Error("Invalid MODULE_CODE_SECTIONNAME record");
1395       SectionTable.push_back(S);
1396       break;
1397     }
1398     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1399       std::string S;
1400       if (ConvertToString(Record, 0, S))
1401         return Error("Invalid MODULE_CODE_GCNAME record");
1402       GCTable.push_back(S);
1403       break;
1404     }
1405     // GLOBALVAR: [pointer type, isconst, initid,
1406     //             linkage, alignment, section, visibility, threadlocal,
1407     //             unnamed_addr]
1408     case bitc::MODULE_CODE_GLOBALVAR: {
1409       if (Record.size() < 6)
1410         return Error("Invalid MODULE_CODE_GLOBALVAR record");
1411       const Type *Ty = getTypeByID(Record[0]);
1412       if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1413       if (!Ty->isPointerTy())
1414         return Error("Global not a pointer type!");
1415       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1416       Ty = cast<PointerType>(Ty)->getElementType();
1417
1418       bool isConstant = Record[1];
1419       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1420       unsigned Alignment = (1 << Record[4]) >> 1;
1421       std::string Section;
1422       if (Record[5]) {
1423         if (Record[5]-1 >= SectionTable.size())
1424           return Error("Invalid section ID");
1425         Section = SectionTable[Record[5]-1];
1426       }
1427       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1428       if (Record.size() > 6)
1429         Visibility = GetDecodedVisibility(Record[6]);
1430       bool isThreadLocal = false;
1431       if (Record.size() > 7)
1432         isThreadLocal = Record[7];
1433
1434       bool UnnamedAddr = false;
1435       if (Record.size() > 8)
1436         UnnamedAddr = Record[8];
1437
1438       GlobalVariable *NewGV =
1439         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1440                            isThreadLocal, AddressSpace);
1441       NewGV->setAlignment(Alignment);
1442       if (!Section.empty())
1443         NewGV->setSection(Section);
1444       NewGV->setVisibility(Visibility);
1445       NewGV->setThreadLocal(isThreadLocal);
1446       NewGV->setUnnamedAddr(UnnamedAddr);
1447
1448       ValueList.push_back(NewGV);
1449
1450       // Remember which value to use for the global initializer.
1451       if (unsigned InitID = Record[2])
1452         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1453       break;
1454     }
1455     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1456     //             alignment, section, visibility, gc, unnamed_addr]
1457     case bitc::MODULE_CODE_FUNCTION: {
1458       if (Record.size() < 8)
1459         return Error("Invalid MODULE_CODE_FUNCTION record");
1460       const Type *Ty = getTypeByID(Record[0]);
1461       if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1462       if (!Ty->isPointerTy())
1463         return Error("Function not a pointer type!");
1464       const FunctionType *FTy =
1465         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1466       if (!FTy)
1467         return Error("Function not a pointer to function type!");
1468
1469       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1470                                         "", TheModule);
1471
1472       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1473       bool isProto = Record[2];
1474       Func->setLinkage(GetDecodedLinkage(Record[3]));
1475       Func->setAttributes(getAttributes(Record[4]));
1476
1477       Func->setAlignment((1 << Record[5]) >> 1);
1478       if (Record[6]) {
1479         if (Record[6]-1 >= SectionTable.size())
1480           return Error("Invalid section ID");
1481         Func->setSection(SectionTable[Record[6]-1]);
1482       }
1483       Func->setVisibility(GetDecodedVisibility(Record[7]));
1484       if (Record.size() > 8 && Record[8]) {
1485         if (Record[8]-1 > GCTable.size())
1486           return Error("Invalid GC ID");
1487         Func->setGC(GCTable[Record[8]-1].c_str());
1488       }
1489       bool UnnamedAddr = false;
1490       if (Record.size() > 9)
1491         UnnamedAddr = Record[9];
1492       Func->setUnnamedAddr(UnnamedAddr);
1493       ValueList.push_back(Func);
1494
1495       // If this is a function with a body, remember the prototype we are
1496       // creating now, so that we can match up the body with them later.
1497       if (!isProto)
1498         FunctionsWithBodies.push_back(Func);
1499       break;
1500     }
1501     // ALIAS: [alias type, aliasee val#, linkage]
1502     // ALIAS: [alias type, aliasee val#, linkage, visibility]
1503     case bitc::MODULE_CODE_ALIAS: {
1504       if (Record.size() < 3)
1505         return Error("Invalid MODULE_ALIAS record");
1506       const Type *Ty = getTypeByID(Record[0]);
1507       if (!Ty) return Error("Invalid MODULE_ALIAS record");
1508       if (!Ty->isPointerTy())
1509         return Error("Function not a pointer type!");
1510
1511       GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1512                                            "", 0, TheModule);
1513       // Old bitcode files didn't have visibility field.
1514       if (Record.size() > 3)
1515         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1516       ValueList.push_back(NewGA);
1517       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1518       break;
1519     }
1520     /// MODULE_CODE_PURGEVALS: [numvals]
1521     case bitc::MODULE_CODE_PURGEVALS:
1522       // Trim down the value list to the specified size.
1523       if (Record.size() < 1 || Record[0] > ValueList.size())
1524         return Error("Invalid MODULE_PURGEVALS record");
1525       ValueList.shrinkTo(Record[0]);
1526       break;
1527     }
1528     Record.clear();
1529   }
1530
1531   return Error("Premature end of bitstream");
1532 }
1533
1534 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1535   TheModule = 0;
1536
1537   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1538   unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1539
1540   if (Buffer->getBufferSize() & 3) {
1541     if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1542       return Error("Invalid bitcode signature");
1543     else
1544       return Error("Bitcode stream should be a multiple of 4 bytes in length");
1545   }
1546
1547   // If we have a wrapper header, parse it and ignore the non-bc file contents.
1548   // The magic number is 0x0B17C0DE stored in little endian.
1549   if (isBitcodeWrapper(BufPtr, BufEnd))
1550     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1551       return Error("Invalid bitcode wrapper header");
1552
1553   StreamFile.init(BufPtr, BufEnd);
1554   Stream.init(StreamFile);
1555
1556   // Sniff for the signature.
1557   if (Stream.Read(8) != 'B' ||
1558       Stream.Read(8) != 'C' ||
1559       Stream.Read(4) != 0x0 ||
1560       Stream.Read(4) != 0xC ||
1561       Stream.Read(4) != 0xE ||
1562       Stream.Read(4) != 0xD)
1563     return Error("Invalid bitcode signature");
1564
1565   // We expect a number of well-defined blocks, though we don't necessarily
1566   // need to understand them all.
1567   while (!Stream.AtEndOfStream()) {
1568     unsigned Code = Stream.ReadCode();
1569
1570     if (Code != bitc::ENTER_SUBBLOCK) {
1571
1572       // The ranlib in xcode 4 will align archive members by appending newlines to the
1573       // end of them. If this file size is a multiple of 4 but not 8, we have to read and
1574       // ignore these final 4 bytes :-(
1575       if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1576           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1577           Stream.AtEndOfStream())
1578         return false;
1579
1580       return Error("Invalid record at top-level");
1581     }
1582
1583     unsigned BlockID = Stream.ReadSubBlockID();
1584
1585     // We only know the MODULE subblock ID.
1586     switch (BlockID) {
1587     case bitc::BLOCKINFO_BLOCK_ID:
1588       if (Stream.ReadBlockInfoBlock())
1589         return Error("Malformed BlockInfoBlock");
1590       break;
1591     case bitc::MODULE_BLOCK_ID:
1592       // Reject multiple MODULE_BLOCK's in a single bitstream.
1593       if (TheModule)
1594         return Error("Multiple MODULE_BLOCKs in same stream");
1595       TheModule = M;
1596       if (ParseModule())
1597         return true;
1598       break;
1599     default:
1600       if (Stream.SkipBlock())
1601         return Error("Malformed block record");
1602       break;
1603     }
1604   }
1605
1606   return false;
1607 }
1608
1609 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1610   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1611     return Error("Malformed block record");
1612
1613   SmallVector<uint64_t, 64> Record;
1614
1615   // Read all the records for this module.
1616   while (!Stream.AtEndOfStream()) {
1617     unsigned Code = Stream.ReadCode();
1618     if (Code == bitc::END_BLOCK) {
1619       if (Stream.ReadBlockEnd())
1620         return Error("Error at end of module block");
1621
1622       return false;
1623     }
1624
1625     if (Code == bitc::ENTER_SUBBLOCK) {
1626       switch (Stream.ReadSubBlockID()) {
1627       default:  // Skip unknown content.
1628         if (Stream.SkipBlock())
1629           return Error("Malformed block record");
1630         break;
1631       }
1632       continue;
1633     }
1634
1635     if (Code == bitc::DEFINE_ABBREV) {
1636       Stream.ReadAbbrevRecord();
1637       continue;
1638     }
1639
1640     // Read a record.
1641     switch (Stream.ReadRecord(Code, Record)) {
1642     default: break;  // Default behavior, ignore unknown content.
1643     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1644       if (Record.size() < 1)
1645         return Error("Malformed MODULE_CODE_VERSION");
1646       // Only version #0 is supported so far.
1647       if (Record[0] != 0)
1648         return Error("Unknown bitstream version!");
1649       break;
1650     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1651       std::string S;
1652       if (ConvertToString(Record, 0, S))
1653         return Error("Invalid MODULE_CODE_TRIPLE record");
1654       Triple = S;
1655       break;
1656     }
1657     }
1658     Record.clear();
1659   }
1660
1661   return Error("Premature end of bitstream");
1662 }
1663
1664 bool BitcodeReader::ParseTriple(std::string &Triple) {
1665   if (Buffer->getBufferSize() & 3)
1666     return Error("Bitcode stream should be a multiple of 4 bytes in length");
1667
1668   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1669   unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1670
1671   // If we have a wrapper header, parse it and ignore the non-bc file contents.
1672   // The magic number is 0x0B17C0DE stored in little endian.
1673   if (isBitcodeWrapper(BufPtr, BufEnd))
1674     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1675       return Error("Invalid bitcode wrapper header");
1676
1677   StreamFile.init(BufPtr, BufEnd);
1678   Stream.init(StreamFile);
1679
1680   // Sniff for the signature.
1681   if (Stream.Read(8) != 'B' ||
1682       Stream.Read(8) != 'C' ||
1683       Stream.Read(4) != 0x0 ||
1684       Stream.Read(4) != 0xC ||
1685       Stream.Read(4) != 0xE ||
1686       Stream.Read(4) != 0xD)
1687     return Error("Invalid bitcode signature");
1688
1689   // We expect a number of well-defined blocks, though we don't necessarily
1690   // need to understand them all.
1691   while (!Stream.AtEndOfStream()) {
1692     unsigned Code = Stream.ReadCode();
1693
1694     if (Code != bitc::ENTER_SUBBLOCK)
1695       return Error("Invalid record at top-level");
1696
1697     unsigned BlockID = Stream.ReadSubBlockID();
1698
1699     // We only know the MODULE subblock ID.
1700     switch (BlockID) {
1701     case bitc::MODULE_BLOCK_ID:
1702       if (ParseModuleTriple(Triple))
1703         return true;
1704       break;
1705     default:
1706       if (Stream.SkipBlock())
1707         return Error("Malformed block record");
1708       break;
1709     }
1710   }
1711
1712   return false;
1713 }
1714
1715 /// ParseMetadataAttachment - Parse metadata attachments.
1716 bool BitcodeReader::ParseMetadataAttachment() {
1717   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1718     return Error("Malformed block record");
1719
1720   SmallVector<uint64_t, 64> Record;
1721   while(1) {
1722     unsigned Code = Stream.ReadCode();
1723     if (Code == bitc::END_BLOCK) {
1724       if (Stream.ReadBlockEnd())
1725         return Error("Error at end of PARAMATTR block");
1726       break;
1727     }
1728     if (Code == bitc::DEFINE_ABBREV) {
1729       Stream.ReadAbbrevRecord();
1730       continue;
1731     }
1732     // Read a metadata attachment record.
1733     Record.clear();
1734     switch (Stream.ReadRecord(Code, Record)) {
1735     default:  // Default behavior: ignore.
1736       break;
1737     case bitc::METADATA_ATTACHMENT: {
1738       unsigned RecordLength = Record.size();
1739       if (Record.empty() || (RecordLength - 1) % 2 == 1)
1740         return Error ("Invalid METADATA_ATTACHMENT reader!");
1741       Instruction *Inst = InstructionList[Record[0]];
1742       for (unsigned i = 1; i != RecordLength; i = i+2) {
1743         unsigned Kind = Record[i];
1744         DenseMap<unsigned, unsigned>::iterator I =
1745           MDKindMap.find(Kind);
1746         if (I == MDKindMap.end())
1747           return Error("Invalid metadata kind ID");
1748         Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1749         Inst->setMetadata(I->second, cast<MDNode>(Node));
1750       }
1751       break;
1752     }
1753     }
1754   }
1755   return false;
1756 }
1757
1758 /// ParseFunctionBody - Lazily parse the specified function body block.
1759 bool BitcodeReader::ParseFunctionBody(Function *F) {
1760   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1761     return Error("Malformed block record");
1762
1763   InstructionList.clear();
1764   unsigned ModuleValueListSize = ValueList.size();
1765   unsigned ModuleMDValueListSize = MDValueList.size();
1766
1767   // Add all the function arguments to the value table.
1768   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1769     ValueList.push_back(I);
1770
1771   unsigned NextValueNo = ValueList.size();
1772   BasicBlock *CurBB = 0;
1773   unsigned CurBBNo = 0;
1774
1775   DebugLoc LastLoc;
1776   
1777   // Read all the records.
1778   SmallVector<uint64_t, 64> Record;
1779   while (1) {
1780     unsigned Code = Stream.ReadCode();
1781     if (Code == bitc::END_BLOCK) {
1782       if (Stream.ReadBlockEnd())
1783         return Error("Error at end of function block");
1784       break;
1785     }
1786
1787     if (Code == bitc::ENTER_SUBBLOCK) {
1788       switch (Stream.ReadSubBlockID()) {
1789       default:  // Skip unknown content.
1790         if (Stream.SkipBlock())
1791           return Error("Malformed block record");
1792         break;
1793       case bitc::CONSTANTS_BLOCK_ID:
1794         if (ParseConstants()) return true;
1795         NextValueNo = ValueList.size();
1796         break;
1797       case bitc::VALUE_SYMTAB_BLOCK_ID:
1798         if (ParseValueSymbolTable()) return true;
1799         break;
1800       case bitc::METADATA_ATTACHMENT_ID:
1801         if (ParseMetadataAttachment()) return true;
1802         break;
1803       case bitc::METADATA_BLOCK_ID:
1804         if (ParseMetadata()) return true;
1805         break;
1806       }
1807       continue;
1808     }
1809
1810     if (Code == bitc::DEFINE_ABBREV) {
1811       Stream.ReadAbbrevRecord();
1812       continue;
1813     }
1814
1815     // Read a record.
1816     Record.clear();
1817     Instruction *I = 0;
1818     unsigned BitCode = Stream.ReadRecord(Code, Record);
1819     switch (BitCode) {
1820     default: // Default behavior: reject
1821       return Error("Unknown instruction");
1822     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1823       if (Record.size() < 1 || Record[0] == 0)
1824         return Error("Invalid DECLAREBLOCKS record");
1825       // Create all the basic blocks for the function.
1826       FunctionBBs.resize(Record[0]);
1827       for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1828         FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1829       CurBB = FunctionBBs[0];
1830       continue;
1831         
1832     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
1833       // This record indicates that the last instruction is at the same
1834       // location as the previous instruction with a location.
1835       I = 0;
1836         
1837       // Get the last instruction emitted.
1838       if (CurBB && !CurBB->empty())
1839         I = &CurBB->back();
1840       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1841                !FunctionBBs[CurBBNo-1]->empty())
1842         I = &FunctionBBs[CurBBNo-1]->back();
1843         
1844       if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1845       I->setDebugLoc(LastLoc);
1846       I = 0;
1847       continue;
1848         
1849     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
1850       I = 0;     // Get the last instruction emitted.
1851       if (CurBB && !CurBB->empty())
1852         I = &CurBB->back();
1853       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1854                !FunctionBBs[CurBBNo-1]->empty())
1855         I = &FunctionBBs[CurBBNo-1]->back();
1856       if (I == 0 || Record.size() < 4)
1857         return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1858       
1859       unsigned Line = Record[0], Col = Record[1];
1860       unsigned ScopeID = Record[2], IAID = Record[3];
1861       
1862       MDNode *Scope = 0, *IA = 0;
1863       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1864       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1865       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1866       I->setDebugLoc(LastLoc);
1867       I = 0;
1868       continue;
1869     }
1870
1871     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1872       unsigned OpNum = 0;
1873       Value *LHS, *RHS;
1874       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1875           getValue(Record, OpNum, LHS->getType(), RHS) ||
1876           OpNum+1 > Record.size())
1877         return Error("Invalid BINOP record");
1878
1879       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1880       if (Opc == -1) return Error("Invalid BINOP record");
1881       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1882       InstructionList.push_back(I);
1883       if (OpNum < Record.size()) {
1884         if (Opc == Instruction::Add ||
1885             Opc == Instruction::Sub ||
1886             Opc == Instruction::Mul ||
1887             Opc == Instruction::Shl) {
1888           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1889             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
1890           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1891             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1892         } else if (Opc == Instruction::SDiv ||
1893                    Opc == Instruction::UDiv ||
1894                    Opc == Instruction::LShr ||
1895                    Opc == Instruction::AShr) {
1896           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
1897             cast<BinaryOperator>(I)->setIsExact(true);
1898         }
1899       }
1900       break;
1901     }
1902     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1903       unsigned OpNum = 0;
1904       Value *Op;
1905       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1906           OpNum+2 != Record.size())
1907         return Error("Invalid CAST record");
1908
1909       const Type *ResTy = getTypeByID(Record[OpNum]);
1910       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1911       if (Opc == -1 || ResTy == 0)
1912         return Error("Invalid CAST record");
1913       I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1914       InstructionList.push_back(I);
1915       break;
1916     }
1917     case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
1918     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1919       unsigned OpNum = 0;
1920       Value *BasePtr;
1921       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1922         return Error("Invalid GEP record");
1923
1924       SmallVector<Value*, 16> GEPIdx;
1925       while (OpNum != Record.size()) {
1926         Value *Op;
1927         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1928           return Error("Invalid GEP record");
1929         GEPIdx.push_back(Op);
1930       }
1931
1932       I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1933       InstructionList.push_back(I);
1934       if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
1935         cast<GetElementPtrInst>(I)->setIsInBounds(true);
1936       break;
1937     }
1938
1939     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1940                                        // EXTRACTVAL: [opty, opval, n x indices]
1941       unsigned OpNum = 0;
1942       Value *Agg;
1943       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1944         return Error("Invalid EXTRACTVAL record");
1945
1946       SmallVector<unsigned, 4> EXTRACTVALIdx;
1947       for (unsigned RecSize = Record.size();
1948            OpNum != RecSize; ++OpNum) {
1949         uint64_t Index = Record[OpNum];
1950         if ((unsigned)Index != Index)
1951           return Error("Invalid EXTRACTVAL index");
1952         EXTRACTVALIdx.push_back((unsigned)Index);
1953       }
1954
1955       I = ExtractValueInst::Create(Agg,
1956                                    EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1957       InstructionList.push_back(I);
1958       break;
1959     }
1960
1961     case bitc::FUNC_CODE_INST_INSERTVAL: {
1962                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
1963       unsigned OpNum = 0;
1964       Value *Agg;
1965       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1966         return Error("Invalid INSERTVAL record");
1967       Value *Val;
1968       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1969         return Error("Invalid INSERTVAL record");
1970
1971       SmallVector<unsigned, 4> INSERTVALIdx;
1972       for (unsigned RecSize = Record.size();
1973            OpNum != RecSize; ++OpNum) {
1974         uint64_t Index = Record[OpNum];
1975         if ((unsigned)Index != Index)
1976           return Error("Invalid INSERTVAL index");
1977         INSERTVALIdx.push_back((unsigned)Index);
1978       }
1979
1980       I = InsertValueInst::Create(Agg, Val,
1981                                   INSERTVALIdx.begin(), INSERTVALIdx.end());
1982       InstructionList.push_back(I);
1983       break;
1984     }
1985
1986     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1987       // obsolete form of select
1988       // handles select i1 ... in old bitcode
1989       unsigned OpNum = 0;
1990       Value *TrueVal, *FalseVal, *Cond;
1991       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1992           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1993           getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
1994         return Error("Invalid SELECT record");
1995
1996       I = SelectInst::Create(Cond, TrueVal, FalseVal);
1997       InstructionList.push_back(I);
1998       break;
1999     }
2000
2001     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2002       // new form of select
2003       // handles select i1 or select [N x i1]
2004       unsigned OpNum = 0;
2005       Value *TrueVal, *FalseVal, *Cond;
2006       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2007           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2008           getValueTypePair(Record, OpNum, NextValueNo, Cond))
2009         return Error("Invalid SELECT record");
2010
2011       // select condition can be either i1 or [N x i1]
2012       if (const VectorType* vector_type =
2013           dyn_cast<const VectorType>(Cond->getType())) {
2014         // expect <n x i1>
2015         if (vector_type->getElementType() != Type::getInt1Ty(Context))
2016           return Error("Invalid SELECT condition type");
2017       } else {
2018         // expect i1
2019         if (Cond->getType() != Type::getInt1Ty(Context))
2020           return Error("Invalid SELECT condition type");
2021       }
2022
2023       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2024       InstructionList.push_back(I);
2025       break;
2026     }
2027
2028     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2029       unsigned OpNum = 0;
2030       Value *Vec, *Idx;
2031       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2032           getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2033         return Error("Invalid EXTRACTELT record");
2034       I = ExtractElementInst::Create(Vec, Idx);
2035       InstructionList.push_back(I);
2036       break;
2037     }
2038
2039     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2040       unsigned OpNum = 0;
2041       Value *Vec, *Elt, *Idx;
2042       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2043           getValue(Record, OpNum,
2044                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2045           getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2046         return Error("Invalid INSERTELT record");
2047       I = InsertElementInst::Create(Vec, Elt, Idx);
2048       InstructionList.push_back(I);
2049       break;
2050     }
2051
2052     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2053       unsigned OpNum = 0;
2054       Value *Vec1, *Vec2, *Mask;
2055       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2056           getValue(Record, OpNum, Vec1->getType(), Vec2))
2057         return Error("Invalid SHUFFLEVEC record");
2058
2059       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2060         return Error("Invalid SHUFFLEVEC record");
2061       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2062       InstructionList.push_back(I);
2063       break;
2064     }
2065
2066     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2067       // Old form of ICmp/FCmp returning bool
2068       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2069       // both legal on vectors but had different behaviour.
2070     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2071       // FCmp/ICmp returning bool or vector of bool
2072
2073       unsigned OpNum = 0;
2074       Value *LHS, *RHS;
2075       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2076           getValue(Record, OpNum, LHS->getType(), RHS) ||
2077           OpNum+1 != Record.size())
2078         return Error("Invalid CMP record");
2079
2080       if (LHS->getType()->isFPOrFPVectorTy())
2081         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2082       else
2083         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2084       InstructionList.push_back(I);
2085       break;
2086     }
2087
2088     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2089       {
2090         unsigned Size = Record.size();
2091         if (Size == 0) {
2092           I = ReturnInst::Create(Context);
2093           InstructionList.push_back(I);
2094           break;
2095         }
2096
2097         unsigned OpNum = 0;
2098         Value *Op = NULL;
2099         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2100           return Error("Invalid RET record");
2101         if (OpNum != Record.size())
2102           return Error("Invalid RET record");
2103
2104         I = ReturnInst::Create(Context, Op);
2105         InstructionList.push_back(I);
2106         break;
2107       }
2108     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2109       if (Record.size() != 1 && Record.size() != 3)
2110         return Error("Invalid BR record");
2111       BasicBlock *TrueDest = getBasicBlock(Record[0]);
2112       if (TrueDest == 0)
2113         return Error("Invalid BR record");
2114
2115       if (Record.size() == 1) {
2116         I = BranchInst::Create(TrueDest);
2117         InstructionList.push_back(I);
2118       }
2119       else {
2120         BasicBlock *FalseDest = getBasicBlock(Record[1]);
2121         Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2122         if (FalseDest == 0 || Cond == 0)
2123           return Error("Invalid BR record");
2124         I = BranchInst::Create(TrueDest, FalseDest, Cond);
2125         InstructionList.push_back(I);
2126       }
2127       break;
2128     }
2129     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2130       if (Record.size() < 3 || (Record.size() & 1) == 0)
2131         return Error("Invalid SWITCH record");
2132       const Type *OpTy = getTypeByID(Record[0]);
2133       Value *Cond = getFnValueByID(Record[1], OpTy);
2134       BasicBlock *Default = getBasicBlock(Record[2]);
2135       if (OpTy == 0 || Cond == 0 || Default == 0)
2136         return Error("Invalid SWITCH record");
2137       unsigned NumCases = (Record.size()-3)/2;
2138       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2139       InstructionList.push_back(SI);
2140       for (unsigned i = 0, e = NumCases; i != e; ++i) {
2141         ConstantInt *CaseVal =
2142           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2143         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2144         if (CaseVal == 0 || DestBB == 0) {
2145           delete SI;
2146           return Error("Invalid SWITCH record!");
2147         }
2148         SI->addCase(CaseVal, DestBB);
2149       }
2150       I = SI;
2151       break;
2152     }
2153     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2154       if (Record.size() < 2)
2155         return Error("Invalid INDIRECTBR record");
2156       const Type *OpTy = getTypeByID(Record[0]);
2157       Value *Address = getFnValueByID(Record[1], OpTy);
2158       if (OpTy == 0 || Address == 0)
2159         return Error("Invalid INDIRECTBR record");
2160       unsigned NumDests = Record.size()-2;
2161       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2162       InstructionList.push_back(IBI);
2163       for (unsigned i = 0, e = NumDests; i != e; ++i) {
2164         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2165           IBI->addDestination(DestBB);
2166         } else {
2167           delete IBI;
2168           return Error("Invalid INDIRECTBR record!");
2169         }
2170       }
2171       I = IBI;
2172       break;
2173     }
2174         
2175     case bitc::FUNC_CODE_INST_INVOKE: {
2176       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2177       if (Record.size() < 4) return Error("Invalid INVOKE record");
2178       AttrListPtr PAL = getAttributes(Record[0]);
2179       unsigned CCInfo = Record[1];
2180       BasicBlock *NormalBB = getBasicBlock(Record[2]);
2181       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2182
2183       unsigned OpNum = 4;
2184       Value *Callee;
2185       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2186         return Error("Invalid INVOKE record");
2187
2188       const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2189       const FunctionType *FTy = !CalleeTy ? 0 :
2190         dyn_cast<FunctionType>(CalleeTy->getElementType());
2191
2192       // Check that the right number of fixed parameters are here.
2193       if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2194           Record.size() < OpNum+FTy->getNumParams())
2195         return Error("Invalid INVOKE record");
2196
2197       SmallVector<Value*, 16> Ops;
2198       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2199         Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2200         if (Ops.back() == 0) return Error("Invalid INVOKE record");
2201       }
2202
2203       if (!FTy->isVarArg()) {
2204         if (Record.size() != OpNum)
2205           return Error("Invalid INVOKE record");
2206       } else {
2207         // Read type/value pairs for varargs params.
2208         while (OpNum != Record.size()) {
2209           Value *Op;
2210           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2211             return Error("Invalid INVOKE record");
2212           Ops.push_back(Op);
2213         }
2214       }
2215
2216       I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
2217                              Ops.begin(), Ops.end());
2218       InstructionList.push_back(I);
2219       cast<InvokeInst>(I)->setCallingConv(
2220         static_cast<CallingConv::ID>(CCInfo));
2221       cast<InvokeInst>(I)->setAttributes(PAL);
2222       break;
2223     }
2224     case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2225       I = new UnwindInst(Context);
2226       InstructionList.push_back(I);
2227       break;
2228     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2229       I = new UnreachableInst(Context);
2230       InstructionList.push_back(I);
2231       break;
2232     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2233       if (Record.size() < 1 || ((Record.size()-1)&1))
2234         return Error("Invalid PHI record");
2235       const Type *Ty = getTypeByID(Record[0]);
2236       if (!Ty) return Error("Invalid PHI record");
2237
2238       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2239       InstructionList.push_back(PN);
2240
2241       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2242         Value *V = getFnValueByID(Record[1+i], Ty);
2243         BasicBlock *BB = getBasicBlock(Record[2+i]);
2244         if (!V || !BB) return Error("Invalid PHI record");
2245         PN->addIncoming(V, BB);
2246       }
2247       I = PN;
2248       break;
2249     }
2250
2251     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2252       if (Record.size() != 4)
2253         return Error("Invalid ALLOCA record");
2254       const PointerType *Ty =
2255         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2256       const Type *OpTy = getTypeByID(Record[1]);
2257       Value *Size = getFnValueByID(Record[2], OpTy);
2258       unsigned Align = Record[3];
2259       if (!Ty || !Size) return Error("Invalid ALLOCA record");
2260       I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2261       InstructionList.push_back(I);
2262       break;
2263     }
2264     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2265       unsigned OpNum = 0;
2266       Value *Op;
2267       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2268           OpNum+2 != Record.size())
2269         return Error("Invalid LOAD record");
2270
2271       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2272       InstructionList.push_back(I);
2273       break;
2274     }
2275     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2276       unsigned OpNum = 0;
2277       Value *Val, *Ptr;
2278       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2279           getValue(Record, OpNum,
2280                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2281           OpNum+2 != Record.size())
2282         return Error("Invalid STORE record");
2283
2284       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2285       InstructionList.push_back(I);
2286       break;
2287     }
2288     case bitc::FUNC_CODE_INST_CALL: {
2289       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2290       if (Record.size() < 3)
2291         return Error("Invalid CALL record");
2292
2293       AttrListPtr PAL = getAttributes(Record[0]);
2294       unsigned CCInfo = Record[1];
2295
2296       unsigned OpNum = 2;
2297       Value *Callee;
2298       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2299         return Error("Invalid CALL record");
2300
2301       const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2302       const FunctionType *FTy = 0;
2303       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2304       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2305         return Error("Invalid CALL record");
2306
2307       SmallVector<Value*, 16> Args;
2308       // Read the fixed params.
2309       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2310         if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
2311           Args.push_back(getBasicBlock(Record[OpNum]));
2312         else
2313           Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2314         if (Args.back() == 0) return Error("Invalid CALL record");
2315       }
2316
2317       // Read type/value pairs for varargs params.
2318       if (!FTy->isVarArg()) {
2319         if (OpNum != Record.size())
2320           return Error("Invalid CALL record");
2321       } else {
2322         while (OpNum != Record.size()) {
2323           Value *Op;
2324           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2325             return Error("Invalid CALL record");
2326           Args.push_back(Op);
2327         }
2328       }
2329
2330       I = CallInst::Create(Callee, Args.begin(), Args.end());
2331       InstructionList.push_back(I);
2332       cast<CallInst>(I)->setCallingConv(
2333         static_cast<CallingConv::ID>(CCInfo>>1));
2334       cast<CallInst>(I)->setTailCall(CCInfo & 1);
2335       cast<CallInst>(I)->setAttributes(PAL);
2336       break;
2337     }
2338     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2339       if (Record.size() < 3)
2340         return Error("Invalid VAARG record");
2341       const Type *OpTy = getTypeByID(Record[0]);
2342       Value *Op = getFnValueByID(Record[1], OpTy);
2343       const Type *ResTy = getTypeByID(Record[2]);
2344       if (!OpTy || !Op || !ResTy)
2345         return Error("Invalid VAARG record");
2346       I = new VAArgInst(Op, ResTy);
2347       InstructionList.push_back(I);
2348       break;
2349     }
2350     }
2351
2352     // Add instruction to end of current BB.  If there is no current BB, reject
2353     // this file.
2354     if (CurBB == 0) {
2355       delete I;
2356       return Error("Invalid instruction with no BB");
2357     }
2358     CurBB->getInstList().push_back(I);
2359
2360     // If this was a terminator instruction, move to the next block.
2361     if (isa<TerminatorInst>(I)) {
2362       ++CurBBNo;
2363       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2364     }
2365
2366     // Non-void values get registered in the value table for future use.
2367     if (I && !I->getType()->isVoidTy())
2368       ValueList.AssignValue(I, NextValueNo++);
2369   }
2370
2371   // Check the function list for unresolved values.
2372   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2373     if (A->getParent() == 0) {
2374       // We found at least one unresolved value.  Nuke them all to avoid leaks.
2375       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2376         if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2377           A->replaceAllUsesWith(UndefValue::get(A->getType()));
2378           delete A;
2379         }
2380       }
2381       return Error("Never resolved value found in function!");
2382     }
2383   }
2384
2385   // FIXME: Check for unresolved forward-declared metadata references
2386   // and clean up leaks.
2387
2388   // See if anything took the address of blocks in this function.  If so,
2389   // resolve them now.
2390   DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2391     BlockAddrFwdRefs.find(F);
2392   if (BAFRI != BlockAddrFwdRefs.end()) {
2393     std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2394     for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2395       unsigned BlockIdx = RefList[i].first;
2396       if (BlockIdx >= FunctionBBs.size())
2397         return Error("Invalid blockaddress block #");
2398     
2399       GlobalVariable *FwdRef = RefList[i].second;
2400       FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2401       FwdRef->eraseFromParent();
2402     }
2403     
2404     BlockAddrFwdRefs.erase(BAFRI);
2405   }
2406   
2407   // Trim the value list down to the size it was before we parsed this function.
2408   ValueList.shrinkTo(ModuleValueListSize);
2409   MDValueList.shrinkTo(ModuleMDValueListSize);
2410   std::vector<BasicBlock*>().swap(FunctionBBs);
2411   return false;
2412 }
2413
2414 //===----------------------------------------------------------------------===//
2415 // GVMaterializer implementation
2416 //===----------------------------------------------------------------------===//
2417
2418
2419 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2420   if (const Function *F = dyn_cast<Function>(GV)) {
2421     return F->isDeclaration() &&
2422       DeferredFunctionInfo.count(const_cast<Function*>(F));
2423   }
2424   return false;
2425 }
2426
2427 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2428   Function *F = dyn_cast<Function>(GV);
2429   // If it's not a function or is already material, ignore the request.
2430   if (!F || !F->isMaterializable()) return false;
2431
2432   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2433   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2434
2435   // Move the bit stream to the saved position of the deferred function body.
2436   Stream.JumpToBit(DFII->second);
2437
2438   if (ParseFunctionBody(F)) {
2439     if (ErrInfo) *ErrInfo = ErrorString;
2440     return true;
2441   }
2442
2443   // Upgrade any old intrinsic calls in the function.
2444   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2445        E = UpgradedIntrinsics.end(); I != E; ++I) {
2446     if (I->first != I->second) {
2447       for (Value::use_iterator UI = I->first->use_begin(),
2448            UE = I->first->use_end(); UI != UE; ) {
2449         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2450           UpgradeIntrinsicCall(CI, I->second);
2451       }
2452     }
2453   }
2454
2455   return false;
2456 }
2457
2458 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2459   const Function *F = dyn_cast<Function>(GV);
2460   if (!F || F->isDeclaration())
2461     return false;
2462   return DeferredFunctionInfo.count(const_cast<Function*>(F));
2463 }
2464
2465 void BitcodeReader::Dematerialize(GlobalValue *GV) {
2466   Function *F = dyn_cast<Function>(GV);
2467   // If this function isn't dematerializable, this is a noop.
2468   if (!F || !isDematerializable(F))
2469     return;
2470
2471   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2472
2473   // Just forget the function body, we can remat it later.
2474   F->deleteBody();
2475 }
2476
2477
2478 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2479   assert(M == TheModule &&
2480          "Can only Materialize the Module this BitcodeReader is attached to.");
2481   // Iterate over the module, deserializing any functions that are still on
2482   // disk.
2483   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2484        F != E; ++F)
2485     if (F->isMaterializable() &&
2486         Materialize(F, ErrInfo))
2487       return true;
2488
2489   // Upgrade any intrinsic calls that slipped through (should not happen!) and
2490   // delete the old functions to clean up. We can't do this unless the entire
2491   // module is materialized because there could always be another function body
2492   // with calls to the old function.
2493   for (std::vector<std::pair<Function*, Function*> >::iterator I =
2494        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2495     if (I->first != I->second) {
2496       for (Value::use_iterator UI = I->first->use_begin(),
2497            UE = I->first->use_end(); UI != UE; ) {
2498         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2499           UpgradeIntrinsicCall(CI, I->second);
2500       }
2501       if (!I->first->use_empty())
2502         I->first->replaceAllUsesWith(I->second);
2503       I->first->eraseFromParent();
2504     }
2505   }
2506   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2507
2508   // Check debug info intrinsics.
2509   CheckDebugInfoIntrinsics(TheModule);
2510
2511   return false;
2512 }
2513
2514
2515 //===----------------------------------------------------------------------===//
2516 // External interface
2517 //===----------------------------------------------------------------------===//
2518
2519 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2520 ///
2521 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2522                                    LLVMContext& Context,
2523                                    std::string *ErrMsg) {
2524   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2525   BitcodeReader *R = new BitcodeReader(Buffer, Context);
2526   M->setMaterializer(R);
2527   if (R->ParseBitcodeInto(M)) {
2528     if (ErrMsg)
2529       *ErrMsg = R->getErrorString();
2530
2531     delete M;  // Also deletes R.
2532     return 0;
2533   }
2534   // Have the BitcodeReader dtor delete 'Buffer'.
2535   R->setBufferOwned(true);
2536   return M;
2537 }
2538
2539 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2540 /// If an error occurs, return null and fill in *ErrMsg if non-null.
2541 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2542                                std::string *ErrMsg){
2543   Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2544   if (!M) return 0;
2545
2546   // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2547   // there was an error.
2548   static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2549
2550   // Read in the entire module, and destroy the BitcodeReader.
2551   if (M->MaterializeAllPermanently(ErrMsg)) {
2552     delete M;
2553     return 0;
2554   }
2555
2556   return M;
2557 }
2558
2559 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2560                                          LLVMContext& Context,
2561                                          std::string *ErrMsg) {
2562   BitcodeReader *R = new BitcodeReader(Buffer, Context);
2563   // Don't let the BitcodeReader dtor delete 'Buffer'.
2564   R->setBufferOwned(false);
2565
2566   std::string Triple("");
2567   if (R->ParseTriple(Triple))
2568     if (ErrMsg)
2569       *ErrMsg = R->getErrorString();
2570
2571   delete R;
2572   return Triple;
2573 }