Patch provide by Tom Roeder!
[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
1110   GlobalInitWorklist.swap(GlobalInits);
1111   AliasInitWorklist.swap(AliasInits);
1112
1113   while (!GlobalInitWorklist.empty()) {
1114     unsigned ValID = GlobalInitWorklist.back().second;
1115     if (ValID >= ValueList.size()) {
1116       // Not ready to resolve this yet, it requires something later in the file.
1117       GlobalInits.push_back(GlobalInitWorklist.back());
1118     } else {
1119       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1120         GlobalInitWorklist.back().first->setInitializer(C);
1121       else
1122         return Error("Global variable initializer is not a constant!");
1123     }
1124     GlobalInitWorklist.pop_back();
1125   }
1126
1127   while (!AliasInitWorklist.empty()) {
1128     unsigned ValID = AliasInitWorklist.back().second;
1129     if (ValID >= ValueList.size()) {
1130       AliasInits.push_back(AliasInitWorklist.back());
1131     } else {
1132       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1133         AliasInitWorklist.back().first->setAliasee(C);
1134       else
1135         return Error("Alias initializer is not a constant!");
1136     }
1137     AliasInitWorklist.pop_back();
1138   }
1139   return false;
1140 }
1141
1142 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1143   SmallVector<uint64_t, 8> Words(Vals.size());
1144   std::transform(Vals.begin(), Vals.end(), Words.begin(),
1145                  BitcodeReader::decodeSignRotatedValue);
1146
1147   return APInt(TypeBits, Words);
1148 }
1149
1150 bool BitcodeReader::ParseConstants() {
1151   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1152     return Error("Malformed block record");
1153
1154   SmallVector<uint64_t, 64> Record;
1155
1156   // Read all the records for this value table.
1157   Type *CurTy = Type::getInt32Ty(Context);
1158   unsigned NextCstNo = ValueList.size();
1159   while (1) {
1160     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1161
1162     switch (Entry.Kind) {
1163     case BitstreamEntry::SubBlock: // Handled for us already.
1164     case BitstreamEntry::Error:
1165       return Error("malformed block record in AST file");
1166     case BitstreamEntry::EndBlock:
1167       if (NextCstNo != ValueList.size())
1168         return Error("Invalid constant reference!");
1169
1170       // Once all the constants have been read, go through and resolve forward
1171       // references.
1172       ValueList.ResolveConstantForwardRefs();
1173       return false;
1174     case BitstreamEntry::Record:
1175       // The interesting case.
1176       break;
1177     }
1178
1179     // Read a record.
1180     Record.clear();
1181     Value *V = 0;
1182     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1183     switch (BitCode) {
1184     default:  // Default behavior: unknown constant
1185     case bitc::CST_CODE_UNDEF:     // UNDEF
1186       V = UndefValue::get(CurTy);
1187       break;
1188     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
1189       if (Record.empty())
1190         return Error("Malformed CST_SETTYPE record");
1191       if (Record[0] >= TypeList.size())
1192         return Error("Invalid Type ID in CST_SETTYPE record");
1193       CurTy = TypeList[Record[0]];
1194       continue;  // Skip the ValueList manipulation.
1195     case bitc::CST_CODE_NULL:      // NULL
1196       V = Constant::getNullValue(CurTy);
1197       break;
1198     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
1199       if (!CurTy->isIntegerTy() || Record.empty())
1200         return Error("Invalid CST_INTEGER record");
1201       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1202       break;
1203     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1204       if (!CurTy->isIntegerTy() || Record.empty())
1205         return Error("Invalid WIDE_INTEGER record");
1206
1207       APInt VInt = ReadWideAPInt(Record,
1208                                  cast<IntegerType>(CurTy)->getBitWidth());
1209       V = ConstantInt::get(Context, VInt);
1210
1211       break;
1212     }
1213     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1214       if (Record.empty())
1215         return Error("Invalid FLOAT record");
1216       if (CurTy->isHalfTy())
1217         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1218                                              APInt(16, (uint16_t)Record[0])));
1219       else if (CurTy->isFloatTy())
1220         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1221                                              APInt(32, (uint32_t)Record[0])));
1222       else if (CurTy->isDoubleTy())
1223         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1224                                              APInt(64, Record[0])));
1225       else if (CurTy->isX86_FP80Ty()) {
1226         // Bits are not stored the same way as a normal i80 APInt, compensate.
1227         uint64_t Rearrange[2];
1228         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1229         Rearrange[1] = Record[0] >> 48;
1230         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1231                                              APInt(80, Rearrange)));
1232       } else if (CurTy->isFP128Ty())
1233         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1234                                              APInt(128, Record)));
1235       else if (CurTy->isPPC_FP128Ty())
1236         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1237                                              APInt(128, Record)));
1238       else
1239         V = UndefValue::get(CurTy);
1240       break;
1241     }
1242
1243     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1244       if (Record.empty())
1245         return Error("Invalid CST_AGGREGATE record");
1246
1247       unsigned Size = Record.size();
1248       SmallVector<Constant*, 16> Elts;
1249
1250       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1251         for (unsigned i = 0; i != Size; ++i)
1252           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1253                                                      STy->getElementType(i)));
1254         V = ConstantStruct::get(STy, Elts);
1255       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1256         Type *EltTy = ATy->getElementType();
1257         for (unsigned i = 0; i != Size; ++i)
1258           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1259         V = ConstantArray::get(ATy, Elts);
1260       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1261         Type *EltTy = VTy->getElementType();
1262         for (unsigned i = 0; i != Size; ++i)
1263           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1264         V = ConstantVector::get(Elts);
1265       } else {
1266         V = UndefValue::get(CurTy);
1267       }
1268       break;
1269     }
1270     case bitc::CST_CODE_STRING:    // STRING: [values]
1271     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1272       if (Record.empty())
1273         return Error("Invalid CST_STRING record");
1274
1275       SmallString<16> Elts(Record.begin(), Record.end());
1276       V = ConstantDataArray::getString(Context, Elts,
1277                                        BitCode == bitc::CST_CODE_CSTRING);
1278       break;
1279     }
1280     case bitc::CST_CODE_DATA: {// DATA: [n x value]
1281       if (Record.empty())
1282         return Error("Invalid CST_DATA record");
1283
1284       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1285       unsigned Size = Record.size();
1286
1287       if (EltTy->isIntegerTy(8)) {
1288         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1289         if (isa<VectorType>(CurTy))
1290           V = ConstantDataVector::get(Context, Elts);
1291         else
1292           V = ConstantDataArray::get(Context, Elts);
1293       } else if (EltTy->isIntegerTy(16)) {
1294         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1295         if (isa<VectorType>(CurTy))
1296           V = ConstantDataVector::get(Context, Elts);
1297         else
1298           V = ConstantDataArray::get(Context, Elts);
1299       } else if (EltTy->isIntegerTy(32)) {
1300         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1301         if (isa<VectorType>(CurTy))
1302           V = ConstantDataVector::get(Context, Elts);
1303         else
1304           V = ConstantDataArray::get(Context, Elts);
1305       } else if (EltTy->isIntegerTy(64)) {
1306         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1307         if (isa<VectorType>(CurTy))
1308           V = ConstantDataVector::get(Context, Elts);
1309         else
1310           V = ConstantDataArray::get(Context, Elts);
1311       } else if (EltTy->isFloatTy()) {
1312         SmallVector<float, 16> Elts(Size);
1313         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1314         if (isa<VectorType>(CurTy))
1315           V = ConstantDataVector::get(Context, Elts);
1316         else
1317           V = ConstantDataArray::get(Context, Elts);
1318       } else if (EltTy->isDoubleTy()) {
1319         SmallVector<double, 16> Elts(Size);
1320         std::transform(Record.begin(), Record.end(), Elts.begin(),
1321                        BitsToDouble);
1322         if (isa<VectorType>(CurTy))
1323           V = ConstantDataVector::get(Context, Elts);
1324         else
1325           V = ConstantDataArray::get(Context, Elts);
1326       } else {
1327         return Error("Unknown element type in CE_DATA");
1328       }
1329       break;
1330     }
1331
1332     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1333       if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1334       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1335       if (Opc < 0) {
1336         V = UndefValue::get(CurTy);  // Unknown binop.
1337       } else {
1338         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1339         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1340         unsigned Flags = 0;
1341         if (Record.size() >= 4) {
1342           if (Opc == Instruction::Add ||
1343               Opc == Instruction::Sub ||
1344               Opc == Instruction::Mul ||
1345               Opc == Instruction::Shl) {
1346             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1347               Flags |= OverflowingBinaryOperator::NoSignedWrap;
1348             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1349               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1350           } else if (Opc == Instruction::SDiv ||
1351                      Opc == Instruction::UDiv ||
1352                      Opc == Instruction::LShr ||
1353                      Opc == Instruction::AShr) {
1354             if (Record[3] & (1 << bitc::PEO_EXACT))
1355               Flags |= SDivOperator::IsExact;
1356           }
1357         }
1358         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1359       }
1360       break;
1361     }
1362     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1363       if (Record.size() < 3) return Error("Invalid CE_CAST record");
1364       int Opc = GetDecodedCastOpcode(Record[0]);
1365       if (Opc < 0) {
1366         V = UndefValue::get(CurTy);  // Unknown cast.
1367       } else {
1368         Type *OpTy = getTypeByID(Record[1]);
1369         if (!OpTy) return Error("Invalid CE_CAST record");
1370         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1371         V = ConstantExpr::getCast(Opc, Op, CurTy);
1372       }
1373       break;
1374     }
1375     case bitc::CST_CODE_CE_INBOUNDS_GEP:
1376     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1377       if (Record.size() & 1) return Error("Invalid CE_GEP record");
1378       SmallVector<Constant*, 16> Elts;
1379       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1380         Type *ElTy = getTypeByID(Record[i]);
1381         if (!ElTy) return Error("Invalid CE_GEP record");
1382         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1383       }
1384       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1385       V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1386                                          BitCode ==
1387                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
1388       break;
1389     }
1390     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
1391       if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1392
1393       Type *SelectorTy = Type::getInt1Ty(Context);
1394
1395       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1396       // vector. Otherwise, it must be a single bit.
1397       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1398         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1399                                      VTy->getNumElements());
1400
1401       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1402                                                               SelectorTy),
1403                                   ValueList.getConstantFwdRef(Record[1],CurTy),
1404                                   ValueList.getConstantFwdRef(Record[2],CurTy));
1405       break;
1406     }
1407     case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1408       if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1409       VectorType *OpTy =
1410         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1411       if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1412       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1413       Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1414                                                   Type::getInt32Ty(Context));
1415       V = ConstantExpr::getExtractElement(Op0, Op1);
1416       break;
1417     }
1418     case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1419       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1420       if (Record.size() < 3 || OpTy == 0)
1421         return Error("Invalid CE_INSERTELT record");
1422       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1423       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1424                                                   OpTy->getElementType());
1425       Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1426                                                   Type::getInt32Ty(Context));
1427       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1428       break;
1429     }
1430     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1431       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1432       if (Record.size() < 3 || OpTy == 0)
1433         return Error("Invalid CE_SHUFFLEVEC record");
1434       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1435       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1436       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1437                                                  OpTy->getNumElements());
1438       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1439       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1440       break;
1441     }
1442     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1443       VectorType *RTy = dyn_cast<VectorType>(CurTy);
1444       VectorType *OpTy =
1445         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1446       if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1447         return Error("Invalid CE_SHUFVEC_EX record");
1448       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1449       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1450       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1451                                                  RTy->getNumElements());
1452       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1453       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1454       break;
1455     }
1456     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1457       if (Record.size() < 4) return Error("Invalid CE_CMP record");
1458       Type *OpTy = getTypeByID(Record[0]);
1459       if (OpTy == 0) return Error("Invalid CE_CMP record");
1460       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1461       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1462
1463       if (OpTy->isFPOrFPVectorTy())
1464         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1465       else
1466         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1467       break;
1468     }
1469     // This maintains backward compatibility, pre-asm dialect keywords.
1470     // FIXME: Remove with the 4.0 release.
1471     case bitc::CST_CODE_INLINEASM_OLD: {
1472       if (Record.size() < 2) return Error("Invalid INLINEASM record");
1473       std::string AsmStr, ConstrStr;
1474       bool HasSideEffects = Record[0] & 1;
1475       bool IsAlignStack = Record[0] >> 1;
1476       unsigned AsmStrSize = Record[1];
1477       if (2+AsmStrSize >= Record.size())
1478         return Error("Invalid INLINEASM record");
1479       unsigned ConstStrSize = Record[2+AsmStrSize];
1480       if (3+AsmStrSize+ConstStrSize > Record.size())
1481         return Error("Invalid INLINEASM record");
1482
1483       for (unsigned i = 0; i != AsmStrSize; ++i)
1484         AsmStr += (char)Record[2+i];
1485       for (unsigned i = 0; i != ConstStrSize; ++i)
1486         ConstrStr += (char)Record[3+AsmStrSize+i];
1487       PointerType *PTy = cast<PointerType>(CurTy);
1488       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1489                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1490       break;
1491     }
1492     // This version adds support for the asm dialect keywords (e.g.,
1493     // inteldialect).
1494     case bitc::CST_CODE_INLINEASM: {
1495       if (Record.size() < 2) return Error("Invalid INLINEASM record");
1496       std::string AsmStr, ConstrStr;
1497       bool HasSideEffects = Record[0] & 1;
1498       bool IsAlignStack = (Record[0] >> 1) & 1;
1499       unsigned AsmDialect = Record[0] >> 2;
1500       unsigned AsmStrSize = Record[1];
1501       if (2+AsmStrSize >= Record.size())
1502         return Error("Invalid INLINEASM record");
1503       unsigned ConstStrSize = Record[2+AsmStrSize];
1504       if (3+AsmStrSize+ConstStrSize > Record.size())
1505         return Error("Invalid INLINEASM record");
1506
1507       for (unsigned i = 0; i != AsmStrSize; ++i)
1508         AsmStr += (char)Record[2+i];
1509       for (unsigned i = 0; i != ConstStrSize; ++i)
1510         ConstrStr += (char)Record[3+AsmStrSize+i];
1511       PointerType *PTy = cast<PointerType>(CurTy);
1512       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1513                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1514                          InlineAsm::AsmDialect(AsmDialect));
1515       break;
1516     }
1517     case bitc::CST_CODE_BLOCKADDRESS:{
1518       if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1519       Type *FnTy = getTypeByID(Record[0]);
1520       if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1521       Function *Fn =
1522         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1523       if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1524
1525       // If the function is already parsed we can insert the block address right
1526       // away.
1527       if (!Fn->empty()) {
1528         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1529         for (size_t I = 0, E = Record[2]; I != E; ++I) {
1530           if (BBI == BBE)
1531             return Error("Invalid blockaddress block #");
1532           ++BBI;
1533         }
1534         V = BlockAddress::get(Fn, BBI);
1535       } else {
1536         // Otherwise insert a placeholder and remember it so it can be inserted
1537         // when the function is parsed.
1538         GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1539                                                     Type::getInt8Ty(Context),
1540                                             false, GlobalValue::InternalLinkage,
1541                                                     0, "");
1542         BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1543         V = FwdRef;
1544       }
1545       break;
1546     }
1547     }
1548
1549     ValueList.AssignValue(V, NextCstNo);
1550     ++NextCstNo;
1551   }
1552 }
1553
1554 bool BitcodeReader::ParseUseLists() {
1555   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1556     return Error("Malformed block record");
1557
1558   SmallVector<uint64_t, 64> Record;
1559
1560   // Read all the records.
1561   while (1) {
1562     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1563
1564     switch (Entry.Kind) {
1565     case BitstreamEntry::SubBlock: // Handled for us already.
1566     case BitstreamEntry::Error:
1567       return Error("malformed use list block");
1568     case BitstreamEntry::EndBlock:
1569       return false;
1570     case BitstreamEntry::Record:
1571       // The interesting case.
1572       break;
1573     }
1574
1575     // Read a use list record.
1576     Record.clear();
1577     switch (Stream.readRecord(Entry.ID, Record)) {
1578     default:  // Default behavior: unknown type.
1579       break;
1580     case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1581       unsigned RecordLength = Record.size();
1582       if (RecordLength < 1)
1583         return Error ("Invalid UseList reader!");
1584       UseListRecords.push_back(Record);
1585       break;
1586     }
1587     }
1588   }
1589 }
1590
1591 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1592 /// remember where it is and then skip it.  This lets us lazily deserialize the
1593 /// functions.
1594 bool BitcodeReader::RememberAndSkipFunctionBody() {
1595   // Get the function we are talking about.
1596   if (FunctionsWithBodies.empty())
1597     return Error("Insufficient function protos");
1598
1599   Function *Fn = FunctionsWithBodies.back();
1600   FunctionsWithBodies.pop_back();
1601
1602   // Save the current stream state.
1603   uint64_t CurBit = Stream.GetCurrentBitNo();
1604   DeferredFunctionInfo[Fn] = CurBit;
1605
1606   // Skip over the function block for now.
1607   if (Stream.SkipBlock())
1608     return Error("Malformed block record");
1609   return false;
1610 }
1611
1612 bool BitcodeReader::GlobalCleanup() {
1613   // Patch the initializers for globals and aliases up.
1614   ResolveGlobalAndAliasInits();
1615   if (!GlobalInits.empty() || !AliasInits.empty())
1616     return Error("Malformed global initializer set");
1617
1618   // Look for intrinsic functions which need to be upgraded at some point
1619   for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1620        FI != FE; ++FI) {
1621     Function *NewFn;
1622     if (UpgradeIntrinsicFunction(FI, NewFn))
1623       UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1624   }
1625
1626   // Look for global variables which need to be renamed.
1627   for (Module::global_iterator
1628          GI = TheModule->global_begin(), GE = TheModule->global_end();
1629        GI != GE; ++GI)
1630     UpgradeGlobalVariable(GI);
1631   // Force deallocation of memory for these vectors to favor the client that
1632   // want lazy deserialization.
1633   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1634   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1635   return false;
1636 }
1637
1638 bool BitcodeReader::ParseModule(bool Resume) {
1639   if (Resume)
1640     Stream.JumpToBit(NextUnreadBit);
1641   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1642     return Error("Malformed block record");
1643
1644   SmallVector<uint64_t, 64> Record;
1645   std::vector<std::string> SectionTable;
1646   std::vector<std::string> GCTable;
1647
1648   // Read all the records for this module.
1649   while (1) {
1650     BitstreamEntry Entry = Stream.advance();
1651
1652     switch (Entry.Kind) {
1653     case BitstreamEntry::Error:
1654       Error("malformed module block");
1655       return true;
1656     case BitstreamEntry::EndBlock:
1657       return GlobalCleanup();
1658
1659     case BitstreamEntry::SubBlock:
1660       switch (Entry.ID) {
1661       default:  // Skip unknown content.
1662         if (Stream.SkipBlock())
1663           return Error("Malformed block record");
1664         break;
1665       case bitc::BLOCKINFO_BLOCK_ID:
1666         if (Stream.ReadBlockInfoBlock())
1667           return Error("Malformed BlockInfoBlock");
1668         break;
1669       case bitc::PARAMATTR_BLOCK_ID:
1670         if (ParseAttributeBlock())
1671           return true;
1672         break;
1673       case bitc::PARAMATTR_GROUP_BLOCK_ID:
1674         if (ParseAttributeGroupBlock())
1675           return true;
1676         break;
1677       case bitc::TYPE_BLOCK_ID_NEW:
1678         if (ParseTypeTable())
1679           return true;
1680         break;
1681       case bitc::VALUE_SYMTAB_BLOCK_ID:
1682         if (ParseValueSymbolTable())
1683           return true;
1684         SeenValueSymbolTable = true;
1685         break;
1686       case bitc::CONSTANTS_BLOCK_ID:
1687         if (ParseConstants() || ResolveGlobalAndAliasInits())
1688           return true;
1689         break;
1690       case bitc::METADATA_BLOCK_ID:
1691         if (ParseMetadata())
1692           return true;
1693         break;
1694       case bitc::FUNCTION_BLOCK_ID:
1695         // If this is the first function body we've seen, reverse the
1696         // FunctionsWithBodies list.
1697         if (!SeenFirstFunctionBody) {
1698           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1699           if (GlobalCleanup())
1700             return true;
1701           SeenFirstFunctionBody = true;
1702         }
1703
1704         if (RememberAndSkipFunctionBody())
1705           return true;
1706         // For streaming bitcode, suspend parsing when we reach the function
1707         // bodies. Subsequent materialization calls will resume it when
1708         // necessary. For streaming, the function bodies must be at the end of
1709         // the bitcode. If the bitcode file is old, the symbol table will be
1710         // at the end instead and will not have been seen yet. In this case,
1711         // just finish the parse now.
1712         if (LazyStreamer && SeenValueSymbolTable) {
1713           NextUnreadBit = Stream.GetCurrentBitNo();
1714           return false;
1715         }
1716         break;
1717       case bitc::USELIST_BLOCK_ID:
1718         if (ParseUseLists())
1719           return true;
1720         break;
1721       }
1722       continue;
1723
1724     case BitstreamEntry::Record:
1725       // The interesting case.
1726       break;
1727     }
1728
1729
1730     // Read a record.
1731     switch (Stream.readRecord(Entry.ID, Record)) {
1732     default: break;  // Default behavior, ignore unknown content.
1733     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
1734       if (Record.size() < 1)
1735         return Error("Malformed MODULE_CODE_VERSION");
1736       // Only version #0 and #1 are supported so far.
1737       unsigned module_version = Record[0];
1738       switch (module_version) {
1739         default: return Error("Unknown bitstream version!");
1740         case 0:
1741           UseRelativeIDs = false;
1742           break;
1743         case 1:
1744           UseRelativeIDs = true;
1745           break;
1746       }
1747       break;
1748     }
1749     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1750       std::string S;
1751       if (ConvertToString(Record, 0, S))
1752         return Error("Invalid MODULE_CODE_TRIPLE record");
1753       TheModule->setTargetTriple(S);
1754       break;
1755     }
1756     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1757       std::string S;
1758       if (ConvertToString(Record, 0, S))
1759         return Error("Invalid MODULE_CODE_DATALAYOUT record");
1760       TheModule->setDataLayout(S);
1761       break;
1762     }
1763     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1764       std::string S;
1765       if (ConvertToString(Record, 0, S))
1766         return Error("Invalid MODULE_CODE_ASM record");
1767       TheModule->setModuleInlineAsm(S);
1768       break;
1769     }
1770     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1771       // FIXME: Remove in 4.0.
1772       std::string S;
1773       if (ConvertToString(Record, 0, S))
1774         return Error("Invalid MODULE_CODE_DEPLIB record");
1775       // Ignore value.
1776       break;
1777     }
1778     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1779       std::string S;
1780       if (ConvertToString(Record, 0, S))
1781         return Error("Invalid MODULE_CODE_SECTIONNAME record");
1782       SectionTable.push_back(S);
1783       break;
1784     }
1785     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1786       std::string S;
1787       if (ConvertToString(Record, 0, S))
1788         return Error("Invalid MODULE_CODE_GCNAME record");
1789       GCTable.push_back(S);
1790       break;
1791     }
1792     // GLOBALVAR: [pointer type, isconst, initid,
1793     //             linkage, alignment, section, visibility, threadlocal,
1794     //             unnamed_addr]
1795     case bitc::MODULE_CODE_GLOBALVAR: {
1796       if (Record.size() < 6)
1797         return Error("Invalid MODULE_CODE_GLOBALVAR record");
1798       Type *Ty = getTypeByID(Record[0]);
1799       if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1800       if (!Ty->isPointerTy())
1801         return Error("Global not a pointer type!");
1802       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1803       Ty = cast<PointerType>(Ty)->getElementType();
1804
1805       bool isConstant = Record[1];
1806       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1807       unsigned Alignment = (1 << Record[4]) >> 1;
1808       std::string Section;
1809       if (Record[5]) {
1810         if (Record[5]-1 >= SectionTable.size())
1811           return Error("Invalid section ID");
1812         Section = SectionTable[Record[5]-1];
1813       }
1814       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1815       if (Record.size() > 6)
1816         Visibility = GetDecodedVisibility(Record[6]);
1817
1818       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1819       if (Record.size() > 7)
1820         TLM = GetDecodedThreadLocalMode(Record[7]);
1821
1822       bool UnnamedAddr = false;
1823       if (Record.size() > 8)
1824         UnnamedAddr = Record[8];
1825
1826       bool ExternallyInitialized = false;
1827       if (Record.size() > 9)
1828         ExternallyInitialized = Record[9];
1829
1830       GlobalVariable *NewGV =
1831         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1832                            TLM, AddressSpace, ExternallyInitialized);
1833       NewGV->setAlignment(Alignment);
1834       if (!Section.empty())
1835         NewGV->setSection(Section);
1836       NewGV->setVisibility(Visibility);
1837       NewGV->setUnnamedAddr(UnnamedAddr);
1838
1839       ValueList.push_back(NewGV);
1840
1841       // Remember which value to use for the global initializer.
1842       if (unsigned InitID = Record[2])
1843         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1844       break;
1845     }
1846     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1847     //             alignment, section, visibility, gc, unnamed_addr]
1848     case bitc::MODULE_CODE_FUNCTION: {
1849       if (Record.size() < 8)
1850         return Error("Invalid MODULE_CODE_FUNCTION record");
1851       Type *Ty = getTypeByID(Record[0]);
1852       if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1853       if (!Ty->isPointerTy())
1854         return Error("Function not a pointer type!");
1855       FunctionType *FTy =
1856         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1857       if (!FTy)
1858         return Error("Function not a pointer to function type!");
1859
1860       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1861                                         "", TheModule);
1862
1863       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1864       bool isProto = Record[2];
1865       Func->setLinkage(GetDecodedLinkage(Record[3]));
1866       Func->setAttributes(getAttributes(Record[4]));
1867
1868       Func->setAlignment((1 << Record[5]) >> 1);
1869       if (Record[6]) {
1870         if (Record[6]-1 >= SectionTable.size())
1871           return Error("Invalid section ID");
1872         Func->setSection(SectionTable[Record[6]-1]);
1873       }
1874       Func->setVisibility(GetDecodedVisibility(Record[7]));
1875       if (Record.size() > 8 && Record[8]) {
1876         if (Record[8]-1 > GCTable.size())
1877           return Error("Invalid GC ID");
1878         Func->setGC(GCTable[Record[8]-1].c_str());
1879       }
1880       bool UnnamedAddr = false;
1881       if (Record.size() > 9)
1882         UnnamedAddr = Record[9];
1883       Func->setUnnamedAddr(UnnamedAddr);
1884       ValueList.push_back(Func);
1885
1886       // If this is a function with a body, remember the prototype we are
1887       // creating now, so that we can match up the body with them later.
1888       if (!isProto) {
1889         FunctionsWithBodies.push_back(Func);
1890         if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1891       }
1892       break;
1893     }
1894     // ALIAS: [alias type, aliasee val#, linkage]
1895     // ALIAS: [alias type, aliasee val#, linkage, visibility]
1896     case bitc::MODULE_CODE_ALIAS: {
1897       if (Record.size() < 3)
1898         return Error("Invalid MODULE_ALIAS record");
1899       Type *Ty = getTypeByID(Record[0]);
1900       if (!Ty) return Error("Invalid MODULE_ALIAS record");
1901       if (!Ty->isPointerTy())
1902         return Error("Function not a pointer type!");
1903
1904       GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1905                                            "", 0, TheModule);
1906       // Old bitcode files didn't have visibility field.
1907       if (Record.size() > 3)
1908         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1909       ValueList.push_back(NewGA);
1910       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1911       break;
1912     }
1913     /// MODULE_CODE_PURGEVALS: [numvals]
1914     case bitc::MODULE_CODE_PURGEVALS:
1915       // Trim down the value list to the specified size.
1916       if (Record.size() < 1 || Record[0] > ValueList.size())
1917         return Error("Invalid MODULE_PURGEVALS record");
1918       ValueList.shrinkTo(Record[0]);
1919       break;
1920     }
1921     Record.clear();
1922   }
1923 }
1924
1925 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1926   TheModule = 0;
1927
1928   if (InitStream()) return true;
1929
1930   // Sniff for the signature.
1931   if (Stream.Read(8) != 'B' ||
1932       Stream.Read(8) != 'C' ||
1933       Stream.Read(4) != 0x0 ||
1934       Stream.Read(4) != 0xC ||
1935       Stream.Read(4) != 0xE ||
1936       Stream.Read(4) != 0xD)
1937     return Error("Invalid bitcode signature");
1938
1939   // We expect a number of well-defined blocks, though we don't necessarily
1940   // need to understand them all.
1941   while (1) {
1942     if (Stream.AtEndOfStream())
1943       return false;
1944
1945     BitstreamEntry Entry =
1946       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1947
1948     switch (Entry.Kind) {
1949     case BitstreamEntry::Error:
1950       Error("malformed module file");
1951       return true;
1952     case BitstreamEntry::EndBlock:
1953       return false;
1954
1955     case BitstreamEntry::SubBlock:
1956       switch (Entry.ID) {
1957       case bitc::BLOCKINFO_BLOCK_ID:
1958         if (Stream.ReadBlockInfoBlock())
1959           return Error("Malformed BlockInfoBlock");
1960         break;
1961       case bitc::MODULE_BLOCK_ID:
1962         // Reject multiple MODULE_BLOCK's in a single bitstream.
1963         if (TheModule)
1964           return Error("Multiple MODULE_BLOCKs in same stream");
1965         TheModule = M;
1966         if (ParseModule(false))
1967           return true;
1968         if (LazyStreamer) return false;
1969         break;
1970       default:
1971         if (Stream.SkipBlock())
1972           return Error("Malformed block record");
1973         break;
1974       }
1975       continue;
1976     case BitstreamEntry::Record:
1977       // There should be no records in the top-level of blocks.
1978
1979       // The ranlib in Xcode 4 will align archive members by appending newlines
1980       // to the end of them. If this file size is a multiple of 4 but not 8, we
1981       // have to read and ignore these final 4 bytes :-(
1982       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
1983           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1984           Stream.AtEndOfStream())
1985         return false;
1986
1987       return Error("Invalid record at top-level");
1988     }
1989   }
1990 }
1991
1992 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1993   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1994     return Error("Malformed block record");
1995
1996   SmallVector<uint64_t, 64> Record;
1997
1998   // Read all the records for this module.
1999   while (1) {
2000     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2001
2002     switch (Entry.Kind) {
2003     case BitstreamEntry::SubBlock: // Handled for us already.
2004     case BitstreamEntry::Error:
2005       return Error("malformed module block");
2006     case BitstreamEntry::EndBlock:
2007       return false;
2008     case BitstreamEntry::Record:
2009       // The interesting case.
2010       break;
2011     }
2012
2013     // Read a record.
2014     switch (Stream.readRecord(Entry.ID, Record)) {
2015     default: break;  // Default behavior, ignore unknown content.
2016     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2017       std::string S;
2018       if (ConvertToString(Record, 0, S))
2019         return Error("Invalid MODULE_CODE_TRIPLE record");
2020       Triple = S;
2021       break;
2022     }
2023     }
2024     Record.clear();
2025   }
2026 }
2027
2028 bool BitcodeReader::ParseTriple(std::string &Triple) {
2029   if (InitStream()) return true;
2030
2031   // Sniff for the signature.
2032   if (Stream.Read(8) != 'B' ||
2033       Stream.Read(8) != 'C' ||
2034       Stream.Read(4) != 0x0 ||
2035       Stream.Read(4) != 0xC ||
2036       Stream.Read(4) != 0xE ||
2037       Stream.Read(4) != 0xD)
2038     return Error("Invalid bitcode signature");
2039
2040   // We expect a number of well-defined blocks, though we don't necessarily
2041   // need to understand them all.
2042   while (1) {
2043     BitstreamEntry Entry = Stream.advance();
2044
2045     switch (Entry.Kind) {
2046     case BitstreamEntry::Error:
2047       Error("malformed module file");
2048       return true;
2049     case BitstreamEntry::EndBlock:
2050       return false;
2051
2052     case BitstreamEntry::SubBlock:
2053       if (Entry.ID == bitc::MODULE_BLOCK_ID)
2054         return ParseModuleTriple(Triple);
2055
2056       // Ignore other sub-blocks.
2057       if (Stream.SkipBlock()) {
2058         Error("malformed block record in AST file");
2059         return true;
2060       }
2061       continue;
2062
2063     case BitstreamEntry::Record:
2064       Stream.skipRecord(Entry.ID);
2065       continue;
2066     }
2067   }
2068 }
2069
2070 /// ParseMetadataAttachment - Parse metadata attachments.
2071 bool BitcodeReader::ParseMetadataAttachment() {
2072   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2073     return Error("Malformed block record");
2074
2075   SmallVector<uint64_t, 64> Record;
2076   while (1) {
2077     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2078
2079     switch (Entry.Kind) {
2080     case BitstreamEntry::SubBlock: // Handled for us already.
2081     case BitstreamEntry::Error:
2082       return Error("malformed metadata block");
2083     case BitstreamEntry::EndBlock:
2084       return false;
2085     case BitstreamEntry::Record:
2086       // The interesting case.
2087       break;
2088     }
2089
2090     // Read a metadata attachment record.
2091     Record.clear();
2092     switch (Stream.readRecord(Entry.ID, Record)) {
2093     default:  // Default behavior: ignore.
2094       break;
2095     case bitc::METADATA_ATTACHMENT: {
2096       unsigned RecordLength = Record.size();
2097       if (Record.empty() || (RecordLength - 1) % 2 == 1)
2098         return Error ("Invalid METADATA_ATTACHMENT reader!");
2099       Instruction *Inst = InstructionList[Record[0]];
2100       for (unsigned i = 1; i != RecordLength; i = i+2) {
2101         unsigned Kind = Record[i];
2102         DenseMap<unsigned, unsigned>::iterator I =
2103           MDKindMap.find(Kind);
2104         if (I == MDKindMap.end())
2105           return Error("Invalid metadata kind ID");
2106         Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2107         Inst->setMetadata(I->second, cast<MDNode>(Node));
2108       }
2109       break;
2110     }
2111     }
2112   }
2113 }
2114
2115 /// ParseFunctionBody - Lazily parse the specified function body block.
2116 bool BitcodeReader::ParseFunctionBody(Function *F) {
2117   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2118     return Error("Malformed block record");
2119
2120   InstructionList.clear();
2121   unsigned ModuleValueListSize = ValueList.size();
2122   unsigned ModuleMDValueListSize = MDValueList.size();
2123
2124   // Add all the function arguments to the value table.
2125   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2126     ValueList.push_back(I);
2127
2128   unsigned NextValueNo = ValueList.size();
2129   BasicBlock *CurBB = 0;
2130   unsigned CurBBNo = 0;
2131
2132   DebugLoc LastLoc;
2133
2134   // Read all the records.
2135   SmallVector<uint64_t, 64> Record;
2136   while (1) {
2137     BitstreamEntry Entry = Stream.advance();
2138
2139     switch (Entry.Kind) {
2140     case BitstreamEntry::Error:
2141       return Error("Bitcode error in function block");
2142     case BitstreamEntry::EndBlock:
2143       goto OutOfRecordLoop;
2144
2145     case BitstreamEntry::SubBlock:
2146       switch (Entry.ID) {
2147       default:  // Skip unknown content.
2148         if (Stream.SkipBlock())
2149           return Error("Malformed block record");
2150         break;
2151       case bitc::CONSTANTS_BLOCK_ID:
2152         if (ParseConstants()) return true;
2153         NextValueNo = ValueList.size();
2154         break;
2155       case bitc::VALUE_SYMTAB_BLOCK_ID:
2156         if (ParseValueSymbolTable()) return true;
2157         break;
2158       case bitc::METADATA_ATTACHMENT_ID:
2159         if (ParseMetadataAttachment()) return true;
2160         break;
2161       case bitc::METADATA_BLOCK_ID:
2162         if (ParseMetadata()) return true;
2163         break;
2164       }
2165       continue;
2166
2167     case BitstreamEntry::Record:
2168       // The interesting case.
2169       break;
2170     }
2171
2172     // Read a record.
2173     Record.clear();
2174     Instruction *I = 0;
2175     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2176     switch (BitCode) {
2177     default: // Default behavior: reject
2178       return Error("Unknown instruction");
2179     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
2180       if (Record.size() < 1 || Record[0] == 0)
2181         return Error("Invalid DECLAREBLOCKS record");
2182       // Create all the basic blocks for the function.
2183       FunctionBBs.resize(Record[0]);
2184       for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2185         FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2186       CurBB = FunctionBBs[0];
2187       continue;
2188
2189     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
2190       // This record indicates that the last instruction is at the same
2191       // location as the previous instruction with a location.
2192       I = 0;
2193
2194       // Get the last instruction emitted.
2195       if (CurBB && !CurBB->empty())
2196         I = &CurBB->back();
2197       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2198                !FunctionBBs[CurBBNo-1]->empty())
2199         I = &FunctionBBs[CurBBNo-1]->back();
2200
2201       if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2202       I->setDebugLoc(LastLoc);
2203       I = 0;
2204       continue;
2205
2206     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
2207       I = 0;     // Get the last instruction emitted.
2208       if (CurBB && !CurBB->empty())
2209         I = &CurBB->back();
2210       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2211                !FunctionBBs[CurBBNo-1]->empty())
2212         I = &FunctionBBs[CurBBNo-1]->back();
2213       if (I == 0 || Record.size() < 4)
2214         return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2215
2216       unsigned Line = Record[0], Col = Record[1];
2217       unsigned ScopeID = Record[2], IAID = Record[3];
2218
2219       MDNode *Scope = 0, *IA = 0;
2220       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2221       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2222       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2223       I->setDebugLoc(LastLoc);
2224       I = 0;
2225       continue;
2226     }
2227
2228     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
2229       unsigned OpNum = 0;
2230       Value *LHS, *RHS;
2231       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2232           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2233           OpNum+1 > Record.size())
2234         return Error("Invalid BINOP record");
2235
2236       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2237       if (Opc == -1) return Error("Invalid BINOP record");
2238       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2239       InstructionList.push_back(I);
2240       if (OpNum < Record.size()) {
2241         if (Opc == Instruction::Add ||
2242             Opc == Instruction::Sub ||
2243             Opc == Instruction::Mul ||
2244             Opc == Instruction::Shl) {
2245           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2246             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2247           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2248             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2249         } else if (Opc == Instruction::SDiv ||
2250                    Opc == Instruction::UDiv ||
2251                    Opc == Instruction::LShr ||
2252                    Opc == Instruction::AShr) {
2253           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2254             cast<BinaryOperator>(I)->setIsExact(true);
2255         } else if (isa<FPMathOperator>(I)) {
2256           FastMathFlags FMF;
2257           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2258             FMF.setUnsafeAlgebra();
2259           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2260             FMF.setNoNaNs();
2261           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2262             FMF.setNoInfs();
2263           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2264             FMF.setNoSignedZeros();
2265           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2266             FMF.setAllowReciprocal();
2267           if (FMF.any())
2268             I->setFastMathFlags(FMF);
2269         }
2270
2271       }
2272       break;
2273     }
2274     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
2275       unsigned OpNum = 0;
2276       Value *Op;
2277       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2278           OpNum+2 != Record.size())
2279         return Error("Invalid CAST record");
2280
2281       Type *ResTy = getTypeByID(Record[OpNum]);
2282       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2283       if (Opc == -1 || ResTy == 0)
2284         return Error("Invalid CAST record");
2285       I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2286       InstructionList.push_back(I);
2287       break;
2288     }
2289     case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2290     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2291       unsigned OpNum = 0;
2292       Value *BasePtr;
2293       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2294         return Error("Invalid GEP record");
2295
2296       SmallVector<Value*, 16> GEPIdx;
2297       while (OpNum != Record.size()) {
2298         Value *Op;
2299         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2300           return Error("Invalid GEP record");
2301         GEPIdx.push_back(Op);
2302       }
2303
2304       I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2305       InstructionList.push_back(I);
2306       if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2307         cast<GetElementPtrInst>(I)->setIsInBounds(true);
2308       break;
2309     }
2310
2311     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2312                                        // EXTRACTVAL: [opty, opval, n x indices]
2313       unsigned OpNum = 0;
2314       Value *Agg;
2315       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2316         return Error("Invalid EXTRACTVAL record");
2317
2318       SmallVector<unsigned, 4> EXTRACTVALIdx;
2319       for (unsigned RecSize = Record.size();
2320            OpNum != RecSize; ++OpNum) {
2321         uint64_t Index = Record[OpNum];
2322         if ((unsigned)Index != Index)
2323           return Error("Invalid EXTRACTVAL index");
2324         EXTRACTVALIdx.push_back((unsigned)Index);
2325       }
2326
2327       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2328       InstructionList.push_back(I);
2329       break;
2330     }
2331
2332     case bitc::FUNC_CODE_INST_INSERTVAL: {
2333                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
2334       unsigned OpNum = 0;
2335       Value *Agg;
2336       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2337         return Error("Invalid INSERTVAL record");
2338       Value *Val;
2339       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2340         return Error("Invalid INSERTVAL record");
2341
2342       SmallVector<unsigned, 4> INSERTVALIdx;
2343       for (unsigned RecSize = Record.size();
2344            OpNum != RecSize; ++OpNum) {
2345         uint64_t Index = Record[OpNum];
2346         if ((unsigned)Index != Index)
2347           return Error("Invalid INSERTVAL index");
2348         INSERTVALIdx.push_back((unsigned)Index);
2349       }
2350
2351       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2352       InstructionList.push_back(I);
2353       break;
2354     }
2355
2356     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2357       // obsolete form of select
2358       // handles select i1 ... in old bitcode
2359       unsigned OpNum = 0;
2360       Value *TrueVal, *FalseVal, *Cond;
2361       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2362           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2363           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2364         return Error("Invalid SELECT record");
2365
2366       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2367       InstructionList.push_back(I);
2368       break;
2369     }
2370
2371     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2372       // new form of select
2373       // handles select i1 or select [N x i1]
2374       unsigned OpNum = 0;
2375       Value *TrueVal, *FalseVal, *Cond;
2376       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2377           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2378           getValueTypePair(Record, OpNum, NextValueNo, Cond))
2379         return Error("Invalid SELECT record");
2380
2381       // select condition can be either i1 or [N x i1]
2382       if (VectorType* vector_type =
2383           dyn_cast<VectorType>(Cond->getType())) {
2384         // expect <n x i1>
2385         if (vector_type->getElementType() != Type::getInt1Ty(Context))
2386           return Error("Invalid SELECT condition type");
2387       } else {
2388         // expect i1
2389         if (Cond->getType() != Type::getInt1Ty(Context))
2390           return Error("Invalid SELECT condition type");
2391       }
2392
2393       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2394       InstructionList.push_back(I);
2395       break;
2396     }
2397
2398     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2399       unsigned OpNum = 0;
2400       Value *Vec, *Idx;
2401       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2402           popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2403         return Error("Invalid EXTRACTELT record");
2404       I = ExtractElementInst::Create(Vec, Idx);
2405       InstructionList.push_back(I);
2406       break;
2407     }
2408
2409     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2410       unsigned OpNum = 0;
2411       Value *Vec, *Elt, *Idx;
2412       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2413           popValue(Record, OpNum, NextValueNo,
2414                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2415           popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2416         return Error("Invalid INSERTELT record");
2417       I = InsertElementInst::Create(Vec, Elt, Idx);
2418       InstructionList.push_back(I);
2419       break;
2420     }
2421
2422     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2423       unsigned OpNum = 0;
2424       Value *Vec1, *Vec2, *Mask;
2425       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2426           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2427         return Error("Invalid SHUFFLEVEC record");
2428
2429       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2430         return Error("Invalid SHUFFLEVEC record");
2431       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2432       InstructionList.push_back(I);
2433       break;
2434     }
2435
2436     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2437       // Old form of ICmp/FCmp returning bool
2438       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2439       // both legal on vectors but had different behaviour.
2440     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2441       // FCmp/ICmp returning bool or vector of bool
2442
2443       unsigned OpNum = 0;
2444       Value *LHS, *RHS;
2445       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2446           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2447           OpNum+1 != Record.size())
2448         return Error("Invalid CMP record");
2449
2450       if (LHS->getType()->isFPOrFPVectorTy())
2451         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2452       else
2453         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2454       InstructionList.push_back(I);
2455       break;
2456     }
2457
2458     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2459       {
2460         unsigned Size = Record.size();
2461         if (Size == 0) {
2462           I = ReturnInst::Create(Context);
2463           InstructionList.push_back(I);
2464           break;
2465         }
2466
2467         unsigned OpNum = 0;
2468         Value *Op = NULL;
2469         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2470           return Error("Invalid RET record");
2471         if (OpNum != Record.size())
2472           return Error("Invalid RET record");
2473
2474         I = ReturnInst::Create(Context, Op);
2475         InstructionList.push_back(I);
2476         break;
2477       }
2478     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2479       if (Record.size() != 1 && Record.size() != 3)
2480         return Error("Invalid BR record");
2481       BasicBlock *TrueDest = getBasicBlock(Record[0]);
2482       if (TrueDest == 0)
2483         return Error("Invalid BR record");
2484
2485       if (Record.size() == 1) {
2486         I = BranchInst::Create(TrueDest);
2487         InstructionList.push_back(I);
2488       }
2489       else {
2490         BasicBlock *FalseDest = getBasicBlock(Record[1]);
2491         Value *Cond = getValue(Record, 2, NextValueNo,
2492                                Type::getInt1Ty(Context));
2493         if (FalseDest == 0 || Cond == 0)
2494           return Error("Invalid BR record");
2495         I = BranchInst::Create(TrueDest, FalseDest, Cond);
2496         InstructionList.push_back(I);
2497       }
2498       break;
2499     }
2500     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2501       // Check magic
2502       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2503         // "New" SwitchInst format with case ranges. The changes to write this
2504         // format were reverted but we still recognize bitcode that uses it.
2505         // Hopefully someday we will have support for case ranges and can use
2506         // this format again.
2507
2508         Type *OpTy = getTypeByID(Record[1]);
2509         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2510
2511         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2512         BasicBlock *Default = getBasicBlock(Record[3]);
2513         if (OpTy == 0 || Cond == 0 || Default == 0)
2514           return Error("Invalid SWITCH record");
2515
2516         unsigned NumCases = Record[4];
2517
2518         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2519         InstructionList.push_back(SI);
2520
2521         unsigned CurIdx = 5;
2522         for (unsigned i = 0; i != NumCases; ++i) {
2523           SmallVector<ConstantInt*, 1> CaseVals;
2524           unsigned NumItems = Record[CurIdx++];
2525           for (unsigned ci = 0; ci != NumItems; ++ci) {
2526             bool isSingleNumber = Record[CurIdx++];
2527
2528             APInt Low;
2529             unsigned ActiveWords = 1;
2530             if (ValueBitWidth > 64)
2531               ActiveWords = Record[CurIdx++];
2532             Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2533                                 ValueBitWidth);
2534             CurIdx += ActiveWords;
2535
2536             if (!isSingleNumber) {
2537               ActiveWords = 1;
2538               if (ValueBitWidth > 64)
2539                 ActiveWords = Record[CurIdx++];
2540               APInt High =
2541                   ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2542                                 ValueBitWidth);
2543               CurIdx += ActiveWords;
2544
2545               // FIXME: It is not clear whether values in the range should be
2546               // compared as signed or unsigned values. The partially
2547               // implemented changes that used this format in the past used
2548               // unsigned comparisons.
2549               for ( ; Low.ule(High); ++Low)
2550                 CaseVals.push_back(ConstantInt::get(Context, Low));
2551             } else
2552               CaseVals.push_back(ConstantInt::get(Context, Low));
2553           }
2554           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2555           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2556                  cve = CaseVals.end(); cvi != cve; ++cvi)
2557             SI->addCase(*cvi, DestBB);
2558         }
2559         I = SI;
2560         break;
2561       }
2562
2563       // Old SwitchInst format without case ranges.
2564
2565       if (Record.size() < 3 || (Record.size() & 1) == 0)
2566         return Error("Invalid SWITCH record");
2567       Type *OpTy = getTypeByID(Record[0]);
2568       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2569       BasicBlock *Default = getBasicBlock(Record[2]);
2570       if (OpTy == 0 || Cond == 0 || Default == 0)
2571         return Error("Invalid SWITCH record");
2572       unsigned NumCases = (Record.size()-3)/2;
2573       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2574       InstructionList.push_back(SI);
2575       for (unsigned i = 0, e = NumCases; i != e; ++i) {
2576         ConstantInt *CaseVal =
2577           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2578         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2579         if (CaseVal == 0 || DestBB == 0) {
2580           delete SI;
2581           return Error("Invalid SWITCH record!");
2582         }
2583         SI->addCase(CaseVal, DestBB);
2584       }
2585       I = SI;
2586       break;
2587     }
2588     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2589       if (Record.size() < 2)
2590         return Error("Invalid INDIRECTBR record");
2591       Type *OpTy = getTypeByID(Record[0]);
2592       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2593       if (OpTy == 0 || Address == 0)
2594         return Error("Invalid INDIRECTBR record");
2595       unsigned NumDests = Record.size()-2;
2596       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2597       InstructionList.push_back(IBI);
2598       for (unsigned i = 0, e = NumDests; i != e; ++i) {
2599         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2600           IBI->addDestination(DestBB);
2601         } else {
2602           delete IBI;
2603           return Error("Invalid INDIRECTBR record!");
2604         }
2605       }
2606       I = IBI;
2607       break;
2608     }
2609
2610     case bitc::FUNC_CODE_INST_INVOKE: {
2611       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2612       if (Record.size() < 4) return Error("Invalid INVOKE record");
2613       AttributeSet PAL = getAttributes(Record[0]);
2614       unsigned CCInfo = Record[1];
2615       BasicBlock *NormalBB = getBasicBlock(Record[2]);
2616       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2617
2618       unsigned OpNum = 4;
2619       Value *Callee;
2620       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2621         return Error("Invalid INVOKE record");
2622
2623       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2624       FunctionType *FTy = !CalleeTy ? 0 :
2625         dyn_cast<FunctionType>(CalleeTy->getElementType());
2626
2627       // Check that the right number of fixed parameters are here.
2628       if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2629           Record.size() < OpNum+FTy->getNumParams())
2630         return Error("Invalid INVOKE record");
2631
2632       SmallVector<Value*, 16> Ops;
2633       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2634         Ops.push_back(getValue(Record, OpNum, NextValueNo,
2635                                FTy->getParamType(i)));
2636         if (Ops.back() == 0) return Error("Invalid INVOKE record");
2637       }
2638
2639       if (!FTy->isVarArg()) {
2640         if (Record.size() != OpNum)
2641           return Error("Invalid INVOKE record");
2642       } else {
2643         // Read type/value pairs for varargs params.
2644         while (OpNum != Record.size()) {
2645           Value *Op;
2646           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2647             return Error("Invalid INVOKE record");
2648           Ops.push_back(Op);
2649         }
2650       }
2651
2652       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2653       InstructionList.push_back(I);
2654       cast<InvokeInst>(I)->setCallingConv(
2655         static_cast<CallingConv::ID>(CCInfo));
2656       cast<InvokeInst>(I)->setAttributes(PAL);
2657       break;
2658     }
2659     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2660       unsigned Idx = 0;
2661       Value *Val = 0;
2662       if (getValueTypePair(Record, Idx, NextValueNo, Val))
2663         return Error("Invalid RESUME record");
2664       I = ResumeInst::Create(Val);
2665       InstructionList.push_back(I);
2666       break;
2667     }
2668     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2669       I = new UnreachableInst(Context);
2670       InstructionList.push_back(I);
2671       break;
2672     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2673       if (Record.size() < 1 || ((Record.size()-1)&1))
2674         return Error("Invalid PHI record");
2675       Type *Ty = getTypeByID(Record[0]);
2676       if (!Ty) return Error("Invalid PHI record");
2677
2678       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2679       InstructionList.push_back(PN);
2680
2681       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2682         Value *V;
2683         // With the new function encoding, it is possible that operands have
2684         // negative IDs (for forward references).  Use a signed VBR
2685         // representation to keep the encoding small.
2686         if (UseRelativeIDs)
2687           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2688         else
2689           V = getValue(Record, 1+i, NextValueNo, Ty);
2690         BasicBlock *BB = getBasicBlock(Record[2+i]);
2691         if (!V || !BB) return Error("Invalid PHI record");
2692         PN->addIncoming(V, BB);
2693       }
2694       I = PN;
2695       break;
2696     }
2697
2698     case bitc::FUNC_CODE_INST_LANDINGPAD: {
2699       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2700       unsigned Idx = 0;
2701       if (Record.size() < 4)
2702         return Error("Invalid LANDINGPAD record");
2703       Type *Ty = getTypeByID(Record[Idx++]);
2704       if (!Ty) return Error("Invalid LANDINGPAD record");
2705       Value *PersFn = 0;
2706       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2707         return Error("Invalid LANDINGPAD record");
2708
2709       bool IsCleanup = !!Record[Idx++];
2710       unsigned NumClauses = Record[Idx++];
2711       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2712       LP->setCleanup(IsCleanup);
2713       for (unsigned J = 0; J != NumClauses; ++J) {
2714         LandingPadInst::ClauseType CT =
2715           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2716         Value *Val;
2717
2718         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2719           delete LP;
2720           return Error("Invalid LANDINGPAD record");
2721         }
2722
2723         assert((CT != LandingPadInst::Catch ||
2724                 !isa<ArrayType>(Val->getType())) &&
2725                "Catch clause has a invalid type!");
2726         assert((CT != LandingPadInst::Filter ||
2727                 isa<ArrayType>(Val->getType())) &&
2728                "Filter clause has invalid type!");
2729         LP->addClause(Val);
2730       }
2731
2732       I = LP;
2733       InstructionList.push_back(I);
2734       break;
2735     }
2736
2737     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2738       if (Record.size() != 4)
2739         return Error("Invalid ALLOCA record");
2740       PointerType *Ty =
2741         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2742       Type *OpTy = getTypeByID(Record[1]);
2743       Value *Size = getFnValueByID(Record[2], OpTy);
2744       unsigned Align = Record[3];
2745       if (!Ty || !Size) return Error("Invalid ALLOCA record");
2746       I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2747       InstructionList.push_back(I);
2748       break;
2749     }
2750     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2751       unsigned OpNum = 0;
2752       Value *Op;
2753       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2754           OpNum+2 != Record.size())
2755         return Error("Invalid LOAD record");
2756
2757       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2758       InstructionList.push_back(I);
2759       break;
2760     }
2761     case bitc::FUNC_CODE_INST_LOADATOMIC: {
2762        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2763       unsigned OpNum = 0;
2764       Value *Op;
2765       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2766           OpNum+4 != Record.size())
2767         return Error("Invalid LOADATOMIC record");
2768
2769
2770       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2771       if (Ordering == NotAtomic || Ordering == Release ||
2772           Ordering == AcquireRelease)
2773         return Error("Invalid LOADATOMIC record");
2774       if (Ordering != NotAtomic && Record[OpNum] == 0)
2775         return Error("Invalid LOADATOMIC record");
2776       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2777
2778       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2779                        Ordering, SynchScope);
2780       InstructionList.push_back(I);
2781       break;
2782     }
2783     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2784       unsigned OpNum = 0;
2785       Value *Val, *Ptr;
2786       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2787           popValue(Record, OpNum, NextValueNo,
2788                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2789           OpNum+2 != Record.size())
2790         return Error("Invalid STORE record");
2791
2792       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2793       InstructionList.push_back(I);
2794       break;
2795     }
2796     case bitc::FUNC_CODE_INST_STOREATOMIC: {
2797       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2798       unsigned OpNum = 0;
2799       Value *Val, *Ptr;
2800       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2801           popValue(Record, OpNum, NextValueNo,
2802                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2803           OpNum+4 != Record.size())
2804         return Error("Invalid STOREATOMIC record");
2805
2806       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2807       if (Ordering == NotAtomic || Ordering == Acquire ||
2808           Ordering == AcquireRelease)
2809         return Error("Invalid STOREATOMIC record");
2810       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2811       if (Ordering != NotAtomic && Record[OpNum] == 0)
2812         return Error("Invalid STOREATOMIC record");
2813
2814       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2815                         Ordering, SynchScope);
2816       InstructionList.push_back(I);
2817       break;
2818     }
2819     case bitc::FUNC_CODE_INST_CMPXCHG: {
2820       // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2821       unsigned OpNum = 0;
2822       Value *Ptr, *Cmp, *New;
2823       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2824           popValue(Record, OpNum, NextValueNo,
2825                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2826           popValue(Record, OpNum, NextValueNo,
2827                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2828           OpNum+3 != Record.size())
2829         return Error("Invalid CMPXCHG record");
2830       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2831       if (Ordering == NotAtomic || Ordering == Unordered)
2832         return Error("Invalid CMPXCHG record");
2833       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2834       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2835       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2836       InstructionList.push_back(I);
2837       break;
2838     }
2839     case bitc::FUNC_CODE_INST_ATOMICRMW: {
2840       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2841       unsigned OpNum = 0;
2842       Value *Ptr, *Val;
2843       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2844           popValue(Record, OpNum, NextValueNo,
2845                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2846           OpNum+4 != Record.size())
2847         return Error("Invalid ATOMICRMW record");
2848       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2849       if (Operation < AtomicRMWInst::FIRST_BINOP ||
2850           Operation > AtomicRMWInst::LAST_BINOP)
2851         return Error("Invalid ATOMICRMW record");
2852       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2853       if (Ordering == NotAtomic || Ordering == Unordered)
2854         return Error("Invalid ATOMICRMW record");
2855       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2856       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2857       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2858       InstructionList.push_back(I);
2859       break;
2860     }
2861     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2862       if (2 != Record.size())
2863         return Error("Invalid FENCE record");
2864       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2865       if (Ordering == NotAtomic || Ordering == Unordered ||
2866           Ordering == Monotonic)
2867         return Error("Invalid FENCE record");
2868       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2869       I = new FenceInst(Context, Ordering, SynchScope);
2870       InstructionList.push_back(I);
2871       break;
2872     }
2873     case bitc::FUNC_CODE_INST_CALL: {
2874       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2875       if (Record.size() < 3)
2876         return Error("Invalid CALL record");
2877
2878       AttributeSet PAL = getAttributes(Record[0]);
2879       unsigned CCInfo = Record[1];
2880
2881       unsigned OpNum = 2;
2882       Value *Callee;
2883       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2884         return Error("Invalid CALL record");
2885
2886       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2887       FunctionType *FTy = 0;
2888       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2889       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2890         return Error("Invalid CALL record");
2891
2892       SmallVector<Value*, 16> Args;
2893       // Read the fixed params.
2894       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2895         if (FTy->getParamType(i)->isLabelTy())
2896           Args.push_back(getBasicBlock(Record[OpNum]));
2897         else
2898           Args.push_back(getValue(Record, OpNum, NextValueNo,
2899                                   FTy->getParamType(i)));
2900         if (Args.back() == 0) return Error("Invalid CALL record");
2901       }
2902
2903       // Read type/value pairs for varargs params.
2904       if (!FTy->isVarArg()) {
2905         if (OpNum != Record.size())
2906           return Error("Invalid CALL record");
2907       } else {
2908         while (OpNum != Record.size()) {
2909           Value *Op;
2910           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2911             return Error("Invalid CALL record");
2912           Args.push_back(Op);
2913         }
2914       }
2915
2916       I = CallInst::Create(Callee, Args);
2917       InstructionList.push_back(I);
2918       cast<CallInst>(I)->setCallingConv(
2919         static_cast<CallingConv::ID>(CCInfo>>1));
2920       cast<CallInst>(I)->setTailCall(CCInfo & 1);
2921       cast<CallInst>(I)->setAttributes(PAL);
2922       break;
2923     }
2924     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2925       if (Record.size() < 3)
2926         return Error("Invalid VAARG record");
2927       Type *OpTy = getTypeByID(Record[0]);
2928       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2929       Type *ResTy = getTypeByID(Record[2]);
2930       if (!OpTy || !Op || !ResTy)
2931         return Error("Invalid VAARG record");
2932       I = new VAArgInst(Op, ResTy);
2933       InstructionList.push_back(I);
2934       break;
2935     }
2936     }
2937
2938     // Add instruction to end of current BB.  If there is no current BB, reject
2939     // this file.
2940     if (CurBB == 0) {
2941       delete I;
2942       return Error("Invalid instruction with no BB");
2943     }
2944     CurBB->getInstList().push_back(I);
2945
2946     // If this was a terminator instruction, move to the next block.
2947     if (isa<TerminatorInst>(I)) {
2948       ++CurBBNo;
2949       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2950     }
2951
2952     // Non-void values get registered in the value table for future use.
2953     if (I && !I->getType()->isVoidTy())
2954       ValueList.AssignValue(I, NextValueNo++);
2955   }
2956
2957 OutOfRecordLoop:
2958
2959   // Check the function list for unresolved values.
2960   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2961     if (A->getParent() == 0) {
2962       // We found at least one unresolved value.  Nuke them all to avoid leaks.
2963       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2964         if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2965           A->replaceAllUsesWith(UndefValue::get(A->getType()));
2966           delete A;
2967         }
2968       }
2969       return Error("Never resolved value found in function!");
2970     }
2971   }
2972
2973   // FIXME: Check for unresolved forward-declared metadata references
2974   // and clean up leaks.
2975
2976   // See if anything took the address of blocks in this function.  If so,
2977   // resolve them now.
2978   DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2979     BlockAddrFwdRefs.find(F);
2980   if (BAFRI != BlockAddrFwdRefs.end()) {
2981     std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2982     for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2983       unsigned BlockIdx = RefList[i].first;
2984       if (BlockIdx >= FunctionBBs.size())
2985         return Error("Invalid blockaddress block #");
2986
2987       GlobalVariable *FwdRef = RefList[i].second;
2988       FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2989       FwdRef->eraseFromParent();
2990     }
2991
2992     BlockAddrFwdRefs.erase(BAFRI);
2993   }
2994
2995   // Trim the value list down to the size it was before we parsed this function.
2996   ValueList.shrinkTo(ModuleValueListSize);
2997   MDValueList.shrinkTo(ModuleMDValueListSize);
2998   std::vector<BasicBlock*>().swap(FunctionBBs);
2999   return false;
3000 }
3001
3002 /// FindFunctionInStream - Find the function body in the bitcode stream
3003 bool BitcodeReader::FindFunctionInStream(Function *F,
3004        DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3005   while (DeferredFunctionInfoIterator->second == 0) {
3006     if (Stream.AtEndOfStream())
3007       return Error("Could not find Function in stream");
3008     // ParseModule will parse the next body in the stream and set its
3009     // position in the DeferredFunctionInfo map.
3010     if (ParseModule(true)) return true;
3011   }
3012   return false;
3013 }
3014
3015 //===----------------------------------------------------------------------===//
3016 // GVMaterializer implementation
3017 //===----------------------------------------------------------------------===//
3018
3019
3020 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3021   if (const Function *F = dyn_cast<Function>(GV)) {
3022     return F->isDeclaration() &&
3023       DeferredFunctionInfo.count(const_cast<Function*>(F));
3024   }
3025   return false;
3026 }
3027
3028 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
3029   Function *F = dyn_cast<Function>(GV);
3030   // If it's not a function or is already material, ignore the request.
3031   if (!F || !F->isMaterializable()) return false;
3032
3033   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3034   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3035   // If its position is recorded as 0, its body is somewhere in the stream
3036   // but we haven't seen it yet.
3037   if (DFII->second == 0)
3038     if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
3039
3040   // Move the bit stream to the saved position of the deferred function body.
3041   Stream.JumpToBit(DFII->second);
3042
3043   if (ParseFunctionBody(F)) {
3044     if (ErrInfo) *ErrInfo = ErrorString;
3045     return true;
3046   }
3047
3048   // Upgrade any old intrinsic calls in the function.
3049   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3050        E = UpgradedIntrinsics.end(); I != E; ++I) {
3051     if (I->first != I->second) {
3052       for (Value::use_iterator UI = I->first->use_begin(),
3053            UE = I->first->use_end(); UI != UE; ) {
3054         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3055           UpgradeIntrinsicCall(CI, I->second);
3056       }
3057     }
3058   }
3059
3060   return false;
3061 }
3062
3063 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3064   const Function *F = dyn_cast<Function>(GV);
3065   if (!F || F->isDeclaration())
3066     return false;
3067   return DeferredFunctionInfo.count(const_cast<Function*>(F));
3068 }
3069
3070 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3071   Function *F = dyn_cast<Function>(GV);
3072   // If this function isn't dematerializable, this is a noop.
3073   if (!F || !isDematerializable(F))
3074     return;
3075
3076   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3077
3078   // Just forget the function body, we can remat it later.
3079   F->deleteBody();
3080 }
3081
3082
3083 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
3084   assert(M == TheModule &&
3085          "Can only Materialize the Module this BitcodeReader is attached to.");
3086   // Iterate over the module, deserializing any functions that are still on
3087   // disk.
3088   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3089        F != E; ++F)
3090     if (F->isMaterializable() &&
3091         Materialize(F, ErrInfo))
3092       return true;
3093
3094   // At this point, if there are any function bodies, the current bit is
3095   // pointing to the END_BLOCK record after them. Now make sure the rest
3096   // of the bits in the module have been read.
3097   if (NextUnreadBit)
3098     ParseModule(true);
3099
3100   // Upgrade any intrinsic calls that slipped through (should not happen!) and
3101   // delete the old functions to clean up. We can't do this unless the entire
3102   // module is materialized because there could always be another function body
3103   // with calls to the old function.
3104   for (std::vector<std::pair<Function*, Function*> >::iterator I =
3105        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3106     if (I->first != I->second) {
3107       for (Value::use_iterator UI = I->first->use_begin(),
3108            UE = I->first->use_end(); UI != UE; ) {
3109         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3110           UpgradeIntrinsicCall(CI, I->second);
3111       }
3112       if (!I->first->use_empty())
3113         I->first->replaceAllUsesWith(I->second);
3114       I->first->eraseFromParent();
3115     }
3116   }
3117   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3118
3119   return false;
3120 }
3121
3122 bool BitcodeReader::InitStream() {
3123   if (LazyStreamer) return InitLazyStream();
3124   return InitStreamFromBuffer();
3125 }
3126
3127 bool BitcodeReader::InitStreamFromBuffer() {
3128   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3129   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3130
3131   if (Buffer->getBufferSize() & 3) {
3132     if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3133       return Error("Invalid bitcode signature");
3134     else
3135       return Error("Bitcode stream should be a multiple of 4 bytes in length");
3136   }
3137
3138   // If we have a wrapper header, parse it and ignore the non-bc file contents.
3139   // The magic number is 0x0B17C0DE stored in little endian.
3140   if (isBitcodeWrapper(BufPtr, BufEnd))
3141     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3142       return Error("Invalid bitcode wrapper header");
3143
3144   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3145   Stream.init(*StreamFile);
3146
3147   return false;
3148 }
3149
3150 bool BitcodeReader::InitLazyStream() {
3151   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3152   // see it.
3153   StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3154   StreamFile.reset(new BitstreamReader(Bytes));
3155   Stream.init(*StreamFile);
3156
3157   unsigned char buf[16];
3158   if (Bytes->readBytes(0, 16, buf) == -1)
3159     return Error("Bitcode stream must be at least 16 bytes in length");
3160
3161   if (!isBitcode(buf, buf + 16))
3162     return Error("Invalid bitcode signature");
3163
3164   if (isBitcodeWrapper(buf, buf + 4)) {
3165     const unsigned char *bitcodeStart = buf;
3166     const unsigned char *bitcodeEnd = buf + 16;
3167     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3168     Bytes->dropLeadingBytes(bitcodeStart - buf);
3169     Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3170   }
3171   return false;
3172 }
3173
3174 //===----------------------------------------------------------------------===//
3175 // External interface
3176 //===----------------------------------------------------------------------===//
3177
3178 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3179 ///
3180 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3181                                    LLVMContext& Context,
3182                                    std::string *ErrMsg) {
3183   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3184   BitcodeReader *R = new BitcodeReader(Buffer, Context);
3185   M->setMaterializer(R);
3186   if (R->ParseBitcodeInto(M)) {
3187     if (ErrMsg)
3188       *ErrMsg = R->getErrorString();
3189
3190     delete M;  // Also deletes R.
3191     return 0;
3192   }
3193   // Have the BitcodeReader dtor delete 'Buffer'.
3194   R->setBufferOwned(true);
3195
3196   R->materializeForwardReferencedFunctions();
3197
3198   return M;
3199 }
3200
3201
3202 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3203                                        DataStreamer *streamer,
3204                                        LLVMContext &Context,
3205                                        std::string *ErrMsg) {
3206   Module *M = new Module(name, Context);
3207   BitcodeReader *R = new BitcodeReader(streamer, Context);
3208   M->setMaterializer(R);
3209   if (R->ParseBitcodeInto(M)) {
3210     if (ErrMsg)
3211       *ErrMsg = R->getErrorString();
3212     delete M;  // Also deletes R.
3213     return 0;
3214   }
3215   R->setBufferOwned(false); // no buffer to delete
3216   return M;
3217 }
3218
3219 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3220 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3221 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3222                                std::string *ErrMsg){
3223   Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3224   if (!M) return 0;
3225
3226   // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3227   // there was an error.
3228   static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3229
3230   // Read in the entire module, and destroy the BitcodeReader.
3231   if (M->MaterializeAllPermanently(ErrMsg)) {
3232     delete M;
3233     return 0;
3234   }
3235
3236   // TODO: Restore the use-lists to the in-memory state when the bitcode was
3237   // written.  We must defer until the Module has been fully materialized.
3238
3239   return M;
3240 }
3241
3242 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3243                                          LLVMContext& Context,
3244                                          std::string *ErrMsg) {
3245   BitcodeReader *R = new BitcodeReader(Buffer, Context);
3246   // Don't let the BitcodeReader dtor delete 'Buffer'.
3247   R->setBufferOwned(false);
3248
3249   std::string Triple("");
3250   if (R->ParseTriple(Triple))
3251     if (ErrMsg)
3252       *ErrMsg = R->getErrorString();
3253
3254   delete R;
3255   return Triple;
3256 }