Verifier: Check accessors of MDLocation
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Bitcode/LLVMBitCodes.h"
17 #include "llvm/IR/AutoUpgrade.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfoMetadata.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/GVMaterializer.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/OperandTraits.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/DataStream.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <deque>
36 using namespace llvm;
37
38 namespace {
39 enum {
40   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
41 };
42
43 class BitcodeReaderValueList {
44   std::vector<WeakVH> ValuePtrs;
45
46   /// ResolveConstants - As we resolve forward-referenced constants, we add
47   /// information about them to this vector.  This allows us to resolve them in
48   /// bulk instead of resolving each reference at a time.  See the code in
49   /// ResolveConstantForwardRefs for more information about this.
50   ///
51   /// The key of this vector is the placeholder constant, the value is the slot
52   /// number that holds the resolved value.
53   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
54   ResolveConstantsTy ResolveConstants;
55   LLVMContext &Context;
56 public:
57   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
58   ~BitcodeReaderValueList() {
59     assert(ResolveConstants.empty() && "Constants not resolved?");
60   }
61
62   // vector compatibility methods
63   unsigned size() const { return ValuePtrs.size(); }
64   void resize(unsigned N) { ValuePtrs.resize(N); }
65   void push_back(Value *V) {
66     ValuePtrs.push_back(V);
67   }
68
69   void clear() {
70     assert(ResolveConstants.empty() && "Constants not resolved?");
71     ValuePtrs.clear();
72   }
73
74   Value *operator[](unsigned i) const {
75     assert(i < ValuePtrs.size());
76     return ValuePtrs[i];
77   }
78
79   Value *back() const { return ValuePtrs.back(); }
80     void pop_back() { ValuePtrs.pop_back(); }
81   bool empty() const { return ValuePtrs.empty(); }
82   void shrinkTo(unsigned N) {
83     assert(N <= size() && "Invalid shrinkTo request!");
84     ValuePtrs.resize(N);
85   }
86
87   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
88   Value *getValueFwdRef(unsigned Idx, Type *Ty);
89
90   void AssignValue(Value *V, unsigned Idx);
91
92   /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
93   /// resolves any forward references.
94   void ResolveConstantForwardRefs();
95 };
96
97 class BitcodeReaderMDValueList {
98   unsigned NumFwdRefs;
99   bool AnyFwdRefs;
100   unsigned MinFwdRef;
101   unsigned MaxFwdRef;
102   std::vector<TrackingMDRef> MDValuePtrs;
103
104   LLVMContext &Context;
105 public:
106   BitcodeReaderMDValueList(LLVMContext &C)
107       : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
108
109   // vector compatibility methods
110   unsigned size() const       { return MDValuePtrs.size(); }
111   void resize(unsigned N)     { MDValuePtrs.resize(N); }
112   void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
113   void clear()                { MDValuePtrs.clear();  }
114   Metadata *back() const      { return MDValuePtrs.back(); }
115   void pop_back()             { MDValuePtrs.pop_back(); }
116   bool empty() const          { return MDValuePtrs.empty(); }
117
118   Metadata *operator[](unsigned i) const {
119     assert(i < MDValuePtrs.size());
120     return MDValuePtrs[i];
121   }
122
123   void shrinkTo(unsigned N) {
124     assert(N <= size() && "Invalid shrinkTo request!");
125     MDValuePtrs.resize(N);
126   }
127
128   Metadata *getValueFwdRef(unsigned Idx);
129   void AssignValue(Metadata *MD, unsigned Idx);
130   void tryToResolveCycles();
131 };
132
133 class BitcodeReader : public GVMaterializer {
134   LLVMContext &Context;
135   DiagnosticHandlerFunction DiagnosticHandler;
136   Module *TheModule;
137   std::unique_ptr<MemoryBuffer> Buffer;
138   std::unique_ptr<BitstreamReader> StreamFile;
139   BitstreamCursor Stream;
140   DataStreamer *LazyStreamer;
141   uint64_t NextUnreadBit;
142   bool SeenValueSymbolTable;
143
144   std::vector<Type*> TypeList;
145   BitcodeReaderValueList ValueList;
146   BitcodeReaderMDValueList MDValueList;
147   std::vector<Comdat *> ComdatList;
148   SmallVector<Instruction *, 64> InstructionList;
149
150   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
151   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
152   std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
153   std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
154
155   SmallVector<Instruction*, 64> InstsWithTBAATag;
156
157   /// MAttributes - The set of attributes by index.  Index zero in the
158   /// file is for null, and is thus not represented here.  As such all indices
159   /// are off by one.
160   std::vector<AttributeSet> MAttributes;
161
162   /// \brief The set of attribute groups.
163   std::map<unsigned, AttributeSet> MAttributeGroups;
164
165   /// FunctionBBs - While parsing a function body, this is a list of the basic
166   /// blocks for the function.
167   std::vector<BasicBlock*> FunctionBBs;
168
169   // When reading the module header, this list is populated with functions that
170   // have bodies later in the file.
171   std::vector<Function*> FunctionsWithBodies;
172
173   // When intrinsic functions are encountered which require upgrading they are
174   // stored here with their replacement function.
175   typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
176   UpgradedIntrinsicMap UpgradedIntrinsics;
177
178   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
179   DenseMap<unsigned, unsigned> MDKindMap;
180
181   // Several operations happen after the module header has been read, but
182   // before function bodies are processed. This keeps track of whether
183   // we've done this yet.
184   bool SeenFirstFunctionBody;
185
186   /// DeferredFunctionInfo - When function bodies are initially scanned, this
187   /// map contains info about where to find deferred function body in the
188   /// stream.
189   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
190
191   /// When Metadata block is initially scanned when parsing the module, we may
192   /// choose to defer parsing of the metadata. This vector contains info about
193   /// which Metadata blocks are deferred.
194   std::vector<uint64_t> DeferredMetadataInfo;
195
196   /// These are basic blocks forward-referenced by block addresses.  They are
197   /// inserted lazily into functions when they're loaded.  The basic block ID is
198   /// its index into the vector.
199   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
200   std::deque<Function *> BasicBlockFwdRefQueue;
201
202   /// UseRelativeIDs - Indicates that we are using a new encoding for
203   /// instruction operands where most operands in the current
204   /// FUNCTION_BLOCK are encoded relative to the instruction number,
205   /// for a more compact encoding.  Some instruction operands are not
206   /// relative to the instruction ID: basic block numbers, and types.
207   /// Once the old style function blocks have been phased out, we would
208   /// not need this flag.
209   bool UseRelativeIDs;
210
211   /// True if all functions will be materialized, negating the need to process
212   /// (e.g.) blockaddress forward references.
213   bool WillMaterializeAllForwardRefs;
214
215   /// Functions that have block addresses taken.  This is usually empty.
216   SmallPtrSet<const Function *, 4> BlockAddressesTaken;
217
218   /// True if any Metadata block has been materialized.
219   bool IsMetadataMaterialized;
220
221 public:
222   std::error_code Error(BitcodeError E, const Twine &Message);
223   std::error_code Error(BitcodeError E);
224   std::error_code Error(const Twine &Message);
225
226   explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
227                          DiagnosticHandlerFunction DiagnosticHandler);
228   explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C,
229                          DiagnosticHandlerFunction DiagnosticHandler);
230   ~BitcodeReader() { FreeState(); }
231
232   std::error_code materializeForwardReferencedFunctions();
233
234   void FreeState();
235
236   void releaseBuffer();
237
238   bool isDematerializable(const GlobalValue *GV) const override;
239   std::error_code materialize(GlobalValue *GV) override;
240   std::error_code MaterializeModule(Module *M) override;
241   std::vector<StructType *> getIdentifiedStructTypes() const override;
242   void Dematerialize(GlobalValue *GV) override;
243
244   /// @brief Main interface to parsing a bitcode buffer.
245   /// @returns true if an error occurred.
246   std::error_code ParseBitcodeInto(Module *M,
247                                    bool ShouldLazyLoadMetadata = false);
248
249   /// @brief Cheap mechanism to just extract module triple
250   /// @returns true if an error occurred.
251   ErrorOr<std::string> parseTriple();
252
253   static uint64_t decodeSignRotatedValue(uint64_t V);
254
255   /// Materialize any deferred Metadata block.
256   std::error_code materializeMetadata() override;
257
258 private:
259   std::vector<StructType *> IdentifiedStructTypes;
260   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
261   StructType *createIdentifiedStructType(LLVMContext &Context);
262
263   Type *getTypeByID(unsigned ID);
264   Value *getFnValueByID(unsigned ID, Type *Ty) {
265     if (Ty && Ty->isMetadataTy())
266       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
267     return ValueList.getValueFwdRef(ID, Ty);
268   }
269   Metadata *getFnMetadataByID(unsigned ID) {
270     return MDValueList.getValueFwdRef(ID);
271   }
272   BasicBlock *getBasicBlock(unsigned ID) const {
273     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
274     return FunctionBBs[ID];
275   }
276   AttributeSet getAttributes(unsigned i) const {
277     if (i-1 < MAttributes.size())
278       return MAttributes[i-1];
279     return AttributeSet();
280   }
281
282   /// getValueTypePair - Read a value/type pair out of the specified record from
283   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
284   /// Return true on failure.
285   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
286                         unsigned InstNum, Value *&ResVal) {
287     if (Slot == Record.size()) return true;
288     unsigned ValNo = (unsigned)Record[Slot++];
289     // Adjust the ValNo, if it was encoded relative to the InstNum.
290     if (UseRelativeIDs)
291       ValNo = InstNum - ValNo;
292     if (ValNo < InstNum) {
293       // If this is not a forward reference, just return the value we already
294       // have.
295       ResVal = getFnValueByID(ValNo, nullptr);
296       return ResVal == nullptr;
297     } else if (Slot == Record.size()) {
298       return true;
299     }
300
301     unsigned TypeNo = (unsigned)Record[Slot++];
302     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
303     return ResVal == nullptr;
304   }
305
306   /// popValue - Read a value out of the specified record from slot 'Slot'.
307   /// Increment Slot past the number of slots used by the value in the record.
308   /// Return true if there is an error.
309   bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
310                 unsigned InstNum, Type *Ty, Value *&ResVal) {
311     if (getValue(Record, Slot, InstNum, Ty, ResVal))
312       return true;
313     // All values currently take a single record slot.
314     ++Slot;
315     return false;
316   }
317
318   /// getValue -- Like popValue, but does not increment the Slot number.
319   bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
320                 unsigned InstNum, Type *Ty, Value *&ResVal) {
321     ResVal = getValue(Record, Slot, InstNum, Ty);
322     return ResVal == nullptr;
323   }
324
325   /// getValue -- Version of getValue that returns ResVal directly,
326   /// or 0 if there is an error.
327   Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
328                   unsigned InstNum, Type *Ty) {
329     if (Slot == Record.size()) return nullptr;
330     unsigned ValNo = (unsigned)Record[Slot];
331     // Adjust the ValNo, if it was encoded relative to the InstNum.
332     if (UseRelativeIDs)
333       ValNo = InstNum - ValNo;
334     return getFnValueByID(ValNo, Ty);
335   }
336
337   /// getValueSigned -- Like getValue, but decodes signed VBRs.
338   Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
339                         unsigned InstNum, Type *Ty) {
340     if (Slot == Record.size()) return nullptr;
341     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
342     // Adjust the ValNo, if it was encoded relative to the InstNum.
343     if (UseRelativeIDs)
344       ValNo = InstNum - ValNo;
345     return getFnValueByID(ValNo, Ty);
346   }
347
348   /// Converts alignment exponent (i.e. power of two (or zero)) to the
349   /// corresponding alignment to use. If alignment is too large, returns
350   /// a corresponding error code.
351   std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
352   std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
353   std::error_code ParseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
354   std::error_code ParseAttributeBlock();
355   std::error_code ParseAttributeGroupBlock();
356   std::error_code ParseTypeTable();
357   std::error_code ParseTypeTableBody();
358
359   std::error_code ParseValueSymbolTable();
360   std::error_code ParseConstants();
361   std::error_code RememberAndSkipFunctionBody();
362   /// Save the positions of the Metadata blocks and skip parsing the blocks.
363   std::error_code rememberAndSkipMetadata();
364   std::error_code ParseFunctionBody(Function *F);
365   std::error_code GlobalCleanup();
366   std::error_code ResolveGlobalAndAliasInits();
367   std::error_code ParseMetadata();
368   std::error_code ParseMetadataAttachment();
369   ErrorOr<std::string> parseModuleTriple();
370   std::error_code ParseUseLists();
371   std::error_code InitStream();
372   std::error_code InitStreamFromBuffer();
373   std::error_code InitLazyStream();
374   std::error_code FindFunctionInStream(
375       Function *F,
376       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
377 };
378 } // namespace
379
380 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
381                                              DiagnosticSeverity Severity,
382                                              const Twine &Msg)
383     : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
384
385 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
386
387 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
388                              std::error_code EC, const Twine &Message) {
389   BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
390   DiagnosticHandler(DI);
391   return EC;
392 }
393
394 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
395                              std::error_code EC) {
396   return Error(DiagnosticHandler, EC, EC.message());
397 }
398
399 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
400   return ::Error(DiagnosticHandler, make_error_code(E), Message);
401 }
402
403 std::error_code BitcodeReader::Error(const Twine &Message) {
404   return ::Error(DiagnosticHandler,
405                  make_error_code(BitcodeError::CorruptedBitcode), Message);
406 }
407
408 std::error_code BitcodeReader::Error(BitcodeError E) {
409   return ::Error(DiagnosticHandler, make_error_code(E));
410 }
411
412 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
413                                                 LLVMContext &C) {
414   if (F)
415     return F;
416   return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
417 }
418
419 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
420                              DiagnosticHandlerFunction DiagnosticHandler)
421     : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
422       TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
423       NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
424       MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
425       WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
426
427 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
428                              DiagnosticHandlerFunction DiagnosticHandler)
429     : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
430       TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
431       NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
432       MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
433       WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
434
435 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
436   if (WillMaterializeAllForwardRefs)
437     return std::error_code();
438
439   // Prevent recursion.
440   WillMaterializeAllForwardRefs = true;
441
442   while (!BasicBlockFwdRefQueue.empty()) {
443     Function *F = BasicBlockFwdRefQueue.front();
444     BasicBlockFwdRefQueue.pop_front();
445     assert(F && "Expected valid function");
446     if (!BasicBlockFwdRefs.count(F))
447       // Already materialized.
448       continue;
449
450     // Check for a function that isn't materializable to prevent an infinite
451     // loop.  When parsing a blockaddress stored in a global variable, there
452     // isn't a trivial way to check if a function will have a body without a
453     // linear search through FunctionsWithBodies, so just check it here.
454     if (!F->isMaterializable())
455       return Error("Never resolved function from blockaddress");
456
457     // Try to materialize F.
458     if (std::error_code EC = materialize(F))
459       return EC;
460   }
461   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
462
463   // Reset state.
464   WillMaterializeAllForwardRefs = false;
465   return std::error_code();
466 }
467
468 void BitcodeReader::FreeState() {
469   Buffer = nullptr;
470   std::vector<Type*>().swap(TypeList);
471   ValueList.clear();
472   MDValueList.clear();
473   std::vector<Comdat *>().swap(ComdatList);
474
475   std::vector<AttributeSet>().swap(MAttributes);
476   std::vector<BasicBlock*>().swap(FunctionBBs);
477   std::vector<Function*>().swap(FunctionsWithBodies);
478   DeferredFunctionInfo.clear();
479   DeferredMetadataInfo.clear();
480   MDKindMap.clear();
481
482   assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
483   BasicBlockFwdRefQueue.clear();
484 }
485
486 //===----------------------------------------------------------------------===//
487 //  Helper functions to implement forward reference resolution, etc.
488 //===----------------------------------------------------------------------===//
489
490 /// ConvertToString - Convert a string from a record into an std::string, return
491 /// true on failure.
492 template<typename StrTy>
493 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
494                             StrTy &Result) {
495   if (Idx > Record.size())
496     return true;
497
498   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
499     Result += (char)Record[i];
500   return false;
501 }
502
503 static bool hasImplicitComdat(size_t Val) {
504   switch (Val) {
505   default:
506     return false;
507   case 1:  // Old WeakAnyLinkage
508   case 4:  // Old LinkOnceAnyLinkage
509   case 10: // Old WeakODRLinkage
510   case 11: // Old LinkOnceODRLinkage
511     return true;
512   }
513 }
514
515 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
516   switch (Val) {
517   default: // Map unknown/new linkages to external
518   case 0:
519     return GlobalValue::ExternalLinkage;
520   case 2:
521     return GlobalValue::AppendingLinkage;
522   case 3:
523     return GlobalValue::InternalLinkage;
524   case 5:
525     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
526   case 6:
527     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
528   case 7:
529     return GlobalValue::ExternalWeakLinkage;
530   case 8:
531     return GlobalValue::CommonLinkage;
532   case 9:
533     return GlobalValue::PrivateLinkage;
534   case 12:
535     return GlobalValue::AvailableExternallyLinkage;
536   case 13:
537     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
538   case 14:
539     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
540   case 15:
541     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
542   case 1: // Old value with implicit comdat.
543   case 16:
544     return GlobalValue::WeakAnyLinkage;
545   case 10: // Old value with implicit comdat.
546   case 17:
547     return GlobalValue::WeakODRLinkage;
548   case 4: // Old value with implicit comdat.
549   case 18:
550     return GlobalValue::LinkOnceAnyLinkage;
551   case 11: // Old value with implicit comdat.
552   case 19:
553     return GlobalValue::LinkOnceODRLinkage;
554   }
555 }
556
557 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
558   switch (Val) {
559   default: // Map unknown visibilities to default.
560   case 0: return GlobalValue::DefaultVisibility;
561   case 1: return GlobalValue::HiddenVisibility;
562   case 2: return GlobalValue::ProtectedVisibility;
563   }
564 }
565
566 static GlobalValue::DLLStorageClassTypes
567 GetDecodedDLLStorageClass(unsigned Val) {
568   switch (Val) {
569   default: // Map unknown values to default.
570   case 0: return GlobalValue::DefaultStorageClass;
571   case 1: return GlobalValue::DLLImportStorageClass;
572   case 2: return GlobalValue::DLLExportStorageClass;
573   }
574 }
575
576 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
577   switch (Val) {
578     case 0: return GlobalVariable::NotThreadLocal;
579     default: // Map unknown non-zero value to general dynamic.
580     case 1: return GlobalVariable::GeneralDynamicTLSModel;
581     case 2: return GlobalVariable::LocalDynamicTLSModel;
582     case 3: return GlobalVariable::InitialExecTLSModel;
583     case 4: return GlobalVariable::LocalExecTLSModel;
584   }
585 }
586
587 static int GetDecodedCastOpcode(unsigned Val) {
588   switch (Val) {
589   default: return -1;
590   case bitc::CAST_TRUNC   : return Instruction::Trunc;
591   case bitc::CAST_ZEXT    : return Instruction::ZExt;
592   case bitc::CAST_SEXT    : return Instruction::SExt;
593   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
594   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
595   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
596   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
597   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
598   case bitc::CAST_FPEXT   : return Instruction::FPExt;
599   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
600   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
601   case bitc::CAST_BITCAST : return Instruction::BitCast;
602   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
603   }
604 }
605 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
606   switch (Val) {
607   default: return -1;
608   case bitc::BINOP_ADD:
609     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
610   case bitc::BINOP_SUB:
611     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
612   case bitc::BINOP_MUL:
613     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
614   case bitc::BINOP_UDIV: return Instruction::UDiv;
615   case bitc::BINOP_SDIV:
616     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
617   case bitc::BINOP_UREM: return Instruction::URem;
618   case bitc::BINOP_SREM:
619     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
620   case bitc::BINOP_SHL:  return Instruction::Shl;
621   case bitc::BINOP_LSHR: return Instruction::LShr;
622   case bitc::BINOP_ASHR: return Instruction::AShr;
623   case bitc::BINOP_AND:  return Instruction::And;
624   case bitc::BINOP_OR:   return Instruction::Or;
625   case bitc::BINOP_XOR:  return Instruction::Xor;
626   }
627 }
628
629 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
630   switch (Val) {
631   default: return AtomicRMWInst::BAD_BINOP;
632   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
633   case bitc::RMW_ADD: return AtomicRMWInst::Add;
634   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
635   case bitc::RMW_AND: return AtomicRMWInst::And;
636   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
637   case bitc::RMW_OR: return AtomicRMWInst::Or;
638   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
639   case bitc::RMW_MAX: return AtomicRMWInst::Max;
640   case bitc::RMW_MIN: return AtomicRMWInst::Min;
641   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
642   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
643   }
644 }
645
646 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
647   switch (Val) {
648   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
649   case bitc::ORDERING_UNORDERED: return Unordered;
650   case bitc::ORDERING_MONOTONIC: return Monotonic;
651   case bitc::ORDERING_ACQUIRE: return Acquire;
652   case bitc::ORDERING_RELEASE: return Release;
653   case bitc::ORDERING_ACQREL: return AcquireRelease;
654   default: // Map unknown orderings to sequentially-consistent.
655   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
656   }
657 }
658
659 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
660   switch (Val) {
661   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
662   default: // Map unknown scopes to cross-thread.
663   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
664   }
665 }
666
667 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
668   switch (Val) {
669   default: // Map unknown selection kinds to any.
670   case bitc::COMDAT_SELECTION_KIND_ANY:
671     return Comdat::Any;
672   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
673     return Comdat::ExactMatch;
674   case bitc::COMDAT_SELECTION_KIND_LARGEST:
675     return Comdat::Largest;
676   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
677     return Comdat::NoDuplicates;
678   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
679     return Comdat::SameSize;
680   }
681 }
682
683 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
684   switch (Val) {
685   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
686   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
687   }
688 }
689
690 namespace llvm {
691 namespace {
692   /// @brief A class for maintaining the slot number definition
693   /// as a placeholder for the actual definition for forward constants defs.
694   class ConstantPlaceHolder : public ConstantExpr {
695     void operator=(const ConstantPlaceHolder &) = delete;
696   public:
697     // allocate space for exactly one operand
698     void *operator new(size_t s) {
699       return User::operator new(s, 1);
700     }
701     explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
702       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
703       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
704     }
705
706     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
707     static bool classof(const Value *V) {
708       return isa<ConstantExpr>(V) &&
709              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
710     }
711
712
713     /// Provide fast operand accessors
714     DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
715   };
716 }
717
718 // FIXME: can we inherit this from ConstantExpr?
719 template <>
720 struct OperandTraits<ConstantPlaceHolder> :
721   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
722 };
723 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
724 }
725
726
727 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
728   if (Idx == size()) {
729     push_back(V);
730     return;
731   }
732
733   if (Idx >= size())
734     resize(Idx+1);
735
736   WeakVH &OldV = ValuePtrs[Idx];
737   if (!OldV) {
738     OldV = V;
739     return;
740   }
741
742   // Handle constants and non-constants (e.g. instrs) differently for
743   // efficiency.
744   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
745     ResolveConstants.push_back(std::make_pair(PHC, Idx));
746     OldV = V;
747   } else {
748     // If there was a forward reference to this value, replace it.
749     Value *PrevVal = OldV;
750     OldV->replaceAllUsesWith(V);
751     delete PrevVal;
752   }
753 }
754
755
756 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
757                                                     Type *Ty) {
758   if (Idx >= size())
759     resize(Idx + 1);
760
761   if (Value *V = ValuePtrs[Idx]) {
762     assert(Ty == V->getType() && "Type mismatch in constant table!");
763     return cast<Constant>(V);
764   }
765
766   // Create and return a placeholder, which will later be RAUW'd.
767   Constant *C = new ConstantPlaceHolder(Ty, Context);
768   ValuePtrs[Idx] = C;
769   return C;
770 }
771
772 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
773   if (Idx >= size())
774     resize(Idx + 1);
775
776   if (Value *V = ValuePtrs[Idx]) {
777     assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
778     return V;
779   }
780
781   // No type specified, must be invalid reference.
782   if (!Ty) return nullptr;
783
784   // Create and return a placeholder, which will later be RAUW'd.
785   Value *V = new Argument(Ty);
786   ValuePtrs[Idx] = V;
787   return V;
788 }
789
790 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
791 /// resolves any forward references.  The idea behind this is that we sometimes
792 /// get constants (such as large arrays) which reference *many* forward ref
793 /// constants.  Replacing each of these causes a lot of thrashing when
794 /// building/reuniquing the constant.  Instead of doing this, we look at all the
795 /// uses and rewrite all the place holders at once for any constant that uses
796 /// a placeholder.
797 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
798   // Sort the values by-pointer so that they are efficient to look up with a
799   // binary search.
800   std::sort(ResolveConstants.begin(), ResolveConstants.end());
801
802   SmallVector<Constant*, 64> NewOps;
803
804   while (!ResolveConstants.empty()) {
805     Value *RealVal = operator[](ResolveConstants.back().second);
806     Constant *Placeholder = ResolveConstants.back().first;
807     ResolveConstants.pop_back();
808
809     // Loop over all users of the placeholder, updating them to reference the
810     // new value.  If they reference more than one placeholder, update them all
811     // at once.
812     while (!Placeholder->use_empty()) {
813       auto UI = Placeholder->user_begin();
814       User *U = *UI;
815
816       // If the using object isn't uniqued, just update the operands.  This
817       // handles instructions and initializers for global variables.
818       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
819         UI.getUse().set(RealVal);
820         continue;
821       }
822
823       // Otherwise, we have a constant that uses the placeholder.  Replace that
824       // constant with a new constant that has *all* placeholder uses updated.
825       Constant *UserC = cast<Constant>(U);
826       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
827            I != E; ++I) {
828         Value *NewOp;
829         if (!isa<ConstantPlaceHolder>(*I)) {
830           // Not a placeholder reference.
831           NewOp = *I;
832         } else if (*I == Placeholder) {
833           // Common case is that it just references this one placeholder.
834           NewOp = RealVal;
835         } else {
836           // Otherwise, look up the placeholder in ResolveConstants.
837           ResolveConstantsTy::iterator It =
838             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
839                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
840                                                             0));
841           assert(It != ResolveConstants.end() && It->first == *I);
842           NewOp = operator[](It->second);
843         }
844
845         NewOps.push_back(cast<Constant>(NewOp));
846       }
847
848       // Make the new constant.
849       Constant *NewC;
850       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
851         NewC = ConstantArray::get(UserCA->getType(), NewOps);
852       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
853         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
854       } else if (isa<ConstantVector>(UserC)) {
855         NewC = ConstantVector::get(NewOps);
856       } else {
857         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
858         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
859       }
860
861       UserC->replaceAllUsesWith(NewC);
862       UserC->destroyConstant();
863       NewOps.clear();
864     }
865
866     // Update all ValueHandles, they should be the only users at this point.
867     Placeholder->replaceAllUsesWith(RealVal);
868     delete Placeholder;
869   }
870 }
871
872 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
873   if (Idx == size()) {
874     push_back(MD);
875     return;
876   }
877
878   if (Idx >= size())
879     resize(Idx+1);
880
881   TrackingMDRef &OldMD = MDValuePtrs[Idx];
882   if (!OldMD) {
883     OldMD.reset(MD);
884     return;
885   }
886
887   // If there was a forward reference to this value, replace it.
888   TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
889   PrevMD->replaceAllUsesWith(MD);
890   --NumFwdRefs;
891 }
892
893 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
894   if (Idx >= size())
895     resize(Idx + 1);
896
897   if (Metadata *MD = MDValuePtrs[Idx])
898     return MD;
899
900   // Track forward refs to be resolved later.
901   if (AnyFwdRefs) {
902     MinFwdRef = std::min(MinFwdRef, Idx);
903     MaxFwdRef = std::max(MaxFwdRef, Idx);
904   } else {
905     AnyFwdRefs = true;
906     MinFwdRef = MaxFwdRef = Idx;
907   }
908   ++NumFwdRefs;
909
910   // Create and return a placeholder, which will later be RAUW'd.
911   Metadata *MD = MDNode::getTemporary(Context, None).release();
912   MDValuePtrs[Idx].reset(MD);
913   return MD;
914 }
915
916 void BitcodeReaderMDValueList::tryToResolveCycles() {
917   if (!AnyFwdRefs)
918     // Nothing to do.
919     return;
920
921   if (NumFwdRefs)
922     // Still forward references... can't resolve cycles.
923     return;
924
925   // Resolve any cycles.
926   for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
927     auto &MD = MDValuePtrs[I];
928     auto *N = dyn_cast_or_null<MDNode>(MD);
929     if (!N)
930       continue;
931
932     assert(!N->isTemporary() && "Unexpected forward reference");
933     N->resolveCycles();
934   }
935
936   // Make sure we return early again until there's another forward ref.
937   AnyFwdRefs = false;
938 }
939
940 Type *BitcodeReader::getTypeByID(unsigned ID) {
941   // The type table size is always specified correctly.
942   if (ID >= TypeList.size())
943     return nullptr;
944
945   if (Type *Ty = TypeList[ID])
946     return Ty;
947
948   // If we have a forward reference, the only possible case is when it is to a
949   // named struct.  Just create a placeholder for now.
950   return TypeList[ID] = createIdentifiedStructType(Context);
951 }
952
953 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
954                                                       StringRef Name) {
955   auto *Ret = StructType::create(Context, Name);
956   IdentifiedStructTypes.push_back(Ret);
957   return Ret;
958 }
959
960 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
961   auto *Ret = StructType::create(Context);
962   IdentifiedStructTypes.push_back(Ret);
963   return Ret;
964 }
965
966
967 //===----------------------------------------------------------------------===//
968 //  Functions for parsing blocks from the bitcode file
969 //===----------------------------------------------------------------------===//
970
971
972 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
973 /// been decoded from the given integer. This function must stay in sync with
974 /// 'encodeLLVMAttributesForBitcode'.
975 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
976                                            uint64_t EncodedAttrs) {
977   // FIXME: Remove in 4.0.
978
979   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
980   // the bits above 31 down by 11 bits.
981   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
982   assert((!Alignment || isPowerOf2_32(Alignment)) &&
983          "Alignment must be a power of two.");
984
985   if (Alignment)
986     B.addAlignmentAttr(Alignment);
987   B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
988                 (EncodedAttrs & 0xffff));
989 }
990
991 std::error_code BitcodeReader::ParseAttributeBlock() {
992   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
993     return Error("Invalid record");
994
995   if (!MAttributes.empty())
996     return Error("Invalid multiple blocks");
997
998   SmallVector<uint64_t, 64> Record;
999
1000   SmallVector<AttributeSet, 8> Attrs;
1001
1002   // Read all the records.
1003   while (1) {
1004     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1005
1006     switch (Entry.Kind) {
1007     case BitstreamEntry::SubBlock: // Handled for us already.
1008     case BitstreamEntry::Error:
1009       return Error("Malformed block");
1010     case BitstreamEntry::EndBlock:
1011       return std::error_code();
1012     case BitstreamEntry::Record:
1013       // The interesting case.
1014       break;
1015     }
1016
1017     // Read a record.
1018     Record.clear();
1019     switch (Stream.readRecord(Entry.ID, Record)) {
1020     default:  // Default behavior: ignore.
1021       break;
1022     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1023       // FIXME: Remove in 4.0.
1024       if (Record.size() & 1)
1025         return Error("Invalid record");
1026
1027       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1028         AttrBuilder B;
1029         decodeLLVMAttributesForBitcode(B, Record[i+1]);
1030         Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1031       }
1032
1033       MAttributes.push_back(AttributeSet::get(Context, Attrs));
1034       Attrs.clear();
1035       break;
1036     }
1037     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1038       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1039         Attrs.push_back(MAttributeGroups[Record[i]]);
1040
1041       MAttributes.push_back(AttributeSet::get(Context, Attrs));
1042       Attrs.clear();
1043       break;
1044     }
1045     }
1046   }
1047 }
1048
1049 // Returns Attribute::None on unrecognized codes.
1050 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1051   switch (Code) {
1052   default:
1053     return Attribute::None;
1054   case bitc::ATTR_KIND_ALIGNMENT:
1055     return Attribute::Alignment;
1056   case bitc::ATTR_KIND_ALWAYS_INLINE:
1057     return Attribute::AlwaysInline;
1058   case bitc::ATTR_KIND_BUILTIN:
1059     return Attribute::Builtin;
1060   case bitc::ATTR_KIND_BY_VAL:
1061     return Attribute::ByVal;
1062   case bitc::ATTR_KIND_IN_ALLOCA:
1063     return Attribute::InAlloca;
1064   case bitc::ATTR_KIND_COLD:
1065     return Attribute::Cold;
1066   case bitc::ATTR_KIND_INLINE_HINT:
1067     return Attribute::InlineHint;
1068   case bitc::ATTR_KIND_IN_REG:
1069     return Attribute::InReg;
1070   case bitc::ATTR_KIND_JUMP_TABLE:
1071     return Attribute::JumpTable;
1072   case bitc::ATTR_KIND_MIN_SIZE:
1073     return Attribute::MinSize;
1074   case bitc::ATTR_KIND_NAKED:
1075     return Attribute::Naked;
1076   case bitc::ATTR_KIND_NEST:
1077     return Attribute::Nest;
1078   case bitc::ATTR_KIND_NO_ALIAS:
1079     return Attribute::NoAlias;
1080   case bitc::ATTR_KIND_NO_BUILTIN:
1081     return Attribute::NoBuiltin;
1082   case bitc::ATTR_KIND_NO_CAPTURE:
1083     return Attribute::NoCapture;
1084   case bitc::ATTR_KIND_NO_DUPLICATE:
1085     return Attribute::NoDuplicate;
1086   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1087     return Attribute::NoImplicitFloat;
1088   case bitc::ATTR_KIND_NO_INLINE:
1089     return Attribute::NoInline;
1090   case bitc::ATTR_KIND_NON_LAZY_BIND:
1091     return Attribute::NonLazyBind;
1092   case bitc::ATTR_KIND_NON_NULL:
1093     return Attribute::NonNull;
1094   case bitc::ATTR_KIND_DEREFERENCEABLE:
1095     return Attribute::Dereferenceable;
1096   case bitc::ATTR_KIND_NO_RED_ZONE:
1097     return Attribute::NoRedZone;
1098   case bitc::ATTR_KIND_NO_RETURN:
1099     return Attribute::NoReturn;
1100   case bitc::ATTR_KIND_NO_UNWIND:
1101     return Attribute::NoUnwind;
1102   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1103     return Attribute::OptimizeForSize;
1104   case bitc::ATTR_KIND_OPTIMIZE_NONE:
1105     return Attribute::OptimizeNone;
1106   case bitc::ATTR_KIND_READ_NONE:
1107     return Attribute::ReadNone;
1108   case bitc::ATTR_KIND_READ_ONLY:
1109     return Attribute::ReadOnly;
1110   case bitc::ATTR_KIND_RETURNED:
1111     return Attribute::Returned;
1112   case bitc::ATTR_KIND_RETURNS_TWICE:
1113     return Attribute::ReturnsTwice;
1114   case bitc::ATTR_KIND_S_EXT:
1115     return Attribute::SExt;
1116   case bitc::ATTR_KIND_STACK_ALIGNMENT:
1117     return Attribute::StackAlignment;
1118   case bitc::ATTR_KIND_STACK_PROTECT:
1119     return Attribute::StackProtect;
1120   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1121     return Attribute::StackProtectReq;
1122   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1123     return Attribute::StackProtectStrong;
1124   case bitc::ATTR_KIND_STRUCT_RET:
1125     return Attribute::StructRet;
1126   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1127     return Attribute::SanitizeAddress;
1128   case bitc::ATTR_KIND_SANITIZE_THREAD:
1129     return Attribute::SanitizeThread;
1130   case bitc::ATTR_KIND_SANITIZE_MEMORY:
1131     return Attribute::SanitizeMemory;
1132   case bitc::ATTR_KIND_UW_TABLE:
1133     return Attribute::UWTable;
1134   case bitc::ATTR_KIND_Z_EXT:
1135     return Attribute::ZExt;
1136   }
1137 }
1138
1139 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1140                                                    unsigned &Alignment) {
1141   // Note: Alignment in bitcode files is incremented by 1, so that zero
1142   // can be used for default alignment.
1143   if (Exponent > Value::MaxAlignmentExponent + 1)
1144     return Error("Invalid alignment value");
1145   Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1146   return std::error_code();
1147 }
1148
1149 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1150                                              Attribute::AttrKind *Kind) {
1151   *Kind = GetAttrFromCode(Code);
1152   if (*Kind == Attribute::None)
1153     return Error(BitcodeError::CorruptedBitcode,
1154                  "Unknown attribute kind (" + Twine(Code) + ")");
1155   return std::error_code();
1156 }
1157
1158 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
1159   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1160     return Error("Invalid record");
1161
1162   if (!MAttributeGroups.empty())
1163     return Error("Invalid multiple blocks");
1164
1165   SmallVector<uint64_t, 64> Record;
1166
1167   // Read all the records.
1168   while (1) {
1169     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1170
1171     switch (Entry.Kind) {
1172     case BitstreamEntry::SubBlock: // Handled for us already.
1173     case BitstreamEntry::Error:
1174       return Error("Malformed block");
1175     case BitstreamEntry::EndBlock:
1176       return std::error_code();
1177     case BitstreamEntry::Record:
1178       // The interesting case.
1179       break;
1180     }
1181
1182     // Read a record.
1183     Record.clear();
1184     switch (Stream.readRecord(Entry.ID, Record)) {
1185     default:  // Default behavior: ignore.
1186       break;
1187     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1188       if (Record.size() < 3)
1189         return Error("Invalid record");
1190
1191       uint64_t GrpID = Record[0];
1192       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1193
1194       AttrBuilder B;
1195       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1196         if (Record[i] == 0) {        // Enum attribute
1197           Attribute::AttrKind Kind;
1198           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1199             return EC;
1200
1201           B.addAttribute(Kind);
1202         } else if (Record[i] == 1) { // Integer attribute
1203           Attribute::AttrKind Kind;
1204           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
1205             return EC;
1206           if (Kind == Attribute::Alignment)
1207             B.addAlignmentAttr(Record[++i]);
1208           else if (Kind == Attribute::StackAlignment)
1209             B.addStackAlignmentAttr(Record[++i]);
1210           else if (Kind == Attribute::Dereferenceable)
1211             B.addDereferenceableAttr(Record[++i]);
1212         } else {                     // String attribute
1213           assert((Record[i] == 3 || Record[i] == 4) &&
1214                  "Invalid attribute group entry");
1215           bool HasValue = (Record[i++] == 4);
1216           SmallString<64> KindStr;
1217           SmallString<64> ValStr;
1218
1219           while (Record[i] != 0 && i != e)
1220             KindStr += Record[i++];
1221           assert(Record[i] == 0 && "Kind string not null terminated");
1222
1223           if (HasValue) {
1224             // Has a value associated with it.
1225             ++i; // Skip the '0' that terminates the "kind" string.
1226             while (Record[i] != 0 && i != e)
1227               ValStr += Record[i++];
1228             assert(Record[i] == 0 && "Value string not null terminated");
1229           }
1230
1231           B.addAttribute(KindStr.str(), ValStr.str());
1232         }
1233       }
1234
1235       MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1236       break;
1237     }
1238     }
1239   }
1240 }
1241
1242 std::error_code BitcodeReader::ParseTypeTable() {
1243   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1244     return Error("Invalid record");
1245
1246   return ParseTypeTableBody();
1247 }
1248
1249 std::error_code BitcodeReader::ParseTypeTableBody() {
1250   if (!TypeList.empty())
1251     return Error("Invalid multiple blocks");
1252
1253   SmallVector<uint64_t, 64> Record;
1254   unsigned NumRecords = 0;
1255
1256   SmallString<64> TypeName;
1257
1258   // Read all the records for this type table.
1259   while (1) {
1260     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1261
1262     switch (Entry.Kind) {
1263     case BitstreamEntry::SubBlock: // Handled for us already.
1264     case BitstreamEntry::Error:
1265       return Error("Malformed block");
1266     case BitstreamEntry::EndBlock:
1267       if (NumRecords != TypeList.size())
1268         return Error("Malformed block");
1269       return std::error_code();
1270     case BitstreamEntry::Record:
1271       // The interesting case.
1272       break;
1273     }
1274
1275     // Read a record.
1276     Record.clear();
1277     Type *ResultTy = nullptr;
1278     switch (Stream.readRecord(Entry.ID, Record)) {
1279     default:
1280       return Error("Invalid value");
1281     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1282       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1283       // type list.  This allows us to reserve space.
1284       if (Record.size() < 1)
1285         return Error("Invalid record");
1286       TypeList.resize(Record[0]);
1287       continue;
1288     case bitc::TYPE_CODE_VOID:      // VOID
1289       ResultTy = Type::getVoidTy(Context);
1290       break;
1291     case bitc::TYPE_CODE_HALF:     // HALF
1292       ResultTy = Type::getHalfTy(Context);
1293       break;
1294     case bitc::TYPE_CODE_FLOAT:     // FLOAT
1295       ResultTy = Type::getFloatTy(Context);
1296       break;
1297     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1298       ResultTy = Type::getDoubleTy(Context);
1299       break;
1300     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1301       ResultTy = Type::getX86_FP80Ty(Context);
1302       break;
1303     case bitc::TYPE_CODE_FP128:     // FP128
1304       ResultTy = Type::getFP128Ty(Context);
1305       break;
1306     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1307       ResultTy = Type::getPPC_FP128Ty(Context);
1308       break;
1309     case bitc::TYPE_CODE_LABEL:     // LABEL
1310       ResultTy = Type::getLabelTy(Context);
1311       break;
1312     case bitc::TYPE_CODE_METADATA:  // METADATA
1313       ResultTy = Type::getMetadataTy(Context);
1314       break;
1315     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
1316       ResultTy = Type::getX86_MMXTy(Context);
1317       break;
1318     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1319       if (Record.size() < 1)
1320         return Error("Invalid record");
1321
1322       uint64_t NumBits = Record[0];
1323       if (NumBits < IntegerType::MIN_INT_BITS ||
1324           NumBits > IntegerType::MAX_INT_BITS)
1325         return Error("Bitwidth for integer type out of range");
1326       ResultTy = IntegerType::get(Context, NumBits);
1327       break;
1328     }
1329     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1330                                     //          [pointee type, address space]
1331       if (Record.size() < 1)
1332         return Error("Invalid record");
1333       unsigned AddressSpace = 0;
1334       if (Record.size() == 2)
1335         AddressSpace = Record[1];
1336       ResultTy = getTypeByID(Record[0]);
1337       if (!ResultTy)
1338         return Error("Invalid type");
1339       ResultTy = PointerType::get(ResultTy, AddressSpace);
1340       break;
1341     }
1342     case bitc::TYPE_CODE_FUNCTION_OLD: {
1343       // FIXME: attrid is dead, remove it in LLVM 4.0
1344       // FUNCTION: [vararg, attrid, retty, paramty x N]
1345       if (Record.size() < 3)
1346         return Error("Invalid record");
1347       SmallVector<Type*, 8> ArgTys;
1348       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1349         if (Type *T = getTypeByID(Record[i]))
1350           ArgTys.push_back(T);
1351         else
1352           break;
1353       }
1354
1355       ResultTy = getTypeByID(Record[2]);
1356       if (!ResultTy || ArgTys.size() < Record.size()-3)
1357         return Error("Invalid type");
1358
1359       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1360       break;
1361     }
1362     case bitc::TYPE_CODE_FUNCTION: {
1363       // FUNCTION: [vararg, retty, paramty x N]
1364       if (Record.size() < 2)
1365         return Error("Invalid record");
1366       SmallVector<Type*, 8> ArgTys;
1367       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1368         if (Type *T = getTypeByID(Record[i]))
1369           ArgTys.push_back(T);
1370         else
1371           break;
1372       }
1373
1374       ResultTy = getTypeByID(Record[1]);
1375       if (!ResultTy || ArgTys.size() < Record.size()-2)
1376         return Error("Invalid type");
1377
1378       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1379       break;
1380     }
1381     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1382       if (Record.size() < 1)
1383         return Error("Invalid record");
1384       SmallVector<Type*, 8> EltTys;
1385       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1386         if (Type *T = getTypeByID(Record[i]))
1387           EltTys.push_back(T);
1388         else
1389           break;
1390       }
1391       if (EltTys.size() != Record.size()-1)
1392         return Error("Invalid type");
1393       ResultTy = StructType::get(Context, EltTys, Record[0]);
1394       break;
1395     }
1396     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1397       if (ConvertToString(Record, 0, TypeName))
1398         return Error("Invalid record");
1399       continue;
1400
1401     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1402       if (Record.size() < 1)
1403         return Error("Invalid record");
1404
1405       if (NumRecords >= TypeList.size())
1406         return Error("Invalid TYPE table");
1407
1408       // Check to see if this was forward referenced, if so fill in the temp.
1409       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1410       if (Res) {
1411         Res->setName(TypeName);
1412         TypeList[NumRecords] = nullptr;
1413       } else  // Otherwise, create a new struct.
1414         Res = createIdentifiedStructType(Context, TypeName);
1415       TypeName.clear();
1416
1417       SmallVector<Type*, 8> EltTys;
1418       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1419         if (Type *T = getTypeByID(Record[i]))
1420           EltTys.push_back(T);
1421         else
1422           break;
1423       }
1424       if (EltTys.size() != Record.size()-1)
1425         return Error("Invalid record");
1426       Res->setBody(EltTys, Record[0]);
1427       ResultTy = Res;
1428       break;
1429     }
1430     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1431       if (Record.size() != 1)
1432         return Error("Invalid record");
1433
1434       if (NumRecords >= TypeList.size())
1435         return Error("Invalid TYPE table");
1436
1437       // Check to see if this was forward referenced, if so fill in the temp.
1438       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1439       if (Res) {
1440         Res->setName(TypeName);
1441         TypeList[NumRecords] = nullptr;
1442       } else  // Otherwise, create a new struct with no body.
1443         Res = createIdentifiedStructType(Context, TypeName);
1444       TypeName.clear();
1445       ResultTy = Res;
1446       break;
1447     }
1448     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1449       if (Record.size() < 2)
1450         return Error("Invalid record");
1451       if ((ResultTy = getTypeByID(Record[1])))
1452         ResultTy = ArrayType::get(ResultTy, Record[0]);
1453       else
1454         return Error("Invalid type");
1455       break;
1456     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
1457       if (Record.size() < 2)
1458         return Error("Invalid record");
1459       if ((ResultTy = getTypeByID(Record[1])))
1460         ResultTy = VectorType::get(ResultTy, Record[0]);
1461       else
1462         return Error("Invalid type");
1463       break;
1464     }
1465
1466     if (NumRecords >= TypeList.size())
1467       return Error("Invalid TYPE table");
1468     if (TypeList[NumRecords])
1469       return Error(
1470           "Invalid TYPE table: Only named structs can be forward referenced");
1471     assert(ResultTy && "Didn't read a type?");
1472     TypeList[NumRecords++] = ResultTy;
1473   }
1474 }
1475
1476 std::error_code BitcodeReader::ParseValueSymbolTable() {
1477   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1478     return Error("Invalid record");
1479
1480   SmallVector<uint64_t, 64> Record;
1481
1482   Triple TT(TheModule->getTargetTriple());
1483
1484   // Read all the records for this value table.
1485   SmallString<128> ValueName;
1486   while (1) {
1487     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1488
1489     switch (Entry.Kind) {
1490     case BitstreamEntry::SubBlock: // Handled for us already.
1491     case BitstreamEntry::Error:
1492       return Error("Malformed block");
1493     case BitstreamEntry::EndBlock:
1494       return std::error_code();
1495     case BitstreamEntry::Record:
1496       // The interesting case.
1497       break;
1498     }
1499
1500     // Read a record.
1501     Record.clear();
1502     switch (Stream.readRecord(Entry.ID, Record)) {
1503     default:  // Default behavior: unknown type.
1504       break;
1505     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
1506       if (ConvertToString(Record, 1, ValueName))
1507         return Error("Invalid record");
1508       unsigned ValueID = Record[0];
1509       if (ValueID >= ValueList.size() || !ValueList[ValueID])
1510         return Error("Invalid record");
1511       Value *V = ValueList[ValueID];
1512
1513       V->setName(StringRef(ValueName.data(), ValueName.size()));
1514       if (auto *GO = dyn_cast<GlobalObject>(V)) {
1515         if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1516           if (TT.isOSBinFormatMachO())
1517             GO->setComdat(nullptr);
1518           else
1519             GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1520         }
1521       }
1522       ValueName.clear();
1523       break;
1524     }
1525     case bitc::VST_CODE_BBENTRY: {
1526       if (ConvertToString(Record, 1, ValueName))
1527         return Error("Invalid record");
1528       BasicBlock *BB = getBasicBlock(Record[0]);
1529       if (!BB)
1530         return Error("Invalid record");
1531
1532       BB->setName(StringRef(ValueName.data(), ValueName.size()));
1533       ValueName.clear();
1534       break;
1535     }
1536     }
1537   }
1538 }
1539
1540 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1541
1542 std::error_code BitcodeReader::ParseMetadata() {
1543   IsMetadataMaterialized = true;
1544   unsigned NextMDValueNo = MDValueList.size();
1545
1546   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1547     return Error("Invalid record");
1548
1549   SmallVector<uint64_t, 64> Record;
1550
1551   auto getMD =
1552       [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1553   auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1554     if (ID)
1555       return getMD(ID - 1);
1556     return nullptr;
1557   };
1558   auto getMDString = [&](unsigned ID) -> MDString *{
1559     // This requires that the ID is not really a forward reference.  In
1560     // particular, the MDString must already have been resolved.
1561     return cast_or_null<MDString>(getMDOrNull(ID));
1562   };
1563
1564 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS)                                 \
1565   (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1566
1567   // Read all the records.
1568   while (1) {
1569     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1570
1571     switch (Entry.Kind) {
1572     case BitstreamEntry::SubBlock: // Handled for us already.
1573     case BitstreamEntry::Error:
1574       return Error("Malformed block");
1575     case BitstreamEntry::EndBlock:
1576       MDValueList.tryToResolveCycles();
1577       return std::error_code();
1578     case BitstreamEntry::Record:
1579       // The interesting case.
1580       break;
1581     }
1582
1583     // Read a record.
1584     Record.clear();
1585     unsigned Code = Stream.readRecord(Entry.ID, Record);
1586     bool IsDistinct = false;
1587     switch (Code) {
1588     default:  // Default behavior: ignore.
1589       break;
1590     case bitc::METADATA_NAME: {
1591       // Read name of the named metadata.
1592       SmallString<8> Name(Record.begin(), Record.end());
1593       Record.clear();
1594       Code = Stream.ReadCode();
1595
1596       // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1597       unsigned NextBitCode = Stream.readRecord(Code, Record);
1598       assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1599
1600       // Read named metadata elements.
1601       unsigned Size = Record.size();
1602       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1603       for (unsigned i = 0; i != Size; ++i) {
1604         MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1605         if (!MD)
1606           return Error("Invalid record");
1607         NMD->addOperand(MD);
1608       }
1609       break;
1610     }
1611     case bitc::METADATA_OLD_FN_NODE: {
1612       // FIXME: Remove in 4.0.
1613       // This is a LocalAsMetadata record, the only type of function-local
1614       // metadata.
1615       if (Record.size() % 2 == 1)
1616         return Error("Invalid record");
1617
1618       // If this isn't a LocalAsMetadata record, we're dropping it.  This used
1619       // to be legal, but there's no upgrade path.
1620       auto dropRecord = [&] {
1621         MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1622       };
1623       if (Record.size() != 2) {
1624         dropRecord();
1625         break;
1626       }
1627
1628       Type *Ty = getTypeByID(Record[0]);
1629       if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1630         dropRecord();
1631         break;
1632       }
1633
1634       MDValueList.AssignValue(
1635           LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1636           NextMDValueNo++);
1637       break;
1638     }
1639     case bitc::METADATA_OLD_NODE: {
1640       // FIXME: Remove in 4.0.
1641       if (Record.size() % 2 == 1)
1642         return Error("Invalid record");
1643
1644       unsigned Size = Record.size();
1645       SmallVector<Metadata *, 8> Elts;
1646       for (unsigned i = 0; i != Size; i += 2) {
1647         Type *Ty = getTypeByID(Record[i]);
1648         if (!Ty)
1649           return Error("Invalid record");
1650         if (Ty->isMetadataTy())
1651           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1652         else if (!Ty->isVoidTy()) {
1653           auto *MD =
1654               ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1655           assert(isa<ConstantAsMetadata>(MD) &&
1656                  "Expected non-function-local metadata");
1657           Elts.push_back(MD);
1658         } else
1659           Elts.push_back(nullptr);
1660       }
1661       MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1662       break;
1663     }
1664     case bitc::METADATA_VALUE: {
1665       if (Record.size() != 2)
1666         return Error("Invalid record");
1667
1668       Type *Ty = getTypeByID(Record[0]);
1669       if (Ty->isMetadataTy() || Ty->isVoidTy())
1670         return Error("Invalid record");
1671
1672       MDValueList.AssignValue(
1673           ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1674           NextMDValueNo++);
1675       break;
1676     }
1677     case bitc::METADATA_DISTINCT_NODE:
1678       IsDistinct = true;
1679       // fallthrough...
1680     case bitc::METADATA_NODE: {
1681       SmallVector<Metadata *, 8> Elts;
1682       Elts.reserve(Record.size());
1683       for (unsigned ID : Record)
1684         Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
1685       MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1686                                          : MDNode::get(Context, Elts),
1687                               NextMDValueNo++);
1688       break;
1689     }
1690     case bitc::METADATA_LOCATION: {
1691       if (Record.size() != 5)
1692         return Error("Invalid record");
1693
1694       unsigned Line = Record[1];
1695       unsigned Column = Record[2];
1696       MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1697       Metadata *InlinedAt =
1698           Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
1699       MDValueList.AssignValue(
1700           GET_OR_DISTINCT(MDLocation, Record[0],
1701                           (Context, Line, Column, Scope, InlinedAt)),
1702           NextMDValueNo++);
1703       break;
1704     }
1705     case bitc::METADATA_GENERIC_DEBUG: {
1706       if (Record.size() < 4)
1707         return Error("Invalid record");
1708
1709       unsigned Tag = Record[1];
1710       unsigned Version = Record[2];
1711
1712       if (Tag >= 1u << 16 || Version != 0)
1713         return Error("Invalid record");
1714
1715       auto *Header = getMDString(Record[3]);
1716       SmallVector<Metadata *, 8> DwarfOps;
1717       for (unsigned I = 4, E = Record.size(); I != E; ++I)
1718         DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1719                                      : nullptr);
1720       MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1721                                               (Context, Tag, Header, DwarfOps)),
1722                               NextMDValueNo++);
1723       break;
1724     }
1725     case bitc::METADATA_SUBRANGE: {
1726       if (Record.size() != 3)
1727         return Error("Invalid record");
1728
1729       MDValueList.AssignValue(
1730           GET_OR_DISTINCT(MDSubrange, Record[0],
1731                           (Context, Record[1], unrotateSign(Record[2]))),
1732           NextMDValueNo++);
1733       break;
1734     }
1735     case bitc::METADATA_ENUMERATOR: {
1736       if (Record.size() != 3)
1737         return Error("Invalid record");
1738
1739       MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1740                                               (Context, unrotateSign(Record[1]),
1741                                                getMDString(Record[2]))),
1742                               NextMDValueNo++);
1743       break;
1744     }
1745     case bitc::METADATA_BASIC_TYPE: {
1746       if (Record.size() != 6)
1747         return Error("Invalid record");
1748
1749       MDValueList.AssignValue(
1750           GET_OR_DISTINCT(MDBasicType, Record[0],
1751                           (Context, Record[1], getMDString(Record[2]),
1752                            Record[3], Record[4], Record[5])),
1753           NextMDValueNo++);
1754       break;
1755     }
1756     case bitc::METADATA_DERIVED_TYPE: {
1757       if (Record.size() != 12)
1758         return Error("Invalid record");
1759
1760       MDValueList.AssignValue(
1761           GET_OR_DISTINCT(MDDerivedType, Record[0],
1762                           (Context, Record[1], getMDString(Record[2]),
1763                            getMDOrNull(Record[3]), Record[4],
1764                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1765                            Record[7], Record[8], Record[9], Record[10],
1766                            getMDOrNull(Record[11]))),
1767           NextMDValueNo++);
1768       break;
1769     }
1770     case bitc::METADATA_COMPOSITE_TYPE: {
1771       if (Record.size() != 16)
1772         return Error("Invalid record");
1773
1774       MDValueList.AssignValue(
1775           GET_OR_DISTINCT(MDCompositeType, Record[0],
1776                           (Context, Record[1], getMDString(Record[2]),
1777                            getMDOrNull(Record[3]), Record[4],
1778                            getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1779                            Record[7], Record[8], Record[9], Record[10],
1780                            getMDOrNull(Record[11]), Record[12],
1781                            getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1782                            getMDString(Record[15]))),
1783           NextMDValueNo++);
1784       break;
1785     }
1786     case bitc::METADATA_SUBROUTINE_TYPE: {
1787       if (Record.size() != 3)
1788         return Error("Invalid record");
1789
1790       MDValueList.AssignValue(
1791           GET_OR_DISTINCT(MDSubroutineType, Record[0],
1792                           (Context, Record[1], getMDOrNull(Record[2]))),
1793           NextMDValueNo++);
1794       break;
1795     }
1796     case bitc::METADATA_FILE: {
1797       if (Record.size() != 3)
1798         return Error("Invalid record");
1799
1800       MDValueList.AssignValue(
1801           GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1802                                               getMDString(Record[2]))),
1803           NextMDValueNo++);
1804       break;
1805     }
1806     case bitc::METADATA_COMPILE_UNIT: {
1807       if (Record.size() != 14)
1808         return Error("Invalid record");
1809
1810       MDValueList.AssignValue(
1811           GET_OR_DISTINCT(MDCompileUnit, Record[0],
1812                           (Context, Record[1], getMDOrNull(Record[2]),
1813                            getMDString(Record[3]), Record[4],
1814                            getMDString(Record[5]), Record[6],
1815                            getMDString(Record[7]), Record[8],
1816                            getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1817                            getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1818                            getMDOrNull(Record[13]))),
1819           NextMDValueNo++);
1820       break;
1821     }
1822     case bitc::METADATA_SUBPROGRAM: {
1823       if (Record.size() != 19)
1824         return Error("Invalid record");
1825
1826       MDValueList.AssignValue(
1827           GET_OR_DISTINCT(
1828               MDSubprogram, Record[0],
1829               (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1830                getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1831                getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1832                getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1833                Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1834                getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1835           NextMDValueNo++);
1836       break;
1837     }
1838     case bitc::METADATA_LEXICAL_BLOCK: {
1839       if (Record.size() != 5)
1840         return Error("Invalid record");
1841
1842       MDValueList.AssignValue(
1843           GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1844                           (Context, getMDOrNull(Record[1]),
1845                            getMDOrNull(Record[2]), Record[3], Record[4])),
1846           NextMDValueNo++);
1847       break;
1848     }
1849     case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1850       if (Record.size() != 4)
1851         return Error("Invalid record");
1852
1853       MDValueList.AssignValue(
1854           GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1855                           (Context, getMDOrNull(Record[1]),
1856                            getMDOrNull(Record[2]), Record[3])),
1857           NextMDValueNo++);
1858       break;
1859     }
1860     case bitc::METADATA_NAMESPACE: {
1861       if (Record.size() != 5)
1862         return Error("Invalid record");
1863
1864       MDValueList.AssignValue(
1865           GET_OR_DISTINCT(MDNamespace, Record[0],
1866                           (Context, getMDOrNull(Record[1]),
1867                            getMDOrNull(Record[2]), getMDString(Record[3]),
1868                            Record[4])),
1869           NextMDValueNo++);
1870       break;
1871     }
1872     case bitc::METADATA_TEMPLATE_TYPE: {
1873       if (Record.size() != 3)
1874         return Error("Invalid record");
1875
1876       MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1877                                               Record[0],
1878                                               (Context, getMDString(Record[1]),
1879                                                getMDOrNull(Record[2]))),
1880                               NextMDValueNo++);
1881       break;
1882     }
1883     case bitc::METADATA_TEMPLATE_VALUE: {
1884       if (Record.size() != 5)
1885         return Error("Invalid record");
1886
1887       MDValueList.AssignValue(
1888           GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
1889                           (Context, Record[1], getMDString(Record[2]),
1890                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1891           NextMDValueNo++);
1892       break;
1893     }
1894     case bitc::METADATA_GLOBAL_VAR: {
1895       if (Record.size() != 11)
1896         return Error("Invalid record");
1897
1898       MDValueList.AssignValue(
1899           GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1900                           (Context, getMDOrNull(Record[1]),
1901                            getMDString(Record[2]), getMDString(Record[3]),
1902                            getMDOrNull(Record[4]), Record[5],
1903                            getMDOrNull(Record[6]), Record[7], Record[8],
1904                            getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1905           NextMDValueNo++);
1906       break;
1907     }
1908     case bitc::METADATA_LOCAL_VAR: {
1909       if (Record.size() != 10)
1910         return Error("Invalid record");
1911
1912       MDValueList.AssignValue(
1913           GET_OR_DISTINCT(MDLocalVariable, Record[0],
1914                           (Context, Record[1], getMDOrNull(Record[2]),
1915                            getMDString(Record[3]), getMDOrNull(Record[4]),
1916                            Record[5], getMDOrNull(Record[6]), Record[7],
1917                            Record[8], getMDOrNull(Record[9]))),
1918           NextMDValueNo++);
1919       break;
1920     }
1921     case bitc::METADATA_EXPRESSION: {
1922       if (Record.size() < 1)
1923         return Error("Invalid record");
1924
1925       MDValueList.AssignValue(
1926           GET_OR_DISTINCT(MDExpression, Record[0],
1927                           (Context, makeArrayRef(Record).slice(1))),
1928           NextMDValueNo++);
1929       break;
1930     }
1931     case bitc::METADATA_OBJC_PROPERTY: {
1932       if (Record.size() != 8)
1933         return Error("Invalid record");
1934
1935       MDValueList.AssignValue(
1936           GET_OR_DISTINCT(MDObjCProperty, Record[0],
1937                           (Context, getMDString(Record[1]),
1938                            getMDOrNull(Record[2]), Record[3],
1939                            getMDString(Record[4]), getMDString(Record[5]),
1940                            Record[6], getMDOrNull(Record[7]))),
1941           NextMDValueNo++);
1942       break;
1943     }
1944     case bitc::METADATA_IMPORTED_ENTITY: {
1945       if (Record.size() != 6)
1946         return Error("Invalid record");
1947
1948       MDValueList.AssignValue(
1949           GET_OR_DISTINCT(MDImportedEntity, Record[0],
1950                           (Context, Record[1], getMDOrNull(Record[2]),
1951                            getMDOrNull(Record[3]), Record[4],
1952                            getMDString(Record[5]))),
1953           NextMDValueNo++);
1954       break;
1955     }
1956     case bitc::METADATA_STRING: {
1957       std::string String(Record.begin(), Record.end());
1958       llvm::UpgradeMDStringConstant(String);
1959       Metadata *MD = MDString::get(Context, String);
1960       MDValueList.AssignValue(MD, NextMDValueNo++);
1961       break;
1962     }
1963     case bitc::METADATA_KIND: {
1964       if (Record.size() < 2)
1965         return Error("Invalid record");
1966
1967       unsigned Kind = Record[0];
1968       SmallString<8> Name(Record.begin()+1, Record.end());
1969
1970       unsigned NewKind = TheModule->getMDKindID(Name.str());
1971       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1972         return Error("Conflicting METADATA_KIND records");
1973       break;
1974     }
1975     }
1976   }
1977 #undef GET_OR_DISTINCT
1978 }
1979
1980 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1981 /// the LSB for dense VBR encoding.
1982 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1983   if ((V & 1) == 0)
1984     return V >> 1;
1985   if (V != 1)
1986     return -(V >> 1);
1987   // There is no such thing as -0 with integers.  "-0" really means MININT.
1988   return 1ULL << 63;
1989 }
1990
1991 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1992 /// values and aliases that we can.
1993 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1994   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1995   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1996   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1997   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1998
1999   GlobalInitWorklist.swap(GlobalInits);
2000   AliasInitWorklist.swap(AliasInits);
2001   FunctionPrefixWorklist.swap(FunctionPrefixes);
2002   FunctionPrologueWorklist.swap(FunctionPrologues);
2003
2004   while (!GlobalInitWorklist.empty()) {
2005     unsigned ValID = GlobalInitWorklist.back().second;
2006     if (ValID >= ValueList.size()) {
2007       // Not ready to resolve this yet, it requires something later in the file.
2008       GlobalInits.push_back(GlobalInitWorklist.back());
2009     } else {
2010       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2011         GlobalInitWorklist.back().first->setInitializer(C);
2012       else
2013         return Error("Expected a constant");
2014     }
2015     GlobalInitWorklist.pop_back();
2016   }
2017
2018   while (!AliasInitWorklist.empty()) {
2019     unsigned ValID = AliasInitWorklist.back().second;
2020     if (ValID >= ValueList.size()) {
2021       AliasInits.push_back(AliasInitWorklist.back());
2022     } else {
2023       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2024         AliasInitWorklist.back().first->setAliasee(C);
2025       else
2026         return Error("Expected a constant");
2027     }
2028     AliasInitWorklist.pop_back();
2029   }
2030
2031   while (!FunctionPrefixWorklist.empty()) {
2032     unsigned ValID = FunctionPrefixWorklist.back().second;
2033     if (ValID >= ValueList.size()) {
2034       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2035     } else {
2036       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2037         FunctionPrefixWorklist.back().first->setPrefixData(C);
2038       else
2039         return Error("Expected a constant");
2040     }
2041     FunctionPrefixWorklist.pop_back();
2042   }
2043
2044   while (!FunctionPrologueWorklist.empty()) {
2045     unsigned ValID = FunctionPrologueWorklist.back().second;
2046     if (ValID >= ValueList.size()) {
2047       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2048     } else {
2049       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2050         FunctionPrologueWorklist.back().first->setPrologueData(C);
2051       else
2052         return Error("Expected a constant");
2053     }
2054     FunctionPrologueWorklist.pop_back();
2055   }
2056
2057   return std::error_code();
2058 }
2059
2060 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2061   SmallVector<uint64_t, 8> Words(Vals.size());
2062   std::transform(Vals.begin(), Vals.end(), Words.begin(),
2063                  BitcodeReader::decodeSignRotatedValue);
2064
2065   return APInt(TypeBits, Words);
2066 }
2067
2068 std::error_code BitcodeReader::ParseConstants() {
2069   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2070     return Error("Invalid record");
2071
2072   SmallVector<uint64_t, 64> Record;
2073
2074   // Read all the records for this value table.
2075   Type *CurTy = Type::getInt32Ty(Context);
2076   unsigned NextCstNo = ValueList.size();
2077   while (1) {
2078     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2079
2080     switch (Entry.Kind) {
2081     case BitstreamEntry::SubBlock: // Handled for us already.
2082     case BitstreamEntry::Error:
2083       return Error("Malformed block");
2084     case BitstreamEntry::EndBlock:
2085       if (NextCstNo != ValueList.size())
2086         return Error("Invalid ronstant reference");
2087
2088       // Once all the constants have been read, go through and resolve forward
2089       // references.
2090       ValueList.ResolveConstantForwardRefs();
2091       return std::error_code();
2092     case BitstreamEntry::Record:
2093       // The interesting case.
2094       break;
2095     }
2096
2097     // Read a record.
2098     Record.clear();
2099     Value *V = nullptr;
2100     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2101     switch (BitCode) {
2102     default:  // Default behavior: unknown constant
2103     case bitc::CST_CODE_UNDEF:     // UNDEF
2104       V = UndefValue::get(CurTy);
2105       break;
2106     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2107       if (Record.empty())
2108         return Error("Invalid record");
2109       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2110         return Error("Invalid record");
2111       CurTy = TypeList[Record[0]];
2112       continue;  // Skip the ValueList manipulation.
2113     case bitc::CST_CODE_NULL:      // NULL
2114       V = Constant::getNullValue(CurTy);
2115       break;
2116     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2117       if (!CurTy->isIntegerTy() || Record.empty())
2118         return Error("Invalid record");
2119       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2120       break;
2121     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2122       if (!CurTy->isIntegerTy() || Record.empty())
2123         return Error("Invalid record");
2124
2125       APInt VInt = ReadWideAPInt(Record,
2126                                  cast<IntegerType>(CurTy)->getBitWidth());
2127       V = ConstantInt::get(Context, VInt);
2128
2129       break;
2130     }
2131     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2132       if (Record.empty())
2133         return Error("Invalid record");
2134       if (CurTy->isHalfTy())
2135         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2136                                              APInt(16, (uint16_t)Record[0])));
2137       else if (CurTy->isFloatTy())
2138         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2139                                              APInt(32, (uint32_t)Record[0])));
2140       else if (CurTy->isDoubleTy())
2141         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2142                                              APInt(64, Record[0])));
2143       else if (CurTy->isX86_FP80Ty()) {
2144         // Bits are not stored the same way as a normal i80 APInt, compensate.
2145         uint64_t Rearrange[2];
2146         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2147         Rearrange[1] = Record[0] >> 48;
2148         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2149                                              APInt(80, Rearrange)));
2150       } else if (CurTy->isFP128Ty())
2151         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2152                                              APInt(128, Record)));
2153       else if (CurTy->isPPC_FP128Ty())
2154         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2155                                              APInt(128, Record)));
2156       else
2157         V = UndefValue::get(CurTy);
2158       break;
2159     }
2160
2161     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2162       if (Record.empty())
2163         return Error("Invalid record");
2164
2165       unsigned Size = Record.size();
2166       SmallVector<Constant*, 16> Elts;
2167
2168       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2169         for (unsigned i = 0; i != Size; ++i)
2170           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2171                                                      STy->getElementType(i)));
2172         V = ConstantStruct::get(STy, Elts);
2173       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2174         Type *EltTy = ATy->getElementType();
2175         for (unsigned i = 0; i != Size; ++i)
2176           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2177         V = ConstantArray::get(ATy, Elts);
2178       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2179         Type *EltTy = VTy->getElementType();
2180         for (unsigned i = 0; i != Size; ++i)
2181           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2182         V = ConstantVector::get(Elts);
2183       } else {
2184         V = UndefValue::get(CurTy);
2185       }
2186       break;
2187     }
2188     case bitc::CST_CODE_STRING:    // STRING: [values]
2189     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2190       if (Record.empty())
2191         return Error("Invalid record");
2192
2193       SmallString<16> Elts(Record.begin(), Record.end());
2194       V = ConstantDataArray::getString(Context, Elts,
2195                                        BitCode == bitc::CST_CODE_CSTRING);
2196       break;
2197     }
2198     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2199       if (Record.empty())
2200         return Error("Invalid record");
2201
2202       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2203       unsigned Size = Record.size();
2204
2205       if (EltTy->isIntegerTy(8)) {
2206         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2207         if (isa<VectorType>(CurTy))
2208           V = ConstantDataVector::get(Context, Elts);
2209         else
2210           V = ConstantDataArray::get(Context, Elts);
2211       } else if (EltTy->isIntegerTy(16)) {
2212         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2213         if (isa<VectorType>(CurTy))
2214           V = ConstantDataVector::get(Context, Elts);
2215         else
2216           V = ConstantDataArray::get(Context, Elts);
2217       } else if (EltTy->isIntegerTy(32)) {
2218         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2219         if (isa<VectorType>(CurTy))
2220           V = ConstantDataVector::get(Context, Elts);
2221         else
2222           V = ConstantDataArray::get(Context, Elts);
2223       } else if (EltTy->isIntegerTy(64)) {
2224         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2225         if (isa<VectorType>(CurTy))
2226           V = ConstantDataVector::get(Context, Elts);
2227         else
2228           V = ConstantDataArray::get(Context, Elts);
2229       } else if (EltTy->isFloatTy()) {
2230         SmallVector<float, 16> Elts(Size);
2231         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2232         if (isa<VectorType>(CurTy))
2233           V = ConstantDataVector::get(Context, Elts);
2234         else
2235           V = ConstantDataArray::get(Context, Elts);
2236       } else if (EltTy->isDoubleTy()) {
2237         SmallVector<double, 16> Elts(Size);
2238         std::transform(Record.begin(), Record.end(), Elts.begin(),
2239                        BitsToDouble);
2240         if (isa<VectorType>(CurTy))
2241           V = ConstantDataVector::get(Context, Elts);
2242         else
2243           V = ConstantDataArray::get(Context, Elts);
2244       } else {
2245         return Error("Invalid type for value");
2246       }
2247       break;
2248     }
2249
2250     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2251       if (Record.size() < 3)
2252         return Error("Invalid record");
2253       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
2254       if (Opc < 0) {
2255         V = UndefValue::get(CurTy);  // Unknown binop.
2256       } else {
2257         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2258         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2259         unsigned Flags = 0;
2260         if (Record.size() >= 4) {
2261           if (Opc == Instruction::Add ||
2262               Opc == Instruction::Sub ||
2263               Opc == Instruction::Mul ||
2264               Opc == Instruction::Shl) {
2265             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2266               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2267             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2268               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2269           } else if (Opc == Instruction::SDiv ||
2270                      Opc == Instruction::UDiv ||
2271                      Opc == Instruction::LShr ||
2272                      Opc == Instruction::AShr) {
2273             if (Record[3] & (1 << bitc::PEO_EXACT))
2274               Flags |= SDivOperator::IsExact;
2275           }
2276         }
2277         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2278       }
2279       break;
2280     }
2281     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2282       if (Record.size() < 3)
2283         return Error("Invalid record");
2284       int Opc = GetDecodedCastOpcode(Record[0]);
2285       if (Opc < 0) {
2286         V = UndefValue::get(CurTy);  // Unknown cast.
2287       } else {
2288         Type *OpTy = getTypeByID(Record[1]);
2289         if (!OpTy)
2290           return Error("Invalid record");
2291         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2292         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2293         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2294       }
2295       break;
2296     }
2297     case bitc::CST_CODE_CE_INBOUNDS_GEP:
2298     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
2299       unsigned OpNum = 0;
2300       Type *PointeeType = nullptr;
2301       if (Record.size() % 2)
2302         PointeeType = getTypeByID(Record[OpNum++]);
2303       SmallVector<Constant*, 16> Elts;
2304       while (OpNum != Record.size()) {
2305         Type *ElTy = getTypeByID(Record[OpNum++]);
2306         if (!ElTy)
2307           return Error("Invalid record");
2308         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2309       }
2310
2311       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2312       V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2313                                          BitCode ==
2314                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
2315       if (PointeeType &&
2316           PointeeType != cast<GEPOperator>(V)->getSourceElementType())
2317         return Error("Explicit gep operator type does not match pointee type "
2318                      "of pointer operand");
2319       break;
2320     }
2321     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2322       if (Record.size() < 3)
2323         return Error("Invalid record");
2324
2325       Type *SelectorTy = Type::getInt1Ty(Context);
2326
2327       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2328       // vector. Otherwise, it must be a single bit.
2329       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2330         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2331                                      VTy->getNumElements());
2332
2333       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2334                                                               SelectorTy),
2335                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2336                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2337       break;
2338     }
2339     case bitc::CST_CODE_CE_EXTRACTELT
2340         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2341       if (Record.size() < 3)
2342         return Error("Invalid record");
2343       VectorType *OpTy =
2344         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2345       if (!OpTy)
2346         return Error("Invalid record");
2347       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2348       Constant *Op1 = nullptr;
2349       if (Record.size() == 4) {
2350         Type *IdxTy = getTypeByID(Record[2]);
2351         if (!IdxTy)
2352           return Error("Invalid record");
2353         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2354       } else // TODO: Remove with llvm 4.0
2355         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2356       if (!Op1)
2357         return Error("Invalid record");
2358       V = ConstantExpr::getExtractElement(Op0, Op1);
2359       break;
2360     }
2361     case bitc::CST_CODE_CE_INSERTELT
2362         : { // CE_INSERTELT: [opval, opval, opty, opval]
2363       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2364       if (Record.size() < 3 || !OpTy)
2365         return Error("Invalid record");
2366       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2367       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2368                                                   OpTy->getElementType());
2369       Constant *Op2 = nullptr;
2370       if (Record.size() == 4) {
2371         Type *IdxTy = getTypeByID(Record[2]);
2372         if (!IdxTy)
2373           return Error("Invalid record");
2374         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2375       } else // TODO: Remove with llvm 4.0
2376         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2377       if (!Op2)
2378         return Error("Invalid record");
2379       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2380       break;
2381     }
2382     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2383       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2384       if (Record.size() < 3 || !OpTy)
2385         return Error("Invalid record");
2386       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2387       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2388       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2389                                                  OpTy->getNumElements());
2390       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2391       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2392       break;
2393     }
2394     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2395       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2396       VectorType *OpTy =
2397         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2398       if (Record.size() < 4 || !RTy || !OpTy)
2399         return Error("Invalid record");
2400       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2401       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2402       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2403                                                  RTy->getNumElements());
2404       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2405       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2406       break;
2407     }
2408     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2409       if (Record.size() < 4)
2410         return Error("Invalid record");
2411       Type *OpTy = getTypeByID(Record[0]);
2412       if (!OpTy)
2413         return Error("Invalid record");
2414       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2415       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2416
2417       if (OpTy->isFPOrFPVectorTy())
2418         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2419       else
2420         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2421       break;
2422     }
2423     // This maintains backward compatibility, pre-asm dialect keywords.
2424     // FIXME: Remove with the 4.0 release.
2425     case bitc::CST_CODE_INLINEASM_OLD: {
2426       if (Record.size() < 2)
2427         return Error("Invalid record");
2428       std::string AsmStr, ConstrStr;
2429       bool HasSideEffects = Record[0] & 1;
2430       bool IsAlignStack = Record[0] >> 1;
2431       unsigned AsmStrSize = Record[1];
2432       if (2+AsmStrSize >= Record.size())
2433         return Error("Invalid record");
2434       unsigned ConstStrSize = Record[2+AsmStrSize];
2435       if (3+AsmStrSize+ConstStrSize > Record.size())
2436         return Error("Invalid record");
2437
2438       for (unsigned i = 0; i != AsmStrSize; ++i)
2439         AsmStr += (char)Record[2+i];
2440       for (unsigned i = 0; i != ConstStrSize; ++i)
2441         ConstrStr += (char)Record[3+AsmStrSize+i];
2442       PointerType *PTy = cast<PointerType>(CurTy);
2443       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2444                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2445       break;
2446     }
2447     // This version adds support for the asm dialect keywords (e.g.,
2448     // inteldialect).
2449     case bitc::CST_CODE_INLINEASM: {
2450       if (Record.size() < 2)
2451         return Error("Invalid record");
2452       std::string AsmStr, ConstrStr;
2453       bool HasSideEffects = Record[0] & 1;
2454       bool IsAlignStack = (Record[0] >> 1) & 1;
2455       unsigned AsmDialect = Record[0] >> 2;
2456       unsigned AsmStrSize = Record[1];
2457       if (2+AsmStrSize >= Record.size())
2458         return Error("Invalid record");
2459       unsigned ConstStrSize = Record[2+AsmStrSize];
2460       if (3+AsmStrSize+ConstStrSize > Record.size())
2461         return Error("Invalid record");
2462
2463       for (unsigned i = 0; i != AsmStrSize; ++i)
2464         AsmStr += (char)Record[2+i];
2465       for (unsigned i = 0; i != ConstStrSize; ++i)
2466         ConstrStr += (char)Record[3+AsmStrSize+i];
2467       PointerType *PTy = cast<PointerType>(CurTy);
2468       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2469                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2470                          InlineAsm::AsmDialect(AsmDialect));
2471       break;
2472     }
2473     case bitc::CST_CODE_BLOCKADDRESS:{
2474       if (Record.size() < 3)
2475         return Error("Invalid record");
2476       Type *FnTy = getTypeByID(Record[0]);
2477       if (!FnTy)
2478         return Error("Invalid record");
2479       Function *Fn =
2480         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2481       if (!Fn)
2482         return Error("Invalid record");
2483
2484       // Don't let Fn get dematerialized.
2485       BlockAddressesTaken.insert(Fn);
2486
2487       // If the function is already parsed we can insert the block address right
2488       // away.
2489       BasicBlock *BB;
2490       unsigned BBID = Record[2];
2491       if (!BBID)
2492         // Invalid reference to entry block.
2493         return Error("Invalid ID");
2494       if (!Fn->empty()) {
2495         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2496         for (size_t I = 0, E = BBID; I != E; ++I) {
2497           if (BBI == BBE)
2498             return Error("Invalid ID");
2499           ++BBI;
2500         }
2501         BB = BBI;
2502       } else {
2503         // Otherwise insert a placeholder and remember it so it can be inserted
2504         // when the function is parsed.
2505         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2506         if (FwdBBs.empty())
2507           BasicBlockFwdRefQueue.push_back(Fn);
2508         if (FwdBBs.size() < BBID + 1)
2509           FwdBBs.resize(BBID + 1);
2510         if (!FwdBBs[BBID])
2511           FwdBBs[BBID] = BasicBlock::Create(Context);
2512         BB = FwdBBs[BBID];
2513       }
2514       V = BlockAddress::get(Fn, BB);
2515       break;
2516     }
2517     }
2518
2519     ValueList.AssignValue(V, NextCstNo);
2520     ++NextCstNo;
2521   }
2522 }
2523
2524 std::error_code BitcodeReader::ParseUseLists() {
2525   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2526     return Error("Invalid record");
2527
2528   // Read all the records.
2529   SmallVector<uint64_t, 64> Record;
2530   while (1) {
2531     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2532
2533     switch (Entry.Kind) {
2534     case BitstreamEntry::SubBlock: // Handled for us already.
2535     case BitstreamEntry::Error:
2536       return Error("Malformed block");
2537     case BitstreamEntry::EndBlock:
2538       return std::error_code();
2539     case BitstreamEntry::Record:
2540       // The interesting case.
2541       break;
2542     }
2543
2544     // Read a use list record.
2545     Record.clear();
2546     bool IsBB = false;
2547     switch (Stream.readRecord(Entry.ID, Record)) {
2548     default:  // Default behavior: unknown type.
2549       break;
2550     case bitc::USELIST_CODE_BB:
2551       IsBB = true;
2552       // fallthrough
2553     case bitc::USELIST_CODE_DEFAULT: {
2554       unsigned RecordLength = Record.size();
2555       if (RecordLength < 3)
2556         // Records should have at least an ID and two indexes.
2557         return Error("Invalid record");
2558       unsigned ID = Record.back();
2559       Record.pop_back();
2560
2561       Value *V;
2562       if (IsBB) {
2563         assert(ID < FunctionBBs.size() && "Basic block not found");
2564         V = FunctionBBs[ID];
2565       } else
2566         V = ValueList[ID];
2567       unsigned NumUses = 0;
2568       SmallDenseMap<const Use *, unsigned, 16> Order;
2569       for (const Use &U : V->uses()) {
2570         if (++NumUses > Record.size())
2571           break;
2572         Order[&U] = Record[NumUses - 1];
2573       }
2574       if (Order.size() != Record.size() || NumUses > Record.size())
2575         // Mismatches can happen if the functions are being materialized lazily
2576         // (out-of-order), or a value has been upgraded.
2577         break;
2578
2579       V->sortUseList([&](const Use &L, const Use &R) {
2580         return Order.lookup(&L) < Order.lookup(&R);
2581       });
2582       break;
2583     }
2584     }
2585   }
2586 }
2587
2588 /// When we see the block for metadata, remember where it is and then skip it.
2589 /// This lets us lazily deserialize the metadata.
2590 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2591   // Save the current stream state.
2592   uint64_t CurBit = Stream.GetCurrentBitNo();
2593   DeferredMetadataInfo.push_back(CurBit);
2594
2595   // Skip over the block for now.
2596   if (Stream.SkipBlock())
2597     return Error("Invalid record");
2598   return std::error_code();
2599 }
2600
2601 std::error_code BitcodeReader::materializeMetadata() {
2602   for (uint64_t BitPos : DeferredMetadataInfo) {
2603     // Move the bit stream to the saved position.
2604     Stream.JumpToBit(BitPos);
2605     if (std::error_code EC = ParseMetadata())
2606       return EC;
2607   }
2608   DeferredMetadataInfo.clear();
2609   return std::error_code();
2610 }
2611
2612 /// RememberAndSkipFunctionBody - When we see the block for a function body,
2613 /// remember where it is and then skip it.  This lets us lazily deserialize the
2614 /// functions.
2615 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
2616   // Get the function we are talking about.
2617   if (FunctionsWithBodies.empty())
2618     return Error("Insufficient function protos");
2619
2620   Function *Fn = FunctionsWithBodies.back();
2621   FunctionsWithBodies.pop_back();
2622
2623   // Save the current stream state.
2624   uint64_t CurBit = Stream.GetCurrentBitNo();
2625   DeferredFunctionInfo[Fn] = CurBit;
2626
2627   // Skip over the function block for now.
2628   if (Stream.SkipBlock())
2629     return Error("Invalid record");
2630   return std::error_code();
2631 }
2632
2633 std::error_code BitcodeReader::GlobalCleanup() {
2634   // Patch the initializers for globals and aliases up.
2635   ResolveGlobalAndAliasInits();
2636   if (!GlobalInits.empty() || !AliasInits.empty())
2637     return Error("Malformed global initializer set");
2638
2639   // Look for intrinsic functions which need to be upgraded at some point
2640   for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2641        FI != FE; ++FI) {
2642     Function *NewFn;
2643     if (UpgradeIntrinsicFunction(FI, NewFn))
2644       UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2645   }
2646
2647   // Look for global variables which need to be renamed.
2648   for (Module::global_iterator
2649          GI = TheModule->global_begin(), GE = TheModule->global_end();
2650        GI != GE;) {
2651     GlobalVariable *GV = GI++;
2652     UpgradeGlobalVariable(GV);
2653   }
2654
2655   // Force deallocation of memory for these vectors to favor the client that
2656   // want lazy deserialization.
2657   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2658   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2659   return std::error_code();
2660 }
2661
2662 std::error_code BitcodeReader::ParseModule(bool Resume,
2663                                            bool ShouldLazyLoadMetadata) {
2664   if (Resume)
2665     Stream.JumpToBit(NextUnreadBit);
2666   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2667     return Error("Invalid record");
2668
2669   SmallVector<uint64_t, 64> Record;
2670   std::vector<std::string> SectionTable;
2671   std::vector<std::string> GCTable;
2672
2673   // Read all the records for this module.
2674   while (1) {
2675     BitstreamEntry Entry = Stream.advance();
2676
2677     switch (Entry.Kind) {
2678     case BitstreamEntry::Error:
2679       return Error("Malformed block");
2680     case BitstreamEntry::EndBlock:
2681       return GlobalCleanup();
2682
2683     case BitstreamEntry::SubBlock:
2684       switch (Entry.ID) {
2685       default:  // Skip unknown content.
2686         if (Stream.SkipBlock())
2687           return Error("Invalid record");
2688         break;
2689       case bitc::BLOCKINFO_BLOCK_ID:
2690         if (Stream.ReadBlockInfoBlock())
2691           return Error("Malformed block");
2692         break;
2693       case bitc::PARAMATTR_BLOCK_ID:
2694         if (std::error_code EC = ParseAttributeBlock())
2695           return EC;
2696         break;
2697       case bitc::PARAMATTR_GROUP_BLOCK_ID:
2698         if (std::error_code EC = ParseAttributeGroupBlock())
2699           return EC;
2700         break;
2701       case bitc::TYPE_BLOCK_ID_NEW:
2702         if (std::error_code EC = ParseTypeTable())
2703           return EC;
2704         break;
2705       case bitc::VALUE_SYMTAB_BLOCK_ID:
2706         if (std::error_code EC = ParseValueSymbolTable())
2707           return EC;
2708         SeenValueSymbolTable = true;
2709         break;
2710       case bitc::CONSTANTS_BLOCK_ID:
2711         if (std::error_code EC = ParseConstants())
2712           return EC;
2713         if (std::error_code EC = ResolveGlobalAndAliasInits())
2714           return EC;
2715         break;
2716       case bitc::METADATA_BLOCK_ID:
2717         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2718           if (std::error_code EC = rememberAndSkipMetadata())
2719             return EC;
2720           break;
2721         }
2722         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2723         if (std::error_code EC = ParseMetadata())
2724           return EC;
2725         break;
2726       case bitc::FUNCTION_BLOCK_ID:
2727         // If this is the first function body we've seen, reverse the
2728         // FunctionsWithBodies list.
2729         if (!SeenFirstFunctionBody) {
2730           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2731           if (std::error_code EC = GlobalCleanup())
2732             return EC;
2733           SeenFirstFunctionBody = true;
2734         }
2735
2736         if (std::error_code EC = RememberAndSkipFunctionBody())
2737           return EC;
2738         // For streaming bitcode, suspend parsing when we reach the function
2739         // bodies. Subsequent materialization calls will resume it when
2740         // necessary. For streaming, the function bodies must be at the end of
2741         // the bitcode. If the bitcode file is old, the symbol table will be
2742         // at the end instead and will not have been seen yet. In this case,
2743         // just finish the parse now.
2744         if (LazyStreamer && SeenValueSymbolTable) {
2745           NextUnreadBit = Stream.GetCurrentBitNo();
2746           return std::error_code();
2747         }
2748         break;
2749       case bitc::USELIST_BLOCK_ID:
2750         if (std::error_code EC = ParseUseLists())
2751           return EC;
2752         break;
2753       }
2754       continue;
2755
2756     case BitstreamEntry::Record:
2757       // The interesting case.
2758       break;
2759     }
2760
2761
2762     // Read a record.
2763     switch (Stream.readRecord(Entry.ID, Record)) {
2764     default: break;  // Default behavior, ignore unknown content.
2765     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
2766       if (Record.size() < 1)
2767         return Error("Invalid record");
2768       // Only version #0 and #1 are supported so far.
2769       unsigned module_version = Record[0];
2770       switch (module_version) {
2771         default:
2772           return Error("Invalid value");
2773         case 0:
2774           UseRelativeIDs = false;
2775           break;
2776         case 1:
2777           UseRelativeIDs = true;
2778           break;
2779       }
2780       break;
2781     }
2782     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2783       std::string S;
2784       if (ConvertToString(Record, 0, S))
2785         return Error("Invalid record");
2786       TheModule->setTargetTriple(S);
2787       break;
2788     }
2789     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
2790       std::string S;
2791       if (ConvertToString(Record, 0, S))
2792         return Error("Invalid record");
2793       TheModule->setDataLayout(S);
2794       break;
2795     }
2796     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
2797       std::string S;
2798       if (ConvertToString(Record, 0, S))
2799         return Error("Invalid record");
2800       TheModule->setModuleInlineAsm(S);
2801       break;
2802     }
2803     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
2804       // FIXME: Remove in 4.0.
2805       std::string S;
2806       if (ConvertToString(Record, 0, S))
2807         return Error("Invalid record");
2808       // Ignore value.
2809       break;
2810     }
2811     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
2812       std::string S;
2813       if (ConvertToString(Record, 0, S))
2814         return Error("Invalid record");
2815       SectionTable.push_back(S);
2816       break;
2817     }
2818     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
2819       std::string S;
2820       if (ConvertToString(Record, 0, S))
2821         return Error("Invalid record");
2822       GCTable.push_back(S);
2823       break;
2824     }
2825     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2826       if (Record.size() < 2)
2827         return Error("Invalid record");
2828       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2829       unsigned ComdatNameSize = Record[1];
2830       std::string ComdatName;
2831       ComdatName.reserve(ComdatNameSize);
2832       for (unsigned i = 0; i != ComdatNameSize; ++i)
2833         ComdatName += (char)Record[2 + i];
2834       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2835       C->setSelectionKind(SK);
2836       ComdatList.push_back(C);
2837       break;
2838     }
2839     // GLOBALVAR: [pointer type, isconst, initid,
2840     //             linkage, alignment, section, visibility, threadlocal,
2841     //             unnamed_addr, externally_initialized, dllstorageclass,
2842     //             comdat]
2843     case bitc::MODULE_CODE_GLOBALVAR: {
2844       if (Record.size() < 6)
2845         return Error("Invalid record");
2846       Type *Ty = getTypeByID(Record[0]);
2847       if (!Ty)
2848         return Error("Invalid record");
2849       if (!Ty->isPointerTy())
2850         return Error("Invalid type for value");
2851       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2852       Ty = cast<PointerType>(Ty)->getElementType();
2853
2854       bool isConstant = Record[1];
2855       uint64_t RawLinkage = Record[3];
2856       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2857       unsigned Alignment;
2858       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2859         return EC;
2860       std::string Section;
2861       if (Record[5]) {
2862         if (Record[5]-1 >= SectionTable.size())
2863           return Error("Invalid ID");
2864         Section = SectionTable[Record[5]-1];
2865       }
2866       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2867       // Local linkage must have default visibility.
2868       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2869         // FIXME: Change to an error if non-default in 4.0.
2870         Visibility = GetDecodedVisibility(Record[6]);
2871
2872       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2873       if (Record.size() > 7)
2874         TLM = GetDecodedThreadLocalMode(Record[7]);
2875
2876       bool UnnamedAddr = false;
2877       if (Record.size() > 8)
2878         UnnamedAddr = Record[8];
2879
2880       bool ExternallyInitialized = false;
2881       if (Record.size() > 9)
2882         ExternallyInitialized = Record[9];
2883
2884       GlobalVariable *NewGV =
2885         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2886                            TLM, AddressSpace, ExternallyInitialized);
2887       NewGV->setAlignment(Alignment);
2888       if (!Section.empty())
2889         NewGV->setSection(Section);
2890       NewGV->setVisibility(Visibility);
2891       NewGV->setUnnamedAddr(UnnamedAddr);
2892
2893       if (Record.size() > 10)
2894         NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2895       else
2896         UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
2897
2898       ValueList.push_back(NewGV);
2899
2900       // Remember which value to use for the global initializer.
2901       if (unsigned InitID = Record[2])
2902         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2903
2904       if (Record.size() > 11) {
2905         if (unsigned ComdatID = Record[11]) {
2906           assert(ComdatID <= ComdatList.size());
2907           NewGV->setComdat(ComdatList[ComdatID - 1]);
2908         }
2909       } else if (hasImplicitComdat(RawLinkage)) {
2910         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2911       }
2912       break;
2913     }
2914     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
2915     //             alignment, section, visibility, gc, unnamed_addr,
2916     //             prologuedata, dllstorageclass, comdat, prefixdata]
2917     case bitc::MODULE_CODE_FUNCTION: {
2918       if (Record.size() < 8)
2919         return Error("Invalid record");
2920       Type *Ty = getTypeByID(Record[0]);
2921       if (!Ty)
2922         return Error("Invalid record");
2923       if (!Ty->isPointerTy())
2924         return Error("Invalid type for value");
2925       FunctionType *FTy =
2926         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2927       if (!FTy)
2928         return Error("Invalid type for value");
2929
2930       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2931                                         "", TheModule);
2932
2933       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2934       bool isProto = Record[2];
2935       uint64_t RawLinkage = Record[3];
2936       Func->setLinkage(getDecodedLinkage(RawLinkage));
2937       Func->setAttributes(getAttributes(Record[4]));
2938
2939       unsigned Alignment;
2940       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2941         return EC;
2942       Func->setAlignment(Alignment);
2943       if (Record[6]) {
2944         if (Record[6]-1 >= SectionTable.size())
2945           return Error("Invalid ID");
2946         Func->setSection(SectionTable[Record[6]-1]);
2947       }
2948       // Local linkage must have default visibility.
2949       if (!Func->hasLocalLinkage())
2950         // FIXME: Change to an error if non-default in 4.0.
2951         Func->setVisibility(GetDecodedVisibility(Record[7]));
2952       if (Record.size() > 8 && Record[8]) {
2953         if (Record[8]-1 > GCTable.size())
2954           return Error("Invalid ID");
2955         Func->setGC(GCTable[Record[8]-1].c_str());
2956       }
2957       bool UnnamedAddr = false;
2958       if (Record.size() > 9)
2959         UnnamedAddr = Record[9];
2960       Func->setUnnamedAddr(UnnamedAddr);
2961       if (Record.size() > 10 && Record[10] != 0)
2962         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2963
2964       if (Record.size() > 11)
2965         Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2966       else
2967         UpgradeDLLImportExportLinkage(Func, RawLinkage);
2968
2969       if (Record.size() > 12) {
2970         if (unsigned ComdatID = Record[12]) {
2971           assert(ComdatID <= ComdatList.size());
2972           Func->setComdat(ComdatList[ComdatID - 1]);
2973         }
2974       } else if (hasImplicitComdat(RawLinkage)) {
2975         Func->setComdat(reinterpret_cast<Comdat *>(1));
2976       }
2977
2978       if (Record.size() > 13 && Record[13] != 0)
2979         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2980
2981       ValueList.push_back(Func);
2982
2983       // If this is a function with a body, remember the prototype we are
2984       // creating now, so that we can match up the body with them later.
2985       if (!isProto) {
2986         Func->setIsMaterializable(true);
2987         FunctionsWithBodies.push_back(Func);
2988         if (LazyStreamer)
2989           DeferredFunctionInfo[Func] = 0;
2990       }
2991       break;
2992     }
2993     // ALIAS: [alias type, aliasee val#, linkage]
2994     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
2995     case bitc::MODULE_CODE_ALIAS: {
2996       if (Record.size() < 3)
2997         return Error("Invalid record");
2998       Type *Ty = getTypeByID(Record[0]);
2999       if (!Ty)
3000         return Error("Invalid record");
3001       auto *PTy = dyn_cast<PointerType>(Ty);
3002       if (!PTy)
3003         return Error("Invalid type for value");
3004
3005       auto *NewGA =
3006           GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
3007                               getDecodedLinkage(Record[2]), "", TheModule);
3008       // Old bitcode files didn't have visibility field.
3009       // Local linkage must have default visibility.
3010       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3011         // FIXME: Change to an error if non-default in 4.0.
3012         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
3013       if (Record.size() > 4)
3014         NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3015       else
3016         UpgradeDLLImportExportLinkage(NewGA, Record[2]);
3017       if (Record.size() > 5)
3018         NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
3019       if (Record.size() > 6)
3020         NewGA->setUnnamedAddr(Record[6]);
3021       ValueList.push_back(NewGA);
3022       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3023       break;
3024     }
3025     /// MODULE_CODE_PURGEVALS: [numvals]
3026     case bitc::MODULE_CODE_PURGEVALS:
3027       // Trim down the value list to the specified size.
3028       if (Record.size() < 1 || Record[0] > ValueList.size())
3029         return Error("Invalid record");
3030       ValueList.shrinkTo(Record[0]);
3031       break;
3032     }
3033     Record.clear();
3034   }
3035 }
3036
3037 std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3038                                                 bool ShouldLazyLoadMetadata) {
3039   TheModule = nullptr;
3040
3041   if (std::error_code EC = InitStream())
3042     return EC;
3043
3044   // Sniff for the signature.
3045   if (Stream.Read(8) != 'B' ||
3046       Stream.Read(8) != 'C' ||
3047       Stream.Read(4) != 0x0 ||
3048       Stream.Read(4) != 0xC ||
3049       Stream.Read(4) != 0xE ||
3050       Stream.Read(4) != 0xD)
3051     return Error("Invalid bitcode signature");
3052
3053   // We expect a number of well-defined blocks, though we don't necessarily
3054   // need to understand them all.
3055   while (1) {
3056     if (Stream.AtEndOfStream())
3057       return std::error_code();
3058
3059     BitstreamEntry Entry =
3060       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3061
3062     switch (Entry.Kind) {
3063     case BitstreamEntry::Error:
3064       return Error("Malformed block");
3065     case BitstreamEntry::EndBlock:
3066       return std::error_code();
3067
3068     case BitstreamEntry::SubBlock:
3069       switch (Entry.ID) {
3070       case bitc::BLOCKINFO_BLOCK_ID:
3071         if (Stream.ReadBlockInfoBlock())
3072           return Error("Malformed block");
3073         break;
3074       case bitc::MODULE_BLOCK_ID:
3075         // Reject multiple MODULE_BLOCK's in a single bitstream.
3076         if (TheModule)
3077           return Error("Invalid multiple blocks");
3078         TheModule = M;
3079         if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
3080           return EC;
3081         if (LazyStreamer)
3082           return std::error_code();
3083         break;
3084       default:
3085         if (Stream.SkipBlock())
3086           return Error("Invalid record");
3087         break;
3088       }
3089       continue;
3090     case BitstreamEntry::Record:
3091       // There should be no records in the top-level of blocks.
3092
3093       // The ranlib in Xcode 4 will align archive members by appending newlines
3094       // to the end of them. If this file size is a multiple of 4 but not 8, we
3095       // have to read and ignore these final 4 bytes :-(
3096       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
3097           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
3098           Stream.AtEndOfStream())
3099         return std::error_code();
3100
3101       return Error("Invalid record");
3102     }
3103   }
3104 }
3105
3106 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3107   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3108     return Error("Invalid record");
3109
3110   SmallVector<uint64_t, 64> Record;
3111
3112   std::string Triple;
3113   // Read all the records for this module.
3114   while (1) {
3115     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3116
3117     switch (Entry.Kind) {
3118     case BitstreamEntry::SubBlock: // Handled for us already.
3119     case BitstreamEntry::Error:
3120       return Error("Malformed block");
3121     case BitstreamEntry::EndBlock:
3122       return Triple;
3123     case BitstreamEntry::Record:
3124       // The interesting case.
3125       break;
3126     }
3127
3128     // Read a record.
3129     switch (Stream.readRecord(Entry.ID, Record)) {
3130     default: break;  // Default behavior, ignore unknown content.
3131     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3132       std::string S;
3133       if (ConvertToString(Record, 0, S))
3134         return Error("Invalid record");
3135       Triple = S;
3136       break;
3137     }
3138     }
3139     Record.clear();
3140   }
3141   llvm_unreachable("Exit infinite loop");
3142 }
3143
3144 ErrorOr<std::string> BitcodeReader::parseTriple() {
3145   if (std::error_code EC = InitStream())
3146     return EC;
3147
3148   // Sniff for the signature.
3149   if (Stream.Read(8) != 'B' ||
3150       Stream.Read(8) != 'C' ||
3151       Stream.Read(4) != 0x0 ||
3152       Stream.Read(4) != 0xC ||
3153       Stream.Read(4) != 0xE ||
3154       Stream.Read(4) != 0xD)
3155     return Error("Invalid bitcode signature");
3156
3157   // We expect a number of well-defined blocks, though we don't necessarily
3158   // need to understand them all.
3159   while (1) {
3160     BitstreamEntry Entry = Stream.advance();
3161
3162     switch (Entry.Kind) {
3163     case BitstreamEntry::Error:
3164       return Error("Malformed block");
3165     case BitstreamEntry::EndBlock:
3166       return std::error_code();
3167
3168     case BitstreamEntry::SubBlock:
3169       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3170         return parseModuleTriple();
3171
3172       // Ignore other sub-blocks.
3173       if (Stream.SkipBlock())
3174         return Error("Malformed block");
3175       continue;
3176
3177     case BitstreamEntry::Record:
3178       Stream.skipRecord(Entry.ID);
3179       continue;
3180     }
3181   }
3182 }
3183
3184 /// ParseMetadataAttachment - Parse metadata attachments.
3185 std::error_code BitcodeReader::ParseMetadataAttachment() {
3186   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3187     return Error("Invalid record");
3188
3189   SmallVector<uint64_t, 64> Record;
3190   while (1) {
3191     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3192
3193     switch (Entry.Kind) {
3194     case BitstreamEntry::SubBlock: // Handled for us already.
3195     case BitstreamEntry::Error:
3196       return Error("Malformed block");
3197     case BitstreamEntry::EndBlock:
3198       return std::error_code();
3199     case BitstreamEntry::Record:
3200       // The interesting case.
3201       break;
3202     }
3203
3204     // Read a metadata attachment record.
3205     Record.clear();
3206     switch (Stream.readRecord(Entry.ID, Record)) {
3207     default:  // Default behavior: ignore.
3208       break;
3209     case bitc::METADATA_ATTACHMENT: {
3210       unsigned RecordLength = Record.size();
3211       if (Record.empty() || (RecordLength - 1) % 2 == 1)
3212         return Error("Invalid record");
3213       Instruction *Inst = InstructionList[Record[0]];
3214       for (unsigned i = 1; i != RecordLength; i = i+2) {
3215         unsigned Kind = Record[i];
3216         DenseMap<unsigned, unsigned>::iterator I =
3217           MDKindMap.find(Kind);
3218         if (I == MDKindMap.end())
3219           return Error("Invalid ID");
3220         Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3221         if (isa<LocalAsMetadata>(Node))
3222           // Drop the attachment.  This used to be legal, but there's no
3223           // upgrade path.
3224           break;
3225         Inst->setMetadata(I->second, cast<MDNode>(Node));
3226         if (I->second == LLVMContext::MD_tbaa)
3227           InstsWithTBAATag.push_back(Inst);
3228       }
3229       break;
3230     }
3231     }
3232   }
3233 }
3234
3235 /// ParseFunctionBody - Lazily parse the specified function body block.
3236 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
3237   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3238     return Error("Invalid record");
3239
3240   InstructionList.clear();
3241   unsigned ModuleValueListSize = ValueList.size();
3242   unsigned ModuleMDValueListSize = MDValueList.size();
3243
3244   // Add all the function arguments to the value table.
3245   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3246     ValueList.push_back(I);
3247
3248   unsigned NextValueNo = ValueList.size();
3249   BasicBlock *CurBB = nullptr;
3250   unsigned CurBBNo = 0;
3251
3252   DebugLoc LastLoc;
3253   auto getLastInstruction = [&]() -> Instruction * {
3254     if (CurBB && !CurBB->empty())
3255       return &CurBB->back();
3256     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3257              !FunctionBBs[CurBBNo - 1]->empty())
3258       return &FunctionBBs[CurBBNo - 1]->back();
3259     return nullptr;
3260   };
3261
3262   // Read all the records.
3263   SmallVector<uint64_t, 64> Record;
3264   while (1) {
3265     BitstreamEntry Entry = Stream.advance();
3266
3267     switch (Entry.Kind) {
3268     case BitstreamEntry::Error:
3269       return Error("Malformed block");
3270     case BitstreamEntry::EndBlock:
3271       goto OutOfRecordLoop;
3272
3273     case BitstreamEntry::SubBlock:
3274       switch (Entry.ID) {
3275       default:  // Skip unknown content.
3276         if (Stream.SkipBlock())
3277           return Error("Invalid record");
3278         break;
3279       case bitc::CONSTANTS_BLOCK_ID:
3280         if (std::error_code EC = ParseConstants())
3281           return EC;
3282         NextValueNo = ValueList.size();
3283         break;
3284       case bitc::VALUE_SYMTAB_BLOCK_ID:
3285         if (std::error_code EC = ParseValueSymbolTable())
3286           return EC;
3287         break;
3288       case bitc::METADATA_ATTACHMENT_ID:
3289         if (std::error_code EC = ParseMetadataAttachment())
3290           return EC;
3291         break;
3292       case bitc::METADATA_BLOCK_ID:
3293         if (std::error_code EC = ParseMetadata())
3294           return EC;
3295         break;
3296       case bitc::USELIST_BLOCK_ID:
3297         if (std::error_code EC = ParseUseLists())
3298           return EC;
3299         break;
3300       }
3301       continue;
3302
3303     case BitstreamEntry::Record:
3304       // The interesting case.
3305       break;
3306     }
3307
3308     // Read a record.
3309     Record.clear();
3310     Instruction *I = nullptr;
3311     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3312     switch (BitCode) {
3313     default: // Default behavior: reject
3314       return Error("Invalid value");
3315     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3316       if (Record.size() < 1 || Record[0] == 0)
3317         return Error("Invalid record");
3318       // Create all the basic blocks for the function.
3319       FunctionBBs.resize(Record[0]);
3320
3321       // See if anything took the address of blocks in this function.
3322       auto BBFRI = BasicBlockFwdRefs.find(F);
3323       if (BBFRI == BasicBlockFwdRefs.end()) {
3324         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3325           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3326       } else {
3327         auto &BBRefs = BBFRI->second;
3328         // Check for invalid basic block references.
3329         if (BBRefs.size() > FunctionBBs.size())
3330           return Error("Invalid ID");
3331         assert(!BBRefs.empty() && "Unexpected empty array");
3332         assert(!BBRefs.front() && "Invalid reference to entry block");
3333         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3334              ++I)
3335           if (I < RE && BBRefs[I]) {
3336             BBRefs[I]->insertInto(F);
3337             FunctionBBs[I] = BBRefs[I];
3338           } else {
3339             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3340           }
3341
3342         // Erase from the table.
3343         BasicBlockFwdRefs.erase(BBFRI);
3344       }
3345
3346       CurBB = FunctionBBs[0];
3347       continue;
3348     }
3349
3350     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
3351       // This record indicates that the last instruction is at the same
3352       // location as the previous instruction with a location.
3353       I = getLastInstruction();
3354
3355       if (!I)
3356         return Error("Invalid record");
3357       I->setDebugLoc(LastLoc);
3358       I = nullptr;
3359       continue;
3360
3361     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
3362       I = getLastInstruction();
3363       if (!I || Record.size() < 4)
3364         return Error("Invalid record");
3365
3366       unsigned Line = Record[0], Col = Record[1];
3367       unsigned ScopeID = Record[2], IAID = Record[3];
3368
3369       MDNode *Scope = nullptr, *IA = nullptr;
3370       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3371       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3372       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3373       I->setDebugLoc(LastLoc);
3374       I = nullptr;
3375       continue;
3376     }
3377
3378     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
3379       unsigned OpNum = 0;
3380       Value *LHS, *RHS;
3381       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3382           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3383           OpNum+1 > Record.size())
3384         return Error("Invalid record");
3385
3386       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3387       if (Opc == -1)
3388         return Error("Invalid record");
3389       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3390       InstructionList.push_back(I);
3391       if (OpNum < Record.size()) {
3392         if (Opc == Instruction::Add ||
3393             Opc == Instruction::Sub ||
3394             Opc == Instruction::Mul ||
3395             Opc == Instruction::Shl) {
3396           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3397             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3398           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3399             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3400         } else if (Opc == Instruction::SDiv ||
3401                    Opc == Instruction::UDiv ||
3402                    Opc == Instruction::LShr ||
3403                    Opc == Instruction::AShr) {
3404           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3405             cast<BinaryOperator>(I)->setIsExact(true);
3406         } else if (isa<FPMathOperator>(I)) {
3407           FastMathFlags FMF;
3408           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3409             FMF.setUnsafeAlgebra();
3410           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3411             FMF.setNoNaNs();
3412           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3413             FMF.setNoInfs();
3414           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3415             FMF.setNoSignedZeros();
3416           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3417             FMF.setAllowReciprocal();
3418           if (FMF.any())
3419             I->setFastMathFlags(FMF);
3420         }
3421
3422       }
3423       break;
3424     }
3425     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
3426       unsigned OpNum = 0;
3427       Value *Op;
3428       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3429           OpNum+2 != Record.size())
3430         return Error("Invalid record");
3431
3432       Type *ResTy = getTypeByID(Record[OpNum]);
3433       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
3434       if (Opc == -1 || !ResTy)
3435         return Error("Invalid record");
3436       Instruction *Temp = nullptr;
3437       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3438         if (Temp) {
3439           InstructionList.push_back(Temp);
3440           CurBB->getInstList().push_back(Temp);
3441         }
3442       } else {
3443         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3444       }
3445       InstructionList.push_back(I);
3446       break;
3447     }
3448     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3449     case bitc::FUNC_CODE_INST_GEP_OLD:
3450     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3451       unsigned OpNum = 0;
3452
3453       Type *Ty;
3454       bool InBounds;
3455
3456       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3457         InBounds = Record[OpNum++];
3458         Ty = getTypeByID(Record[OpNum++]);
3459       } else {
3460         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3461         Ty = nullptr;
3462       }
3463
3464       Value *BasePtr;
3465       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3466         return Error("Invalid record");
3467
3468       if (Ty &&
3469           Ty !=
3470               cast<SequentialType>(BasePtr->getType()->getScalarType())
3471                   ->getElementType())
3472         return Error(
3473             "Explicit gep type does not match pointee type of pointer operand");
3474
3475       SmallVector<Value*, 16> GEPIdx;
3476       while (OpNum != Record.size()) {
3477         Value *Op;
3478         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3479           return Error("Invalid record");
3480         GEPIdx.push_back(Op);
3481       }
3482
3483       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3484
3485       InstructionList.push_back(I);
3486       if (InBounds)
3487         cast<GetElementPtrInst>(I)->setIsInBounds(true);
3488       break;
3489     }
3490
3491     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3492                                        // EXTRACTVAL: [opty, opval, n x indices]
3493       unsigned OpNum = 0;
3494       Value *Agg;
3495       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3496         return Error("Invalid record");
3497
3498       SmallVector<unsigned, 4> EXTRACTVALIdx;
3499       Type *CurTy = Agg->getType();
3500       for (unsigned RecSize = Record.size();
3501            OpNum != RecSize; ++OpNum) {
3502         bool IsArray = CurTy->isArrayTy();
3503         bool IsStruct = CurTy->isStructTy();
3504         uint64_t Index = Record[OpNum];
3505
3506         if (!IsStruct && !IsArray)
3507           return Error("EXTRACTVAL: Invalid type");
3508         if ((unsigned)Index != Index)
3509           return Error("Invalid value");
3510         if (IsStruct && Index >= CurTy->subtypes().size())
3511           return Error("EXTRACTVAL: Invalid struct index");
3512         if (IsArray && Index >= CurTy->getArrayNumElements())
3513           return Error("EXTRACTVAL: Invalid array index");
3514         EXTRACTVALIdx.push_back((unsigned)Index);
3515
3516         if (IsStruct)
3517           CurTy = CurTy->subtypes()[Index];
3518         else
3519           CurTy = CurTy->subtypes()[0];
3520       }
3521
3522       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3523       InstructionList.push_back(I);
3524       break;
3525     }
3526
3527     case bitc::FUNC_CODE_INST_INSERTVAL: {
3528                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
3529       unsigned OpNum = 0;
3530       Value *Agg;
3531       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3532         return Error("Invalid record");
3533       Value *Val;
3534       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3535         return Error("Invalid record");
3536
3537       SmallVector<unsigned, 4> INSERTVALIdx;
3538       Type *CurTy = Agg->getType();
3539       for (unsigned RecSize = Record.size();
3540            OpNum != RecSize; ++OpNum) {
3541         bool IsArray = CurTy->isArrayTy();
3542         bool IsStruct = CurTy->isStructTy();
3543         uint64_t Index = Record[OpNum];
3544
3545         if (!IsStruct && !IsArray)
3546           return Error("INSERTVAL: Invalid type");
3547         if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3548           return Error("Invalid type");
3549         if ((unsigned)Index != Index)
3550           return Error("Invalid value");
3551         if (IsStruct && Index >= CurTy->subtypes().size())
3552           return Error("INSERTVAL: Invalid struct index");
3553         if (IsArray && Index >= CurTy->getArrayNumElements())
3554           return Error("INSERTVAL: Invalid array index");
3555
3556         INSERTVALIdx.push_back((unsigned)Index);
3557         if (IsStruct)
3558           CurTy = CurTy->subtypes()[Index];
3559         else
3560           CurTy = CurTy->subtypes()[0];
3561       }
3562
3563       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3564       InstructionList.push_back(I);
3565       break;
3566     }
3567
3568     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3569       // obsolete form of select
3570       // handles select i1 ... in old bitcode
3571       unsigned OpNum = 0;
3572       Value *TrueVal, *FalseVal, *Cond;
3573       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3574           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3575           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3576         return Error("Invalid record");
3577
3578       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3579       InstructionList.push_back(I);
3580       break;
3581     }
3582
3583     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3584       // new form of select
3585       // handles select i1 or select [N x i1]
3586       unsigned OpNum = 0;
3587       Value *TrueVal, *FalseVal, *Cond;
3588       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3589           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3590           getValueTypePair(Record, OpNum, NextValueNo, Cond))
3591         return Error("Invalid record");
3592
3593       // select condition can be either i1 or [N x i1]
3594       if (VectorType* vector_type =
3595           dyn_cast<VectorType>(Cond->getType())) {
3596         // expect <n x i1>
3597         if (vector_type->getElementType() != Type::getInt1Ty(Context))
3598           return Error("Invalid type for value");
3599       } else {
3600         // expect i1
3601         if (Cond->getType() != Type::getInt1Ty(Context))
3602           return Error("Invalid type for value");
3603       }
3604
3605       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3606       InstructionList.push_back(I);
3607       break;
3608     }
3609
3610     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3611       unsigned OpNum = 0;
3612       Value *Vec, *Idx;
3613       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3614           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3615         return Error("Invalid record");
3616       I = ExtractElementInst::Create(Vec, Idx);
3617       InstructionList.push_back(I);
3618       break;
3619     }
3620
3621     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3622       unsigned OpNum = 0;
3623       Value *Vec, *Elt, *Idx;
3624       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3625           popValue(Record, OpNum, NextValueNo,
3626                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3627           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3628         return Error("Invalid record");
3629       I = InsertElementInst::Create(Vec, Elt, Idx);
3630       InstructionList.push_back(I);
3631       break;
3632     }
3633
3634     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3635       unsigned OpNum = 0;
3636       Value *Vec1, *Vec2, *Mask;
3637       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3638           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3639         return Error("Invalid record");
3640
3641       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3642         return Error("Invalid record");
3643       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3644       InstructionList.push_back(I);
3645       break;
3646     }
3647
3648     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
3649       // Old form of ICmp/FCmp returning bool
3650       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3651       // both legal on vectors but had different behaviour.
3652     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3653       // FCmp/ICmp returning bool or vector of bool
3654
3655       unsigned OpNum = 0;
3656       Value *LHS, *RHS;
3657       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3658           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3659           OpNum+1 != Record.size())
3660         return Error("Invalid record");
3661
3662       if (LHS->getType()->isFPOrFPVectorTy())
3663         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3664       else
3665         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3666       InstructionList.push_back(I);
3667       break;
3668     }
3669
3670     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3671       {
3672         unsigned Size = Record.size();
3673         if (Size == 0) {
3674           I = ReturnInst::Create(Context);
3675           InstructionList.push_back(I);
3676           break;
3677         }
3678
3679         unsigned OpNum = 0;
3680         Value *Op = nullptr;
3681         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3682           return Error("Invalid record");
3683         if (OpNum != Record.size())
3684           return Error("Invalid record");
3685
3686         I = ReturnInst::Create(Context, Op);
3687         InstructionList.push_back(I);
3688         break;
3689       }
3690     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3691       if (Record.size() != 1 && Record.size() != 3)
3692         return Error("Invalid record");
3693       BasicBlock *TrueDest = getBasicBlock(Record[0]);
3694       if (!TrueDest)
3695         return Error("Invalid record");
3696
3697       if (Record.size() == 1) {
3698         I = BranchInst::Create(TrueDest);
3699         InstructionList.push_back(I);
3700       }
3701       else {
3702         BasicBlock *FalseDest = getBasicBlock(Record[1]);
3703         Value *Cond = getValue(Record, 2, NextValueNo,
3704                                Type::getInt1Ty(Context));
3705         if (!FalseDest || !Cond)
3706           return Error("Invalid record");
3707         I = BranchInst::Create(TrueDest, FalseDest, Cond);
3708         InstructionList.push_back(I);
3709       }
3710       break;
3711     }
3712     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3713       // Check magic
3714       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3715         // "New" SwitchInst format with case ranges. The changes to write this
3716         // format were reverted but we still recognize bitcode that uses it.
3717         // Hopefully someday we will have support for case ranges and can use
3718         // this format again.
3719
3720         Type *OpTy = getTypeByID(Record[1]);
3721         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3722
3723         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3724         BasicBlock *Default = getBasicBlock(Record[3]);
3725         if (!OpTy || !Cond || !Default)
3726           return Error("Invalid record");
3727
3728         unsigned NumCases = Record[4];
3729
3730         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3731         InstructionList.push_back(SI);
3732
3733         unsigned CurIdx = 5;
3734         for (unsigned i = 0; i != NumCases; ++i) {
3735           SmallVector<ConstantInt*, 1> CaseVals;
3736           unsigned NumItems = Record[CurIdx++];
3737           for (unsigned ci = 0; ci != NumItems; ++ci) {
3738             bool isSingleNumber = Record[CurIdx++];
3739
3740             APInt Low;
3741             unsigned ActiveWords = 1;
3742             if (ValueBitWidth > 64)
3743               ActiveWords = Record[CurIdx++];
3744             Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3745                                 ValueBitWidth);
3746             CurIdx += ActiveWords;
3747
3748             if (!isSingleNumber) {
3749               ActiveWords = 1;
3750               if (ValueBitWidth > 64)
3751                 ActiveWords = Record[CurIdx++];
3752               APInt High =
3753                   ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3754                                 ValueBitWidth);
3755               CurIdx += ActiveWords;
3756
3757               // FIXME: It is not clear whether values in the range should be
3758               // compared as signed or unsigned values. The partially
3759               // implemented changes that used this format in the past used
3760               // unsigned comparisons.
3761               for ( ; Low.ule(High); ++Low)
3762                 CaseVals.push_back(ConstantInt::get(Context, Low));
3763             } else
3764               CaseVals.push_back(ConstantInt::get(Context, Low));
3765           }
3766           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3767           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3768                  cve = CaseVals.end(); cvi != cve; ++cvi)
3769             SI->addCase(*cvi, DestBB);
3770         }
3771         I = SI;
3772         break;
3773       }
3774
3775       // Old SwitchInst format without case ranges.
3776
3777       if (Record.size() < 3 || (Record.size() & 1) == 0)
3778         return Error("Invalid record");
3779       Type *OpTy = getTypeByID(Record[0]);
3780       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3781       BasicBlock *Default = getBasicBlock(Record[2]);
3782       if (!OpTy || !Cond || !Default)
3783         return Error("Invalid record");
3784       unsigned NumCases = (Record.size()-3)/2;
3785       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3786       InstructionList.push_back(SI);
3787       for (unsigned i = 0, e = NumCases; i != e; ++i) {
3788         ConstantInt *CaseVal =
3789           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3790         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3791         if (!CaseVal || !DestBB) {
3792           delete SI;
3793           return Error("Invalid record");
3794         }
3795         SI->addCase(CaseVal, DestBB);
3796       }
3797       I = SI;
3798       break;
3799     }
3800     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3801       if (Record.size() < 2)
3802         return Error("Invalid record");
3803       Type *OpTy = getTypeByID(Record[0]);
3804       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3805       if (!OpTy || !Address)
3806         return Error("Invalid record");
3807       unsigned NumDests = Record.size()-2;
3808       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3809       InstructionList.push_back(IBI);
3810       for (unsigned i = 0, e = NumDests; i != e; ++i) {
3811         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3812           IBI->addDestination(DestBB);
3813         } else {
3814           delete IBI;
3815           return Error("Invalid record");
3816         }
3817       }
3818       I = IBI;
3819       break;
3820     }
3821
3822     case bitc::FUNC_CODE_INST_INVOKE: {
3823       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3824       if (Record.size() < 4)
3825         return Error("Invalid record");
3826       AttributeSet PAL = getAttributes(Record[0]);
3827       unsigned CCInfo = Record[1];
3828       BasicBlock *NormalBB = getBasicBlock(Record[2]);
3829       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
3830
3831       unsigned OpNum = 4;
3832       Value *Callee;
3833       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3834         return Error("Invalid record");
3835
3836       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3837       FunctionType *FTy = !CalleeTy ? nullptr :
3838         dyn_cast<FunctionType>(CalleeTy->getElementType());
3839
3840       // Check that the right number of fixed parameters are here.
3841       if (!FTy || !NormalBB || !UnwindBB ||
3842           Record.size() < OpNum+FTy->getNumParams())
3843         return Error("Invalid record");
3844
3845       SmallVector<Value*, 16> Ops;
3846       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3847         Ops.push_back(getValue(Record, OpNum, NextValueNo,
3848                                FTy->getParamType(i)));
3849         if (!Ops.back())
3850           return Error("Invalid record");
3851       }
3852
3853       if (!FTy->isVarArg()) {
3854         if (Record.size() != OpNum)
3855           return Error("Invalid record");
3856       } else {
3857         // Read type/value pairs for varargs params.
3858         while (OpNum != Record.size()) {
3859           Value *Op;
3860           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3861             return Error("Invalid record");
3862           Ops.push_back(Op);
3863         }
3864       }
3865
3866       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3867       InstructionList.push_back(I);
3868       cast<InvokeInst>(I)->setCallingConv(
3869         static_cast<CallingConv::ID>(CCInfo));
3870       cast<InvokeInst>(I)->setAttributes(PAL);
3871       break;
3872     }
3873     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3874       unsigned Idx = 0;
3875       Value *Val = nullptr;
3876       if (getValueTypePair(Record, Idx, NextValueNo, Val))
3877         return Error("Invalid record");
3878       I = ResumeInst::Create(Val);
3879       InstructionList.push_back(I);
3880       break;
3881     }
3882     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3883       I = new UnreachableInst(Context);
3884       InstructionList.push_back(I);
3885       break;
3886     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3887       if (Record.size() < 1 || ((Record.size()-1)&1))
3888         return Error("Invalid record");
3889       Type *Ty = getTypeByID(Record[0]);
3890       if (!Ty)
3891         return Error("Invalid record");
3892
3893       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3894       InstructionList.push_back(PN);
3895
3896       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3897         Value *V;
3898         // With the new function encoding, it is possible that operands have
3899         // negative IDs (for forward references).  Use a signed VBR
3900         // representation to keep the encoding small.
3901         if (UseRelativeIDs)
3902           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3903         else
3904           V = getValue(Record, 1+i, NextValueNo, Ty);
3905         BasicBlock *BB = getBasicBlock(Record[2+i]);
3906         if (!V || !BB)
3907           return Error("Invalid record");
3908         PN->addIncoming(V, BB);
3909       }
3910       I = PN;
3911       break;
3912     }
3913
3914     case bitc::FUNC_CODE_INST_LANDINGPAD: {
3915       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3916       unsigned Idx = 0;
3917       if (Record.size() < 4)
3918         return Error("Invalid record");
3919       Type *Ty = getTypeByID(Record[Idx++]);
3920       if (!Ty)
3921         return Error("Invalid record");
3922       Value *PersFn = nullptr;
3923       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3924         return Error("Invalid record");
3925
3926       bool IsCleanup = !!Record[Idx++];
3927       unsigned NumClauses = Record[Idx++];
3928       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3929       LP->setCleanup(IsCleanup);
3930       for (unsigned J = 0; J != NumClauses; ++J) {
3931         LandingPadInst::ClauseType CT =
3932           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3933         Value *Val;
3934
3935         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3936           delete LP;
3937           return Error("Invalid record");
3938         }
3939
3940         assert((CT != LandingPadInst::Catch ||
3941                 !isa<ArrayType>(Val->getType())) &&
3942                "Catch clause has a invalid type!");
3943         assert((CT != LandingPadInst::Filter ||
3944                 isa<ArrayType>(Val->getType())) &&
3945                "Filter clause has invalid type!");
3946         LP->addClause(cast<Constant>(Val));
3947       }
3948
3949       I = LP;
3950       InstructionList.push_back(I);
3951       break;
3952     }
3953
3954     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3955       if (Record.size() != 4)
3956         return Error("Invalid record");
3957       PointerType *Ty =
3958         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3959       Type *OpTy = getTypeByID(Record[1]);
3960       Value *Size = getFnValueByID(Record[2], OpTy);
3961       uint64_t AlignRecord = Record[3];
3962       const uint64_t InAllocaMask = uint64_t(1) << 5;
3963       bool InAlloca = AlignRecord & InAllocaMask;
3964       unsigned Align;
3965       if (std::error_code EC =
3966           parseAlignmentValue(AlignRecord & ~InAllocaMask, Align)) {
3967         return EC;
3968       }
3969       if (!Ty || !Size)
3970         return Error("Invalid record");
3971       AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, Align);
3972       AI->setUsedWithInAlloca(InAlloca);
3973       I = AI;
3974       InstructionList.push_back(I);
3975       break;
3976     }
3977     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3978       unsigned OpNum = 0;
3979       Value *Op;
3980       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3981           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
3982         return Error("Invalid record");
3983
3984       Type *Ty = nullptr;
3985       if (OpNum + 3 == Record.size())
3986         Ty = getTypeByID(Record[OpNum++]);
3987
3988       unsigned Align;
3989       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3990         return EC;
3991       I = new LoadInst(Op, "", Record[OpNum+1], Align);
3992
3993       if (Ty && Ty != I->getType())
3994         return Error("Explicit load type does not match pointee type of "
3995                      "pointer operand");
3996
3997       InstructionList.push_back(I);
3998       break;
3999     }
4000     case bitc::FUNC_CODE_INST_LOADATOMIC: {
4001        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4002       unsigned OpNum = 0;
4003       Value *Op;
4004       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4005           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4006         return Error("Invalid record");
4007
4008       Type *Ty = nullptr;
4009       if (OpNum + 5 == Record.size())
4010         Ty = getTypeByID(Record[OpNum++]);
4011
4012       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4013       if (Ordering == NotAtomic || Ordering == Release ||
4014           Ordering == AcquireRelease)
4015         return Error("Invalid record");
4016       if (Ordering != NotAtomic && Record[OpNum] == 0)
4017         return Error("Invalid record");
4018       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4019
4020       unsigned Align;
4021       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4022         return EC;
4023       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4024
4025       (void)Ty;
4026       assert((!Ty || Ty == I->getType()) &&
4027              "Explicit type doesn't match pointee type of the first operand");
4028
4029       InstructionList.push_back(I);
4030       break;
4031     }
4032     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
4033       unsigned OpNum = 0;
4034       Value *Val, *Ptr;
4035       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4036           popValue(Record, OpNum, NextValueNo,
4037                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4038           OpNum+2 != Record.size())
4039         return Error("Invalid record");
4040       unsigned Align;
4041       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4042         return EC;
4043       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4044       InstructionList.push_back(I);
4045       break;
4046     }
4047     case bitc::FUNC_CODE_INST_STOREATOMIC: {
4048       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4049       unsigned OpNum = 0;
4050       Value *Val, *Ptr;
4051       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4052           popValue(Record, OpNum, NextValueNo,
4053                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4054           OpNum+4 != Record.size())
4055         return Error("Invalid record");
4056
4057       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4058       if (Ordering == NotAtomic || Ordering == Acquire ||
4059           Ordering == AcquireRelease)
4060         return Error("Invalid record");
4061       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4062       if (Ordering != NotAtomic && Record[OpNum] == 0)
4063         return Error("Invalid record");
4064
4065       unsigned Align;
4066       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4067         return EC;
4068       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4069       InstructionList.push_back(I);
4070       break;
4071     }
4072     case bitc::FUNC_CODE_INST_CMPXCHG: {
4073       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4074       //          failureordering?, isweak?]
4075       unsigned OpNum = 0;
4076       Value *Ptr, *Cmp, *New;
4077       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4078           popValue(Record, OpNum, NextValueNo,
4079                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
4080           popValue(Record, OpNum, NextValueNo,
4081                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
4082           (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
4083         return Error("Invalid record");
4084       AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4085       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4086         return Error("Invalid record");
4087       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
4088
4089       AtomicOrdering FailureOrdering;
4090       if (Record.size() < 7)
4091         FailureOrdering =
4092             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4093       else
4094         FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4095
4096       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4097                                 SynchScope);
4098       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4099
4100       if (Record.size() < 8) {
4101         // Before weak cmpxchgs existed, the instruction simply returned the
4102         // value loaded from memory, so bitcode files from that era will be
4103         // expecting the first component of a modern cmpxchg.
4104         CurBB->getInstList().push_back(I);
4105         I = ExtractValueInst::Create(I, 0);
4106       } else {
4107         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4108       }
4109
4110       InstructionList.push_back(I);
4111       break;
4112     }
4113     case bitc::FUNC_CODE_INST_ATOMICRMW: {
4114       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4115       unsigned OpNum = 0;
4116       Value *Ptr, *Val;
4117       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4118           popValue(Record, OpNum, NextValueNo,
4119                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4120           OpNum+4 != Record.size())
4121         return Error("Invalid record");
4122       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4123       if (Operation < AtomicRMWInst::FIRST_BINOP ||
4124           Operation > AtomicRMWInst::LAST_BINOP)
4125         return Error("Invalid record");
4126       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4127       if (Ordering == NotAtomic || Ordering == Unordered)
4128         return Error("Invalid record");
4129       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4130       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4131       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4132       InstructionList.push_back(I);
4133       break;
4134     }
4135     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4136       if (2 != Record.size())
4137         return Error("Invalid record");
4138       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4139       if (Ordering == NotAtomic || Ordering == Unordered ||
4140           Ordering == Monotonic)
4141         return Error("Invalid record");
4142       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4143       I = new FenceInst(Context, Ordering, SynchScope);
4144       InstructionList.push_back(I);
4145       break;
4146     }
4147     case bitc::FUNC_CODE_INST_CALL: {
4148       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4149       if (Record.size() < 3)
4150         return Error("Invalid record");
4151
4152       AttributeSet PAL = getAttributes(Record[0]);
4153       unsigned CCInfo = Record[1];
4154
4155       unsigned OpNum = 2;
4156       Value *Callee;
4157       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4158         return Error("Invalid record");
4159
4160       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4161       FunctionType *FTy = nullptr;
4162       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4163       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
4164         return Error("Invalid record");
4165
4166       SmallVector<Value*, 16> Args;
4167       // Read the fixed params.
4168       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4169         if (FTy->getParamType(i)->isLabelTy())
4170           Args.push_back(getBasicBlock(Record[OpNum]));
4171         else
4172           Args.push_back(getValue(Record, OpNum, NextValueNo,
4173                                   FTy->getParamType(i)));
4174         if (!Args.back())
4175           return Error("Invalid record");
4176       }
4177
4178       // Read type/value pairs for varargs params.
4179       if (!FTy->isVarArg()) {
4180         if (OpNum != Record.size())
4181           return Error("Invalid record");
4182       } else {
4183         while (OpNum != Record.size()) {
4184           Value *Op;
4185           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4186             return Error("Invalid record");
4187           Args.push_back(Op);
4188         }
4189       }
4190
4191       I = CallInst::Create(Callee, Args);
4192       InstructionList.push_back(I);
4193       cast<CallInst>(I)->setCallingConv(
4194           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4195       CallInst::TailCallKind TCK = CallInst::TCK_None;
4196       if (CCInfo & 1)
4197         TCK = CallInst::TCK_Tail;
4198       if (CCInfo & (1 << 14))
4199         TCK = CallInst::TCK_MustTail;
4200       cast<CallInst>(I)->setTailCallKind(TCK);
4201       cast<CallInst>(I)->setAttributes(PAL);
4202       break;
4203     }
4204     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4205       if (Record.size() < 3)
4206         return Error("Invalid record");
4207       Type *OpTy = getTypeByID(Record[0]);
4208       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4209       Type *ResTy = getTypeByID(Record[2]);
4210       if (!OpTy || !Op || !ResTy)
4211         return Error("Invalid record");
4212       I = new VAArgInst(Op, ResTy);
4213       InstructionList.push_back(I);
4214       break;
4215     }
4216     }
4217
4218     // Add instruction to end of current BB.  If there is no current BB, reject
4219     // this file.
4220     if (!CurBB) {
4221       delete I;
4222       return Error("Invalid instruction with no BB");
4223     }
4224     CurBB->getInstList().push_back(I);
4225
4226     // If this was a terminator instruction, move to the next block.
4227     if (isa<TerminatorInst>(I)) {
4228       ++CurBBNo;
4229       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4230     }
4231
4232     // Non-void values get registered in the value table for future use.
4233     if (I && !I->getType()->isVoidTy())
4234       ValueList.AssignValue(I, NextValueNo++);
4235   }
4236
4237 OutOfRecordLoop:
4238
4239   // Check the function list for unresolved values.
4240   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4241     if (!A->getParent()) {
4242       // We found at least one unresolved value.  Nuke them all to avoid leaks.
4243       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4244         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4245           A->replaceAllUsesWith(UndefValue::get(A->getType()));
4246           delete A;
4247         }
4248       }
4249       return Error("Never resolved value found in function");
4250     }
4251   }
4252
4253   // FIXME: Check for unresolved forward-declared metadata references
4254   // and clean up leaks.
4255
4256   // Trim the value list down to the size it was before we parsed this function.
4257   ValueList.shrinkTo(ModuleValueListSize);
4258   MDValueList.shrinkTo(ModuleMDValueListSize);
4259   std::vector<BasicBlock*>().swap(FunctionBBs);
4260   return std::error_code();
4261 }
4262
4263 /// Find the function body in the bitcode stream
4264 std::error_code BitcodeReader::FindFunctionInStream(
4265     Function *F,
4266     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4267   while (DeferredFunctionInfoIterator->second == 0) {
4268     if (Stream.AtEndOfStream())
4269       return Error("Could not find function in stream");
4270     // ParseModule will parse the next body in the stream and set its
4271     // position in the DeferredFunctionInfo map.
4272     if (std::error_code EC = ParseModule(true))
4273       return EC;
4274   }
4275   return std::error_code();
4276 }
4277
4278 //===----------------------------------------------------------------------===//
4279 // GVMaterializer implementation
4280 //===----------------------------------------------------------------------===//
4281
4282 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4283
4284 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4285   if (std::error_code EC = materializeMetadata())
4286     return EC;
4287
4288   Function *F = dyn_cast<Function>(GV);
4289   // If it's not a function or is already material, ignore the request.
4290   if (!F || !F->isMaterializable())
4291     return std::error_code();
4292
4293   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4294   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4295   // If its position is recorded as 0, its body is somewhere in the stream
4296   // but we haven't seen it yet.
4297   if (DFII->second == 0 && LazyStreamer)
4298     if (std::error_code EC = FindFunctionInStream(F, DFII))
4299       return EC;
4300
4301   // Move the bit stream to the saved position of the deferred function body.
4302   Stream.JumpToBit(DFII->second);
4303
4304   if (std::error_code EC = ParseFunctionBody(F))
4305     return EC;
4306   F->setIsMaterializable(false);
4307
4308   // Upgrade any old intrinsic calls in the function.
4309   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4310        E = UpgradedIntrinsics.end(); I != E; ++I) {
4311     if (I->first != I->second) {
4312       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4313            UI != UE;) {
4314         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4315           UpgradeIntrinsicCall(CI, I->second);
4316       }
4317     }
4318   }
4319
4320   // Bring in any functions that this function forward-referenced via
4321   // blockaddresses.
4322   return materializeForwardReferencedFunctions();
4323 }
4324
4325 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4326   const Function *F = dyn_cast<Function>(GV);
4327   if (!F || F->isDeclaration())
4328     return false;
4329
4330   // Dematerializing F would leave dangling references that wouldn't be
4331   // reconnected on re-materialization.
4332   if (BlockAddressesTaken.count(F))
4333     return false;
4334
4335   return DeferredFunctionInfo.count(const_cast<Function*>(F));
4336 }
4337
4338 void BitcodeReader::Dematerialize(GlobalValue *GV) {
4339   Function *F = dyn_cast<Function>(GV);
4340   // If this function isn't dematerializable, this is a noop.
4341   if (!F || !isDematerializable(F))
4342     return;
4343
4344   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4345
4346   // Just forget the function body, we can remat it later.
4347   F->dropAllReferences();
4348   F->setIsMaterializable(true);
4349 }
4350
4351 std::error_code BitcodeReader::MaterializeModule(Module *M) {
4352   assert(M == TheModule &&
4353          "Can only Materialize the Module this BitcodeReader is attached to.");
4354
4355   if (std::error_code EC = materializeMetadata())
4356     return EC;
4357
4358   // Promise to materialize all forward references.
4359   WillMaterializeAllForwardRefs = true;
4360
4361   // Iterate over the module, deserializing any functions that are still on
4362   // disk.
4363   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4364        F != E; ++F) {
4365     if (std::error_code EC = materialize(F))
4366       return EC;
4367   }
4368   // At this point, if there are any function bodies, the current bit is
4369   // pointing to the END_BLOCK record after them. Now make sure the rest
4370   // of the bits in the module have been read.
4371   if (NextUnreadBit)
4372     ParseModule(true);
4373
4374   // Check that all block address forward references got resolved (as we
4375   // promised above).
4376   if (!BasicBlockFwdRefs.empty())
4377     return Error("Never resolved function from blockaddress");
4378
4379   // Upgrade any intrinsic calls that slipped through (should not happen!) and
4380   // delete the old functions to clean up. We can't do this unless the entire
4381   // module is materialized because there could always be another function body
4382   // with calls to the old function.
4383   for (std::vector<std::pair<Function*, Function*> >::iterator I =
4384        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4385     if (I->first != I->second) {
4386       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4387            UI != UE;) {
4388         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4389           UpgradeIntrinsicCall(CI, I->second);
4390       }
4391       if (!I->first->use_empty())
4392         I->first->replaceAllUsesWith(I->second);
4393       I->first->eraseFromParent();
4394     }
4395   }
4396   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
4397
4398   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4399     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4400
4401   UpgradeDebugInfo(*M);
4402   return std::error_code();
4403 }
4404
4405 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4406   return IdentifiedStructTypes;
4407 }
4408
4409 std::error_code BitcodeReader::InitStream() {
4410   if (LazyStreamer)
4411     return InitLazyStream();
4412   return InitStreamFromBuffer();
4413 }
4414
4415 std::error_code BitcodeReader::InitStreamFromBuffer() {
4416   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4417   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4418
4419   if (Buffer->getBufferSize() & 3)
4420     return Error("Invalid bitcode signature");
4421
4422   // If we have a wrapper header, parse it and ignore the non-bc file contents.
4423   // The magic number is 0x0B17C0DE stored in little endian.
4424   if (isBitcodeWrapper(BufPtr, BufEnd))
4425     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4426       return Error("Invalid bitcode wrapper header");
4427
4428   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4429   Stream.init(&*StreamFile);
4430
4431   return std::error_code();
4432 }
4433
4434 std::error_code BitcodeReader::InitLazyStream() {
4435   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4436   // see it.
4437   auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
4438   StreamingMemoryObject &Bytes = *OwnedBytes;
4439   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4440   Stream.init(&*StreamFile);
4441
4442   unsigned char buf[16];
4443   if (Bytes.readBytes(buf, 16, 0) != 16)
4444     return Error("Invalid bitcode signature");
4445
4446   if (!isBitcode(buf, buf + 16))
4447     return Error("Invalid bitcode signature");
4448
4449   if (isBitcodeWrapper(buf, buf + 4)) {
4450     const unsigned char *bitcodeStart = buf;
4451     const unsigned char *bitcodeEnd = buf + 16;
4452     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4453     Bytes.dropLeadingBytes(bitcodeStart - buf);
4454     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4455   }
4456   return std::error_code();
4457 }
4458
4459 namespace {
4460 class BitcodeErrorCategoryType : public std::error_category {
4461   const char *name() const LLVM_NOEXCEPT override {
4462     return "llvm.bitcode";
4463   }
4464   std::string message(int IE) const override {
4465     BitcodeError E = static_cast<BitcodeError>(IE);
4466     switch (E) {
4467     case BitcodeError::InvalidBitcodeSignature:
4468       return "Invalid bitcode signature";
4469     case BitcodeError::CorruptedBitcode:
4470       return "Corrupted bitcode";
4471     }
4472     llvm_unreachable("Unknown error type!");
4473   }
4474 };
4475 }
4476
4477 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4478
4479 const std::error_category &llvm::BitcodeErrorCategory() {
4480   return *ErrorCategory;
4481 }
4482
4483 //===----------------------------------------------------------------------===//
4484 // External interface
4485 //===----------------------------------------------------------------------===//
4486
4487 /// \brief Get a lazy one-at-time loading module from bitcode.
4488 ///
4489 /// This isn't always used in a lazy context.  In particular, it's also used by
4490 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
4491 /// in forward-referenced functions from block address references.
4492 ///
4493 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4494 /// materialize everything -- in particular, if this isn't truly lazy.
4495 static ErrorOr<Module *>
4496 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4497                          LLVMContext &Context, bool WillMaterializeAll,
4498                          DiagnosticHandlerFunction DiagnosticHandler,
4499                          bool ShouldLazyLoadMetadata = false) {
4500   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
4501   BitcodeReader *R =
4502       new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4503   M->setMaterializer(R);
4504
4505   auto cleanupOnError = [&](std::error_code EC) {
4506     R->releaseBuffer(); // Never take ownership on error.
4507     delete M;  // Also deletes R.
4508     return EC;
4509   };
4510
4511   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4512   if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
4513     return cleanupOnError(EC);
4514
4515   if (!WillMaterializeAll)
4516     // Resolve forward references from blockaddresses.
4517     if (std::error_code EC = R->materializeForwardReferencedFunctions())
4518       return cleanupOnError(EC);
4519
4520   Buffer.release(); // The BitcodeReader owns it now.
4521   return M;
4522 }
4523
4524 ErrorOr<Module *>
4525 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
4526                            LLVMContext &Context,
4527                            DiagnosticHandlerFunction DiagnosticHandler,
4528                            bool ShouldLazyLoadMetadata) {
4529   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4530                                   DiagnosticHandler, ShouldLazyLoadMetadata);
4531 }
4532
4533 ErrorOr<std::unique_ptr<Module>>
4534 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
4535                                LLVMContext &Context,
4536                                DiagnosticHandlerFunction DiagnosticHandler) {
4537   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4538   BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
4539   M->setMaterializer(R);
4540   if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4541     return EC;
4542   return std::move(M);
4543 }
4544
4545 ErrorOr<Module *>
4546 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4547                        DiagnosticHandlerFunction DiagnosticHandler) {
4548   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4549   ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4550       std::move(Buf), Context, true, DiagnosticHandler);
4551   if (!ModuleOrErr)
4552     return ModuleOrErr;
4553   Module *M = ModuleOrErr.get();
4554   // Read in the entire module, and destroy the BitcodeReader.
4555   if (std::error_code EC = M->materializeAllPermanently()) {
4556     delete M;
4557     return EC;
4558   }
4559
4560   // TODO: Restore the use-lists to the in-memory state when the bitcode was
4561   // written.  We must defer until the Module has been fully materialized.
4562
4563   return M;
4564 }
4565
4566 std::string
4567 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4568                              DiagnosticHandlerFunction DiagnosticHandler) {
4569   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4570   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4571                                             DiagnosticHandler);
4572   ErrorOr<std::string> Triple = R->parseTriple();
4573   if (Triple.getError())
4574     return "";
4575   return Triple.get();
4576 }