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