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