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