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