New EH representation for MSVC compatibility
[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 DenseMap<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 }
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 }
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
1831     case bitc::METADATA_MODULE: {
1832       if (Record.size() != 6)
1833         return error("Invalid record");
1834
1835       MDValueList.assignValue(
1836           GET_OR_DISTINCT(DIModule, Record[0],
1837                           (Context, getMDOrNull(Record[1]),
1838                           getMDString(Record[2]), getMDString(Record[3]),
1839                           getMDString(Record[4]), getMDString(Record[5]))),
1840           NextMDValueNo++);
1841       break;
1842     }
1843
1844     case bitc::METADATA_FILE: {
1845       if (Record.size() != 3)
1846         return error("Invalid record");
1847
1848       MDValueList.assignValue(
1849           GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
1850                                               getMDString(Record[2]))),
1851           NextMDValueNo++);
1852       break;
1853     }
1854     case bitc::METADATA_COMPILE_UNIT: {
1855       if (Record.size() < 14 || Record.size() > 15)
1856         return error("Invalid record");
1857
1858       MDValueList.assignValue(
1859           GET_OR_DISTINCT(
1860               DICompileUnit, Record[0],
1861               (Context, Record[1], getMDOrNull(Record[2]),
1862                getMDString(Record[3]), Record[4], getMDString(Record[5]),
1863                Record[6], getMDString(Record[7]), Record[8],
1864                getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1865                getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1866                getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14])),
1867           NextMDValueNo++);
1868       break;
1869     }
1870     case bitc::METADATA_SUBPROGRAM: {
1871       if (Record.size() != 19)
1872         return error("Invalid record");
1873
1874       MDValueList.assignValue(
1875           GET_OR_DISTINCT(
1876               DISubprogram, Record[0],
1877               (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1878                getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1879                getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1880                getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1881                Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1882                getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1883           NextMDValueNo++);
1884       break;
1885     }
1886     case bitc::METADATA_LEXICAL_BLOCK: {
1887       if (Record.size() != 5)
1888         return error("Invalid record");
1889
1890       MDValueList.assignValue(
1891           GET_OR_DISTINCT(DILexicalBlock, Record[0],
1892                           (Context, getMDOrNull(Record[1]),
1893                            getMDOrNull(Record[2]), Record[3], Record[4])),
1894           NextMDValueNo++);
1895       break;
1896     }
1897     case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1898       if (Record.size() != 4)
1899         return error("Invalid record");
1900
1901       MDValueList.assignValue(
1902           GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
1903                           (Context, getMDOrNull(Record[1]),
1904                            getMDOrNull(Record[2]), Record[3])),
1905           NextMDValueNo++);
1906       break;
1907     }
1908     case bitc::METADATA_NAMESPACE: {
1909       if (Record.size() != 5)
1910         return error("Invalid record");
1911
1912       MDValueList.assignValue(
1913           GET_OR_DISTINCT(DINamespace, Record[0],
1914                           (Context, getMDOrNull(Record[1]),
1915                            getMDOrNull(Record[2]), getMDString(Record[3]),
1916                            Record[4])),
1917           NextMDValueNo++);
1918       break;
1919     }
1920     case bitc::METADATA_TEMPLATE_TYPE: {
1921       if (Record.size() != 3)
1922         return error("Invalid record");
1923
1924       MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1925                                               Record[0],
1926                                               (Context, getMDString(Record[1]),
1927                                                getMDOrNull(Record[2]))),
1928                               NextMDValueNo++);
1929       break;
1930     }
1931     case bitc::METADATA_TEMPLATE_VALUE: {
1932       if (Record.size() != 5)
1933         return error("Invalid record");
1934
1935       MDValueList.assignValue(
1936           GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
1937                           (Context, Record[1], getMDString(Record[2]),
1938                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
1939           NextMDValueNo++);
1940       break;
1941     }
1942     case bitc::METADATA_GLOBAL_VAR: {
1943       if (Record.size() != 11)
1944         return error("Invalid record");
1945
1946       MDValueList.assignValue(
1947           GET_OR_DISTINCT(DIGlobalVariable, Record[0],
1948                           (Context, getMDOrNull(Record[1]),
1949                            getMDString(Record[2]), getMDString(Record[3]),
1950                            getMDOrNull(Record[4]), Record[5],
1951                            getMDOrNull(Record[6]), Record[7], Record[8],
1952                            getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1953           NextMDValueNo++);
1954       break;
1955     }
1956     case bitc::METADATA_LOCAL_VAR: {
1957       // 10th field is for the obseleted 'inlinedAt:' field.
1958       if (Record.size() != 9 && Record.size() != 10)
1959         return error("Invalid record");
1960
1961       MDValueList.assignValue(
1962           GET_OR_DISTINCT(DILocalVariable, Record[0],
1963                           (Context, Record[1], getMDOrNull(Record[2]),
1964                            getMDString(Record[3]), getMDOrNull(Record[4]),
1965                            Record[5], getMDOrNull(Record[6]), Record[7],
1966                            Record[8])),
1967           NextMDValueNo++);
1968       break;
1969     }
1970     case bitc::METADATA_EXPRESSION: {
1971       if (Record.size() < 1)
1972         return error("Invalid record");
1973
1974       MDValueList.assignValue(
1975           GET_OR_DISTINCT(DIExpression, Record[0],
1976                           (Context, makeArrayRef(Record).slice(1))),
1977           NextMDValueNo++);
1978       break;
1979     }
1980     case bitc::METADATA_OBJC_PROPERTY: {
1981       if (Record.size() != 8)
1982         return error("Invalid record");
1983
1984       MDValueList.assignValue(
1985           GET_OR_DISTINCT(DIObjCProperty, Record[0],
1986                           (Context, getMDString(Record[1]),
1987                            getMDOrNull(Record[2]), Record[3],
1988                            getMDString(Record[4]), getMDString(Record[5]),
1989                            Record[6], getMDOrNull(Record[7]))),
1990           NextMDValueNo++);
1991       break;
1992     }
1993     case bitc::METADATA_IMPORTED_ENTITY: {
1994       if (Record.size() != 6)
1995         return error("Invalid record");
1996
1997       MDValueList.assignValue(
1998           GET_OR_DISTINCT(DIImportedEntity, Record[0],
1999                           (Context, Record[1], getMDOrNull(Record[2]),
2000                            getMDOrNull(Record[3]), Record[4],
2001                            getMDString(Record[5]))),
2002           NextMDValueNo++);
2003       break;
2004     }
2005     case bitc::METADATA_STRING: {
2006       std::string String(Record.begin(), Record.end());
2007       llvm::UpgradeMDStringConstant(String);
2008       Metadata *MD = MDString::get(Context, String);
2009       MDValueList.assignValue(MD, NextMDValueNo++);
2010       break;
2011     }
2012     case bitc::METADATA_KIND: {
2013       if (Record.size() < 2)
2014         return error("Invalid record");
2015
2016       unsigned Kind = Record[0];
2017       SmallString<8> Name(Record.begin()+1, Record.end());
2018
2019       unsigned NewKind = TheModule->getMDKindID(Name.str());
2020       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2021         return error("Conflicting METADATA_KIND records");
2022       break;
2023     }
2024     }
2025   }
2026 #undef GET_OR_DISTINCT
2027 }
2028
2029 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2030 /// encoding.
2031 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2032   if ((V & 1) == 0)
2033     return V >> 1;
2034   if (V != 1)
2035     return -(V >> 1);
2036   // There is no such thing as -0 with integers.  "-0" really means MININT.
2037   return 1ULL << 63;
2038 }
2039
2040 /// Resolve all of the initializers for global values and aliases that we can.
2041 std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
2042   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2043   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
2044   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
2045   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
2046   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2047
2048   GlobalInitWorklist.swap(GlobalInits);
2049   AliasInitWorklist.swap(AliasInits);
2050   FunctionPrefixWorklist.swap(FunctionPrefixes);
2051   FunctionPrologueWorklist.swap(FunctionPrologues);
2052   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2053
2054   while (!GlobalInitWorklist.empty()) {
2055     unsigned ValID = GlobalInitWorklist.back().second;
2056     if (ValID >= ValueList.size()) {
2057       // Not ready to resolve this yet, it requires something later in the file.
2058       GlobalInits.push_back(GlobalInitWorklist.back());
2059     } else {
2060       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2061         GlobalInitWorklist.back().first->setInitializer(C);
2062       else
2063         return error("Expected a constant");
2064     }
2065     GlobalInitWorklist.pop_back();
2066   }
2067
2068   while (!AliasInitWorklist.empty()) {
2069     unsigned ValID = AliasInitWorklist.back().second;
2070     if (ValID >= ValueList.size()) {
2071       AliasInits.push_back(AliasInitWorklist.back());
2072     } else {
2073       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2074       if (!C)
2075         return error("Expected a constant");
2076       GlobalAlias *Alias = AliasInitWorklist.back().first;
2077       if (C->getType() != Alias->getType())
2078         return error("Alias and aliasee types don't match");
2079       Alias->setAliasee(C);
2080     }
2081     AliasInitWorklist.pop_back();
2082   }
2083
2084   while (!FunctionPrefixWorklist.empty()) {
2085     unsigned ValID = FunctionPrefixWorklist.back().second;
2086     if (ValID >= ValueList.size()) {
2087       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2088     } else {
2089       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2090         FunctionPrefixWorklist.back().first->setPrefixData(C);
2091       else
2092         return error("Expected a constant");
2093     }
2094     FunctionPrefixWorklist.pop_back();
2095   }
2096
2097   while (!FunctionPrologueWorklist.empty()) {
2098     unsigned ValID = FunctionPrologueWorklist.back().second;
2099     if (ValID >= ValueList.size()) {
2100       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2101     } else {
2102       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2103         FunctionPrologueWorklist.back().first->setPrologueData(C);
2104       else
2105         return error("Expected a constant");
2106     }
2107     FunctionPrologueWorklist.pop_back();
2108   }
2109
2110   while (!FunctionPersonalityFnWorklist.empty()) {
2111     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2112     if (ValID >= ValueList.size()) {
2113       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2114     } else {
2115       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2116         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2117       else
2118         return error("Expected a constant");
2119     }
2120     FunctionPersonalityFnWorklist.pop_back();
2121   }
2122
2123   return std::error_code();
2124 }
2125
2126 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2127   SmallVector<uint64_t, 8> Words(Vals.size());
2128   std::transform(Vals.begin(), Vals.end(), Words.begin(),
2129                  BitcodeReader::decodeSignRotatedValue);
2130
2131   return APInt(TypeBits, Words);
2132 }
2133
2134 std::error_code BitcodeReader::parseConstants() {
2135   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2136     return error("Invalid record");
2137
2138   SmallVector<uint64_t, 64> Record;
2139
2140   // Read all the records for this value table.
2141   Type *CurTy = Type::getInt32Ty(Context);
2142   unsigned NextCstNo = ValueList.size();
2143   while (1) {
2144     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2145
2146     switch (Entry.Kind) {
2147     case BitstreamEntry::SubBlock: // Handled for us already.
2148     case BitstreamEntry::Error:
2149       return error("Malformed block");
2150     case BitstreamEntry::EndBlock:
2151       if (NextCstNo != ValueList.size())
2152         return error("Invalid ronstant reference");
2153
2154       // Once all the constants have been read, go through and resolve forward
2155       // references.
2156       ValueList.resolveConstantForwardRefs();
2157       return std::error_code();
2158     case BitstreamEntry::Record:
2159       // The interesting case.
2160       break;
2161     }
2162
2163     // Read a record.
2164     Record.clear();
2165     Value *V = nullptr;
2166     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2167     switch (BitCode) {
2168     default:  // Default behavior: unknown constant
2169     case bitc::CST_CODE_UNDEF:     // UNDEF
2170       V = UndefValue::get(CurTy);
2171       break;
2172     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2173       if (Record.empty())
2174         return error("Invalid record");
2175       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2176         return error("Invalid record");
2177       CurTy = TypeList[Record[0]];
2178       continue;  // Skip the ValueList manipulation.
2179     case bitc::CST_CODE_NULL:      // NULL
2180       V = Constant::getNullValue(CurTy);
2181       break;
2182     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2183       if (!CurTy->isIntegerTy() || Record.empty())
2184         return error("Invalid record");
2185       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2186       break;
2187     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2188       if (!CurTy->isIntegerTy() || Record.empty())
2189         return error("Invalid record");
2190
2191       APInt VInt =
2192           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2193       V = ConstantInt::get(Context, VInt);
2194
2195       break;
2196     }
2197     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2198       if (Record.empty())
2199         return error("Invalid record");
2200       if (CurTy->isHalfTy())
2201         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2202                                              APInt(16, (uint16_t)Record[0])));
2203       else if (CurTy->isFloatTy())
2204         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2205                                              APInt(32, (uint32_t)Record[0])));
2206       else if (CurTy->isDoubleTy())
2207         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2208                                              APInt(64, Record[0])));
2209       else if (CurTy->isX86_FP80Ty()) {
2210         // Bits are not stored the same way as a normal i80 APInt, compensate.
2211         uint64_t Rearrange[2];
2212         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2213         Rearrange[1] = Record[0] >> 48;
2214         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2215                                              APInt(80, Rearrange)));
2216       } else if (CurTy->isFP128Ty())
2217         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2218                                              APInt(128, Record)));
2219       else if (CurTy->isPPC_FP128Ty())
2220         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2221                                              APInt(128, Record)));
2222       else
2223         V = UndefValue::get(CurTy);
2224       break;
2225     }
2226
2227     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2228       if (Record.empty())
2229         return error("Invalid record");
2230
2231       unsigned Size = Record.size();
2232       SmallVector<Constant*, 16> Elts;
2233
2234       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2235         for (unsigned i = 0; i != Size; ++i)
2236           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2237                                                      STy->getElementType(i)));
2238         V = ConstantStruct::get(STy, Elts);
2239       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2240         Type *EltTy = ATy->getElementType();
2241         for (unsigned i = 0; i != Size; ++i)
2242           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2243         V = ConstantArray::get(ATy, Elts);
2244       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2245         Type *EltTy = VTy->getElementType();
2246         for (unsigned i = 0; i != Size; ++i)
2247           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2248         V = ConstantVector::get(Elts);
2249       } else {
2250         V = UndefValue::get(CurTy);
2251       }
2252       break;
2253     }
2254     case bitc::CST_CODE_STRING:    // STRING: [values]
2255     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2256       if (Record.empty())
2257         return error("Invalid record");
2258
2259       SmallString<16> Elts(Record.begin(), Record.end());
2260       V = ConstantDataArray::getString(Context, Elts,
2261                                        BitCode == bitc::CST_CODE_CSTRING);
2262       break;
2263     }
2264     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2265       if (Record.empty())
2266         return error("Invalid record");
2267
2268       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2269       unsigned Size = Record.size();
2270
2271       if (EltTy->isIntegerTy(8)) {
2272         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2273         if (isa<VectorType>(CurTy))
2274           V = ConstantDataVector::get(Context, Elts);
2275         else
2276           V = ConstantDataArray::get(Context, Elts);
2277       } else if (EltTy->isIntegerTy(16)) {
2278         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2279         if (isa<VectorType>(CurTy))
2280           V = ConstantDataVector::get(Context, Elts);
2281         else
2282           V = ConstantDataArray::get(Context, Elts);
2283       } else if (EltTy->isIntegerTy(32)) {
2284         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2285         if (isa<VectorType>(CurTy))
2286           V = ConstantDataVector::get(Context, Elts);
2287         else
2288           V = ConstantDataArray::get(Context, Elts);
2289       } else if (EltTy->isIntegerTy(64)) {
2290         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2291         if (isa<VectorType>(CurTy))
2292           V = ConstantDataVector::get(Context, Elts);
2293         else
2294           V = ConstantDataArray::get(Context, Elts);
2295       } else if (EltTy->isFloatTy()) {
2296         SmallVector<float, 16> Elts(Size);
2297         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2298         if (isa<VectorType>(CurTy))
2299           V = ConstantDataVector::get(Context, Elts);
2300         else
2301           V = ConstantDataArray::get(Context, Elts);
2302       } else if (EltTy->isDoubleTy()) {
2303         SmallVector<double, 16> Elts(Size);
2304         std::transform(Record.begin(), Record.end(), Elts.begin(),
2305                        BitsToDouble);
2306         if (isa<VectorType>(CurTy))
2307           V = ConstantDataVector::get(Context, Elts);
2308         else
2309           V = ConstantDataArray::get(Context, Elts);
2310       } else {
2311         return error("Invalid type for value");
2312       }
2313       break;
2314     }
2315
2316     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2317       if (Record.size() < 3)
2318         return error("Invalid record");
2319       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2320       if (Opc < 0) {
2321         V = UndefValue::get(CurTy);  // Unknown binop.
2322       } else {
2323         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2324         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2325         unsigned Flags = 0;
2326         if (Record.size() >= 4) {
2327           if (Opc == Instruction::Add ||
2328               Opc == Instruction::Sub ||
2329               Opc == Instruction::Mul ||
2330               Opc == Instruction::Shl) {
2331             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2332               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2333             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2334               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2335           } else if (Opc == Instruction::SDiv ||
2336                      Opc == Instruction::UDiv ||
2337                      Opc == Instruction::LShr ||
2338                      Opc == Instruction::AShr) {
2339             if (Record[3] & (1 << bitc::PEO_EXACT))
2340               Flags |= SDivOperator::IsExact;
2341           }
2342         }
2343         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2344       }
2345       break;
2346     }
2347     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2348       if (Record.size() < 3)
2349         return error("Invalid record");
2350       int Opc = getDecodedCastOpcode(Record[0]);
2351       if (Opc < 0) {
2352         V = UndefValue::get(CurTy);  // Unknown cast.
2353       } else {
2354         Type *OpTy = getTypeByID(Record[1]);
2355         if (!OpTy)
2356           return error("Invalid record");
2357         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2358         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2359         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2360       }
2361       break;
2362     }
2363     case bitc::CST_CODE_CE_INBOUNDS_GEP:
2364     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
2365       unsigned OpNum = 0;
2366       Type *PointeeType = nullptr;
2367       if (Record.size() % 2)
2368         PointeeType = getTypeByID(Record[OpNum++]);
2369       SmallVector<Constant*, 16> Elts;
2370       while (OpNum != Record.size()) {
2371         Type *ElTy = getTypeByID(Record[OpNum++]);
2372         if (!ElTy)
2373           return error("Invalid record");
2374         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2375       }
2376
2377       if (PointeeType &&
2378           PointeeType !=
2379               cast<SequentialType>(Elts[0]->getType()->getScalarType())
2380                   ->getElementType())
2381         return error("Explicit gep operator type does not match pointee type "
2382                      "of pointer operand");
2383
2384       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2385       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2386                                          BitCode ==
2387                                              bitc::CST_CODE_CE_INBOUNDS_GEP);
2388       break;
2389     }
2390     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2391       if (Record.size() < 3)
2392         return error("Invalid record");
2393
2394       Type *SelectorTy = Type::getInt1Ty(Context);
2395
2396       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2397       // vector. Otherwise, it must be a single bit.
2398       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2399         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2400                                      VTy->getNumElements());
2401
2402       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2403                                                               SelectorTy),
2404                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2405                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2406       break;
2407     }
2408     case bitc::CST_CODE_CE_EXTRACTELT
2409         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2410       if (Record.size() < 3)
2411         return error("Invalid record");
2412       VectorType *OpTy =
2413         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2414       if (!OpTy)
2415         return error("Invalid record");
2416       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2417       Constant *Op1 = nullptr;
2418       if (Record.size() == 4) {
2419         Type *IdxTy = getTypeByID(Record[2]);
2420         if (!IdxTy)
2421           return error("Invalid record");
2422         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2423       } else // TODO: Remove with llvm 4.0
2424         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2425       if (!Op1)
2426         return error("Invalid record");
2427       V = ConstantExpr::getExtractElement(Op0, Op1);
2428       break;
2429     }
2430     case bitc::CST_CODE_CE_INSERTELT
2431         : { // CE_INSERTELT: [opval, opval, opty, opval]
2432       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2433       if (Record.size() < 3 || !OpTy)
2434         return error("Invalid record");
2435       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2436       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2437                                                   OpTy->getElementType());
2438       Constant *Op2 = nullptr;
2439       if (Record.size() == 4) {
2440         Type *IdxTy = getTypeByID(Record[2]);
2441         if (!IdxTy)
2442           return error("Invalid record");
2443         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2444       } else // TODO: Remove with llvm 4.0
2445         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2446       if (!Op2)
2447         return error("Invalid record");
2448       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2449       break;
2450     }
2451     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2452       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2453       if (Record.size() < 3 || !OpTy)
2454         return error("Invalid record");
2455       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2456       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2457       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2458                                                  OpTy->getNumElements());
2459       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2460       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2461       break;
2462     }
2463     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2464       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2465       VectorType *OpTy =
2466         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2467       if (Record.size() < 4 || !RTy || !OpTy)
2468         return error("Invalid record");
2469       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2470       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2471       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2472                                                  RTy->getNumElements());
2473       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2474       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2475       break;
2476     }
2477     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2478       if (Record.size() < 4)
2479         return error("Invalid record");
2480       Type *OpTy = getTypeByID(Record[0]);
2481       if (!OpTy)
2482         return error("Invalid record");
2483       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2484       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2485
2486       if (OpTy->isFPOrFPVectorTy())
2487         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2488       else
2489         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2490       break;
2491     }
2492     // This maintains backward compatibility, pre-asm dialect keywords.
2493     // FIXME: Remove with the 4.0 release.
2494     case bitc::CST_CODE_INLINEASM_OLD: {
2495       if (Record.size() < 2)
2496         return error("Invalid record");
2497       std::string AsmStr, ConstrStr;
2498       bool HasSideEffects = Record[0] & 1;
2499       bool IsAlignStack = Record[0] >> 1;
2500       unsigned AsmStrSize = Record[1];
2501       if (2+AsmStrSize >= Record.size())
2502         return error("Invalid record");
2503       unsigned ConstStrSize = Record[2+AsmStrSize];
2504       if (3+AsmStrSize+ConstStrSize > Record.size())
2505         return error("Invalid record");
2506
2507       for (unsigned i = 0; i != AsmStrSize; ++i)
2508         AsmStr += (char)Record[2+i];
2509       for (unsigned i = 0; i != ConstStrSize; ++i)
2510         ConstrStr += (char)Record[3+AsmStrSize+i];
2511       PointerType *PTy = cast<PointerType>(CurTy);
2512       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2513                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2514       break;
2515     }
2516     // This version adds support for the asm dialect keywords (e.g.,
2517     // inteldialect).
2518     case bitc::CST_CODE_INLINEASM: {
2519       if (Record.size() < 2)
2520         return error("Invalid record");
2521       std::string AsmStr, ConstrStr;
2522       bool HasSideEffects = Record[0] & 1;
2523       bool IsAlignStack = (Record[0] >> 1) & 1;
2524       unsigned AsmDialect = Record[0] >> 2;
2525       unsigned AsmStrSize = Record[1];
2526       if (2+AsmStrSize >= Record.size())
2527         return error("Invalid record");
2528       unsigned ConstStrSize = Record[2+AsmStrSize];
2529       if (3+AsmStrSize+ConstStrSize > Record.size())
2530         return error("Invalid record");
2531
2532       for (unsigned i = 0; i != AsmStrSize; ++i)
2533         AsmStr += (char)Record[2+i];
2534       for (unsigned i = 0; i != ConstStrSize; ++i)
2535         ConstrStr += (char)Record[3+AsmStrSize+i];
2536       PointerType *PTy = cast<PointerType>(CurTy);
2537       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2538                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2539                          InlineAsm::AsmDialect(AsmDialect));
2540       break;
2541     }
2542     case bitc::CST_CODE_BLOCKADDRESS:{
2543       if (Record.size() < 3)
2544         return error("Invalid record");
2545       Type *FnTy = getTypeByID(Record[0]);
2546       if (!FnTy)
2547         return error("Invalid record");
2548       Function *Fn =
2549         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2550       if (!Fn)
2551         return error("Invalid record");
2552
2553       // Don't let Fn get dematerialized.
2554       BlockAddressesTaken.insert(Fn);
2555
2556       // If the function is already parsed we can insert the block address right
2557       // away.
2558       BasicBlock *BB;
2559       unsigned BBID = Record[2];
2560       if (!BBID)
2561         // Invalid reference to entry block.
2562         return error("Invalid ID");
2563       if (!Fn->empty()) {
2564         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2565         for (size_t I = 0, E = BBID; I != E; ++I) {
2566           if (BBI == BBE)
2567             return error("Invalid ID");
2568           ++BBI;
2569         }
2570         BB = BBI;
2571       } else {
2572         // Otherwise insert a placeholder and remember it so it can be inserted
2573         // when the function is parsed.
2574         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2575         if (FwdBBs.empty())
2576           BasicBlockFwdRefQueue.push_back(Fn);
2577         if (FwdBBs.size() < BBID + 1)
2578           FwdBBs.resize(BBID + 1);
2579         if (!FwdBBs[BBID])
2580           FwdBBs[BBID] = BasicBlock::Create(Context);
2581         BB = FwdBBs[BBID];
2582       }
2583       V = BlockAddress::get(Fn, BB);
2584       break;
2585     }
2586     }
2587
2588     ValueList.assignValue(V, NextCstNo);
2589     ++NextCstNo;
2590   }
2591 }
2592
2593 std::error_code BitcodeReader::parseUseLists() {
2594   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2595     return error("Invalid record");
2596
2597   // Read all the records.
2598   SmallVector<uint64_t, 64> Record;
2599   while (1) {
2600     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2601
2602     switch (Entry.Kind) {
2603     case BitstreamEntry::SubBlock: // Handled for us already.
2604     case BitstreamEntry::Error:
2605       return error("Malformed block");
2606     case BitstreamEntry::EndBlock:
2607       return std::error_code();
2608     case BitstreamEntry::Record:
2609       // The interesting case.
2610       break;
2611     }
2612
2613     // Read a use list record.
2614     Record.clear();
2615     bool IsBB = false;
2616     switch (Stream.readRecord(Entry.ID, Record)) {
2617     default:  // Default behavior: unknown type.
2618       break;
2619     case bitc::USELIST_CODE_BB:
2620       IsBB = true;
2621       // fallthrough
2622     case bitc::USELIST_CODE_DEFAULT: {
2623       unsigned RecordLength = Record.size();
2624       if (RecordLength < 3)
2625         // Records should have at least an ID and two indexes.
2626         return error("Invalid record");
2627       unsigned ID = Record.back();
2628       Record.pop_back();
2629
2630       Value *V;
2631       if (IsBB) {
2632         assert(ID < FunctionBBs.size() && "Basic block not found");
2633         V = FunctionBBs[ID];
2634       } else
2635         V = ValueList[ID];
2636       unsigned NumUses = 0;
2637       SmallDenseMap<const Use *, unsigned, 16> Order;
2638       for (const Use &U : V->uses()) {
2639         if (++NumUses > Record.size())
2640           break;
2641         Order[&U] = Record[NumUses - 1];
2642       }
2643       if (Order.size() != Record.size() || NumUses > Record.size())
2644         // Mismatches can happen if the functions are being materialized lazily
2645         // (out-of-order), or a value has been upgraded.
2646         break;
2647
2648       V->sortUseList([&](const Use &L, const Use &R) {
2649         return Order.lookup(&L) < Order.lookup(&R);
2650       });
2651       break;
2652     }
2653     }
2654   }
2655 }
2656
2657 /// When we see the block for metadata, remember where it is and then skip it.
2658 /// This lets us lazily deserialize the metadata.
2659 std::error_code BitcodeReader::rememberAndSkipMetadata() {
2660   // Save the current stream state.
2661   uint64_t CurBit = Stream.GetCurrentBitNo();
2662   DeferredMetadataInfo.push_back(CurBit);
2663
2664   // Skip over the block for now.
2665   if (Stream.SkipBlock())
2666     return error("Invalid record");
2667   return std::error_code();
2668 }
2669
2670 std::error_code BitcodeReader::materializeMetadata() {
2671   for (uint64_t BitPos : DeferredMetadataInfo) {
2672     // Move the bit stream to the saved position.
2673     Stream.JumpToBit(BitPos);
2674     if (std::error_code EC = parseMetadata())
2675       return EC;
2676   }
2677   DeferredMetadataInfo.clear();
2678   return std::error_code();
2679 }
2680
2681 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2682
2683 /// When we see the block for a function body, remember where it is and then
2684 /// skip it.  This lets us lazily deserialize the functions.
2685 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
2686   // Get the function we are talking about.
2687   if (FunctionsWithBodies.empty())
2688     return error("Insufficient function protos");
2689
2690   Function *Fn = FunctionsWithBodies.back();
2691   FunctionsWithBodies.pop_back();
2692
2693   // Save the current stream state.
2694   uint64_t CurBit = Stream.GetCurrentBitNo();
2695   DeferredFunctionInfo[Fn] = CurBit;
2696
2697   // Skip over the function block for now.
2698   if (Stream.SkipBlock())
2699     return error("Invalid record");
2700   return std::error_code();
2701 }
2702
2703 std::error_code BitcodeReader::globalCleanup() {
2704   // Patch the initializers for globals and aliases up.
2705   resolveGlobalAndAliasInits();
2706   if (!GlobalInits.empty() || !AliasInits.empty())
2707     return error("Malformed global initializer set");
2708
2709   // Look for intrinsic functions which need to be upgraded at some point
2710   for (Function &F : *TheModule) {
2711     Function *NewFn;
2712     if (UpgradeIntrinsicFunction(&F, NewFn))
2713       UpgradedIntrinsics[&F] = NewFn;
2714   }
2715
2716   // Look for global variables which need to be renamed.
2717   for (GlobalVariable &GV : TheModule->globals())
2718     UpgradeGlobalVariable(&GV);
2719
2720   // Force deallocation of memory for these vectors to favor the client that
2721   // want lazy deserialization.
2722   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2723   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2724   return std::error_code();
2725 }
2726
2727 std::error_code BitcodeReader::parseModule(bool Resume,
2728                                            bool ShouldLazyLoadMetadata) {
2729   if (Resume)
2730     Stream.JumpToBit(NextUnreadBit);
2731   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2732     return error("Invalid record");
2733
2734   SmallVector<uint64_t, 64> Record;
2735   std::vector<std::string> SectionTable;
2736   std::vector<std::string> GCTable;
2737
2738   // Read all the records for this module.
2739   while (1) {
2740     BitstreamEntry Entry = Stream.advance();
2741
2742     switch (Entry.Kind) {
2743     case BitstreamEntry::Error:
2744       return error("Malformed block");
2745     case BitstreamEntry::EndBlock:
2746       return globalCleanup();
2747
2748     case BitstreamEntry::SubBlock:
2749       switch (Entry.ID) {
2750       default:  // Skip unknown content.
2751         if (Stream.SkipBlock())
2752           return error("Invalid record");
2753         break;
2754       case bitc::BLOCKINFO_BLOCK_ID:
2755         if (Stream.ReadBlockInfoBlock())
2756           return error("Malformed block");
2757         break;
2758       case bitc::PARAMATTR_BLOCK_ID:
2759         if (std::error_code EC = parseAttributeBlock())
2760           return EC;
2761         break;
2762       case bitc::PARAMATTR_GROUP_BLOCK_ID:
2763         if (std::error_code EC = parseAttributeGroupBlock())
2764           return EC;
2765         break;
2766       case bitc::TYPE_BLOCK_ID_NEW:
2767         if (std::error_code EC = parseTypeTable())
2768           return EC;
2769         break;
2770       case bitc::VALUE_SYMTAB_BLOCK_ID:
2771         if (std::error_code EC = parseValueSymbolTable())
2772           return EC;
2773         SeenValueSymbolTable = true;
2774         break;
2775       case bitc::CONSTANTS_BLOCK_ID:
2776         if (std::error_code EC = parseConstants())
2777           return EC;
2778         if (std::error_code EC = resolveGlobalAndAliasInits())
2779           return EC;
2780         break;
2781       case bitc::METADATA_BLOCK_ID:
2782         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2783           if (std::error_code EC = rememberAndSkipMetadata())
2784             return EC;
2785           break;
2786         }
2787         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2788         if (std::error_code EC = parseMetadata())
2789           return EC;
2790         break;
2791       case bitc::FUNCTION_BLOCK_ID:
2792         // If this is the first function body we've seen, reverse the
2793         // FunctionsWithBodies list.
2794         if (!SeenFirstFunctionBody) {
2795           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2796           if (std::error_code EC = globalCleanup())
2797             return EC;
2798           SeenFirstFunctionBody = true;
2799         }
2800
2801         if (std::error_code EC = rememberAndSkipFunctionBody())
2802           return EC;
2803         // Suspend parsing when we reach the function bodies. Subsequent
2804         // materialization calls will resume it when necessary. If the bitcode
2805         // file is old, the symbol table will be at the end instead and will not
2806         // have been seen yet. In this case, just finish the parse now.
2807         if (SeenValueSymbolTable) {
2808           NextUnreadBit = Stream.GetCurrentBitNo();
2809           return std::error_code();
2810         }
2811         break;
2812       case bitc::USELIST_BLOCK_ID:
2813         if (std::error_code EC = parseUseLists())
2814           return EC;
2815         break;
2816       }
2817       continue;
2818
2819     case BitstreamEntry::Record:
2820       // The interesting case.
2821       break;
2822     }
2823
2824
2825     // Read a record.
2826     switch (Stream.readRecord(Entry.ID, Record)) {
2827     default: break;  // Default behavior, ignore unknown content.
2828     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
2829       if (Record.size() < 1)
2830         return error("Invalid record");
2831       // Only version #0 and #1 are supported so far.
2832       unsigned module_version = Record[0];
2833       switch (module_version) {
2834         default:
2835           return error("Invalid value");
2836         case 0:
2837           UseRelativeIDs = false;
2838           break;
2839         case 1:
2840           UseRelativeIDs = true;
2841           break;
2842       }
2843       break;
2844     }
2845     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2846       std::string S;
2847       if (convertToString(Record, 0, S))
2848         return error("Invalid record");
2849       TheModule->setTargetTriple(S);
2850       break;
2851     }
2852     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
2853       std::string S;
2854       if (convertToString(Record, 0, S))
2855         return error("Invalid record");
2856       TheModule->setDataLayout(S);
2857       break;
2858     }
2859     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
2860       std::string S;
2861       if (convertToString(Record, 0, S))
2862         return error("Invalid record");
2863       TheModule->setModuleInlineAsm(S);
2864       break;
2865     }
2866     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
2867       // FIXME: Remove in 4.0.
2868       std::string S;
2869       if (convertToString(Record, 0, S))
2870         return error("Invalid record");
2871       // Ignore value.
2872       break;
2873     }
2874     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
2875       std::string S;
2876       if (convertToString(Record, 0, S))
2877         return error("Invalid record");
2878       SectionTable.push_back(S);
2879       break;
2880     }
2881     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
2882       std::string S;
2883       if (convertToString(Record, 0, S))
2884         return error("Invalid record");
2885       GCTable.push_back(S);
2886       break;
2887     }
2888     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2889       if (Record.size() < 2)
2890         return error("Invalid record");
2891       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2892       unsigned ComdatNameSize = Record[1];
2893       std::string ComdatName;
2894       ComdatName.reserve(ComdatNameSize);
2895       for (unsigned i = 0; i != ComdatNameSize; ++i)
2896         ComdatName += (char)Record[2 + i];
2897       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2898       C->setSelectionKind(SK);
2899       ComdatList.push_back(C);
2900       break;
2901     }
2902     // GLOBALVAR: [pointer type, isconst, initid,
2903     //             linkage, alignment, section, visibility, threadlocal,
2904     //             unnamed_addr, externally_initialized, dllstorageclass,
2905     //             comdat]
2906     case bitc::MODULE_CODE_GLOBALVAR: {
2907       if (Record.size() < 6)
2908         return error("Invalid record");
2909       Type *Ty = getTypeByID(Record[0]);
2910       if (!Ty)
2911         return error("Invalid record");
2912       bool isConstant = Record[1] & 1;
2913       bool explicitType = Record[1] & 2;
2914       unsigned AddressSpace;
2915       if (explicitType) {
2916         AddressSpace = Record[1] >> 2;
2917       } else {
2918         if (!Ty->isPointerTy())
2919           return error("Invalid type for value");
2920         AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2921         Ty = cast<PointerType>(Ty)->getElementType();
2922       }
2923
2924       uint64_t RawLinkage = Record[3];
2925       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2926       unsigned Alignment;
2927       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2928         return EC;
2929       std::string Section;
2930       if (Record[5]) {
2931         if (Record[5]-1 >= SectionTable.size())
2932           return error("Invalid ID");
2933         Section = SectionTable[Record[5]-1];
2934       }
2935       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2936       // Local linkage must have default visibility.
2937       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2938         // FIXME: Change to an error if non-default in 4.0.
2939         Visibility = getDecodedVisibility(Record[6]);
2940
2941       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2942       if (Record.size() > 7)
2943         TLM = getDecodedThreadLocalMode(Record[7]);
2944
2945       bool UnnamedAddr = false;
2946       if (Record.size() > 8)
2947         UnnamedAddr = Record[8];
2948
2949       bool ExternallyInitialized = false;
2950       if (Record.size() > 9)
2951         ExternallyInitialized = Record[9];
2952
2953       GlobalVariable *NewGV =
2954         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2955                            TLM, AddressSpace, ExternallyInitialized);
2956       NewGV->setAlignment(Alignment);
2957       if (!Section.empty())
2958         NewGV->setSection(Section);
2959       NewGV->setVisibility(Visibility);
2960       NewGV->setUnnamedAddr(UnnamedAddr);
2961
2962       if (Record.size() > 10)
2963         NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2964       else
2965         upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2966
2967       ValueList.push_back(NewGV);
2968
2969       // Remember which value to use for the global initializer.
2970       if (unsigned InitID = Record[2])
2971         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2972
2973       if (Record.size() > 11) {
2974         if (unsigned ComdatID = Record[11]) {
2975           if (ComdatID > ComdatList.size())
2976             return error("Invalid global variable comdat ID");
2977           NewGV->setComdat(ComdatList[ComdatID - 1]);
2978         }
2979       } else if (hasImplicitComdat(RawLinkage)) {
2980         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2981       }
2982       break;
2983     }
2984     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
2985     //             alignment, section, visibility, gc, unnamed_addr,
2986     //             prologuedata, dllstorageclass, comdat, prefixdata]
2987     case bitc::MODULE_CODE_FUNCTION: {
2988       if (Record.size() < 8)
2989         return error("Invalid record");
2990       Type *Ty = getTypeByID(Record[0]);
2991       if (!Ty)
2992         return error("Invalid record");
2993       if (auto *PTy = dyn_cast<PointerType>(Ty))
2994         Ty = PTy->getElementType();
2995       auto *FTy = dyn_cast<FunctionType>(Ty);
2996       if (!FTy)
2997         return error("Invalid type for value");
2998
2999       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3000                                         "", TheModule);
3001
3002       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
3003       bool isProto = Record[2];
3004       uint64_t RawLinkage = Record[3];
3005       Func->setLinkage(getDecodedLinkage(RawLinkage));
3006       Func->setAttributes(getAttributes(Record[4]));
3007
3008       unsigned Alignment;
3009       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3010         return EC;
3011       Func->setAlignment(Alignment);
3012       if (Record[6]) {
3013         if (Record[6]-1 >= SectionTable.size())
3014           return error("Invalid ID");
3015         Func->setSection(SectionTable[Record[6]-1]);
3016       }
3017       // Local linkage must have default visibility.
3018       if (!Func->hasLocalLinkage())
3019         // FIXME: Change to an error if non-default in 4.0.
3020         Func->setVisibility(getDecodedVisibility(Record[7]));
3021       if (Record.size() > 8 && Record[8]) {
3022         if (Record[8]-1 >= GCTable.size())
3023           return error("Invalid ID");
3024         Func->setGC(GCTable[Record[8]-1].c_str());
3025       }
3026       bool UnnamedAddr = false;
3027       if (Record.size() > 9)
3028         UnnamedAddr = Record[9];
3029       Func->setUnnamedAddr(UnnamedAddr);
3030       if (Record.size() > 10 && Record[10] != 0)
3031         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3032
3033       if (Record.size() > 11)
3034         Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3035       else
3036         upgradeDLLImportExportLinkage(Func, RawLinkage);
3037
3038       if (Record.size() > 12) {
3039         if (unsigned ComdatID = Record[12]) {
3040           if (ComdatID > ComdatList.size())
3041             return error("Invalid function comdat ID");
3042           Func->setComdat(ComdatList[ComdatID - 1]);
3043         }
3044       } else if (hasImplicitComdat(RawLinkage)) {
3045         Func->setComdat(reinterpret_cast<Comdat *>(1));
3046       }
3047
3048       if (Record.size() > 13 && Record[13] != 0)
3049         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3050
3051       if (Record.size() > 14 && Record[14] != 0)
3052         FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3053
3054       ValueList.push_back(Func);
3055
3056       // If this is a function with a body, remember the prototype we are
3057       // creating now, so that we can match up the body with them later.
3058       if (!isProto) {
3059         Func->setIsMaterializable(true);
3060         FunctionsWithBodies.push_back(Func);
3061         DeferredFunctionInfo[Func] = 0;
3062       }
3063       break;
3064     }
3065     // ALIAS: [alias type, aliasee val#, linkage]
3066     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
3067     case bitc::MODULE_CODE_ALIAS: {
3068       if (Record.size() < 3)
3069         return error("Invalid record");
3070       Type *Ty = getTypeByID(Record[0]);
3071       if (!Ty)
3072         return error("Invalid record");
3073       auto *PTy = dyn_cast<PointerType>(Ty);
3074       if (!PTy)
3075         return error("Invalid type for value");
3076
3077       auto *NewGA =
3078           GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
3079       // Old bitcode files didn't have visibility field.
3080       // Local linkage must have default visibility.
3081       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3082         // FIXME: Change to an error if non-default in 4.0.
3083         NewGA->setVisibility(getDecodedVisibility(Record[3]));
3084       if (Record.size() > 4)
3085         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
3086       else
3087         upgradeDLLImportExportLinkage(NewGA, Record[2]);
3088       if (Record.size() > 5)
3089         NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
3090       if (Record.size() > 6)
3091         NewGA->setUnnamedAddr(Record[6]);
3092       ValueList.push_back(NewGA);
3093       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3094       break;
3095     }
3096     /// MODULE_CODE_PURGEVALS: [numvals]
3097     case bitc::MODULE_CODE_PURGEVALS:
3098       // Trim down the value list to the specified size.
3099       if (Record.size() < 1 || Record[0] > ValueList.size())
3100         return error("Invalid record");
3101       ValueList.shrinkTo(Record[0]);
3102       break;
3103     }
3104     Record.clear();
3105   }
3106 }
3107
3108 std::error_code
3109 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3110                                 Module *M, bool ShouldLazyLoadMetadata) {
3111   TheModule = M;
3112
3113   if (std::error_code EC = initStream(std::move(Streamer)))
3114     return EC;
3115
3116   // Sniff for the signature.
3117   if (Stream.Read(8) != 'B' ||
3118       Stream.Read(8) != 'C' ||
3119       Stream.Read(4) != 0x0 ||
3120       Stream.Read(4) != 0xC ||
3121       Stream.Read(4) != 0xE ||
3122       Stream.Read(4) != 0xD)
3123     return error("Invalid bitcode signature");
3124
3125   // We expect a number of well-defined blocks, though we don't necessarily
3126   // need to understand them all.
3127   while (1) {
3128     if (Stream.AtEndOfStream()) {
3129       // We didn't really read a proper Module.
3130       return error("Malformed IR file");
3131     }
3132
3133     BitstreamEntry Entry =
3134       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3135
3136     if (Entry.Kind != BitstreamEntry::SubBlock)
3137       return error("Malformed block");
3138
3139     if (Entry.ID == bitc::MODULE_BLOCK_ID)
3140       return parseModule(false, ShouldLazyLoadMetadata);
3141
3142     if (Stream.SkipBlock())
3143       return error("Invalid record");
3144   }
3145 }
3146
3147 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3148   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3149     return error("Invalid record");
3150
3151   SmallVector<uint64_t, 64> Record;
3152
3153   std::string Triple;
3154   // Read all the records for this module.
3155   while (1) {
3156     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3157
3158     switch (Entry.Kind) {
3159     case BitstreamEntry::SubBlock: // Handled for us already.
3160     case BitstreamEntry::Error:
3161       return error("Malformed block");
3162     case BitstreamEntry::EndBlock:
3163       return Triple;
3164     case BitstreamEntry::Record:
3165       // The interesting case.
3166       break;
3167     }
3168
3169     // Read a record.
3170     switch (Stream.readRecord(Entry.ID, Record)) {
3171     default: break;  // Default behavior, ignore unknown content.
3172     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3173       std::string S;
3174       if (convertToString(Record, 0, S))
3175         return error("Invalid record");
3176       Triple = S;
3177       break;
3178     }
3179     }
3180     Record.clear();
3181   }
3182   llvm_unreachable("Exit infinite loop");
3183 }
3184
3185 ErrorOr<std::string> BitcodeReader::parseTriple() {
3186   if (std::error_code EC = initStream(nullptr))
3187     return EC;
3188
3189   // Sniff for the signature.
3190   if (Stream.Read(8) != 'B' ||
3191       Stream.Read(8) != 'C' ||
3192       Stream.Read(4) != 0x0 ||
3193       Stream.Read(4) != 0xC ||
3194       Stream.Read(4) != 0xE ||
3195       Stream.Read(4) != 0xD)
3196     return error("Invalid bitcode signature");
3197
3198   // We expect a number of well-defined blocks, though we don't necessarily
3199   // need to understand them all.
3200   while (1) {
3201     BitstreamEntry Entry = Stream.advance();
3202
3203     switch (Entry.Kind) {
3204     case BitstreamEntry::Error:
3205       return error("Malformed block");
3206     case BitstreamEntry::EndBlock:
3207       return std::error_code();
3208
3209     case BitstreamEntry::SubBlock:
3210       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3211         return parseModuleTriple();
3212
3213       // Ignore other sub-blocks.
3214       if (Stream.SkipBlock())
3215         return error("Malformed block");
3216       continue;
3217
3218     case BitstreamEntry::Record:
3219       Stream.skipRecord(Entry.ID);
3220       continue;
3221     }
3222   }
3223 }
3224
3225 /// Parse metadata attachments.
3226 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3227   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3228     return error("Invalid record");
3229
3230   SmallVector<uint64_t, 64> Record;
3231   while (1) {
3232     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3233
3234     switch (Entry.Kind) {
3235     case BitstreamEntry::SubBlock: // Handled for us already.
3236     case BitstreamEntry::Error:
3237       return error("Malformed block");
3238     case BitstreamEntry::EndBlock:
3239       return std::error_code();
3240     case BitstreamEntry::Record:
3241       // The interesting case.
3242       break;
3243     }
3244
3245     // Read a metadata attachment record.
3246     Record.clear();
3247     switch (Stream.readRecord(Entry.ID, Record)) {
3248     default:  // Default behavior: ignore.
3249       break;
3250     case bitc::METADATA_ATTACHMENT: {
3251       unsigned RecordLength = Record.size();
3252       if (Record.empty())
3253         return error("Invalid record");
3254       if (RecordLength % 2 == 0) {
3255         // A function attachment.
3256         for (unsigned I = 0; I != RecordLength; I += 2) {
3257           auto K = MDKindMap.find(Record[I]);
3258           if (K == MDKindMap.end())
3259             return error("Invalid ID");
3260           Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3261           F.setMetadata(K->second, cast<MDNode>(MD));
3262         }
3263         continue;
3264       }
3265
3266       // An instruction attachment.
3267       Instruction *Inst = InstructionList[Record[0]];
3268       for (unsigned i = 1; i != RecordLength; i = i+2) {
3269         unsigned Kind = Record[i];
3270         DenseMap<unsigned, unsigned>::iterator I =
3271           MDKindMap.find(Kind);
3272         if (I == MDKindMap.end())
3273           return error("Invalid ID");
3274         Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3275         if (isa<LocalAsMetadata>(Node))
3276           // Drop the attachment.  This used to be legal, but there's no
3277           // upgrade path.
3278           break;
3279         Inst->setMetadata(I->second, cast<MDNode>(Node));
3280         if (I->second == LLVMContext::MD_tbaa)
3281           InstsWithTBAATag.push_back(Inst);
3282       }
3283       break;
3284     }
3285     }
3286   }
3287 }
3288
3289 static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
3290                                               Type *ValType, Type *PtrType) {
3291   if (!isa<PointerType>(PtrType))
3292     return error(DH, "Load/Store operand is not a pointer type");
3293   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3294
3295   if (ValType && ValType != ElemType)
3296     return error(DH, "Explicit load/store type does not match pointee type of "
3297                      "pointer operand");
3298   if (!PointerType::isLoadableOrStorableType(ElemType))
3299     return error(DH, "Cannot load/store from pointer");
3300   return std::error_code();
3301 }
3302
3303 /// Lazily parse the specified function body block.
3304 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3305   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3306     return error("Invalid record");
3307
3308   InstructionList.clear();
3309   unsigned ModuleValueListSize = ValueList.size();
3310   unsigned ModuleMDValueListSize = MDValueList.size();
3311
3312   // Add all the function arguments to the value table.
3313   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3314     ValueList.push_back(I);
3315
3316   unsigned NextValueNo = ValueList.size();
3317   BasicBlock *CurBB = nullptr;
3318   unsigned CurBBNo = 0;
3319
3320   DebugLoc LastLoc;
3321   auto getLastInstruction = [&]() -> Instruction * {
3322     if (CurBB && !CurBB->empty())
3323       return &CurBB->back();
3324     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3325              !FunctionBBs[CurBBNo - 1]->empty())
3326       return &FunctionBBs[CurBBNo - 1]->back();
3327     return nullptr;
3328   };
3329
3330   // Read all the records.
3331   SmallVector<uint64_t, 64> Record;
3332   while (1) {
3333     BitstreamEntry Entry = Stream.advance();
3334
3335     switch (Entry.Kind) {
3336     case BitstreamEntry::Error:
3337       return error("Malformed block");
3338     case BitstreamEntry::EndBlock:
3339       goto OutOfRecordLoop;
3340
3341     case BitstreamEntry::SubBlock:
3342       switch (Entry.ID) {
3343       default:  // Skip unknown content.
3344         if (Stream.SkipBlock())
3345           return error("Invalid record");
3346         break;
3347       case bitc::CONSTANTS_BLOCK_ID:
3348         if (std::error_code EC = parseConstants())
3349           return EC;
3350         NextValueNo = ValueList.size();
3351         break;
3352       case bitc::VALUE_SYMTAB_BLOCK_ID:
3353         if (std::error_code EC = parseValueSymbolTable())
3354           return EC;
3355         break;
3356       case bitc::METADATA_ATTACHMENT_ID:
3357         if (std::error_code EC = parseMetadataAttachment(*F))
3358           return EC;
3359         break;
3360       case bitc::METADATA_BLOCK_ID:
3361         if (std::error_code EC = parseMetadata())
3362           return EC;
3363         break;
3364       case bitc::USELIST_BLOCK_ID:
3365         if (std::error_code EC = parseUseLists())
3366           return EC;
3367         break;
3368       }
3369       continue;
3370
3371     case BitstreamEntry::Record:
3372       // The interesting case.
3373       break;
3374     }
3375
3376     // Read a record.
3377     Record.clear();
3378     Instruction *I = nullptr;
3379     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3380     switch (BitCode) {
3381     default: // Default behavior: reject
3382       return error("Invalid value");
3383     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3384       if (Record.size() < 1 || Record[0] == 0)
3385         return error("Invalid record");
3386       // Create all the basic blocks for the function.
3387       FunctionBBs.resize(Record[0]);
3388
3389       // See if anything took the address of blocks in this function.
3390       auto BBFRI = BasicBlockFwdRefs.find(F);
3391       if (BBFRI == BasicBlockFwdRefs.end()) {
3392         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3393           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3394       } else {
3395         auto &BBRefs = BBFRI->second;
3396         // Check for invalid basic block references.
3397         if (BBRefs.size() > FunctionBBs.size())
3398           return error("Invalid ID");
3399         assert(!BBRefs.empty() && "Unexpected empty array");
3400         assert(!BBRefs.front() && "Invalid reference to entry block");
3401         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3402              ++I)
3403           if (I < RE && BBRefs[I]) {
3404             BBRefs[I]->insertInto(F);
3405             FunctionBBs[I] = BBRefs[I];
3406           } else {
3407             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3408           }
3409
3410         // Erase from the table.
3411         BasicBlockFwdRefs.erase(BBFRI);
3412       }
3413
3414       CurBB = FunctionBBs[0];
3415       continue;
3416     }
3417
3418     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
3419       // This record indicates that the last instruction is at the same
3420       // location as the previous instruction with a location.
3421       I = getLastInstruction();
3422
3423       if (!I)
3424         return error("Invalid record");
3425       I->setDebugLoc(LastLoc);
3426       I = nullptr;
3427       continue;
3428
3429     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
3430       I = getLastInstruction();
3431       if (!I || Record.size() < 4)
3432         return error("Invalid record");
3433
3434       unsigned Line = Record[0], Col = Record[1];
3435       unsigned ScopeID = Record[2], IAID = Record[3];
3436
3437       MDNode *Scope = nullptr, *IA = nullptr;
3438       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3439       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3440       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3441       I->setDebugLoc(LastLoc);
3442       I = nullptr;
3443       continue;
3444     }
3445
3446     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
3447       unsigned OpNum = 0;
3448       Value *LHS, *RHS;
3449       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3450           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3451           OpNum+1 > Record.size())
3452         return error("Invalid record");
3453
3454       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3455       if (Opc == -1)
3456         return error("Invalid record");
3457       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3458       InstructionList.push_back(I);
3459       if (OpNum < Record.size()) {
3460         if (Opc == Instruction::Add ||
3461             Opc == Instruction::Sub ||
3462             Opc == Instruction::Mul ||
3463             Opc == Instruction::Shl) {
3464           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3465             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3466           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3467             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3468         } else if (Opc == Instruction::SDiv ||
3469                    Opc == Instruction::UDiv ||
3470                    Opc == Instruction::LShr ||
3471                    Opc == Instruction::AShr) {
3472           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3473             cast<BinaryOperator>(I)->setIsExact(true);
3474         } else if (isa<FPMathOperator>(I)) {
3475           FastMathFlags FMF;
3476           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3477             FMF.setUnsafeAlgebra();
3478           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3479             FMF.setNoNaNs();
3480           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3481             FMF.setNoInfs();
3482           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3483             FMF.setNoSignedZeros();
3484           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3485             FMF.setAllowReciprocal();
3486           if (FMF.any())
3487             I->setFastMathFlags(FMF);
3488         }
3489
3490       }
3491       break;
3492     }
3493     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
3494       unsigned OpNum = 0;
3495       Value *Op;
3496       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3497           OpNum+2 != Record.size())
3498         return error("Invalid record");
3499
3500       Type *ResTy = getTypeByID(Record[OpNum]);
3501       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3502       if (Opc == -1 || !ResTy)
3503         return error("Invalid record");
3504       Instruction *Temp = nullptr;
3505       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3506         if (Temp) {
3507           InstructionList.push_back(Temp);
3508           CurBB->getInstList().push_back(Temp);
3509         }
3510       } else {
3511         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3512       }
3513       InstructionList.push_back(I);
3514       break;
3515     }
3516     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3517     case bitc::FUNC_CODE_INST_GEP_OLD:
3518     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3519       unsigned OpNum = 0;
3520
3521       Type *Ty;
3522       bool InBounds;
3523
3524       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3525         InBounds = Record[OpNum++];
3526         Ty = getTypeByID(Record[OpNum++]);
3527       } else {
3528         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3529         Ty = nullptr;
3530       }
3531
3532       Value *BasePtr;
3533       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3534         return error("Invalid record");
3535
3536       if (!Ty)
3537         Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3538                  ->getElementType();
3539       else if (Ty !=
3540                cast<SequentialType>(BasePtr->getType()->getScalarType())
3541                    ->getElementType())
3542         return error(
3543             "Explicit gep type does not match pointee type of pointer operand");
3544
3545       SmallVector<Value*, 16> GEPIdx;
3546       while (OpNum != Record.size()) {
3547         Value *Op;
3548         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3549           return error("Invalid record");
3550         GEPIdx.push_back(Op);
3551       }
3552
3553       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3554
3555       InstructionList.push_back(I);
3556       if (InBounds)
3557         cast<GetElementPtrInst>(I)->setIsInBounds(true);
3558       break;
3559     }
3560
3561     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3562                                        // EXTRACTVAL: [opty, opval, n x indices]
3563       unsigned OpNum = 0;
3564       Value *Agg;
3565       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3566         return error("Invalid record");
3567
3568       unsigned RecSize = Record.size();
3569       if (OpNum == RecSize)
3570         return error("EXTRACTVAL: Invalid instruction with 0 indices");
3571
3572       SmallVector<unsigned, 4> EXTRACTVALIdx;
3573       Type *CurTy = Agg->getType();
3574       for (; OpNum != RecSize; ++OpNum) {
3575         bool IsArray = CurTy->isArrayTy();
3576         bool IsStruct = CurTy->isStructTy();
3577         uint64_t Index = Record[OpNum];
3578
3579         if (!IsStruct && !IsArray)
3580           return error("EXTRACTVAL: Invalid type");
3581         if ((unsigned)Index != Index)
3582           return error("Invalid value");
3583         if (IsStruct && Index >= CurTy->subtypes().size())
3584           return error("EXTRACTVAL: Invalid struct index");
3585         if (IsArray && Index >= CurTy->getArrayNumElements())
3586           return error("EXTRACTVAL: Invalid array index");
3587         EXTRACTVALIdx.push_back((unsigned)Index);
3588
3589         if (IsStruct)
3590           CurTy = CurTy->subtypes()[Index];
3591         else
3592           CurTy = CurTy->subtypes()[0];
3593       }
3594
3595       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3596       InstructionList.push_back(I);
3597       break;
3598     }
3599
3600     case bitc::FUNC_CODE_INST_INSERTVAL: {
3601                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
3602       unsigned OpNum = 0;
3603       Value *Agg;
3604       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3605         return error("Invalid record");
3606       Value *Val;
3607       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3608         return error("Invalid record");
3609
3610       unsigned RecSize = Record.size();
3611       if (OpNum == RecSize)
3612         return error("INSERTVAL: Invalid instruction with 0 indices");
3613
3614       SmallVector<unsigned, 4> INSERTVALIdx;
3615       Type *CurTy = Agg->getType();
3616       for (; OpNum != RecSize; ++OpNum) {
3617         bool IsArray = CurTy->isArrayTy();
3618         bool IsStruct = CurTy->isStructTy();
3619         uint64_t Index = Record[OpNum];
3620
3621         if (!IsStruct && !IsArray)
3622           return error("INSERTVAL: Invalid type");
3623         if ((unsigned)Index != Index)
3624           return error("Invalid value");
3625         if (IsStruct && Index >= CurTy->subtypes().size())
3626           return error("INSERTVAL: Invalid struct index");
3627         if (IsArray && Index >= CurTy->getArrayNumElements())
3628           return error("INSERTVAL: Invalid array index");
3629
3630         INSERTVALIdx.push_back((unsigned)Index);
3631         if (IsStruct)
3632           CurTy = CurTy->subtypes()[Index];
3633         else
3634           CurTy = CurTy->subtypes()[0];
3635       }
3636
3637       if (CurTy != Val->getType())
3638         return error("Inserted value type doesn't match aggregate type");
3639
3640       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3641       InstructionList.push_back(I);
3642       break;
3643     }
3644
3645     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3646       // obsolete form of select
3647       // handles select i1 ... in old bitcode
3648       unsigned OpNum = 0;
3649       Value *TrueVal, *FalseVal, *Cond;
3650       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3651           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3652           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3653         return error("Invalid record");
3654
3655       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3656       InstructionList.push_back(I);
3657       break;
3658     }
3659
3660     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3661       // new form of select
3662       // handles select i1 or select [N x i1]
3663       unsigned OpNum = 0;
3664       Value *TrueVal, *FalseVal, *Cond;
3665       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3666           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3667           getValueTypePair(Record, OpNum, NextValueNo, Cond))
3668         return error("Invalid record");
3669
3670       // select condition can be either i1 or [N x i1]
3671       if (VectorType* vector_type =
3672           dyn_cast<VectorType>(Cond->getType())) {
3673         // expect <n x i1>
3674         if (vector_type->getElementType() != Type::getInt1Ty(Context))
3675           return error("Invalid type for value");
3676       } else {
3677         // expect i1
3678         if (Cond->getType() != Type::getInt1Ty(Context))
3679           return error("Invalid type for value");
3680       }
3681
3682       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3683       InstructionList.push_back(I);
3684       break;
3685     }
3686
3687     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3688       unsigned OpNum = 0;
3689       Value *Vec, *Idx;
3690       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3691           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3692         return error("Invalid record");
3693       if (!Vec->getType()->isVectorTy())
3694         return error("Invalid type for value");
3695       I = ExtractElementInst::Create(Vec, Idx);
3696       InstructionList.push_back(I);
3697       break;
3698     }
3699
3700     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3701       unsigned OpNum = 0;
3702       Value *Vec, *Elt, *Idx;
3703       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3704         return error("Invalid record");
3705       if (!Vec->getType()->isVectorTy())
3706         return error("Invalid type for value");
3707       if (popValue(Record, OpNum, NextValueNo,
3708                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3709           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3710         return error("Invalid record");
3711       I = InsertElementInst::Create(Vec, Elt, Idx);
3712       InstructionList.push_back(I);
3713       break;
3714     }
3715
3716     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3717       unsigned OpNum = 0;
3718       Value *Vec1, *Vec2, *Mask;
3719       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3720           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3721         return error("Invalid record");
3722
3723       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3724         return error("Invalid record");
3725       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3726         return error("Invalid type for value");
3727       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3728       InstructionList.push_back(I);
3729       break;
3730     }
3731
3732     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
3733       // Old form of ICmp/FCmp returning bool
3734       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3735       // both legal on vectors but had different behaviour.
3736     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3737       // FCmp/ICmp returning bool or vector of bool
3738
3739       unsigned OpNum = 0;
3740       Value *LHS, *RHS;
3741       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3742           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3743           OpNum+1 != Record.size())
3744         return error("Invalid record");
3745
3746       if (LHS->getType()->isFPOrFPVectorTy())
3747         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
3748       else
3749         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
3750       InstructionList.push_back(I);
3751       break;
3752     }
3753
3754     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3755       {
3756         unsigned Size = Record.size();
3757         if (Size == 0) {
3758           I = ReturnInst::Create(Context);
3759           InstructionList.push_back(I);
3760           break;
3761         }
3762
3763         unsigned OpNum = 0;
3764         Value *Op = nullptr;
3765         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3766           return error("Invalid record");
3767         if (OpNum != Record.size())
3768           return error("Invalid record");
3769
3770         I = ReturnInst::Create(Context, Op);
3771         InstructionList.push_back(I);
3772         break;
3773       }
3774     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3775       if (Record.size() != 1 && Record.size() != 3)
3776         return error("Invalid record");
3777       BasicBlock *TrueDest = getBasicBlock(Record[0]);
3778       if (!TrueDest)
3779         return error("Invalid record");
3780
3781       if (Record.size() == 1) {
3782         I = BranchInst::Create(TrueDest);
3783         InstructionList.push_back(I);
3784       }
3785       else {
3786         BasicBlock *FalseDest = getBasicBlock(Record[1]);
3787         Value *Cond = getValue(Record, 2, NextValueNo,
3788                                Type::getInt1Ty(Context));
3789         if (!FalseDest || !Cond)
3790           return error("Invalid record");
3791         I = BranchInst::Create(TrueDest, FalseDest, Cond);
3792         InstructionList.push_back(I);
3793       }
3794       break;
3795     }
3796     // CLEANUPRET: [] or [ty,val] or [bb#] or [ty,val,bb#]
3797     case bitc::FUNC_CODE_INST_CLEANUPRET: {
3798       if (Record.size() < 2)
3799         return error("Invalid record");
3800       unsigned Idx = 0;
3801       bool HasReturnValue = !!Record[Idx++];
3802       bool HasUnwindDest = !!Record[Idx++];
3803       Value *RetVal = nullptr;
3804       BasicBlock *UnwindDest = nullptr;
3805
3806       if (HasReturnValue && getValueTypePair(Record, Idx, NextValueNo, RetVal))
3807         return error("Invalid record");
3808       if (HasUnwindDest) {
3809         if (Idx == Record.size())
3810           return error("Invalid record");
3811         UnwindDest = getBasicBlock(Record[Idx++]);
3812         if (!UnwindDest)
3813           return error("Invalid record");
3814       }
3815
3816       if (Record.size() != Idx)
3817         return error("Invalid record");
3818
3819       I = CleanupReturnInst::Create(Context, RetVal, UnwindDest);
3820       InstructionList.push_back(I);
3821       break;
3822     }
3823     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [bb#]
3824       if (Record.size() != 1)
3825         return error("Invalid record");
3826       BasicBlock *BB = getBasicBlock(Record[0]);
3827       if (!BB)
3828         return error("Invalid record");
3829       I = CatchReturnInst::Create(BB);
3830       InstructionList.push_back(I);
3831       break;
3832     }
3833     case bitc::FUNC_CODE_INST_CATCHBLOCK: { // CATCHBLOCK: [ty,bb#,bb#,num,(ty,val)*]
3834       if (Record.size() < 4)
3835         return error("Invalid record");
3836       unsigned Idx = 0;
3837       Type *Ty = getTypeByID(Record[Idx++]);
3838       if (!Ty)
3839         return error("Invalid record");
3840       BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
3841       if (!NormalBB)
3842         return error("Invalid record");
3843       BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
3844       if (!UnwindBB)
3845         return error("Invalid record");
3846       unsigned NumArgOperands = Record[Idx++];
3847       SmallVector<Value *, 2> Args;
3848       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3849         Value *Val;
3850         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3851           return error("Invalid record");
3852         Args.push_back(Val);
3853       }
3854       if (Record.size() != Idx)
3855         return error("Invalid record");
3856
3857       I = CatchBlockInst::Create(Ty, NormalBB, UnwindBB, Args);
3858       InstructionList.push_back(I);
3859       break;
3860     }
3861     case bitc::FUNC_CODE_INST_TERMINATEBLOCK: { // TERMINATEBLOCK: [bb#,num,(ty,val)*]
3862       if (Record.size() < 1)
3863         return error("Invalid record");
3864       unsigned Idx = 0;
3865       bool HasUnwindDest = !!Record[Idx++];
3866       BasicBlock *UnwindDest = nullptr;
3867       if (HasUnwindDest) {
3868         if (Idx == Record.size())
3869           return error("Invalid record");
3870         UnwindDest = getBasicBlock(Record[Idx++]);
3871         if (!UnwindDest)
3872           return error("Invalid record");
3873       }
3874       unsigned NumArgOperands = Record[Idx++];
3875       SmallVector<Value *, 2> Args;
3876       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3877         Value *Val;
3878         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3879           return error("Invalid record");
3880         Args.push_back(Val);
3881       }
3882       if (Record.size() != Idx)
3883         return error("Invalid record");
3884
3885       I = TerminateBlockInst::Create(Context, UnwindDest, Args);
3886       InstructionList.push_back(I);
3887       break;
3888     }
3889     case bitc::FUNC_CODE_INST_CLEANUPBLOCK: { // CLEANUPBLOCK: [ty, num,(ty,val)*]
3890       if (Record.size() < 2)
3891         return error("Invalid record");
3892       unsigned Idx = 0;
3893       Type *Ty = getTypeByID(Record[Idx++]);
3894       if (!Ty)
3895         return error("Invalid record");
3896       unsigned NumArgOperands = Record[Idx++];
3897       SmallVector<Value *, 2> Args;
3898       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3899         Value *Val;
3900         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3901           return error("Invalid record");
3902         Args.push_back(Val);
3903       }
3904       if (Record.size() != Idx)
3905         return error("Invalid record");
3906
3907       I = CleanupBlockInst::Create(Ty, Args);
3908       InstructionList.push_back(I);
3909       break;
3910     }
3911     case bitc::FUNC_CODE_INST_CATCHENDBLOCK: { // CATCHENDBLOCKINST: [bb#] or []
3912       if (Record.size() > 1)
3913         return error("Invalid record");
3914       BasicBlock *BB = nullptr;
3915       if (Record.size() == 1) {
3916         BB = getBasicBlock(Record[0]);
3917         if (!BB)
3918           return error("Invalid record");
3919       }
3920       I = CatchEndBlockInst::Create(Context, BB);
3921       InstructionList.push_back(I);
3922       break;
3923     }
3924     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3925       // Check magic
3926       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3927         // "New" SwitchInst format with case ranges. The changes to write this
3928         // format were reverted but we still recognize bitcode that uses it.
3929         // Hopefully someday we will have support for case ranges and can use
3930         // this format again.
3931
3932         Type *OpTy = getTypeByID(Record[1]);
3933         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3934
3935         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3936         BasicBlock *Default = getBasicBlock(Record[3]);
3937         if (!OpTy || !Cond || !Default)
3938           return error("Invalid record");
3939
3940         unsigned NumCases = Record[4];
3941
3942         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3943         InstructionList.push_back(SI);
3944
3945         unsigned CurIdx = 5;
3946         for (unsigned i = 0; i != NumCases; ++i) {
3947           SmallVector<ConstantInt*, 1> CaseVals;
3948           unsigned NumItems = Record[CurIdx++];
3949           for (unsigned ci = 0; ci != NumItems; ++ci) {
3950             bool isSingleNumber = Record[CurIdx++];
3951
3952             APInt Low;
3953             unsigned ActiveWords = 1;
3954             if (ValueBitWidth > 64)
3955               ActiveWords = Record[CurIdx++];
3956             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3957                                 ValueBitWidth);
3958             CurIdx += ActiveWords;
3959
3960             if (!isSingleNumber) {
3961               ActiveWords = 1;
3962               if (ValueBitWidth > 64)
3963                 ActiveWords = Record[CurIdx++];
3964               APInt High = readWideAPInt(
3965                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3966               CurIdx += ActiveWords;
3967
3968               // FIXME: It is not clear whether values in the range should be
3969               // compared as signed or unsigned values. The partially
3970               // implemented changes that used this format in the past used
3971               // unsigned comparisons.
3972               for ( ; Low.ule(High); ++Low)
3973                 CaseVals.push_back(ConstantInt::get(Context, Low));
3974             } else
3975               CaseVals.push_back(ConstantInt::get(Context, Low));
3976           }
3977           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3978           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3979                  cve = CaseVals.end(); cvi != cve; ++cvi)
3980             SI->addCase(*cvi, DestBB);
3981         }
3982         I = SI;
3983         break;
3984       }
3985
3986       // Old SwitchInst format without case ranges.
3987
3988       if (Record.size() < 3 || (Record.size() & 1) == 0)
3989         return error("Invalid record");
3990       Type *OpTy = getTypeByID(Record[0]);
3991       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3992       BasicBlock *Default = getBasicBlock(Record[2]);
3993       if (!OpTy || !Cond || !Default)
3994         return error("Invalid record");
3995       unsigned NumCases = (Record.size()-3)/2;
3996       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3997       InstructionList.push_back(SI);
3998       for (unsigned i = 0, e = NumCases; i != e; ++i) {
3999         ConstantInt *CaseVal =
4000           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4001         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4002         if (!CaseVal || !DestBB) {
4003           delete SI;
4004           return error("Invalid record");
4005         }
4006         SI->addCase(CaseVal, DestBB);
4007       }
4008       I = SI;
4009       break;
4010     }
4011     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4012       if (Record.size() < 2)
4013         return error("Invalid record");
4014       Type *OpTy = getTypeByID(Record[0]);
4015       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4016       if (!OpTy || !Address)
4017         return error("Invalid record");
4018       unsigned NumDests = Record.size()-2;
4019       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4020       InstructionList.push_back(IBI);
4021       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4022         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4023           IBI->addDestination(DestBB);
4024         } else {
4025           delete IBI;
4026           return error("Invalid record");
4027         }
4028       }
4029       I = IBI;
4030       break;
4031     }
4032
4033     case bitc::FUNC_CODE_INST_INVOKE: {
4034       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4035       if (Record.size() < 4)
4036         return error("Invalid record");
4037       unsigned OpNum = 0;
4038       AttributeSet PAL = getAttributes(Record[OpNum++]);
4039       unsigned CCInfo = Record[OpNum++];
4040       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4041       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4042
4043       FunctionType *FTy = nullptr;
4044       if (CCInfo >> 13 & 1 &&
4045           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4046         return error("Explicit invoke type is not a function type");
4047
4048       Value *Callee;
4049       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4050         return error("Invalid record");
4051
4052       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4053       if (!CalleeTy)
4054         return error("Callee is not a pointer");
4055       if (!FTy) {
4056         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4057         if (!FTy)
4058           return error("Callee is not of pointer to function type");
4059       } else if (CalleeTy->getElementType() != FTy)
4060         return error("Explicit invoke type does not match pointee type of "
4061                      "callee operand");
4062       if (Record.size() < FTy->getNumParams() + OpNum)
4063         return error("Insufficient operands to call");
4064
4065       SmallVector<Value*, 16> Ops;
4066       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4067         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4068                                FTy->getParamType(i)));
4069         if (!Ops.back())
4070           return error("Invalid record");
4071       }
4072
4073       if (!FTy->isVarArg()) {
4074         if (Record.size() != OpNum)
4075           return error("Invalid record");
4076       } else {
4077         // Read type/value pairs for varargs params.
4078         while (OpNum != Record.size()) {
4079           Value *Op;
4080           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4081             return error("Invalid record");
4082           Ops.push_back(Op);
4083         }
4084       }
4085
4086       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
4087       InstructionList.push_back(I);
4088       cast<InvokeInst>(I)
4089           ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
4090       cast<InvokeInst>(I)->setAttributes(PAL);
4091       break;
4092     }
4093     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4094       unsigned Idx = 0;
4095       Value *Val = nullptr;
4096       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4097         return error("Invalid record");
4098       I = ResumeInst::Create(Val);
4099       InstructionList.push_back(I);
4100       break;
4101     }
4102     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4103       I = new UnreachableInst(Context);
4104       InstructionList.push_back(I);
4105       break;
4106     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4107       if (Record.size() < 1 || ((Record.size()-1)&1))
4108         return error("Invalid record");
4109       Type *Ty = getTypeByID(Record[0]);
4110       if (!Ty)
4111         return error("Invalid record");
4112
4113       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4114       InstructionList.push_back(PN);
4115
4116       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4117         Value *V;
4118         // With the new function encoding, it is possible that operands have
4119         // negative IDs (for forward references).  Use a signed VBR
4120         // representation to keep the encoding small.
4121         if (UseRelativeIDs)
4122           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4123         else
4124           V = getValue(Record, 1+i, NextValueNo, Ty);
4125         BasicBlock *BB = getBasicBlock(Record[2+i]);
4126         if (!V || !BB)
4127           return error("Invalid record");
4128         PN->addIncoming(V, BB);
4129       }
4130       I = PN;
4131       break;
4132     }
4133
4134     case bitc::FUNC_CODE_INST_LANDINGPAD:
4135     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4136       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4137       unsigned Idx = 0;
4138       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4139         if (Record.size() < 3)
4140           return error("Invalid record");
4141       } else {
4142         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4143         if (Record.size() < 4)
4144           return error("Invalid record");
4145       }
4146       Type *Ty = getTypeByID(Record[Idx++]);
4147       if (!Ty)
4148         return error("Invalid record");
4149       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4150         Value *PersFn = nullptr;
4151         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4152           return error("Invalid record");
4153
4154         if (!F->hasPersonalityFn())
4155           F->setPersonalityFn(cast<Constant>(PersFn));
4156         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4157           return error("Personality function mismatch");
4158       }
4159
4160       bool IsCleanup = !!Record[Idx++];
4161       unsigned NumClauses = Record[Idx++];
4162       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4163       LP->setCleanup(IsCleanup);
4164       for (unsigned J = 0; J != NumClauses; ++J) {
4165         LandingPadInst::ClauseType CT =
4166           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4167         Value *Val;
4168
4169         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4170           delete LP;
4171           return error("Invalid record");
4172         }
4173
4174         assert((CT != LandingPadInst::Catch ||
4175                 !isa<ArrayType>(Val->getType())) &&
4176                "Catch clause has a invalid type!");
4177         assert((CT != LandingPadInst::Filter ||
4178                 isa<ArrayType>(Val->getType())) &&
4179                "Filter clause has invalid type!");
4180         LP->addClause(cast<Constant>(Val));
4181       }
4182
4183       I = LP;
4184       InstructionList.push_back(I);
4185       break;
4186     }
4187
4188     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4189       if (Record.size() != 4)
4190         return error("Invalid record");
4191       uint64_t AlignRecord = Record[3];
4192       const uint64_t InAllocaMask = uint64_t(1) << 5;
4193       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4194       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4195       bool InAlloca = AlignRecord & InAllocaMask;
4196       Type *Ty = getTypeByID(Record[0]);
4197       if ((AlignRecord & ExplicitTypeMask) == 0) {
4198         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4199         if (!PTy)
4200           return error("Old-style alloca with a non-pointer type");
4201         Ty = PTy->getElementType();
4202       }
4203       Type *OpTy = getTypeByID(Record[1]);
4204       Value *Size = getFnValueByID(Record[2], OpTy);
4205       unsigned Align;
4206       if (std::error_code EC =
4207               parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4208         return EC;
4209       }
4210       if (!Ty || !Size)
4211         return error("Invalid record");
4212       AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4213       AI->setUsedWithInAlloca(InAlloca);
4214       I = AI;
4215       InstructionList.push_back(I);
4216       break;
4217     }
4218     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4219       unsigned OpNum = 0;
4220       Value *Op;
4221       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4222           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4223         return error("Invalid record");
4224
4225       Type *Ty = nullptr;
4226       if (OpNum + 3 == Record.size())
4227         Ty = getTypeByID(Record[OpNum++]);
4228       if (std::error_code EC =
4229               typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4230         return EC;
4231       if (!Ty)
4232         Ty = cast<PointerType>(Op->getType())->getElementType();
4233
4234       unsigned Align;
4235       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4236         return EC;
4237       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4238
4239       InstructionList.push_back(I);
4240       break;
4241     }
4242     case bitc::FUNC_CODE_INST_LOADATOMIC: {
4243        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4244       unsigned OpNum = 0;
4245       Value *Op;
4246       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4247           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4248         return error("Invalid record");
4249
4250       Type *Ty = nullptr;
4251       if (OpNum + 5 == Record.size())
4252         Ty = getTypeByID(Record[OpNum++]);
4253       if (std::error_code EC =
4254               typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
4255         return EC;
4256       if (!Ty)
4257         Ty = cast<PointerType>(Op->getType())->getElementType();
4258
4259       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4260       if (Ordering == NotAtomic || Ordering == Release ||
4261           Ordering == AcquireRelease)
4262         return error("Invalid record");
4263       if (Ordering != NotAtomic && Record[OpNum] == 0)
4264         return error("Invalid record");
4265       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4266
4267       unsigned Align;
4268       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4269         return EC;
4270       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4271
4272       InstructionList.push_back(I);
4273       break;
4274     }
4275     case bitc::FUNC_CODE_INST_STORE:
4276     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4277       unsigned OpNum = 0;
4278       Value *Val, *Ptr;
4279       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4280           (BitCode == bitc::FUNC_CODE_INST_STORE
4281                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4282                : popValue(Record, OpNum, NextValueNo,
4283                           cast<PointerType>(Ptr->getType())->getElementType(),
4284                           Val)) ||
4285           OpNum + 2 != Record.size())
4286         return error("Invalid record");
4287
4288       if (std::error_code EC = typeCheckLoadStoreInst(
4289               DiagnosticHandler, Val->getType(), Ptr->getType()))
4290         return EC;
4291       unsigned Align;
4292       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4293         return EC;
4294       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4295       InstructionList.push_back(I);
4296       break;
4297     }
4298     case bitc::FUNC_CODE_INST_STOREATOMIC:
4299     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4300       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4301       unsigned OpNum = 0;
4302       Value *Val, *Ptr;
4303       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4304           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4305                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4306                : popValue(Record, OpNum, NextValueNo,
4307                           cast<PointerType>(Ptr->getType())->getElementType(),
4308                           Val)) ||
4309           OpNum + 4 != Record.size())
4310         return error("Invalid record");
4311
4312       if (std::error_code EC = typeCheckLoadStoreInst(
4313               DiagnosticHandler, Val->getType(), Ptr->getType()))
4314         return EC;
4315       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4316       if (Ordering == NotAtomic || Ordering == Acquire ||
4317           Ordering == AcquireRelease)
4318         return error("Invalid record");
4319       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4320       if (Ordering != NotAtomic && Record[OpNum] == 0)
4321         return error("Invalid record");
4322
4323       unsigned Align;
4324       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4325         return EC;
4326       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4327       InstructionList.push_back(I);
4328       break;
4329     }
4330     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4331     case bitc::FUNC_CODE_INST_CMPXCHG: {
4332       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4333       //          failureordering?, isweak?]
4334       unsigned OpNum = 0;
4335       Value *Ptr, *Cmp, *New;
4336       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4337           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4338                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4339                : popValue(Record, OpNum, NextValueNo,
4340                           cast<PointerType>(Ptr->getType())->getElementType(),
4341                           Cmp)) ||
4342           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4343           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4344         return error("Invalid record");
4345       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4346       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4347         return error("Invalid record");
4348       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4349
4350       if (std::error_code EC = typeCheckLoadStoreInst(
4351               DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4352         return EC;
4353       AtomicOrdering FailureOrdering;
4354       if (Record.size() < 7)
4355         FailureOrdering =
4356             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4357       else
4358         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4359
4360       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4361                                 SynchScope);
4362       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4363
4364       if (Record.size() < 8) {
4365         // Before weak cmpxchgs existed, the instruction simply returned the
4366         // value loaded from memory, so bitcode files from that era will be
4367         // expecting the first component of a modern cmpxchg.
4368         CurBB->getInstList().push_back(I);
4369         I = ExtractValueInst::Create(I, 0);
4370       } else {
4371         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4372       }
4373
4374       InstructionList.push_back(I);
4375       break;
4376     }
4377     case bitc::FUNC_CODE_INST_ATOMICRMW: {
4378       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4379       unsigned OpNum = 0;
4380       Value *Ptr, *Val;
4381       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4382           popValue(Record, OpNum, NextValueNo,
4383                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4384           OpNum+4 != Record.size())
4385         return error("Invalid record");
4386       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4387       if (Operation < AtomicRMWInst::FIRST_BINOP ||
4388           Operation > AtomicRMWInst::LAST_BINOP)
4389         return error("Invalid record");
4390       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4391       if (Ordering == NotAtomic || Ordering == Unordered)
4392         return error("Invalid record");
4393       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4394       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4395       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4396       InstructionList.push_back(I);
4397       break;
4398     }
4399     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4400       if (2 != Record.size())
4401         return error("Invalid record");
4402       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4403       if (Ordering == NotAtomic || Ordering == Unordered ||
4404           Ordering == Monotonic)
4405         return error("Invalid record");
4406       SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4407       I = new FenceInst(Context, Ordering, SynchScope);
4408       InstructionList.push_back(I);
4409       break;
4410     }
4411     case bitc::FUNC_CODE_INST_CALL: {
4412       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4413       if (Record.size() < 3)
4414         return error("Invalid record");
4415
4416       unsigned OpNum = 0;
4417       AttributeSet PAL = getAttributes(Record[OpNum++]);
4418       unsigned CCInfo = Record[OpNum++];
4419
4420       FunctionType *FTy = nullptr;
4421       if (CCInfo >> 15 & 1 &&
4422           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4423         return error("Explicit call type is not a function type");
4424
4425       Value *Callee;
4426       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4427         return error("Invalid record");
4428
4429       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4430       if (!OpTy)
4431         return error("Callee is not a pointer type");
4432       if (!FTy) {
4433         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4434         if (!FTy)
4435           return error("Callee is not of pointer to function type");
4436       } else if (OpTy->getElementType() != FTy)
4437         return error("Explicit call type does not match pointee type of "
4438                      "callee operand");
4439       if (Record.size() < FTy->getNumParams() + OpNum)
4440         return error("Insufficient operands to call");
4441
4442       SmallVector<Value*, 16> Args;
4443       // Read the fixed params.
4444       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4445         if (FTy->getParamType(i)->isLabelTy())
4446           Args.push_back(getBasicBlock(Record[OpNum]));
4447         else
4448           Args.push_back(getValue(Record, OpNum, NextValueNo,
4449                                   FTy->getParamType(i)));
4450         if (!Args.back())
4451           return error("Invalid record");
4452       }
4453
4454       // Read type/value pairs for varargs params.
4455       if (!FTy->isVarArg()) {
4456         if (OpNum != Record.size())
4457           return error("Invalid record");
4458       } else {
4459         while (OpNum != Record.size()) {
4460           Value *Op;
4461           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4462             return error("Invalid record");
4463           Args.push_back(Op);
4464         }
4465       }
4466
4467       I = CallInst::Create(FTy, Callee, Args);
4468       InstructionList.push_back(I);
4469       cast<CallInst>(I)->setCallingConv(
4470           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4471       CallInst::TailCallKind TCK = CallInst::TCK_None;
4472       if (CCInfo & 1)
4473         TCK = CallInst::TCK_Tail;
4474       if (CCInfo & (1 << 14))
4475         TCK = CallInst::TCK_MustTail;
4476       cast<CallInst>(I)->setTailCallKind(TCK);
4477       cast<CallInst>(I)->setAttributes(PAL);
4478       break;
4479     }
4480     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4481       if (Record.size() < 3)
4482         return error("Invalid record");
4483       Type *OpTy = getTypeByID(Record[0]);
4484       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4485       Type *ResTy = getTypeByID(Record[2]);
4486       if (!OpTy || !Op || !ResTy)
4487         return error("Invalid record");
4488       I = new VAArgInst(Op, ResTy);
4489       InstructionList.push_back(I);
4490       break;
4491     }
4492     }
4493
4494     // Add instruction to end of current BB.  If there is no current BB, reject
4495     // this file.
4496     if (!CurBB) {
4497       delete I;
4498       return error("Invalid instruction with no BB");
4499     }
4500     CurBB->getInstList().push_back(I);
4501
4502     // If this was a terminator instruction, move to the next block.
4503     if (isa<TerminatorInst>(I)) {
4504       ++CurBBNo;
4505       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4506     }
4507
4508     // Non-void values get registered in the value table for future use.
4509     if (I && !I->getType()->isVoidTy())
4510       ValueList.assignValue(I, NextValueNo++);
4511   }
4512
4513 OutOfRecordLoop:
4514
4515   // Check the function list for unresolved values.
4516   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4517     if (!A->getParent()) {
4518       // We found at least one unresolved value.  Nuke them all to avoid leaks.
4519       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4520         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4521           A->replaceAllUsesWith(UndefValue::get(A->getType()));
4522           delete A;
4523         }
4524       }
4525       return error("Never resolved value found in function");
4526     }
4527   }
4528
4529   // FIXME: Check for unresolved forward-declared metadata references
4530   // and clean up leaks.
4531
4532   // Trim the value list down to the size it was before we parsed this function.
4533   ValueList.shrinkTo(ModuleValueListSize);
4534   MDValueList.shrinkTo(ModuleMDValueListSize);
4535   std::vector<BasicBlock*>().swap(FunctionBBs);
4536   return std::error_code();
4537 }
4538
4539 /// Find the function body in the bitcode stream
4540 std::error_code BitcodeReader::findFunctionInStream(
4541     Function *F,
4542     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4543   while (DeferredFunctionInfoIterator->second == 0) {
4544     if (Stream.AtEndOfStream())
4545       return error("Could not find function in stream");
4546     // ParseModule will parse the next body in the stream and set its
4547     // position in the DeferredFunctionInfo map.
4548     if (std::error_code EC = parseModule(true))
4549       return EC;
4550   }
4551   return std::error_code();
4552 }
4553
4554 //===----------------------------------------------------------------------===//
4555 // GVMaterializer implementation
4556 //===----------------------------------------------------------------------===//
4557
4558 void BitcodeReader::releaseBuffer() { Buffer.release(); }
4559
4560 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
4561   if (std::error_code EC = materializeMetadata())
4562     return EC;
4563
4564   Function *F = dyn_cast<Function>(GV);
4565   // If it's not a function or is already material, ignore the request.
4566   if (!F || !F->isMaterializable())
4567     return std::error_code();
4568
4569   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4570   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4571   // If its position is recorded as 0, its body is somewhere in the stream
4572   // but we haven't seen it yet.
4573   if (DFII->second == 0)
4574     if (std::error_code EC = findFunctionInStream(F, DFII))
4575       return EC;
4576
4577   // Move the bit stream to the saved position of the deferred function body.
4578   Stream.JumpToBit(DFII->second);
4579
4580   if (std::error_code EC = parseFunctionBody(F))
4581     return EC;
4582   F->setIsMaterializable(false);
4583
4584   if (StripDebugInfo)
4585     stripDebugInfo(*F);
4586
4587   // Upgrade any old intrinsic calls in the function.
4588   for (auto &I : UpgradedIntrinsics) {
4589     for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
4590       User *U = *UI;
4591       ++UI;
4592       if (CallInst *CI = dyn_cast<CallInst>(U))
4593         UpgradeIntrinsicCall(CI, I.second);
4594     }
4595   }
4596
4597   // Bring in any functions that this function forward-referenced via
4598   // blockaddresses.
4599   return materializeForwardReferencedFunctions();
4600 }
4601
4602 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4603   const Function *F = dyn_cast<Function>(GV);
4604   if (!F || F->isDeclaration())
4605     return false;
4606
4607   // Dematerializing F would leave dangling references that wouldn't be
4608   // reconnected on re-materialization.
4609   if (BlockAddressesTaken.count(F))
4610     return false;
4611
4612   return DeferredFunctionInfo.count(const_cast<Function*>(F));
4613 }
4614
4615 void BitcodeReader::dematerialize(GlobalValue *GV) {
4616   Function *F = dyn_cast<Function>(GV);
4617   // If this function isn't dematerializable, this is a noop.
4618   if (!F || !isDematerializable(F))
4619     return;
4620
4621   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
4622
4623   // Just forget the function body, we can remat it later.
4624   F->dropAllReferences();
4625   F->setIsMaterializable(true);
4626 }
4627
4628 std::error_code BitcodeReader::materializeModule(Module *M) {
4629   assert(M == TheModule &&
4630          "Can only Materialize the Module this BitcodeReader is attached to.");
4631
4632   if (std::error_code EC = materializeMetadata())
4633     return EC;
4634
4635   // Promise to materialize all forward references.
4636   WillMaterializeAllForwardRefs = true;
4637
4638   // Iterate over the module, deserializing any functions that are still on
4639   // disk.
4640   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
4641        F != E; ++F) {
4642     if (std::error_code EC = materialize(F))
4643       return EC;
4644   }
4645   // At this point, if there are any function bodies, the current bit is
4646   // pointing to the END_BLOCK record after them. Now make sure the rest
4647   // of the bits in the module have been read.
4648   if (NextUnreadBit)
4649     parseModule(true);
4650
4651   // Check that all block address forward references got resolved (as we
4652   // promised above).
4653   if (!BasicBlockFwdRefs.empty())
4654     return error("Never resolved function from blockaddress");
4655
4656   // Upgrade any intrinsic calls that slipped through (should not happen!) and
4657   // delete the old functions to clean up. We can't do this unless the entire
4658   // module is materialized because there could always be another function body
4659   // with calls to the old function.
4660   for (auto &I : UpgradedIntrinsics) {
4661     for (auto *U : I.first->users()) {
4662       if (CallInst *CI = dyn_cast<CallInst>(U))
4663         UpgradeIntrinsicCall(CI, I.second);
4664     }
4665     if (!I.first->use_empty())
4666       I.first->replaceAllUsesWith(I.second);
4667     I.first->eraseFromParent();
4668   }
4669   UpgradedIntrinsics.clear();
4670
4671   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4672     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4673
4674   UpgradeDebugInfo(*M);
4675   return std::error_code();
4676 }
4677
4678 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4679   return IdentifiedStructTypes;
4680 }
4681
4682 std::error_code
4683 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
4684   if (Streamer)
4685     return initLazyStream(std::move(Streamer));
4686   return initStreamFromBuffer();
4687 }
4688
4689 std::error_code BitcodeReader::initStreamFromBuffer() {
4690   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
4691   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4692
4693   if (Buffer->getBufferSize() & 3)
4694     return error("Invalid bitcode signature");
4695
4696   // If we have a wrapper header, parse it and ignore the non-bc file contents.
4697   // The magic number is 0x0B17C0DE stored in little endian.
4698   if (isBitcodeWrapper(BufPtr, BufEnd))
4699     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
4700       return error("Invalid bitcode wrapper header");
4701
4702   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
4703   Stream.init(&*StreamFile);
4704
4705   return std::error_code();
4706 }
4707
4708 std::error_code
4709 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
4710   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4711   // see it.
4712   auto OwnedBytes =
4713       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
4714   StreamingMemoryObject &Bytes = *OwnedBytes;
4715   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
4716   Stream.init(&*StreamFile);
4717
4718   unsigned char buf[16];
4719   if (Bytes.readBytes(buf, 16, 0) != 16)
4720     return error("Invalid bitcode signature");
4721
4722   if (!isBitcode(buf, buf + 16))
4723     return error("Invalid bitcode signature");
4724
4725   if (isBitcodeWrapper(buf, buf + 4)) {
4726     const unsigned char *bitcodeStart = buf;
4727     const unsigned char *bitcodeEnd = buf + 16;
4728     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
4729     Bytes.dropLeadingBytes(bitcodeStart - buf);
4730     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
4731   }
4732   return std::error_code();
4733 }
4734
4735 namespace {
4736 class BitcodeErrorCategoryType : public std::error_category {
4737   const char *name() const LLVM_NOEXCEPT override {
4738     return "llvm.bitcode";
4739   }
4740   std::string message(int IE) const override {
4741     BitcodeError E = static_cast<BitcodeError>(IE);
4742     switch (E) {
4743     case BitcodeError::InvalidBitcodeSignature:
4744       return "Invalid bitcode signature";
4745     case BitcodeError::CorruptedBitcode:
4746       return "Corrupted bitcode";
4747     }
4748     llvm_unreachable("Unknown error type!");
4749   }
4750 };
4751 }
4752
4753 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4754
4755 const std::error_category &llvm::BitcodeErrorCategory() {
4756   return *ErrorCategory;
4757 }
4758
4759 //===----------------------------------------------------------------------===//
4760 // External interface
4761 //===----------------------------------------------------------------------===//
4762
4763 static ErrorOr<std::unique_ptr<Module>>
4764 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
4765                      BitcodeReader *R, LLVMContext &Context,
4766                      bool MaterializeAll, bool ShouldLazyLoadMetadata) {
4767   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4768   M->setMaterializer(R);
4769
4770   auto cleanupOnError = [&](std::error_code EC) {
4771     R->releaseBuffer(); // Never take ownership on error.
4772     return EC;
4773   };
4774
4775   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4776   if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
4777                                                ShouldLazyLoadMetadata))
4778     return cleanupOnError(EC);
4779
4780   if (MaterializeAll) {
4781     // Read in the entire module, and destroy the BitcodeReader.
4782     if (std::error_code EC = M->materializeAllPermanently())
4783       return cleanupOnError(EC);
4784   } else {
4785     // Resolve forward references from blockaddresses.
4786     if (std::error_code EC = R->materializeForwardReferencedFunctions())
4787       return cleanupOnError(EC);
4788   }
4789   return std::move(M);
4790 }
4791
4792 /// \brief Get a lazy one-at-time loading module from bitcode.
4793 ///
4794 /// This isn't always used in a lazy context.  In particular, it's also used by
4795 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
4796 /// in forward-referenced functions from block address references.
4797 ///
4798 /// \param[in] MaterializeAll Set to \c true if we should materialize
4799 /// everything.
4800 static ErrorOr<std::unique_ptr<Module>>
4801 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
4802                          LLVMContext &Context, bool MaterializeAll,
4803                          DiagnosticHandlerFunction DiagnosticHandler,
4804                          bool ShouldLazyLoadMetadata = false) {
4805   BitcodeReader *R =
4806       new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
4807
4808   ErrorOr<std::unique_ptr<Module>> Ret =
4809       getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
4810                            MaterializeAll, ShouldLazyLoadMetadata);
4811   if (!Ret)
4812     return Ret;
4813
4814   Buffer.release(); // The BitcodeReader owns it now.
4815   return Ret;
4816 }
4817
4818 ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
4819     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
4820     DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
4821   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
4822                                   DiagnosticHandler, ShouldLazyLoadMetadata);
4823 }
4824
4825 ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
4826     StringRef Name, std::unique_ptr<DataStreamer> Streamer,
4827     LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
4828   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4829   BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
4830
4831   return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
4832                               false);
4833 }
4834
4835 ErrorOr<std::unique_ptr<Module>>
4836 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4837                        DiagnosticHandlerFunction DiagnosticHandler) {
4838   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4839   return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
4840                                   DiagnosticHandler);
4841   // TODO: Restore the use-lists to the in-memory state when the bitcode was
4842   // written.  We must defer until the Module has been fully materialized.
4843 }
4844
4845 std::string
4846 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4847                              DiagnosticHandlerFunction DiagnosticHandler) {
4848   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
4849   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4850                                             DiagnosticHandler);
4851   ErrorOr<std::string> Triple = R->parseTriple();
4852   if (Triple.getError())
4853     return "";
4854   return Triple.get();
4855 }