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