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