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