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