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