1f22ef01cSRoman Divacky //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky 
10ff0cc061SDimitry Andric #include "llvm/ADT/STLExtras.h"
11f22ef01cSRoman Divacky #include "llvm/ADT/SmallString.h"
12f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h"
13ff0cc061SDimitry Andric #include "llvm/ADT/Triple.h"
14ff0cc061SDimitry Andric #include "llvm/Bitcode/BitstreamReader.h"
15f785676fSDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
163ca95b02SDimitry Andric #include "llvm/Bitcode/ReaderWriter.h"
1791bc56edSDimitry Andric #include "llvm/IR/AutoUpgrade.h"
183ca95b02SDimitry Andric #include "llvm/IR/CallSite.h"
19139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
20ff0cc061SDimitry Andric #include "llvm/IR/DebugInfo.h"
21ff0cc061SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
22139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
2339d628a0SDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
24ff0cc061SDimitry Andric #include "llvm/IR/GVMaterializer.h"
25139f7f9bSDimitry Andric #include "llvm/IR/InlineAsm.h"
26139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
27f785676fSDimitry Andric #include "llvm/IR/LLVMContext.h"
28139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
293ca95b02SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
30139f7f9bSDimitry Andric #include "llvm/IR/OperandTraits.h"
31139f7f9bSDimitry Andric #include "llvm/IR/Operator.h"
32ff0cc061SDimitry Andric #include "llvm/IR/ValueHandle.h"
333ca95b02SDimitry Andric #include "llvm/Support/CommandLine.h"
34dff0c46cSDimitry Andric #include "llvm/Support/DataStream.h"
353ca95b02SDimitry Andric #include "llvm/Support/Debug.h"
3639d628a0SDimitry Andric #include "llvm/Support/ManagedStatic.h"
37f22ef01cSRoman Divacky #include "llvm/Support/MathExtras.h"
38f22ef01cSRoman Divacky #include "llvm/Support/MemoryBuffer.h"
39f785676fSDimitry Andric #include "llvm/Support/raw_ostream.h"
40ff0cc061SDimitry Andric #include <deque>
413ca95b02SDimitry Andric #include <utility>
423ca95b02SDimitry Andric 
43f22ef01cSRoman Divacky using namespace llvm;
44f22ef01cSRoman Divacky 
453ca95b02SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs(
463ca95b02SDimitry Andric     "print-summary-global-ids", cl::init(false), cl::Hidden,
473ca95b02SDimitry Andric     cl::desc(
483ca95b02SDimitry Andric         "Print the global id for each value when reading the module summary"));
493ca95b02SDimitry Andric 
50ff0cc061SDimitry Andric namespace {
517ae0e2c9SDimitry Andric enum {
527ae0e2c9SDimitry Andric   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
537ae0e2c9SDimitry Andric };
547ae0e2c9SDimitry Andric 
55ff0cc061SDimitry Andric class BitcodeReaderValueList {
56ff0cc061SDimitry Andric   std::vector<WeakVH> ValuePtrs;
57ff0cc061SDimitry Andric 
588f0fd8f6SDimitry Andric   /// As we resolve forward-referenced constants, we add information about them
598f0fd8f6SDimitry Andric   /// to this vector.  This allows us to resolve them in bulk instead of
608f0fd8f6SDimitry Andric   /// resolving each reference at a time.  See the code in
61ff0cc061SDimitry Andric   /// ResolveConstantForwardRefs for more information about this.
62ff0cc061SDimitry Andric   ///
63ff0cc061SDimitry Andric   /// The key of this vector is the placeholder constant, the value is the slot
64ff0cc061SDimitry Andric   /// number that holds the resolved value.
65ff0cc061SDimitry Andric   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
66ff0cc061SDimitry Andric   ResolveConstantsTy ResolveConstants;
67ff0cc061SDimitry Andric   LLVMContext &Context;
68ff0cc061SDimitry Andric public:
69ff0cc061SDimitry Andric   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
70ff0cc061SDimitry Andric   ~BitcodeReaderValueList() {
71ff0cc061SDimitry Andric     assert(ResolveConstants.empty() && "Constants not resolved?");
72ff0cc061SDimitry Andric   }
73ff0cc061SDimitry Andric 
74ff0cc061SDimitry Andric   // vector compatibility methods
75ff0cc061SDimitry Andric   unsigned size() const { return ValuePtrs.size(); }
76ff0cc061SDimitry Andric   void resize(unsigned N) { ValuePtrs.resize(N); }
7797bc6c73SDimitry Andric   void push_back(Value *V) { ValuePtrs.emplace_back(V); }
78ff0cc061SDimitry Andric 
79ff0cc061SDimitry Andric   void clear() {
80ff0cc061SDimitry Andric     assert(ResolveConstants.empty() && "Constants not resolved?");
81ff0cc061SDimitry Andric     ValuePtrs.clear();
82ff0cc061SDimitry Andric   }
83ff0cc061SDimitry Andric 
84ff0cc061SDimitry Andric   Value *operator[](unsigned i) const {
85ff0cc061SDimitry Andric     assert(i < ValuePtrs.size());
86ff0cc061SDimitry Andric     return ValuePtrs[i];
87ff0cc061SDimitry Andric   }
88ff0cc061SDimitry Andric 
89ff0cc061SDimitry Andric   Value *back() const { return ValuePtrs.back(); }
90ff0cc061SDimitry Andric   void pop_back() { ValuePtrs.pop_back(); }
91ff0cc061SDimitry Andric   bool empty() const { return ValuePtrs.empty(); }
92ff0cc061SDimitry Andric   void shrinkTo(unsigned N) {
93ff0cc061SDimitry Andric     assert(N <= size() && "Invalid shrinkTo request!");
94ff0cc061SDimitry Andric     ValuePtrs.resize(N);
95ff0cc061SDimitry Andric   }
96ff0cc061SDimitry Andric 
97ff0cc061SDimitry Andric   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
98ff0cc061SDimitry Andric   Value *getValueFwdRef(unsigned Idx, Type *Ty);
99ff0cc061SDimitry Andric 
1008f0fd8f6SDimitry Andric   void assignValue(Value *V, unsigned Idx);
101ff0cc061SDimitry Andric 
1028f0fd8f6SDimitry Andric   /// Once all constants are read, this method bulk resolves any forward
1038f0fd8f6SDimitry Andric   /// references.
1048f0fd8f6SDimitry Andric   void resolveConstantForwardRefs();
105ff0cc061SDimitry Andric };
106ff0cc061SDimitry Andric 
1077d523365SDimitry Andric class BitcodeReaderMetadataList {
108ff0cc061SDimitry Andric   unsigned NumFwdRefs;
109ff0cc061SDimitry Andric   bool AnyFwdRefs;
110ff0cc061SDimitry Andric   unsigned MinFwdRef;
111ff0cc061SDimitry Andric   unsigned MaxFwdRef;
1123ca95b02SDimitry Andric 
1133ca95b02SDimitry Andric   /// Array of metadata references.
1143ca95b02SDimitry Andric   ///
1153ca95b02SDimitry Andric   /// Don't use std::vector here.  Some versions of libc++ copy (instead of
1163ca95b02SDimitry Andric   /// move) on resize, and TrackingMDRef is very expensive to copy.
1173ca95b02SDimitry Andric   SmallVector<TrackingMDRef, 1> MetadataPtrs;
1183ca95b02SDimitry Andric 
1193ca95b02SDimitry Andric   /// Structures for resolving old type refs.
1203ca95b02SDimitry Andric   struct {
1213ca95b02SDimitry Andric     SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
1223ca95b02SDimitry Andric     SmallDenseMap<MDString *, DICompositeType *, 1> Final;
1233ca95b02SDimitry Andric     SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
1243ca95b02SDimitry Andric     SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
1253ca95b02SDimitry Andric   } OldTypeRefs;
126ff0cc061SDimitry Andric 
127ff0cc061SDimitry Andric   LLVMContext &Context;
128ff0cc061SDimitry Andric public:
1297d523365SDimitry Andric   BitcodeReaderMetadataList(LLVMContext &C)
130ff0cc061SDimitry Andric       : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
131ff0cc061SDimitry Andric 
132ff0cc061SDimitry Andric   // vector compatibility methods
1337d523365SDimitry Andric   unsigned size() const { return MetadataPtrs.size(); }
1347d523365SDimitry Andric   void resize(unsigned N) { MetadataPtrs.resize(N); }
1357d523365SDimitry Andric   void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
1367d523365SDimitry Andric   void clear() { MetadataPtrs.clear(); }
1377d523365SDimitry Andric   Metadata *back() const { return MetadataPtrs.back(); }
1387d523365SDimitry Andric   void pop_back() { MetadataPtrs.pop_back(); }
1397d523365SDimitry Andric   bool empty() const { return MetadataPtrs.empty(); }
140ff0cc061SDimitry Andric 
141ff0cc061SDimitry Andric   Metadata *operator[](unsigned i) const {
1427d523365SDimitry Andric     assert(i < MetadataPtrs.size());
1437d523365SDimitry Andric     return MetadataPtrs[i];
144ff0cc061SDimitry Andric   }
145ff0cc061SDimitry Andric 
1463ca95b02SDimitry Andric   Metadata *lookup(unsigned I) const {
1473ca95b02SDimitry Andric     if (I < MetadataPtrs.size())
1483ca95b02SDimitry Andric       return MetadataPtrs[I];
1493ca95b02SDimitry Andric     return nullptr;
1503ca95b02SDimitry Andric   }
1513ca95b02SDimitry Andric 
152ff0cc061SDimitry Andric   void shrinkTo(unsigned N) {
153ff0cc061SDimitry Andric     assert(N <= size() && "Invalid shrinkTo request!");
1543ca95b02SDimitry Andric     assert(!AnyFwdRefs && "Unexpected forward refs");
1557d523365SDimitry Andric     MetadataPtrs.resize(N);
156ff0cc061SDimitry Andric   }
157ff0cc061SDimitry Andric 
1583ca95b02SDimitry Andric   /// Return the given metadata, creating a replaceable forward reference if
1593ca95b02SDimitry Andric   /// necessary.
1603ca95b02SDimitry Andric   Metadata *getMetadataFwdRef(unsigned Idx);
1613ca95b02SDimitry Andric 
1623ca95b02SDimitry Andric   /// Return the the given metadata only if it is fully resolved.
1633ca95b02SDimitry Andric   ///
1643ca95b02SDimitry Andric   /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
1653ca95b02SDimitry Andric   /// would give \c false.
1663ca95b02SDimitry Andric   Metadata *getMetadataIfResolved(unsigned Idx);
1673ca95b02SDimitry Andric 
1683ca95b02SDimitry Andric   MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
1698f0fd8f6SDimitry Andric   void assignValue(Metadata *MD, unsigned Idx);
170ff0cc061SDimitry Andric   void tryToResolveCycles();
1713ca95b02SDimitry Andric   bool hasFwdRefs() const { return AnyFwdRefs; }
1723ca95b02SDimitry Andric 
1733ca95b02SDimitry Andric   /// Upgrade a type that had an MDString reference.
1743ca95b02SDimitry Andric   void addTypeRef(MDString &UUID, DICompositeType &CT);
1753ca95b02SDimitry Andric 
1763ca95b02SDimitry Andric   /// Upgrade a type that had an MDString reference.
1773ca95b02SDimitry Andric   Metadata *upgradeTypeRef(Metadata *MaybeUUID);
1783ca95b02SDimitry Andric 
1793ca95b02SDimitry Andric   /// Upgrade a type ref array that may have MDString references.
1803ca95b02SDimitry Andric   Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
1813ca95b02SDimitry Andric 
1823ca95b02SDimitry Andric private:
1833ca95b02SDimitry Andric   Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
184ff0cc061SDimitry Andric };
185ff0cc061SDimitry Andric 
186ff0cc061SDimitry Andric class BitcodeReader : public GVMaterializer {
187ff0cc061SDimitry Andric   LLVMContext &Context;
1888f0fd8f6SDimitry Andric   Module *TheModule = nullptr;
189ff0cc061SDimitry Andric   std::unique_ptr<MemoryBuffer> Buffer;
190ff0cc061SDimitry Andric   std::unique_ptr<BitstreamReader> StreamFile;
191ff0cc061SDimitry Andric   BitstreamCursor Stream;
1927d523365SDimitry Andric   // Next offset to start scanning for lazy parsing of function bodies.
1938f0fd8f6SDimitry Andric   uint64_t NextUnreadBit = 0;
1947d523365SDimitry Andric   // Last function offset found in the VST.
1957d523365SDimitry Andric   uint64_t LastFunctionBlockBit = 0;
1968f0fd8f6SDimitry Andric   bool SeenValueSymbolTable = false;
1977d523365SDimitry Andric   uint64_t VSTOffset = 0;
1987d523365SDimitry Andric   // Contains an arbitrary and optional string identifying the bitcode producer
1997d523365SDimitry Andric   std::string ProducerIdentification;
200ff0cc061SDimitry Andric 
201ff0cc061SDimitry Andric   std::vector<Type*> TypeList;
202ff0cc061SDimitry Andric   BitcodeReaderValueList ValueList;
2037d523365SDimitry Andric   BitcodeReaderMetadataList MetadataList;
204ff0cc061SDimitry Andric   std::vector<Comdat *> ComdatList;
205ff0cc061SDimitry Andric   SmallVector<Instruction *, 64> InstructionList;
206ff0cc061SDimitry Andric 
207ff0cc061SDimitry Andric   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
2083ca95b02SDimitry Andric   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
209ff0cc061SDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
210ff0cc061SDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
2118f0fd8f6SDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
212ff0cc061SDimitry Andric 
213ff0cc061SDimitry Andric   SmallVector<Instruction*, 64> InstsWithTBAATag;
214ff0cc061SDimitry Andric 
2153ca95b02SDimitry Andric   bool HasSeenOldLoopTags = false;
2163ca95b02SDimitry Andric 
2178f0fd8f6SDimitry Andric   /// The set of attributes by index.  Index zero in the file is for null, and
2188f0fd8f6SDimitry Andric   /// is thus not represented here.  As such all indices are off by one.
219ff0cc061SDimitry Andric   std::vector<AttributeSet> MAttributes;
220ff0cc061SDimitry Andric 
2217d523365SDimitry Andric   /// The set of attribute groups.
222ff0cc061SDimitry Andric   std::map<unsigned, AttributeSet> MAttributeGroups;
223ff0cc061SDimitry Andric 
2248f0fd8f6SDimitry Andric   /// While parsing a function body, this is a list of the basic blocks for the
2258f0fd8f6SDimitry Andric   /// function.
226ff0cc061SDimitry Andric   std::vector<BasicBlock*> FunctionBBs;
227ff0cc061SDimitry Andric 
228ff0cc061SDimitry Andric   // When reading the module header, this list is populated with functions that
229ff0cc061SDimitry Andric   // have bodies later in the file.
230ff0cc061SDimitry Andric   std::vector<Function*> FunctionsWithBodies;
231ff0cc061SDimitry Andric 
232ff0cc061SDimitry Andric   // When intrinsic functions are encountered which require upgrading they are
233ff0cc061SDimitry Andric   // stored here with their replacement function.
2343ca95b02SDimitry Andric   typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
2353ca95b02SDimitry Andric   UpdatedIntrinsicMap UpgradedIntrinsics;
2363ca95b02SDimitry Andric   // Intrinsics which were remangled because of types rename
2373ca95b02SDimitry Andric   UpdatedIntrinsicMap RemangledIntrinsics;
238ff0cc061SDimitry Andric 
239ff0cc061SDimitry Andric   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
240ff0cc061SDimitry Andric   DenseMap<unsigned, unsigned> MDKindMap;
241ff0cc061SDimitry Andric 
242ff0cc061SDimitry Andric   // Several operations happen after the module header has been read, but
243ff0cc061SDimitry Andric   // before function bodies are processed. This keeps track of whether
244ff0cc061SDimitry Andric   // we've done this yet.
2458f0fd8f6SDimitry Andric   bool SeenFirstFunctionBody = false;
246ff0cc061SDimitry Andric 
2478f0fd8f6SDimitry Andric   /// When function bodies are initially scanned, this map contains info about
2488f0fd8f6SDimitry Andric   /// where to find deferred function body in the stream.
249ff0cc061SDimitry Andric   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
250ff0cc061SDimitry Andric 
251ff0cc061SDimitry Andric   /// When Metadata block is initially scanned when parsing the module, we may
252ff0cc061SDimitry Andric   /// choose to defer parsing of the metadata. This vector contains info about
253ff0cc061SDimitry Andric   /// which Metadata blocks are deferred.
254ff0cc061SDimitry Andric   std::vector<uint64_t> DeferredMetadataInfo;
255ff0cc061SDimitry Andric 
256ff0cc061SDimitry Andric   /// These are basic blocks forward-referenced by block addresses.  They are
257ff0cc061SDimitry Andric   /// inserted lazily into functions when they're loaded.  The basic block ID is
258ff0cc061SDimitry Andric   /// its index into the vector.
259ff0cc061SDimitry Andric   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
260ff0cc061SDimitry Andric   std::deque<Function *> BasicBlockFwdRefQueue;
261ff0cc061SDimitry Andric 
2628f0fd8f6SDimitry Andric   /// Indicates that we are using a new encoding for instruction operands where
2638f0fd8f6SDimitry Andric   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
2648f0fd8f6SDimitry Andric   /// instruction number, for a more compact encoding.  Some instruction
2658f0fd8f6SDimitry Andric   /// operands are not relative to the instruction ID: basic block numbers, and
2668f0fd8f6SDimitry Andric   /// types. Once the old style function blocks have been phased out, we would
267ff0cc061SDimitry Andric   /// not need this flag.
2688f0fd8f6SDimitry Andric   bool UseRelativeIDs = false;
269ff0cc061SDimitry Andric 
270ff0cc061SDimitry Andric   /// True if all functions will be materialized, negating the need to process
271ff0cc061SDimitry Andric   /// (e.g.) blockaddress forward references.
2728f0fd8f6SDimitry Andric   bool WillMaterializeAllForwardRefs = false;
273ff0cc061SDimitry Andric 
274ff0cc061SDimitry Andric   /// True if any Metadata block has been materialized.
2758f0fd8f6SDimitry Andric   bool IsMetadataMaterialized = false;
276ff0cc061SDimitry Andric 
277ff0cc061SDimitry Andric   bool StripDebugInfo = false;
278ff0cc061SDimitry Andric 
2797d523365SDimitry Andric   /// Functions that need to be matched with subprograms when upgrading old
2807d523365SDimitry Andric   /// metadata.
2817d523365SDimitry Andric   SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
2827d523365SDimitry Andric 
2837d523365SDimitry Andric   std::vector<std::string> BundleTags;
2847d523365SDimitry Andric 
285ff0cc061SDimitry Andric public:
2868f0fd8f6SDimitry Andric   std::error_code error(BitcodeError E, const Twine &Message);
2878f0fd8f6SDimitry Andric   std::error_code error(const Twine &Message);
288ff0cc061SDimitry Andric 
2897d523365SDimitry Andric   BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
2907d523365SDimitry Andric   BitcodeReader(LLVMContext &Context);
2918f0fd8f6SDimitry Andric   ~BitcodeReader() override { freeState(); }
292ff0cc061SDimitry Andric 
293ff0cc061SDimitry Andric   std::error_code materializeForwardReferencedFunctions();
294ff0cc061SDimitry Andric 
2958f0fd8f6SDimitry Andric   void freeState();
296ff0cc061SDimitry Andric 
297ff0cc061SDimitry Andric   void releaseBuffer();
298ff0cc061SDimitry Andric 
299ff0cc061SDimitry Andric   std::error_code materialize(GlobalValue *GV) override;
3007d523365SDimitry Andric   std::error_code materializeModule() override;
301ff0cc061SDimitry Andric   std::vector<StructType *> getIdentifiedStructTypes() const override;
302ff0cc061SDimitry Andric 
3038f0fd8f6SDimitry Andric   /// \brief Main interface to parsing a bitcode buffer.
3048f0fd8f6SDimitry Andric   /// \returns true if an error occurred.
3058f0fd8f6SDimitry Andric   std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3068f0fd8f6SDimitry Andric                                    Module *M,
307ff0cc061SDimitry Andric                                    bool ShouldLazyLoadMetadata = false);
308ff0cc061SDimitry Andric 
3098f0fd8f6SDimitry Andric   /// \brief Cheap mechanism to just extract module triple
3108f0fd8f6SDimitry Andric   /// \returns true if an error occurred.
311ff0cc061SDimitry Andric   ErrorOr<std::string> parseTriple();
312ff0cc061SDimitry Andric 
3137d523365SDimitry Andric   /// Cheap mechanism to just extract the identification block out of bitcode.
3147d523365SDimitry Andric   ErrorOr<std::string> parseIdentificationBlock();
3157d523365SDimitry Andric 
3163ca95b02SDimitry Andric   /// Peak at the module content and return true if any ObjC category or class
3173ca95b02SDimitry Andric   /// is found.
3183ca95b02SDimitry Andric   ErrorOr<bool> hasObjCCategory();
3193ca95b02SDimitry Andric 
320ff0cc061SDimitry Andric   static uint64_t decodeSignRotatedValue(uint64_t V);
321ff0cc061SDimitry Andric 
322ff0cc061SDimitry Andric   /// Materialize any deferred Metadata block.
323ff0cc061SDimitry Andric   std::error_code materializeMetadata() override;
324ff0cc061SDimitry Andric 
325ff0cc061SDimitry Andric   void setStripDebugInfo() override;
326ff0cc061SDimitry Andric 
327ff0cc061SDimitry Andric private:
3287d523365SDimitry Andric   /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
3297d523365SDimitry Andric   // ProducerIdentification data member, and do some basic enforcement on the
3307d523365SDimitry Andric   // "epoch" encoded in the bitcode.
3317d523365SDimitry Andric   std::error_code parseBitcodeVersion();
3327d523365SDimitry Andric 
333ff0cc061SDimitry Andric   std::vector<StructType *> IdentifiedStructTypes;
334ff0cc061SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
335ff0cc061SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context);
336ff0cc061SDimitry Andric 
337ff0cc061SDimitry Andric   Type *getTypeByID(unsigned ID);
338ff0cc061SDimitry Andric   Value *getFnValueByID(unsigned ID, Type *Ty) {
339ff0cc061SDimitry Andric     if (Ty && Ty->isMetadataTy())
340ff0cc061SDimitry Andric       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
341ff0cc061SDimitry Andric     return ValueList.getValueFwdRef(ID, Ty);
342ff0cc061SDimitry Andric   }
343ff0cc061SDimitry Andric   Metadata *getFnMetadataByID(unsigned ID) {
3443ca95b02SDimitry Andric     return MetadataList.getMetadataFwdRef(ID);
345ff0cc061SDimitry Andric   }
346ff0cc061SDimitry Andric   BasicBlock *getBasicBlock(unsigned ID) const {
347ff0cc061SDimitry Andric     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
348ff0cc061SDimitry Andric     return FunctionBBs[ID];
349ff0cc061SDimitry Andric   }
350ff0cc061SDimitry Andric   AttributeSet getAttributes(unsigned i) const {
351ff0cc061SDimitry Andric     if (i-1 < MAttributes.size())
352ff0cc061SDimitry Andric       return MAttributes[i-1];
353ff0cc061SDimitry Andric     return AttributeSet();
354ff0cc061SDimitry Andric   }
355ff0cc061SDimitry Andric 
3568f0fd8f6SDimitry Andric   /// Read a value/type pair out of the specified record from slot 'Slot'.
3578f0fd8f6SDimitry Andric   /// Increment Slot past the number of slots used in the record. Return true on
3588f0fd8f6SDimitry Andric   /// failure.
359ff0cc061SDimitry Andric   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
360ff0cc061SDimitry Andric                         unsigned InstNum, Value *&ResVal) {
361ff0cc061SDimitry Andric     if (Slot == Record.size()) return true;
362ff0cc061SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot++];
363ff0cc061SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
364ff0cc061SDimitry Andric     if (UseRelativeIDs)
365ff0cc061SDimitry Andric       ValNo = InstNum - ValNo;
366ff0cc061SDimitry Andric     if (ValNo < InstNum) {
367ff0cc061SDimitry Andric       // If this is not a forward reference, just return the value we already
368ff0cc061SDimitry Andric       // have.
369ff0cc061SDimitry Andric       ResVal = getFnValueByID(ValNo, nullptr);
370ff0cc061SDimitry Andric       return ResVal == nullptr;
371ff0cc061SDimitry Andric     }
372ff0cc061SDimitry Andric     if (Slot == Record.size())
373ff0cc061SDimitry Andric       return true;
374ff0cc061SDimitry Andric 
375ff0cc061SDimitry Andric     unsigned TypeNo = (unsigned)Record[Slot++];
376ff0cc061SDimitry Andric     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
377ff0cc061SDimitry Andric     return ResVal == nullptr;
378ff0cc061SDimitry Andric   }
379ff0cc061SDimitry Andric 
3808f0fd8f6SDimitry Andric   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
3818f0fd8f6SDimitry Andric   /// past the number of slots used by the value in the record. Return true if
3828f0fd8f6SDimitry Andric   /// there is an error.
383ff0cc061SDimitry Andric   bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
384ff0cc061SDimitry Andric                 unsigned InstNum, Type *Ty, Value *&ResVal) {
385ff0cc061SDimitry Andric     if (getValue(Record, Slot, InstNum, Ty, ResVal))
386ff0cc061SDimitry Andric       return true;
387ff0cc061SDimitry Andric     // All values currently take a single record slot.
388ff0cc061SDimitry Andric     ++Slot;
389ff0cc061SDimitry Andric     return false;
390ff0cc061SDimitry Andric   }
391ff0cc061SDimitry Andric 
3928f0fd8f6SDimitry Andric   /// Like popValue, but does not increment the Slot number.
393ff0cc061SDimitry Andric   bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
394ff0cc061SDimitry Andric                 unsigned InstNum, Type *Ty, Value *&ResVal) {
395ff0cc061SDimitry Andric     ResVal = getValue(Record, Slot, InstNum, Ty);
396ff0cc061SDimitry Andric     return ResVal == nullptr;
397ff0cc061SDimitry Andric   }
398ff0cc061SDimitry Andric 
3998f0fd8f6SDimitry Andric   /// Version of getValue that returns ResVal directly, or 0 if there is an
4008f0fd8f6SDimitry Andric   /// error.
401ff0cc061SDimitry Andric   Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
402ff0cc061SDimitry Andric                   unsigned InstNum, Type *Ty) {
403ff0cc061SDimitry Andric     if (Slot == Record.size()) return nullptr;
404ff0cc061SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot];
405ff0cc061SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
406ff0cc061SDimitry Andric     if (UseRelativeIDs)
407ff0cc061SDimitry Andric       ValNo = InstNum - ValNo;
408ff0cc061SDimitry Andric     return getFnValueByID(ValNo, Ty);
409ff0cc061SDimitry Andric   }
410ff0cc061SDimitry Andric 
4118f0fd8f6SDimitry Andric   /// Like getValue, but decodes signed VBRs.
412ff0cc061SDimitry Andric   Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
413ff0cc061SDimitry Andric                         unsigned InstNum, Type *Ty) {
414ff0cc061SDimitry Andric     if (Slot == Record.size()) return nullptr;
415ff0cc061SDimitry Andric     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
416ff0cc061SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
417ff0cc061SDimitry Andric     if (UseRelativeIDs)
418ff0cc061SDimitry Andric       ValNo = InstNum - ValNo;
419ff0cc061SDimitry Andric     return getFnValueByID(ValNo, Ty);
420ff0cc061SDimitry Andric   }
421ff0cc061SDimitry Andric 
422ff0cc061SDimitry Andric   /// Converts alignment exponent (i.e. power of two (or zero)) to the
423ff0cc061SDimitry Andric   /// corresponding alignment to use. If alignment is too large, returns
424ff0cc061SDimitry Andric   /// a corresponding error code.
425ff0cc061SDimitry Andric   std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
4268f0fd8f6SDimitry Andric   std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
4277d523365SDimitry Andric   std::error_code parseModule(uint64_t ResumeBit,
4287d523365SDimitry Andric                               bool ShouldLazyLoadMetadata = false);
4298f0fd8f6SDimitry Andric   std::error_code parseAttributeBlock();
4308f0fd8f6SDimitry Andric   std::error_code parseAttributeGroupBlock();
4318f0fd8f6SDimitry Andric   std::error_code parseTypeTable();
4328f0fd8f6SDimitry Andric   std::error_code parseTypeTableBody();
4337d523365SDimitry Andric   std::error_code parseOperandBundleTags();
434ff0cc061SDimitry Andric 
4357d523365SDimitry Andric   ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
4367d523365SDimitry Andric                                unsigned NameIndex, Triple &TT);
4377d523365SDimitry Andric   std::error_code parseValueSymbolTable(uint64_t Offset = 0);
4388f0fd8f6SDimitry Andric   std::error_code parseConstants();
4397d523365SDimitry Andric   std::error_code rememberAndSkipFunctionBodies();
4408f0fd8f6SDimitry Andric   std::error_code rememberAndSkipFunctionBody();
441ff0cc061SDimitry Andric   /// Save the positions of the Metadata blocks and skip parsing the blocks.
442ff0cc061SDimitry Andric   std::error_code rememberAndSkipMetadata();
4438f0fd8f6SDimitry Andric   std::error_code parseFunctionBody(Function *F);
4448f0fd8f6SDimitry Andric   std::error_code globalCleanup();
4453ca95b02SDimitry Andric   std::error_code resolveGlobalAndIndirectSymbolInits();
4467d523365SDimitry Andric   std::error_code parseMetadata(bool ModuleLevel = false);
4473ca95b02SDimitry Andric   std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
4483ca95b02SDimitry Andric                                        StringRef Blob,
4493ca95b02SDimitry Andric                                        unsigned &NextMetadataNo);
4507d523365SDimitry Andric   std::error_code parseMetadataKinds();
4517d523365SDimitry Andric   std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
4523ca95b02SDimitry Andric   std::error_code
4533ca95b02SDimitry Andric   parseGlobalObjectAttachment(GlobalObject &GO,
4543ca95b02SDimitry Andric                               ArrayRef<uint64_t> Record);
4558f0fd8f6SDimitry Andric   std::error_code parseMetadataAttachment(Function &F);
456ff0cc061SDimitry Andric   ErrorOr<std::string> parseModuleTriple();
4573ca95b02SDimitry Andric   ErrorOr<bool> hasObjCCategoryInModule();
4588f0fd8f6SDimitry Andric   std::error_code parseUseLists();
4598f0fd8f6SDimitry Andric   std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
4608f0fd8f6SDimitry Andric   std::error_code initStreamFromBuffer();
4618f0fd8f6SDimitry Andric   std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
4628f0fd8f6SDimitry Andric   std::error_code findFunctionInStream(
463ff0cc061SDimitry Andric       Function *F,
464ff0cc061SDimitry Andric       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
465ff0cc061SDimitry Andric };
4667d523365SDimitry Andric 
4677d523365SDimitry Andric /// Class to manage reading and parsing function summary index bitcode
4687d523365SDimitry Andric /// files/sections.
4693ca95b02SDimitry Andric class ModuleSummaryIndexBitcodeReader {
4707d523365SDimitry Andric   DiagnosticHandlerFunction DiagnosticHandler;
4717d523365SDimitry Andric 
4723ca95b02SDimitry Andric   /// Eventually points to the module index built during parsing.
4733ca95b02SDimitry Andric   ModuleSummaryIndex *TheIndex = nullptr;
4747d523365SDimitry Andric 
4757d523365SDimitry Andric   std::unique_ptr<MemoryBuffer> Buffer;
4767d523365SDimitry Andric   std::unique_ptr<BitstreamReader> StreamFile;
4777d523365SDimitry Andric   BitstreamCursor Stream;
4787d523365SDimitry Andric 
4797d523365SDimitry Andric   /// Used to indicate whether caller only wants to check for the presence
4803ca95b02SDimitry Andric   /// of the global value summary bitcode section. All blocks are skipped,
4813ca95b02SDimitry Andric   /// but the SeenGlobalValSummary boolean is set.
4823ca95b02SDimitry Andric   bool CheckGlobalValSummaryPresenceOnly = false;
4837d523365SDimitry Andric 
4843ca95b02SDimitry Andric   /// Indicates whether we have encountered a global value summary section
4853ca95b02SDimitry Andric   /// yet during parsing, used when checking if file contains global value
4867d523365SDimitry Andric   /// summary section.
4873ca95b02SDimitry Andric   bool SeenGlobalValSummary = false;
4887d523365SDimitry Andric 
4893ca95b02SDimitry Andric   /// Indicates whether we have already parsed the VST, used for error checking.
4903ca95b02SDimitry Andric   bool SeenValueSymbolTable = false;
4913ca95b02SDimitry Andric 
4923ca95b02SDimitry Andric   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
4933ca95b02SDimitry Andric   /// Used to enable on-demand parsing of the VST.
4943ca95b02SDimitry Andric   uint64_t VSTOffset = 0;
4953ca95b02SDimitry Andric 
4963ca95b02SDimitry Andric   // Map to save ValueId to GUID association that was recorded in the
4973ca95b02SDimitry Andric   // ValueSymbolTable. It is used after the VST is parsed to convert
4983ca95b02SDimitry Andric   // call graph edges read from the function summary from referencing
4993ca95b02SDimitry Andric   // callees by their ValueId to using the GUID instead, which is how
5003ca95b02SDimitry Andric   // they are recorded in the summary index being built.
5013ca95b02SDimitry Andric   // We save a second GUID which is the same as the first one, but ignoring the
5023ca95b02SDimitry Andric   // linkage, i.e. for value other than local linkage they are identical.
5033ca95b02SDimitry Andric   DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
5043ca95b02SDimitry Andric       ValueIdToCallGraphGUIDMap;
5057d523365SDimitry Andric 
5067d523365SDimitry Andric   /// Map populated during module path string table parsing, from the
5077d523365SDimitry Andric   /// module ID to a string reference owned by the index's module
5083ca95b02SDimitry Andric   /// path string table, used to correlate with combined index
5097d523365SDimitry Andric   /// summary records.
5107d523365SDimitry Andric   DenseMap<uint64_t, StringRef> ModuleIdMap;
5117d523365SDimitry Andric 
5123ca95b02SDimitry Andric   /// Original source file name recorded in a bitcode record.
5133ca95b02SDimitry Andric   std::string SourceFileName;
5143ca95b02SDimitry Andric 
5157d523365SDimitry Andric public:
5167d523365SDimitry Andric   std::error_code error(const Twine &Message);
5177d523365SDimitry Andric 
5183ca95b02SDimitry Andric   ModuleSummaryIndexBitcodeReader(
5193ca95b02SDimitry Andric       MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5203ca95b02SDimitry Andric       bool CheckGlobalValSummaryPresenceOnly = false);
5213ca95b02SDimitry Andric   ~ModuleSummaryIndexBitcodeReader() { freeState(); }
5227d523365SDimitry Andric 
5237d523365SDimitry Andric   void freeState();
5247d523365SDimitry Andric 
5257d523365SDimitry Andric   void releaseBuffer();
5267d523365SDimitry Andric 
5273ca95b02SDimitry Andric   /// Check if the parser has encountered a summary section.
5283ca95b02SDimitry Andric   bool foundGlobalValSummary() { return SeenGlobalValSummary; }
5297d523365SDimitry Andric 
5307d523365SDimitry Andric   /// \brief Main interface to parsing a bitcode buffer.
5317d523365SDimitry Andric   /// \returns true if an error occurred.
5327d523365SDimitry Andric   std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
5333ca95b02SDimitry Andric                                         ModuleSummaryIndex *I);
5347d523365SDimitry Andric 
5357d523365SDimitry Andric private:
5367d523365SDimitry Andric   std::error_code parseModule();
5373ca95b02SDimitry Andric   std::error_code parseValueSymbolTable(
5383ca95b02SDimitry Andric       uint64_t Offset,
5393ca95b02SDimitry Andric       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
5407d523365SDimitry Andric   std::error_code parseEntireSummary();
5417d523365SDimitry Andric   std::error_code parseModuleStringTable();
5427d523365SDimitry Andric   std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
5437d523365SDimitry Andric   std::error_code initStreamFromBuffer();
5447d523365SDimitry Andric   std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
5453ca95b02SDimitry Andric   std::pair<GlobalValue::GUID, GlobalValue::GUID>
5463ca95b02SDimitry Andric   getGUIDFromValueId(unsigned ValueId);
5477d523365SDimitry Andric };
5483ca95b02SDimitry Andric } // end anonymous namespace
549ff0cc061SDimitry Andric 
55039d628a0SDimitry Andric BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
55139d628a0SDimitry Andric                                              DiagnosticSeverity Severity,
55239d628a0SDimitry Andric                                              const Twine &Msg)
55339d628a0SDimitry Andric     : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
55439d628a0SDimitry Andric 
55539d628a0SDimitry Andric void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
55639d628a0SDimitry Andric 
5573ca95b02SDimitry Andric static std::error_code error(const DiagnosticHandlerFunction &DiagnosticHandler,
55839d628a0SDimitry Andric                              std::error_code EC, const Twine &Message) {
55939d628a0SDimitry Andric   BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
56039d628a0SDimitry Andric   DiagnosticHandler(DI);
56139d628a0SDimitry Andric   return EC;
562dff0c46cSDimitry Andric }
56339d628a0SDimitry Andric 
5647d523365SDimitry Andric static std::error_code error(LLVMContext &Context, std::error_code EC,
565ff0cc061SDimitry Andric                              const Twine &Message) {
5667d523365SDimitry Andric   return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
5677d523365SDimitry Andric                Message);
5687d523365SDimitry Andric }
5697d523365SDimitry Andric 
5707d523365SDimitry Andric static std::error_code error(LLVMContext &Context, const Twine &Message) {
5717d523365SDimitry Andric   return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
5727d523365SDimitry Andric                Message);
573ff0cc061SDimitry Andric }
574ff0cc061SDimitry Andric 
5758f0fd8f6SDimitry Andric std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
5767d523365SDimitry Andric   if (!ProducerIdentification.empty()) {
5777d523365SDimitry Andric     return ::error(Context, make_error_code(E),
5787d523365SDimitry Andric                    Message + " (Producer: '" + ProducerIdentification +
5797d523365SDimitry Andric                        "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
5807d523365SDimitry Andric   }
5817d523365SDimitry Andric   return ::error(Context, make_error_code(E), Message);
58239d628a0SDimitry Andric }
58339d628a0SDimitry Andric 
5848f0fd8f6SDimitry Andric std::error_code BitcodeReader::error(const Twine &Message) {
5857d523365SDimitry Andric   if (!ProducerIdentification.empty()) {
5867d523365SDimitry Andric     return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
5877d523365SDimitry Andric                    Message + " (Producer: '" + ProducerIdentification +
5887d523365SDimitry Andric                        "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
5897d523365SDimitry Andric   }
5907d523365SDimitry Andric   return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
5917d523365SDimitry Andric                  Message);
59239d628a0SDimitry Andric }
59339d628a0SDimitry Andric 
5947d523365SDimitry Andric BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
5957d523365SDimitry Andric     : Context(Context), Buffer(Buffer), ValueList(Context),
5967d523365SDimitry Andric       MetadataList(Context) {}
59739d628a0SDimitry Andric 
5987d523365SDimitry Andric BitcodeReader::BitcodeReader(LLVMContext &Context)
5997d523365SDimitry Andric     : Context(Context), Buffer(nullptr), ValueList(Context),
6007d523365SDimitry Andric       MetadataList(Context) {}
60139d628a0SDimitry Andric 
60239d628a0SDimitry Andric std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
60339d628a0SDimitry Andric   if (WillMaterializeAllForwardRefs)
60439d628a0SDimitry Andric     return std::error_code();
60539d628a0SDimitry Andric 
60639d628a0SDimitry Andric   // Prevent recursion.
60739d628a0SDimitry Andric   WillMaterializeAllForwardRefs = true;
60839d628a0SDimitry Andric 
60939d628a0SDimitry Andric   while (!BasicBlockFwdRefQueue.empty()) {
61039d628a0SDimitry Andric     Function *F = BasicBlockFwdRefQueue.front();
61139d628a0SDimitry Andric     BasicBlockFwdRefQueue.pop_front();
61239d628a0SDimitry Andric     assert(F && "Expected valid function");
61339d628a0SDimitry Andric     if (!BasicBlockFwdRefs.count(F))
61439d628a0SDimitry Andric       // Already materialized.
61539d628a0SDimitry Andric       continue;
61639d628a0SDimitry Andric 
61739d628a0SDimitry Andric     // Check for a function that isn't materializable to prevent an infinite
61839d628a0SDimitry Andric     // loop.  When parsing a blockaddress stored in a global variable, there
61939d628a0SDimitry Andric     // isn't a trivial way to check if a function will have a body without a
62039d628a0SDimitry Andric     // linear search through FunctionsWithBodies, so just check it here.
62139d628a0SDimitry Andric     if (!F->isMaterializable())
6228f0fd8f6SDimitry Andric       return error("Never resolved function from blockaddress");
62339d628a0SDimitry Andric 
62439d628a0SDimitry Andric     // Try to materialize F.
62539d628a0SDimitry Andric     if (std::error_code EC = materialize(F))
62639d628a0SDimitry Andric       return EC;
62739d628a0SDimitry Andric   }
62839d628a0SDimitry Andric   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
62939d628a0SDimitry Andric 
63039d628a0SDimitry Andric   // Reset state.
63139d628a0SDimitry Andric   WillMaterializeAllForwardRefs = false;
63239d628a0SDimitry Andric   return std::error_code();
633dff0c46cSDimitry Andric }
634dff0c46cSDimitry Andric 
6358f0fd8f6SDimitry Andric void BitcodeReader::freeState() {
63691bc56edSDimitry Andric   Buffer = nullptr;
63717a519f9SDimitry Andric   std::vector<Type*>().swap(TypeList);
638f22ef01cSRoman Divacky   ValueList.clear();
6397d523365SDimitry Andric   MetadataList.clear();
64091bc56edSDimitry Andric   std::vector<Comdat *>().swap(ComdatList);
641f22ef01cSRoman Divacky 
642139f7f9bSDimitry Andric   std::vector<AttributeSet>().swap(MAttributes);
643f22ef01cSRoman Divacky   std::vector<BasicBlock*>().swap(FunctionBBs);
644f22ef01cSRoman Divacky   std::vector<Function*>().swap(FunctionsWithBodies);
645f22ef01cSRoman Divacky   DeferredFunctionInfo.clear();
646ff0cc061SDimitry Andric   DeferredMetadataInfo.clear();
647e580952dSDimitry Andric   MDKindMap.clear();
6483861d79fSDimitry Andric 
64939d628a0SDimitry Andric   assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
65039d628a0SDimitry Andric   BasicBlockFwdRefQueue.clear();
651f22ef01cSRoman Divacky }
652f22ef01cSRoman Divacky 
653f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
654f22ef01cSRoman Divacky //  Helper functions to implement forward reference resolution, etc.
655f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
656f22ef01cSRoman Divacky 
6578f0fd8f6SDimitry Andric /// Convert a string from a record into an std::string, return true on failure.
658f22ef01cSRoman Divacky template <typename StrTy>
6598f0fd8f6SDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
660f22ef01cSRoman Divacky                             StrTy &Result) {
661f22ef01cSRoman Divacky   if (Idx > Record.size())
662f22ef01cSRoman Divacky     return true;
663f22ef01cSRoman Divacky 
664f22ef01cSRoman Divacky   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
665f22ef01cSRoman Divacky     Result += (char)Record[i];
666f22ef01cSRoman Divacky   return false;
667f22ef01cSRoman Divacky }
668f22ef01cSRoman Divacky 
669ff0cc061SDimitry Andric static bool hasImplicitComdat(size_t Val) {
670ff0cc061SDimitry Andric   switch (Val) {
671ff0cc061SDimitry Andric   default:
672ff0cc061SDimitry Andric     return false;
673ff0cc061SDimitry Andric   case 1:  // Old WeakAnyLinkage
674ff0cc061SDimitry Andric   case 4:  // Old LinkOnceAnyLinkage
675ff0cc061SDimitry Andric   case 10: // Old WeakODRLinkage
676ff0cc061SDimitry Andric   case 11: // Old LinkOnceODRLinkage
677ff0cc061SDimitry Andric     return true;
678ff0cc061SDimitry Andric   }
679ff0cc061SDimitry Andric }
680ff0cc061SDimitry Andric 
68139d628a0SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
682f22ef01cSRoman Divacky   switch (Val) {
683f22ef01cSRoman Divacky   default: // Map unknown/new linkages to external
68439d628a0SDimitry Andric   case 0:
68539d628a0SDimitry Andric     return GlobalValue::ExternalLinkage;
68639d628a0SDimitry Andric   case 2:
68739d628a0SDimitry Andric     return GlobalValue::AppendingLinkage;
68839d628a0SDimitry Andric   case 3:
68939d628a0SDimitry Andric     return GlobalValue::InternalLinkage;
69039d628a0SDimitry Andric   case 5:
69139d628a0SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
69239d628a0SDimitry Andric   case 6:
69339d628a0SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
69439d628a0SDimitry Andric   case 7:
69539d628a0SDimitry Andric     return GlobalValue::ExternalWeakLinkage;
69639d628a0SDimitry Andric   case 8:
69739d628a0SDimitry Andric     return GlobalValue::CommonLinkage;
69839d628a0SDimitry Andric   case 9:
69939d628a0SDimitry Andric     return GlobalValue::PrivateLinkage;
70039d628a0SDimitry Andric   case 12:
70139d628a0SDimitry Andric     return GlobalValue::AvailableExternallyLinkage;
70291bc56edSDimitry Andric   case 13:
70391bc56edSDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
70491bc56edSDimitry Andric   case 14:
70591bc56edSDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
70639d628a0SDimitry Andric   case 15:
70739d628a0SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
708ff0cc061SDimitry Andric   case 1: // Old value with implicit comdat.
709ff0cc061SDimitry Andric   case 16:
710ff0cc061SDimitry Andric     return GlobalValue::WeakAnyLinkage;
711ff0cc061SDimitry Andric   case 10: // Old value with implicit comdat.
712ff0cc061SDimitry Andric   case 17:
713ff0cc061SDimitry Andric     return GlobalValue::WeakODRLinkage;
714ff0cc061SDimitry Andric   case 4: // Old value with implicit comdat.
715ff0cc061SDimitry Andric   case 18:
716ff0cc061SDimitry Andric     return GlobalValue::LinkOnceAnyLinkage;
717ff0cc061SDimitry Andric   case 11: // Old value with implicit comdat.
718ff0cc061SDimitry Andric   case 19:
719ff0cc061SDimitry Andric     return GlobalValue::LinkOnceODRLinkage;
720f22ef01cSRoman Divacky   }
721f22ef01cSRoman Divacky }
722f22ef01cSRoman Divacky 
7233ca95b02SDimitry Andric // Decode the flags for GlobalValue in the summary
7243ca95b02SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
7253ca95b02SDimitry Andric                                                             uint64_t Version) {
7263ca95b02SDimitry Andric   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
7273ca95b02SDimitry Andric   // like getDecodedLinkage() above. Any future change to the linkage enum and
7283ca95b02SDimitry Andric   // to getDecodedLinkage() will need to be taken into account here as above.
7293ca95b02SDimitry Andric   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
7303ca95b02SDimitry Andric   RawFlags = RawFlags >> 4;
7313ca95b02SDimitry Andric   auto HasSection = RawFlags & 0x1; // bool
7323ca95b02SDimitry Andric   return GlobalValueSummary::GVFlags(Linkage, HasSection);
7333ca95b02SDimitry Andric }
7343ca95b02SDimitry Andric 
7358f0fd8f6SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
736f22ef01cSRoman Divacky   switch (Val) {
737f22ef01cSRoman Divacky   default: // Map unknown visibilities to default.
738f22ef01cSRoman Divacky   case 0: return GlobalValue::DefaultVisibility;
739f22ef01cSRoman Divacky   case 1: return GlobalValue::HiddenVisibility;
740f22ef01cSRoman Divacky   case 2: return GlobalValue::ProtectedVisibility;
741f22ef01cSRoman Divacky   }
742f22ef01cSRoman Divacky }
743f22ef01cSRoman Divacky 
74491bc56edSDimitry Andric static GlobalValue::DLLStorageClassTypes
7458f0fd8f6SDimitry Andric getDecodedDLLStorageClass(unsigned Val) {
74691bc56edSDimitry Andric   switch (Val) {
74791bc56edSDimitry Andric   default: // Map unknown values to default.
74891bc56edSDimitry Andric   case 0: return GlobalValue::DefaultStorageClass;
74991bc56edSDimitry Andric   case 1: return GlobalValue::DLLImportStorageClass;
75091bc56edSDimitry Andric   case 2: return GlobalValue::DLLExportStorageClass;
75191bc56edSDimitry Andric   }
75291bc56edSDimitry Andric }
75391bc56edSDimitry Andric 
7548f0fd8f6SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
7557ae0e2c9SDimitry Andric   switch (Val) {
7567ae0e2c9SDimitry Andric     case 0: return GlobalVariable::NotThreadLocal;
7577ae0e2c9SDimitry Andric     default: // Map unknown non-zero value to general dynamic.
7587ae0e2c9SDimitry Andric     case 1: return GlobalVariable::GeneralDynamicTLSModel;
7597ae0e2c9SDimitry Andric     case 2: return GlobalVariable::LocalDynamicTLSModel;
7607ae0e2c9SDimitry Andric     case 3: return GlobalVariable::InitialExecTLSModel;
7617ae0e2c9SDimitry Andric     case 4: return GlobalVariable::LocalExecTLSModel;
7627ae0e2c9SDimitry Andric   }
7637ae0e2c9SDimitry Andric }
7647ae0e2c9SDimitry Andric 
7653ca95b02SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
7663ca95b02SDimitry Andric   switch (Val) {
7673ca95b02SDimitry Andric     default: // Map unknown to UnnamedAddr::None.
7683ca95b02SDimitry Andric     case 0: return GlobalVariable::UnnamedAddr::None;
7693ca95b02SDimitry Andric     case 1: return GlobalVariable::UnnamedAddr::Global;
7703ca95b02SDimitry Andric     case 2: return GlobalVariable::UnnamedAddr::Local;
7713ca95b02SDimitry Andric   }
7723ca95b02SDimitry Andric }
7733ca95b02SDimitry Andric 
7748f0fd8f6SDimitry Andric static int getDecodedCastOpcode(unsigned Val) {
775f22ef01cSRoman Divacky   switch (Val) {
776f22ef01cSRoman Divacky   default: return -1;
777f22ef01cSRoman Divacky   case bitc::CAST_TRUNC   : return Instruction::Trunc;
778f22ef01cSRoman Divacky   case bitc::CAST_ZEXT    : return Instruction::ZExt;
779f22ef01cSRoman Divacky   case bitc::CAST_SEXT    : return Instruction::SExt;
780f22ef01cSRoman Divacky   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
781f22ef01cSRoman Divacky   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
782f22ef01cSRoman Divacky   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
783f22ef01cSRoman Divacky   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
784f22ef01cSRoman Divacky   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
785f22ef01cSRoman Divacky   case bitc::CAST_FPEXT   : return Instruction::FPExt;
786f22ef01cSRoman Divacky   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
787f22ef01cSRoman Divacky   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
788f22ef01cSRoman Divacky   case bitc::CAST_BITCAST : return Instruction::BitCast;
789f785676fSDimitry Andric   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
790f22ef01cSRoman Divacky   }
791f22ef01cSRoman Divacky }
792ff0cc061SDimitry Andric 
7938f0fd8f6SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
794ff0cc061SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
795ff0cc061SDimitry Andric   // BinOps are only valid for int/fp or vector of int/fp types
796ff0cc061SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
797ff0cc061SDimitry Andric     return -1;
798ff0cc061SDimitry Andric 
799f22ef01cSRoman Divacky   switch (Val) {
800ff0cc061SDimitry Andric   default:
801ff0cc061SDimitry Andric     return -1;
802f22ef01cSRoman Divacky   case bitc::BINOP_ADD:
803ff0cc061SDimitry Andric     return IsFP ? Instruction::FAdd : Instruction::Add;
804f22ef01cSRoman Divacky   case bitc::BINOP_SUB:
805ff0cc061SDimitry Andric     return IsFP ? Instruction::FSub : Instruction::Sub;
806f22ef01cSRoman Divacky   case bitc::BINOP_MUL:
807ff0cc061SDimitry Andric     return IsFP ? Instruction::FMul : Instruction::Mul;
808ff0cc061SDimitry Andric   case bitc::BINOP_UDIV:
809ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::UDiv;
810f22ef01cSRoman Divacky   case bitc::BINOP_SDIV:
811ff0cc061SDimitry Andric     return IsFP ? Instruction::FDiv : Instruction::SDiv;
812ff0cc061SDimitry Andric   case bitc::BINOP_UREM:
813ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::URem;
814f22ef01cSRoman Divacky   case bitc::BINOP_SREM:
815ff0cc061SDimitry Andric     return IsFP ? Instruction::FRem : Instruction::SRem;
816ff0cc061SDimitry Andric   case bitc::BINOP_SHL:
817ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::Shl;
818ff0cc061SDimitry Andric   case bitc::BINOP_LSHR:
819ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::LShr;
820ff0cc061SDimitry Andric   case bitc::BINOP_ASHR:
821ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::AShr;
822ff0cc061SDimitry Andric   case bitc::BINOP_AND:
823ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::And;
824ff0cc061SDimitry Andric   case bitc::BINOP_OR:
825ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::Or;
826ff0cc061SDimitry Andric   case bitc::BINOP_XOR:
827ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::Xor;
828f22ef01cSRoman Divacky   }
829f22ef01cSRoman Divacky }
830f22ef01cSRoman Divacky 
8318f0fd8f6SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
8326122f3e6SDimitry Andric   switch (Val) {
8336122f3e6SDimitry Andric   default: return AtomicRMWInst::BAD_BINOP;
8346122f3e6SDimitry Andric   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
8356122f3e6SDimitry Andric   case bitc::RMW_ADD: return AtomicRMWInst::Add;
8366122f3e6SDimitry Andric   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
8376122f3e6SDimitry Andric   case bitc::RMW_AND: return AtomicRMWInst::And;
8386122f3e6SDimitry Andric   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
8396122f3e6SDimitry Andric   case bitc::RMW_OR: return AtomicRMWInst::Or;
8406122f3e6SDimitry Andric   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
8416122f3e6SDimitry Andric   case bitc::RMW_MAX: return AtomicRMWInst::Max;
8426122f3e6SDimitry Andric   case bitc::RMW_MIN: return AtomicRMWInst::Min;
8436122f3e6SDimitry Andric   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
8446122f3e6SDimitry Andric   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
8456122f3e6SDimitry Andric   }
8466122f3e6SDimitry Andric }
8476122f3e6SDimitry Andric 
8488f0fd8f6SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) {
8496122f3e6SDimitry Andric   switch (Val) {
8503ca95b02SDimitry Andric   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
8513ca95b02SDimitry Andric   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
8523ca95b02SDimitry Andric   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
8533ca95b02SDimitry Andric   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
8543ca95b02SDimitry Andric   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
8553ca95b02SDimitry Andric   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
8566122f3e6SDimitry Andric   default: // Map unknown orderings to sequentially-consistent.
8573ca95b02SDimitry Andric   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
8586122f3e6SDimitry Andric   }
8596122f3e6SDimitry Andric }
8606122f3e6SDimitry Andric 
8618f0fd8f6SDimitry Andric static SynchronizationScope getDecodedSynchScope(unsigned Val) {
8626122f3e6SDimitry Andric   switch (Val) {
8636122f3e6SDimitry Andric   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
8646122f3e6SDimitry Andric   default: // Map unknown scopes to cross-thread.
8656122f3e6SDimitry Andric   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
8666122f3e6SDimitry Andric   }
8676122f3e6SDimitry Andric }
8686122f3e6SDimitry Andric 
86991bc56edSDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
87091bc56edSDimitry Andric   switch (Val) {
87191bc56edSDimitry Andric   default: // Map unknown selection kinds to any.
87291bc56edSDimitry Andric   case bitc::COMDAT_SELECTION_KIND_ANY:
87391bc56edSDimitry Andric     return Comdat::Any;
87491bc56edSDimitry Andric   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
87591bc56edSDimitry Andric     return Comdat::ExactMatch;
87691bc56edSDimitry Andric   case bitc::COMDAT_SELECTION_KIND_LARGEST:
87791bc56edSDimitry Andric     return Comdat::Largest;
87891bc56edSDimitry Andric   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
87991bc56edSDimitry Andric     return Comdat::NoDuplicates;
88091bc56edSDimitry Andric   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
88191bc56edSDimitry Andric     return Comdat::SameSize;
88291bc56edSDimitry Andric   }
88391bc56edSDimitry Andric }
88491bc56edSDimitry Andric 
885875ed548SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
886875ed548SDimitry Andric   FastMathFlags FMF;
887875ed548SDimitry Andric   if (0 != (Val & FastMathFlags::UnsafeAlgebra))
888875ed548SDimitry Andric     FMF.setUnsafeAlgebra();
889875ed548SDimitry Andric   if (0 != (Val & FastMathFlags::NoNaNs))
890875ed548SDimitry Andric     FMF.setNoNaNs();
891875ed548SDimitry Andric   if (0 != (Val & FastMathFlags::NoInfs))
892875ed548SDimitry Andric     FMF.setNoInfs();
893875ed548SDimitry Andric   if (0 != (Val & FastMathFlags::NoSignedZeros))
894875ed548SDimitry Andric     FMF.setNoSignedZeros();
895875ed548SDimitry Andric   if (0 != (Val & FastMathFlags::AllowReciprocal))
896875ed548SDimitry Andric     FMF.setAllowReciprocal();
897875ed548SDimitry Andric   return FMF;
898875ed548SDimitry Andric }
899875ed548SDimitry Andric 
9008f0fd8f6SDimitry Andric static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
90191bc56edSDimitry Andric   switch (Val) {
90291bc56edSDimitry Andric   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
90391bc56edSDimitry Andric   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
90491bc56edSDimitry Andric   }
90591bc56edSDimitry Andric }
90691bc56edSDimitry Andric 
907f22ef01cSRoman Divacky namespace llvm {
908f22ef01cSRoman Divacky namespace {
9098f0fd8f6SDimitry Andric /// \brief A class for maintaining the slot number definition
910f22ef01cSRoman Divacky /// as a placeholder for the actual definition for forward constants defs.
911f22ef01cSRoman Divacky class ConstantPlaceHolder : public ConstantExpr {
912ff0cc061SDimitry Andric   void operator=(const ConstantPlaceHolder &) = delete;
9138f0fd8f6SDimitry Andric 
914f22ef01cSRoman Divacky public:
915f22ef01cSRoman Divacky   // allocate space for exactly one operand
9168f0fd8f6SDimitry Andric   void *operator new(size_t s) { return User::operator new(s, 1); }
9176122f3e6SDimitry Andric   explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
918f22ef01cSRoman Divacky       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
919f22ef01cSRoman Divacky     Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
920f22ef01cSRoman Divacky   }
921f22ef01cSRoman Divacky 
9228f0fd8f6SDimitry Andric   /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
923f22ef01cSRoman Divacky   static bool classof(const Value *V) {
924f22ef01cSRoman Divacky     return isa<ConstantExpr>(V) &&
925f22ef01cSRoman Divacky            cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
926f22ef01cSRoman Divacky   }
927f22ef01cSRoman Divacky 
928f22ef01cSRoman Divacky   /// Provide fast operand accessors
92939d628a0SDimitry Andric   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
930f22ef01cSRoman Divacky };
9313ca95b02SDimitry Andric } // end anonymous namespace
932f22ef01cSRoman Divacky 
933f22ef01cSRoman Divacky // FIXME: can we inherit this from ConstantExpr?
934f22ef01cSRoman Divacky template <>
9352754fe60SDimitry Andric struct OperandTraits<ConstantPlaceHolder> :
9362754fe60SDimitry Andric   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
937f22ef01cSRoman Divacky };
93839d628a0SDimitry Andric DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
9393ca95b02SDimitry Andric } // end namespace llvm
940f22ef01cSRoman Divacky 
9418f0fd8f6SDimitry Andric void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
942f22ef01cSRoman Divacky   if (Idx == size()) {
943f22ef01cSRoman Divacky     push_back(V);
944f22ef01cSRoman Divacky     return;
945f22ef01cSRoman Divacky   }
946f22ef01cSRoman Divacky 
947f22ef01cSRoman Divacky   if (Idx >= size())
948f22ef01cSRoman Divacky     resize(Idx+1);
949f22ef01cSRoman Divacky 
950f22ef01cSRoman Divacky   WeakVH &OldV = ValuePtrs[Idx];
95191bc56edSDimitry Andric   if (!OldV) {
952f22ef01cSRoman Divacky     OldV = V;
953f22ef01cSRoman Divacky     return;
954f22ef01cSRoman Divacky   }
955f22ef01cSRoman Divacky 
956f22ef01cSRoman Divacky   // Handle constants and non-constants (e.g. instrs) differently for
957f22ef01cSRoman Divacky   // efficiency.
958f22ef01cSRoman Divacky   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
959f22ef01cSRoman Divacky     ResolveConstants.push_back(std::make_pair(PHC, Idx));
960f22ef01cSRoman Divacky     OldV = V;
961f22ef01cSRoman Divacky   } else {
962f22ef01cSRoman Divacky     // If there was a forward reference to this value, replace it.
963f22ef01cSRoman Divacky     Value *PrevVal = OldV;
964f22ef01cSRoman Divacky     OldV->replaceAllUsesWith(V);
965f22ef01cSRoman Divacky     delete PrevVal;
966f22ef01cSRoman Divacky   }
967f22ef01cSRoman Divacky }
968f22ef01cSRoman Divacky 
969f22ef01cSRoman Divacky Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
9706122f3e6SDimitry Andric                                                     Type *Ty) {
971f22ef01cSRoman Divacky   if (Idx >= size())
972f22ef01cSRoman Divacky     resize(Idx + 1);
973f22ef01cSRoman Divacky 
974f22ef01cSRoman Divacky   if (Value *V = ValuePtrs[Idx]) {
975ff0cc061SDimitry Andric     if (Ty != V->getType())
976ff0cc061SDimitry Andric       report_fatal_error("Type mismatch in constant table!");
977f22ef01cSRoman Divacky     return cast<Constant>(V);
978f22ef01cSRoman Divacky   }
979f22ef01cSRoman Divacky 
980f22ef01cSRoman Divacky   // Create and return a placeholder, which will later be RAUW'd.
981f22ef01cSRoman Divacky   Constant *C = new ConstantPlaceHolder(Ty, Context);
982f22ef01cSRoman Divacky   ValuePtrs[Idx] = C;
983f22ef01cSRoman Divacky   return C;
984f22ef01cSRoman Divacky }
985f22ef01cSRoman Divacky 
9866122f3e6SDimitry Andric Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
987ff0cc061SDimitry Andric   // Bail out for a clearly invalid value. This would make us call resize(0)
988ff0cc061SDimitry Andric   if (Idx == UINT_MAX)
989ff0cc061SDimitry Andric     return nullptr;
990ff0cc061SDimitry Andric 
991f22ef01cSRoman Divacky   if (Idx >= size())
992f22ef01cSRoman Divacky     resize(Idx + 1);
993f22ef01cSRoman Divacky 
994f22ef01cSRoman Divacky   if (Value *V = ValuePtrs[Idx]) {
995ff0cc061SDimitry Andric     // If the types don't match, it's invalid.
996ff0cc061SDimitry Andric     if (Ty && Ty != V->getType())
997ff0cc061SDimitry Andric       return nullptr;
998f22ef01cSRoman Divacky     return V;
999f22ef01cSRoman Divacky   }
1000f22ef01cSRoman Divacky 
1001f22ef01cSRoman Divacky   // No type specified, must be invalid reference.
100291bc56edSDimitry Andric   if (!Ty) return nullptr;
1003f22ef01cSRoman Divacky 
1004f22ef01cSRoman Divacky   // Create and return a placeholder, which will later be RAUW'd.
1005f22ef01cSRoman Divacky   Value *V = new Argument(Ty);
1006f22ef01cSRoman Divacky   ValuePtrs[Idx] = V;
1007f22ef01cSRoman Divacky   return V;
1008f22ef01cSRoman Divacky }
1009f22ef01cSRoman Divacky 
10108f0fd8f6SDimitry Andric /// Once all constants are read, this method bulk resolves any forward
10118f0fd8f6SDimitry Andric /// references.  The idea behind this is that we sometimes get constants (such
10128f0fd8f6SDimitry Andric /// as large arrays) which reference *many* forward ref constants.  Replacing
10138f0fd8f6SDimitry Andric /// each of these causes a lot of thrashing when building/reuniquing the
10148f0fd8f6SDimitry Andric /// constant.  Instead of doing this, we look at all the uses and rewrite all
10158f0fd8f6SDimitry Andric /// the place holders at once for any constant that uses a placeholder.
10168f0fd8f6SDimitry Andric void BitcodeReaderValueList::resolveConstantForwardRefs() {
1017f22ef01cSRoman Divacky   // Sort the values by-pointer so that they are efficient to look up with a
1018f22ef01cSRoman Divacky   // binary search.
1019f22ef01cSRoman Divacky   std::sort(ResolveConstants.begin(), ResolveConstants.end());
1020f22ef01cSRoman Divacky 
1021f22ef01cSRoman Divacky   SmallVector<Constant*, 64> NewOps;
1022f22ef01cSRoman Divacky 
1023f22ef01cSRoman Divacky   while (!ResolveConstants.empty()) {
1024f22ef01cSRoman Divacky     Value *RealVal = operator[](ResolveConstants.back().second);
1025f22ef01cSRoman Divacky     Constant *Placeholder = ResolveConstants.back().first;
1026f22ef01cSRoman Divacky     ResolveConstants.pop_back();
1027f22ef01cSRoman Divacky 
1028f22ef01cSRoman Divacky     // Loop over all users of the placeholder, updating them to reference the
1029f22ef01cSRoman Divacky     // new value.  If they reference more than one placeholder, update them all
1030f22ef01cSRoman Divacky     // at once.
1031f22ef01cSRoman Divacky     while (!Placeholder->use_empty()) {
103291bc56edSDimitry Andric       auto UI = Placeholder->user_begin();
1033ffd1746dSEd Schouten       User *U = *UI;
1034f22ef01cSRoman Divacky 
1035f22ef01cSRoman Divacky       // If the using object isn't uniqued, just update the operands.  This
1036f22ef01cSRoman Divacky       // handles instructions and initializers for global variables.
1037ffd1746dSEd Schouten       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
1038f22ef01cSRoman Divacky         UI.getUse().set(RealVal);
1039f22ef01cSRoman Divacky         continue;
1040f22ef01cSRoman Divacky       }
1041f22ef01cSRoman Divacky 
1042f22ef01cSRoman Divacky       // Otherwise, we have a constant that uses the placeholder.  Replace that
1043f22ef01cSRoman Divacky       // constant with a new constant that has *all* placeholder uses updated.
1044ffd1746dSEd Schouten       Constant *UserC = cast<Constant>(U);
1045f22ef01cSRoman Divacky       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1046f22ef01cSRoman Divacky            I != E; ++I) {
1047f22ef01cSRoman Divacky         Value *NewOp;
1048f22ef01cSRoman Divacky         if (!isa<ConstantPlaceHolder>(*I)) {
1049f22ef01cSRoman Divacky           // Not a placeholder reference.
1050f22ef01cSRoman Divacky           NewOp = *I;
1051f22ef01cSRoman Divacky         } else if (*I == Placeholder) {
1052f22ef01cSRoman Divacky           // Common case is that it just references this one placeholder.
1053f22ef01cSRoman Divacky           NewOp = RealVal;
1054f22ef01cSRoman Divacky         } else {
1055f22ef01cSRoman Divacky           // Otherwise, look up the placeholder in ResolveConstants.
1056f22ef01cSRoman Divacky           ResolveConstantsTy::iterator It =
1057f22ef01cSRoman Divacky             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1058f22ef01cSRoman Divacky                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
1059f22ef01cSRoman Divacky                                                             0));
1060f22ef01cSRoman Divacky           assert(It != ResolveConstants.end() && It->first == *I);
1061f22ef01cSRoman Divacky           NewOp = operator[](It->second);
1062f22ef01cSRoman Divacky         }
1063f22ef01cSRoman Divacky 
1064f22ef01cSRoman Divacky         NewOps.push_back(cast<Constant>(NewOp));
1065f22ef01cSRoman Divacky       }
1066f22ef01cSRoman Divacky 
1067f22ef01cSRoman Divacky       // Make the new constant.
1068f22ef01cSRoman Divacky       Constant *NewC;
1069f22ef01cSRoman Divacky       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
107017a519f9SDimitry Andric         NewC = ConstantArray::get(UserCA->getType(), NewOps);
1071f22ef01cSRoman Divacky       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
107217a519f9SDimitry Andric         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1073f22ef01cSRoman Divacky       } else if (isa<ConstantVector>(UserC)) {
10742754fe60SDimitry Andric         NewC = ConstantVector::get(NewOps);
1075f22ef01cSRoman Divacky       } else {
1076f22ef01cSRoman Divacky         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
10773b0f4066SDimitry Andric         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1078f22ef01cSRoman Divacky       }
1079f22ef01cSRoman Divacky 
1080f22ef01cSRoman Divacky       UserC->replaceAllUsesWith(NewC);
1081f22ef01cSRoman Divacky       UserC->destroyConstant();
1082f22ef01cSRoman Divacky       NewOps.clear();
1083f22ef01cSRoman Divacky     }
1084f22ef01cSRoman Divacky 
1085f22ef01cSRoman Divacky     // Update all ValueHandles, they should be the only users at this point.
1086f22ef01cSRoman Divacky     Placeholder->replaceAllUsesWith(RealVal);
1087f22ef01cSRoman Divacky     delete Placeholder;
1088f22ef01cSRoman Divacky   }
1089f22ef01cSRoman Divacky }
1090f22ef01cSRoman Divacky 
10917d523365SDimitry Andric void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
1092f22ef01cSRoman Divacky   if (Idx == size()) {
109339d628a0SDimitry Andric     push_back(MD);
1094f22ef01cSRoman Divacky     return;
1095f22ef01cSRoman Divacky   }
1096f22ef01cSRoman Divacky 
1097f22ef01cSRoman Divacky   if (Idx >= size())
1098f22ef01cSRoman Divacky     resize(Idx+1);
1099f22ef01cSRoman Divacky 
11007d523365SDimitry Andric   TrackingMDRef &OldMD = MetadataPtrs[Idx];
110139d628a0SDimitry Andric   if (!OldMD) {
110239d628a0SDimitry Andric     OldMD.reset(MD);
1103f22ef01cSRoman Divacky     return;
1104f22ef01cSRoman Divacky   }
1105f22ef01cSRoman Divacky 
1106f22ef01cSRoman Divacky   // If there was a forward reference to this value, replace it.
1107ff0cc061SDimitry Andric   TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
110839d628a0SDimitry Andric   PrevMD->replaceAllUsesWith(MD);
110939d628a0SDimitry Andric   --NumFwdRefs;
1110f22ef01cSRoman Divacky }
1111f22ef01cSRoman Divacky 
11123ca95b02SDimitry Andric Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
1113f22ef01cSRoman Divacky   if (Idx >= size())
1114f22ef01cSRoman Divacky     resize(Idx + 1);
1115f22ef01cSRoman Divacky 
11167d523365SDimitry Andric   if (Metadata *MD = MetadataPtrs[Idx])
111739d628a0SDimitry Andric     return MD;
1118f22ef01cSRoman Divacky 
1119b09980d1SDimitry Andric   // Track forward refs to be resolved later.
1120b09980d1SDimitry Andric   if (AnyFwdRefs) {
1121b09980d1SDimitry Andric     MinFwdRef = std::min(MinFwdRef, Idx);
1122b09980d1SDimitry Andric     MaxFwdRef = std::max(MaxFwdRef, Idx);
1123b09980d1SDimitry Andric   } else {
112439d628a0SDimitry Andric     AnyFwdRefs = true;
1125b09980d1SDimitry Andric     MinFwdRef = MaxFwdRef = Idx;
1126b09980d1SDimitry Andric   }
112739d628a0SDimitry Andric   ++NumFwdRefs;
1128b09980d1SDimitry Andric 
1129b09980d1SDimitry Andric   // Create and return a placeholder, which will later be RAUW'd.
1130ff0cc061SDimitry Andric   Metadata *MD = MDNode::getTemporary(Context, None).release();
11317d523365SDimitry Andric   MetadataPtrs[Idx].reset(MD);
113239d628a0SDimitry Andric   return MD;
113339d628a0SDimitry Andric }
113439d628a0SDimitry Andric 
11353ca95b02SDimitry Andric Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
11363ca95b02SDimitry Andric   Metadata *MD = lookup(Idx);
11373ca95b02SDimitry Andric   if (auto *N = dyn_cast_or_null<MDNode>(MD))
11383ca95b02SDimitry Andric     if (!N->isResolved())
11393ca95b02SDimitry Andric       return nullptr;
11403ca95b02SDimitry Andric   return MD;
11413ca95b02SDimitry Andric }
114239d628a0SDimitry Andric 
11433ca95b02SDimitry Andric MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
11443ca95b02SDimitry Andric   return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
11453ca95b02SDimitry Andric }
11463ca95b02SDimitry Andric 
11473ca95b02SDimitry Andric void BitcodeReaderMetadataList::tryToResolveCycles() {
114839d628a0SDimitry Andric   if (NumFwdRefs)
114939d628a0SDimitry Andric     // Still forward references... can't resolve cycles.
115039d628a0SDimitry Andric     return;
115139d628a0SDimitry Andric 
11523ca95b02SDimitry Andric   bool DidReplaceTypeRefs = false;
11533ca95b02SDimitry Andric 
11543ca95b02SDimitry Andric   // Give up on finding a full definition for any forward decls that remain.
11553ca95b02SDimitry Andric   for (const auto &Ref : OldTypeRefs.FwdDecls)
11563ca95b02SDimitry Andric     OldTypeRefs.Final.insert(Ref);
11573ca95b02SDimitry Andric   OldTypeRefs.FwdDecls.clear();
11583ca95b02SDimitry Andric 
11593ca95b02SDimitry Andric   // Upgrade from old type ref arrays.  In strange cases, this could add to
11603ca95b02SDimitry Andric   // OldTypeRefs.Unknown.
11613ca95b02SDimitry Andric   for (const auto &Array : OldTypeRefs.Arrays) {
11623ca95b02SDimitry Andric     DidReplaceTypeRefs = true;
11633ca95b02SDimitry Andric     Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
11643ca95b02SDimitry Andric   }
11653ca95b02SDimitry Andric   OldTypeRefs.Arrays.clear();
11663ca95b02SDimitry Andric 
11673ca95b02SDimitry Andric   // Replace old string-based type refs with the resolved node, if possible.
11683ca95b02SDimitry Andric   // If we haven't seen the node, leave it to the verifier to complain about
11693ca95b02SDimitry Andric   // the invalid string reference.
11703ca95b02SDimitry Andric   for (const auto &Ref : OldTypeRefs.Unknown) {
11713ca95b02SDimitry Andric     DidReplaceTypeRefs = true;
11723ca95b02SDimitry Andric     if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
11733ca95b02SDimitry Andric       Ref.second->replaceAllUsesWith(CT);
11743ca95b02SDimitry Andric     else
11753ca95b02SDimitry Andric       Ref.second->replaceAllUsesWith(Ref.first);
11763ca95b02SDimitry Andric   }
11773ca95b02SDimitry Andric   OldTypeRefs.Unknown.clear();
11783ca95b02SDimitry Andric 
11793ca95b02SDimitry Andric   // Make sure all the upgraded types are resolved.
11803ca95b02SDimitry Andric   if (DidReplaceTypeRefs) {
11813ca95b02SDimitry Andric     AnyFwdRefs = true;
11823ca95b02SDimitry Andric     MinFwdRef = 0;
11833ca95b02SDimitry Andric     MaxFwdRef = MetadataPtrs.size() - 1;
11843ca95b02SDimitry Andric   }
11853ca95b02SDimitry Andric 
11863ca95b02SDimitry Andric   if (!AnyFwdRefs)
11873ca95b02SDimitry Andric     // Nothing to do.
11883ca95b02SDimitry Andric     return;
11893ca95b02SDimitry Andric 
119039d628a0SDimitry Andric   // Resolve any cycles.
1191b09980d1SDimitry Andric   for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
11927d523365SDimitry Andric     auto &MD = MetadataPtrs[I];
1193ff0cc061SDimitry Andric     auto *N = dyn_cast_or_null<MDNode>(MD);
1194ff0cc061SDimitry Andric     if (!N)
1195ff0cc061SDimitry Andric       continue;
1196ff0cc061SDimitry Andric 
1197ff0cc061SDimitry Andric     assert(!N->isTemporary() && "Unexpected forward reference");
119839d628a0SDimitry Andric     N->resolveCycles();
119939d628a0SDimitry Andric   }
1200b09980d1SDimitry Andric 
1201b09980d1SDimitry Andric   // Make sure we return early again until there's another forward ref.
1202b09980d1SDimitry Andric   AnyFwdRefs = false;
1203f22ef01cSRoman Divacky }
1204f22ef01cSRoman Divacky 
12053ca95b02SDimitry Andric void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
12063ca95b02SDimitry Andric                                            DICompositeType &CT) {
12073ca95b02SDimitry Andric   assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
12083ca95b02SDimitry Andric   if (CT.isForwardDecl())
12093ca95b02SDimitry Andric     OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
12103ca95b02SDimitry Andric   else
12113ca95b02SDimitry Andric     OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
12123ca95b02SDimitry Andric }
12133ca95b02SDimitry Andric 
12143ca95b02SDimitry Andric Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
12153ca95b02SDimitry Andric   auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
12163ca95b02SDimitry Andric   if (LLVM_LIKELY(!UUID))
12173ca95b02SDimitry Andric     return MaybeUUID;
12183ca95b02SDimitry Andric 
12193ca95b02SDimitry Andric   if (auto *CT = OldTypeRefs.Final.lookup(UUID))
12203ca95b02SDimitry Andric     return CT;
12213ca95b02SDimitry Andric 
12223ca95b02SDimitry Andric   auto &Ref = OldTypeRefs.Unknown[UUID];
12233ca95b02SDimitry Andric   if (!Ref)
12243ca95b02SDimitry Andric     Ref = MDNode::getTemporary(Context, None);
12253ca95b02SDimitry Andric   return Ref.get();
12263ca95b02SDimitry Andric }
12273ca95b02SDimitry Andric 
12283ca95b02SDimitry Andric Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
12293ca95b02SDimitry Andric   auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
12303ca95b02SDimitry Andric   if (!Tuple || Tuple->isDistinct())
12313ca95b02SDimitry Andric     return MaybeTuple;
12323ca95b02SDimitry Andric 
12333ca95b02SDimitry Andric   // Look through the array immediately if possible.
12343ca95b02SDimitry Andric   if (!Tuple->isTemporary())
12353ca95b02SDimitry Andric     return resolveTypeRefArray(Tuple);
12363ca95b02SDimitry Andric 
12373ca95b02SDimitry Andric   // Create and return a placeholder to use for now.  Eventually
12383ca95b02SDimitry Andric   // resolveTypeRefArrays() will be resolve this forward reference.
12393ca95b02SDimitry Andric   OldTypeRefs.Arrays.emplace_back(
12403ca95b02SDimitry Andric       std::piecewise_construct, std::forward_as_tuple(Tuple),
12413ca95b02SDimitry Andric       std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
12423ca95b02SDimitry Andric   return OldTypeRefs.Arrays.back().second.get();
12433ca95b02SDimitry Andric }
12443ca95b02SDimitry Andric 
12453ca95b02SDimitry Andric Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
12463ca95b02SDimitry Andric   auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
12473ca95b02SDimitry Andric   if (!Tuple || Tuple->isDistinct())
12483ca95b02SDimitry Andric     return MaybeTuple;
12493ca95b02SDimitry Andric 
12503ca95b02SDimitry Andric   // Look through the DITypeRefArray, upgrading each DITypeRef.
12513ca95b02SDimitry Andric   SmallVector<Metadata *, 32> Ops;
12523ca95b02SDimitry Andric   Ops.reserve(Tuple->getNumOperands());
12533ca95b02SDimitry Andric   for (Metadata *MD : Tuple->operands())
12543ca95b02SDimitry Andric     Ops.push_back(upgradeTypeRef(MD));
12553ca95b02SDimitry Andric 
12563ca95b02SDimitry Andric   return MDTuple::get(Context, Ops);
12573ca95b02SDimitry Andric }
12583ca95b02SDimitry Andric 
125917a519f9SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) {
126017a519f9SDimitry Andric   // The type table size is always specified correctly.
126117a519f9SDimitry Andric   if (ID >= TypeList.size())
126291bc56edSDimitry Andric     return nullptr;
1263f22ef01cSRoman Divacky 
126417a519f9SDimitry Andric   if (Type *Ty = TypeList[ID])
126517a519f9SDimitry Andric     return Ty;
126617a519f9SDimitry Andric 
126717a519f9SDimitry Andric   // If we have a forward reference, the only possible case is when it is to a
126817a519f9SDimitry Andric   // named struct.  Just create a placeholder for now.
126939d628a0SDimitry Andric   return TypeList[ID] = createIdentifiedStructType(Context);
127039d628a0SDimitry Andric }
127139d628a0SDimitry Andric 
127239d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
127339d628a0SDimitry Andric                                                       StringRef Name) {
127439d628a0SDimitry Andric   auto *Ret = StructType::create(Context, Name);
127539d628a0SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
127639d628a0SDimitry Andric   return Ret;
127739d628a0SDimitry Andric }
127839d628a0SDimitry Andric 
127939d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
128039d628a0SDimitry Andric   auto *Ret = StructType::create(Context);
128139d628a0SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
128239d628a0SDimitry Andric   return Ret;
1283f22ef01cSRoman Divacky }
1284f22ef01cSRoman Divacky 
1285f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1286f22ef01cSRoman Divacky //  Functions for parsing blocks from the bitcode file
1287f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1288f22ef01cSRoman Divacky 
1289139f7f9bSDimitry Andric 
1290139f7f9bSDimitry Andric /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1291139f7f9bSDimitry Andric /// been decoded from the given integer. This function must stay in sync with
1292139f7f9bSDimitry Andric /// 'encodeLLVMAttributesForBitcode'.
1293139f7f9bSDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1294139f7f9bSDimitry Andric                                            uint64_t EncodedAttrs) {
1295139f7f9bSDimitry Andric   // FIXME: Remove in 4.0.
1296139f7f9bSDimitry Andric 
1297139f7f9bSDimitry Andric   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
1298139f7f9bSDimitry Andric   // the bits above 31 down by 11 bits.
1299139f7f9bSDimitry Andric   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1300139f7f9bSDimitry Andric   assert((!Alignment || isPowerOf2_32(Alignment)) &&
1301139f7f9bSDimitry Andric          "Alignment must be a power of two.");
1302139f7f9bSDimitry Andric 
1303139f7f9bSDimitry Andric   if (Alignment)
1304139f7f9bSDimitry Andric     B.addAlignmentAttr(Alignment);
1305139f7f9bSDimitry Andric   B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1306139f7f9bSDimitry Andric                 (EncodedAttrs & 0xffff));
1307139f7f9bSDimitry Andric }
1308139f7f9bSDimitry Andric 
13098f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseAttributeBlock() {
1310f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
13118f0fd8f6SDimitry Andric     return error("Invalid record");
1312f22ef01cSRoman Divacky 
1313f22ef01cSRoman Divacky   if (!MAttributes.empty())
13148f0fd8f6SDimitry Andric     return error("Invalid multiple blocks");
1315f22ef01cSRoman Divacky 
1316f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
1317f22ef01cSRoman Divacky 
1318139f7f9bSDimitry Andric   SmallVector<AttributeSet, 8> Attrs;
1319f22ef01cSRoman Divacky 
1320f22ef01cSRoman Divacky   // Read all the records.
1321f22ef01cSRoman Divacky   while (1) {
1322139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1323139f7f9bSDimitry Andric 
1324139f7f9bSDimitry Andric     switch (Entry.Kind) {
1325139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1326139f7f9bSDimitry Andric     case BitstreamEntry::Error:
13278f0fd8f6SDimitry Andric       return error("Malformed block");
1328139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
132991bc56edSDimitry Andric       return std::error_code();
1330139f7f9bSDimitry Andric     case BitstreamEntry::Record:
1331139f7f9bSDimitry Andric       // The interesting case.
1332139f7f9bSDimitry Andric       break;
1333f22ef01cSRoman Divacky     }
1334f22ef01cSRoman Divacky 
1335f22ef01cSRoman Divacky     // Read a record.
1336f22ef01cSRoman Divacky     Record.clear();
1337139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
1338f22ef01cSRoman Divacky     default:  // Default behavior: ignore.
1339f22ef01cSRoman Divacky       break;
1340139f7f9bSDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1341139f7f9bSDimitry Andric       // FIXME: Remove in 4.0.
1342f22ef01cSRoman Divacky       if (Record.size() & 1)
13438f0fd8f6SDimitry Andric         return error("Invalid record");
1344f22ef01cSRoman Divacky 
1345f22ef01cSRoman Divacky       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1346139f7f9bSDimitry Andric         AttrBuilder B;
1347139f7f9bSDimitry Andric         decodeLLVMAttributesForBitcode(B, Record[i+1]);
1348139f7f9bSDimitry Andric         Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1349f22ef01cSRoman Divacky       }
1350f22ef01cSRoman Divacky 
1351139f7f9bSDimitry Andric       MAttributes.push_back(AttributeSet::get(Context, Attrs));
1352f22ef01cSRoman Divacky       Attrs.clear();
1353f22ef01cSRoman Divacky       break;
1354f22ef01cSRoman Divacky     }
1355139f7f9bSDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1356139f7f9bSDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1357139f7f9bSDimitry Andric         Attrs.push_back(MAttributeGroups[Record[i]]);
1358139f7f9bSDimitry Andric 
1359139f7f9bSDimitry Andric       MAttributes.push_back(AttributeSet::get(Context, Attrs));
1360139f7f9bSDimitry Andric       Attrs.clear();
1361139f7f9bSDimitry Andric       break;
1362139f7f9bSDimitry Andric     }
1363139f7f9bSDimitry Andric     }
1364139f7f9bSDimitry Andric   }
1365139f7f9bSDimitry Andric }
1366139f7f9bSDimitry Andric 
1367f785676fSDimitry Andric // Returns Attribute::None on unrecognized codes.
13688f0fd8f6SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1369f785676fSDimitry Andric   switch (Code) {
1370f785676fSDimitry Andric   default:
1371f785676fSDimitry Andric     return Attribute::None;
1372f785676fSDimitry Andric   case bitc::ATTR_KIND_ALIGNMENT:
1373f785676fSDimitry Andric     return Attribute::Alignment;
1374f785676fSDimitry Andric   case bitc::ATTR_KIND_ALWAYS_INLINE:
1375f785676fSDimitry Andric     return Attribute::AlwaysInline;
1376875ed548SDimitry Andric   case bitc::ATTR_KIND_ARGMEMONLY:
1377875ed548SDimitry Andric     return Attribute::ArgMemOnly;
1378f785676fSDimitry Andric   case bitc::ATTR_KIND_BUILTIN:
1379f785676fSDimitry Andric     return Attribute::Builtin;
1380f785676fSDimitry Andric   case bitc::ATTR_KIND_BY_VAL:
1381f785676fSDimitry Andric     return Attribute::ByVal;
138291bc56edSDimitry Andric   case bitc::ATTR_KIND_IN_ALLOCA:
138391bc56edSDimitry Andric     return Attribute::InAlloca;
1384f785676fSDimitry Andric   case bitc::ATTR_KIND_COLD:
1385f785676fSDimitry Andric     return Attribute::Cold;
1386ff0cc061SDimitry Andric   case bitc::ATTR_KIND_CONVERGENT:
1387ff0cc061SDimitry Andric     return Attribute::Convergent;
13887d523365SDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
13897d523365SDimitry Andric     return Attribute::InaccessibleMemOnly;
13907d523365SDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
13917d523365SDimitry Andric     return Attribute::InaccessibleMemOrArgMemOnly;
1392f785676fSDimitry Andric   case bitc::ATTR_KIND_INLINE_HINT:
1393f785676fSDimitry Andric     return Attribute::InlineHint;
1394f785676fSDimitry Andric   case bitc::ATTR_KIND_IN_REG:
1395f785676fSDimitry Andric     return Attribute::InReg;
139691bc56edSDimitry Andric   case bitc::ATTR_KIND_JUMP_TABLE:
139791bc56edSDimitry Andric     return Attribute::JumpTable;
1398f785676fSDimitry Andric   case bitc::ATTR_KIND_MIN_SIZE:
1399f785676fSDimitry Andric     return Attribute::MinSize;
1400f785676fSDimitry Andric   case bitc::ATTR_KIND_NAKED:
1401f785676fSDimitry Andric     return Attribute::Naked;
1402f785676fSDimitry Andric   case bitc::ATTR_KIND_NEST:
1403f785676fSDimitry Andric     return Attribute::Nest;
1404f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_ALIAS:
1405f785676fSDimitry Andric     return Attribute::NoAlias;
1406f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_BUILTIN:
1407f785676fSDimitry Andric     return Attribute::NoBuiltin;
1408f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_CAPTURE:
1409f785676fSDimitry Andric     return Attribute::NoCapture;
1410f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_DUPLICATE:
1411f785676fSDimitry Andric     return Attribute::NoDuplicate;
1412f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1413f785676fSDimitry Andric     return Attribute::NoImplicitFloat;
1414f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_INLINE:
1415f785676fSDimitry Andric     return Attribute::NoInline;
14167d523365SDimitry Andric   case bitc::ATTR_KIND_NO_RECURSE:
14177d523365SDimitry Andric     return Attribute::NoRecurse;
1418f785676fSDimitry Andric   case bitc::ATTR_KIND_NON_LAZY_BIND:
1419f785676fSDimitry Andric     return Attribute::NonLazyBind;
142091bc56edSDimitry Andric   case bitc::ATTR_KIND_NON_NULL:
142191bc56edSDimitry Andric     return Attribute::NonNull;
142291bc56edSDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE:
142391bc56edSDimitry Andric     return Attribute::Dereferenceable;
1424ff0cc061SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1425ff0cc061SDimitry Andric     return Attribute::DereferenceableOrNull;
14263ca95b02SDimitry Andric   case bitc::ATTR_KIND_ALLOC_SIZE:
14273ca95b02SDimitry Andric     return Attribute::AllocSize;
1428f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_RED_ZONE:
1429f785676fSDimitry Andric     return Attribute::NoRedZone;
1430f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_RETURN:
1431f785676fSDimitry Andric     return Attribute::NoReturn;
1432f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_UNWIND:
1433f785676fSDimitry Andric     return Attribute::NoUnwind;
1434f785676fSDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1435f785676fSDimitry Andric     return Attribute::OptimizeForSize;
1436f785676fSDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_NONE:
1437f785676fSDimitry Andric     return Attribute::OptimizeNone;
1438f785676fSDimitry Andric   case bitc::ATTR_KIND_READ_NONE:
1439f785676fSDimitry Andric     return Attribute::ReadNone;
1440f785676fSDimitry Andric   case bitc::ATTR_KIND_READ_ONLY:
1441f785676fSDimitry Andric     return Attribute::ReadOnly;
1442f785676fSDimitry Andric   case bitc::ATTR_KIND_RETURNED:
1443f785676fSDimitry Andric     return Attribute::Returned;
1444f785676fSDimitry Andric   case bitc::ATTR_KIND_RETURNS_TWICE:
1445f785676fSDimitry Andric     return Attribute::ReturnsTwice;
1446f785676fSDimitry Andric   case bitc::ATTR_KIND_S_EXT:
1447f785676fSDimitry Andric     return Attribute::SExt;
1448f785676fSDimitry Andric   case bitc::ATTR_KIND_STACK_ALIGNMENT:
1449f785676fSDimitry Andric     return Attribute::StackAlignment;
1450f785676fSDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT:
1451f785676fSDimitry Andric     return Attribute::StackProtect;
1452f785676fSDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1453f785676fSDimitry Andric     return Attribute::StackProtectReq;
1454f785676fSDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1455f785676fSDimitry Andric     return Attribute::StackProtectStrong;
14568f0fd8f6SDimitry Andric   case bitc::ATTR_KIND_SAFESTACK:
14578f0fd8f6SDimitry Andric     return Attribute::SafeStack;
1458f785676fSDimitry Andric   case bitc::ATTR_KIND_STRUCT_RET:
1459f785676fSDimitry Andric     return Attribute::StructRet;
1460f785676fSDimitry Andric   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1461f785676fSDimitry Andric     return Attribute::SanitizeAddress;
1462f785676fSDimitry Andric   case bitc::ATTR_KIND_SANITIZE_THREAD:
1463f785676fSDimitry Andric     return Attribute::SanitizeThread;
1464f785676fSDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMORY:
1465f785676fSDimitry Andric     return Attribute::SanitizeMemory;
14663ca95b02SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ERROR:
14673ca95b02SDimitry Andric     return Attribute::SwiftError;
14683ca95b02SDimitry Andric   case bitc::ATTR_KIND_SWIFT_SELF:
14693ca95b02SDimitry Andric     return Attribute::SwiftSelf;
1470f785676fSDimitry Andric   case bitc::ATTR_KIND_UW_TABLE:
1471f785676fSDimitry Andric     return Attribute::UWTable;
14723ca95b02SDimitry Andric   case bitc::ATTR_KIND_WRITEONLY:
14733ca95b02SDimitry Andric     return Attribute::WriteOnly;
1474f785676fSDimitry Andric   case bitc::ATTR_KIND_Z_EXT:
1475f785676fSDimitry Andric     return Attribute::ZExt;
1476f785676fSDimitry Andric   }
1477f785676fSDimitry Andric }
1478f785676fSDimitry Andric 
1479ff0cc061SDimitry Andric std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1480ff0cc061SDimitry Andric                                                    unsigned &Alignment) {
1481ff0cc061SDimitry Andric   // Note: Alignment in bitcode files is incremented by 1, so that zero
1482ff0cc061SDimitry Andric   // can be used for default alignment.
1483ff0cc061SDimitry Andric   if (Exponent > Value::MaxAlignmentExponent + 1)
14848f0fd8f6SDimitry Andric     return error("Invalid alignment value");
1485ff0cc061SDimitry Andric   Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1486ff0cc061SDimitry Andric   return std::error_code();
1487ff0cc061SDimitry Andric }
1488ff0cc061SDimitry Andric 
14898f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
1490f785676fSDimitry Andric                                              Attribute::AttrKind *Kind) {
14918f0fd8f6SDimitry Andric   *Kind = getAttrFromCode(Code);
1492f785676fSDimitry Andric   if (*Kind == Attribute::None)
14938f0fd8f6SDimitry Andric     return error(BitcodeError::CorruptedBitcode,
149439d628a0SDimitry Andric                  "Unknown attribute kind (" + Twine(Code) + ")");
149591bc56edSDimitry Andric   return std::error_code();
1496f785676fSDimitry Andric }
1497f785676fSDimitry Andric 
14988f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseAttributeGroupBlock() {
1499139f7f9bSDimitry Andric   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
15008f0fd8f6SDimitry Andric     return error("Invalid record");
1501139f7f9bSDimitry Andric 
1502139f7f9bSDimitry Andric   if (!MAttributeGroups.empty())
15038f0fd8f6SDimitry Andric     return error("Invalid multiple blocks");
1504139f7f9bSDimitry Andric 
1505139f7f9bSDimitry Andric   SmallVector<uint64_t, 64> Record;
1506139f7f9bSDimitry Andric 
1507139f7f9bSDimitry Andric   // Read all the records.
1508139f7f9bSDimitry Andric   while (1) {
1509139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1510139f7f9bSDimitry Andric 
1511139f7f9bSDimitry Andric     switch (Entry.Kind) {
1512139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1513139f7f9bSDimitry Andric     case BitstreamEntry::Error:
15148f0fd8f6SDimitry Andric       return error("Malformed block");
1515139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
151691bc56edSDimitry Andric       return std::error_code();
1517139f7f9bSDimitry Andric     case BitstreamEntry::Record:
1518139f7f9bSDimitry Andric       // The interesting case.
1519139f7f9bSDimitry Andric       break;
1520139f7f9bSDimitry Andric     }
1521139f7f9bSDimitry Andric 
1522139f7f9bSDimitry Andric     // Read a record.
1523139f7f9bSDimitry Andric     Record.clear();
1524139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
1525139f7f9bSDimitry Andric     default:  // Default behavior: ignore.
1526139f7f9bSDimitry Andric       break;
1527139f7f9bSDimitry Andric     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1528139f7f9bSDimitry Andric       if (Record.size() < 3)
15298f0fd8f6SDimitry Andric         return error("Invalid record");
1530139f7f9bSDimitry Andric 
1531139f7f9bSDimitry Andric       uint64_t GrpID = Record[0];
1532139f7f9bSDimitry Andric       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1533139f7f9bSDimitry Andric 
1534139f7f9bSDimitry Andric       AttrBuilder B;
1535139f7f9bSDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1536139f7f9bSDimitry Andric         if (Record[i] == 0) {        // Enum attribute
1537f785676fSDimitry Andric           Attribute::AttrKind Kind;
15388f0fd8f6SDimitry Andric           if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1539f785676fSDimitry Andric             return EC;
1540f785676fSDimitry Andric 
1541f785676fSDimitry Andric           B.addAttribute(Kind);
154291bc56edSDimitry Andric         } else if (Record[i] == 1) { // Integer attribute
1543f785676fSDimitry Andric           Attribute::AttrKind Kind;
15448f0fd8f6SDimitry Andric           if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
1545f785676fSDimitry Andric             return EC;
1546f785676fSDimitry Andric           if (Kind == Attribute::Alignment)
1547139f7f9bSDimitry Andric             B.addAlignmentAttr(Record[++i]);
154891bc56edSDimitry Andric           else if (Kind == Attribute::StackAlignment)
1549139f7f9bSDimitry Andric             B.addStackAlignmentAttr(Record[++i]);
155091bc56edSDimitry Andric           else if (Kind == Attribute::Dereferenceable)
155191bc56edSDimitry Andric             B.addDereferenceableAttr(Record[++i]);
1552ff0cc061SDimitry Andric           else if (Kind == Attribute::DereferenceableOrNull)
1553ff0cc061SDimitry Andric             B.addDereferenceableOrNullAttr(Record[++i]);
15543ca95b02SDimitry Andric           else if (Kind == Attribute::AllocSize)
15553ca95b02SDimitry Andric             B.addAllocSizeAttrFromRawRepr(Record[++i]);
1556139f7f9bSDimitry Andric         } else {                     // String attribute
1557139f7f9bSDimitry Andric           assert((Record[i] == 3 || Record[i] == 4) &&
1558139f7f9bSDimitry Andric                  "Invalid attribute group entry");
1559139f7f9bSDimitry Andric           bool HasValue = (Record[i++] == 4);
1560139f7f9bSDimitry Andric           SmallString<64> KindStr;
1561139f7f9bSDimitry Andric           SmallString<64> ValStr;
1562139f7f9bSDimitry Andric 
1563139f7f9bSDimitry Andric           while (Record[i] != 0 && i != e)
1564139f7f9bSDimitry Andric             KindStr += Record[i++];
1565139f7f9bSDimitry Andric           assert(Record[i] == 0 && "Kind string not null terminated");
1566139f7f9bSDimitry Andric 
1567139f7f9bSDimitry Andric           if (HasValue) {
1568139f7f9bSDimitry Andric             // Has a value associated with it.
1569139f7f9bSDimitry Andric             ++i; // Skip the '0' that terminates the "kind" string.
1570139f7f9bSDimitry Andric             while (Record[i] != 0 && i != e)
1571139f7f9bSDimitry Andric               ValStr += Record[i++];
1572139f7f9bSDimitry Andric             assert(Record[i] == 0 && "Value string not null terminated");
1573139f7f9bSDimitry Andric           }
1574139f7f9bSDimitry Andric 
1575139f7f9bSDimitry Andric           B.addAttribute(KindStr.str(), ValStr.str());
1576139f7f9bSDimitry Andric         }
1577139f7f9bSDimitry Andric       }
1578139f7f9bSDimitry Andric 
1579139f7f9bSDimitry Andric       MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1580139f7f9bSDimitry Andric       break;
1581139f7f9bSDimitry Andric     }
1582f22ef01cSRoman Divacky     }
1583f22ef01cSRoman Divacky   }
1584f22ef01cSRoman Divacky }
1585f22ef01cSRoman Divacky 
15868f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseTypeTable() {
158717a519f9SDimitry Andric   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
15888f0fd8f6SDimitry Andric     return error("Invalid record");
1589f22ef01cSRoman Divacky 
15908f0fd8f6SDimitry Andric   return parseTypeTableBody();
159117a519f9SDimitry Andric }
159217a519f9SDimitry Andric 
15938f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseTypeTableBody() {
1594f22ef01cSRoman Divacky   if (!TypeList.empty())
15958f0fd8f6SDimitry Andric     return error("Invalid multiple blocks");
1596f22ef01cSRoman Divacky 
1597f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
1598f22ef01cSRoman Divacky   unsigned NumRecords = 0;
1599f22ef01cSRoman Divacky 
160017a519f9SDimitry Andric   SmallString<64> TypeName;
160117a519f9SDimitry Andric 
1602f22ef01cSRoman Divacky   // Read all the records for this type table.
1603f22ef01cSRoman Divacky   while (1) {
1604139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1605139f7f9bSDimitry Andric 
1606139f7f9bSDimitry Andric     switch (Entry.Kind) {
1607139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1608139f7f9bSDimitry Andric     case BitstreamEntry::Error:
16098f0fd8f6SDimitry Andric       return error("Malformed block");
1610139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
1611f22ef01cSRoman Divacky       if (NumRecords != TypeList.size())
16128f0fd8f6SDimitry Andric         return error("Malformed block");
161391bc56edSDimitry Andric       return std::error_code();
1614139f7f9bSDimitry Andric     case BitstreamEntry::Record:
1615139f7f9bSDimitry Andric       // The interesting case.
1616139f7f9bSDimitry Andric       break;
1617f22ef01cSRoman Divacky     }
1618f22ef01cSRoman Divacky 
1619f22ef01cSRoman Divacky     // Read a record.
1620f22ef01cSRoman Divacky     Record.clear();
162191bc56edSDimitry Andric     Type *ResultTy = nullptr;
1622139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
1623f785676fSDimitry Andric     default:
16248f0fd8f6SDimitry Andric       return error("Invalid value");
1625f22ef01cSRoman Divacky     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1626f22ef01cSRoman Divacky       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1627f22ef01cSRoman Divacky       // type list.  This allows us to reserve space.
1628f22ef01cSRoman Divacky       if (Record.size() < 1)
16298f0fd8f6SDimitry Andric         return error("Invalid record");
163017a519f9SDimitry Andric       TypeList.resize(Record[0]);
1631f22ef01cSRoman Divacky       continue;
1632f22ef01cSRoman Divacky     case bitc::TYPE_CODE_VOID:      // VOID
1633f22ef01cSRoman Divacky       ResultTy = Type::getVoidTy(Context);
1634f22ef01cSRoman Divacky       break;
1635dff0c46cSDimitry Andric     case bitc::TYPE_CODE_HALF:     // HALF
1636dff0c46cSDimitry Andric       ResultTy = Type::getHalfTy(Context);
1637dff0c46cSDimitry Andric       break;
1638f22ef01cSRoman Divacky     case bitc::TYPE_CODE_FLOAT:     // FLOAT
1639f22ef01cSRoman Divacky       ResultTy = Type::getFloatTy(Context);
1640f22ef01cSRoman Divacky       break;
1641f22ef01cSRoman Divacky     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1642f22ef01cSRoman Divacky       ResultTy = Type::getDoubleTy(Context);
1643f22ef01cSRoman Divacky       break;
1644f22ef01cSRoman Divacky     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1645f22ef01cSRoman Divacky       ResultTy = Type::getX86_FP80Ty(Context);
1646f22ef01cSRoman Divacky       break;
1647f22ef01cSRoman Divacky     case bitc::TYPE_CODE_FP128:     // FP128
1648f22ef01cSRoman Divacky       ResultTy = Type::getFP128Ty(Context);
1649f22ef01cSRoman Divacky       break;
1650f22ef01cSRoman Divacky     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1651f22ef01cSRoman Divacky       ResultTy = Type::getPPC_FP128Ty(Context);
1652f22ef01cSRoman Divacky       break;
1653f22ef01cSRoman Divacky     case bitc::TYPE_CODE_LABEL:     // LABEL
1654f22ef01cSRoman Divacky       ResultTy = Type::getLabelTy(Context);
1655f22ef01cSRoman Divacky       break;
1656f22ef01cSRoman Divacky     case bitc::TYPE_CODE_METADATA:  // METADATA
1657f22ef01cSRoman Divacky       ResultTy = Type::getMetadataTy(Context);
1658f22ef01cSRoman Divacky       break;
16592754fe60SDimitry Andric     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
16602754fe60SDimitry Andric       ResultTy = Type::getX86_MMXTy(Context);
16612754fe60SDimitry Andric       break;
16627d523365SDimitry Andric     case bitc::TYPE_CODE_TOKEN:     // TOKEN
16637d523365SDimitry Andric       ResultTy = Type::getTokenTy(Context);
16647d523365SDimitry Andric       break;
1665ff0cc061SDimitry Andric     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1666f22ef01cSRoman Divacky       if (Record.size() < 1)
16678f0fd8f6SDimitry Andric         return error("Invalid record");
1668f22ef01cSRoman Divacky 
1669ff0cc061SDimitry Andric       uint64_t NumBits = Record[0];
1670ff0cc061SDimitry Andric       if (NumBits < IntegerType::MIN_INT_BITS ||
1671ff0cc061SDimitry Andric           NumBits > IntegerType::MAX_INT_BITS)
16728f0fd8f6SDimitry Andric         return error("Bitwidth for integer type out of range");
1673ff0cc061SDimitry Andric       ResultTy = IntegerType::get(Context, NumBits);
1674f22ef01cSRoman Divacky       break;
1675ff0cc061SDimitry Andric     }
1676f22ef01cSRoman Divacky     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1677f22ef01cSRoman Divacky                                     //          [pointee type, address space]
1678f22ef01cSRoman Divacky       if (Record.size() < 1)
16798f0fd8f6SDimitry Andric         return error("Invalid record");
1680f22ef01cSRoman Divacky       unsigned AddressSpace = 0;
1681f22ef01cSRoman Divacky       if (Record.size() == 2)
1682f22ef01cSRoman Divacky         AddressSpace = Record[1];
168317a519f9SDimitry Andric       ResultTy = getTypeByID(Record[0]);
1684ff0cc061SDimitry Andric       if (!ResultTy ||
1685ff0cc061SDimitry Andric           !PointerType::isValidElementType(ResultTy))
16868f0fd8f6SDimitry Andric         return error("Invalid type");
168717a519f9SDimitry Andric       ResultTy = PointerType::get(ResultTy, AddressSpace);
1688f22ef01cSRoman Divacky       break;
1689f22ef01cSRoman Divacky     }
1690dff0c46cSDimitry Andric     case bitc::TYPE_CODE_FUNCTION_OLD: {
16917ae0e2c9SDimitry Andric       // FIXME: attrid is dead, remove it in LLVM 4.0
1692f22ef01cSRoman Divacky       // FUNCTION: [vararg, attrid, retty, paramty x N]
1693f22ef01cSRoman Divacky       if (Record.size() < 3)
16948f0fd8f6SDimitry Andric         return error("Invalid record");
1695dff0c46cSDimitry Andric       SmallVector<Type*, 8> ArgTys;
169617a519f9SDimitry Andric       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
169717a519f9SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
169817a519f9SDimitry Andric           ArgTys.push_back(T);
169917a519f9SDimitry Andric         else
1700f22ef01cSRoman Divacky           break;
1701f22ef01cSRoman Divacky       }
170217a519f9SDimitry Andric 
170317a519f9SDimitry Andric       ResultTy = getTypeByID(Record[2]);
170491bc56edSDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-3)
17058f0fd8f6SDimitry Andric         return error("Invalid type");
170617a519f9SDimitry Andric 
170717a519f9SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
170817a519f9SDimitry Andric       break;
170917a519f9SDimitry Andric     }
1710dff0c46cSDimitry Andric     case bitc::TYPE_CODE_FUNCTION: {
1711dff0c46cSDimitry Andric       // FUNCTION: [vararg, retty, paramty x N]
1712dff0c46cSDimitry Andric       if (Record.size() < 2)
17138f0fd8f6SDimitry Andric         return error("Invalid record");
1714dff0c46cSDimitry Andric       SmallVector<Type*, 8> ArgTys;
1715dff0c46cSDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1716ff0cc061SDimitry Andric         if (Type *T = getTypeByID(Record[i])) {
1717ff0cc061SDimitry Andric           if (!FunctionType::isValidArgumentType(T))
17188f0fd8f6SDimitry Andric             return error("Invalid function argument type");
1719dff0c46cSDimitry Andric           ArgTys.push_back(T);
1720ff0cc061SDimitry Andric         }
1721dff0c46cSDimitry Andric         else
1722dff0c46cSDimitry Andric           break;
1723dff0c46cSDimitry Andric       }
1724dff0c46cSDimitry Andric 
1725dff0c46cSDimitry Andric       ResultTy = getTypeByID(Record[1]);
172691bc56edSDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-2)
17278f0fd8f6SDimitry Andric         return error("Invalid type");
1728dff0c46cSDimitry Andric 
1729dff0c46cSDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1730dff0c46cSDimitry Andric       break;
1731dff0c46cSDimitry Andric     }
173217a519f9SDimitry Andric     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1733f22ef01cSRoman Divacky       if (Record.size() < 1)
17348f0fd8f6SDimitry Andric         return error("Invalid record");
1735dff0c46cSDimitry Andric       SmallVector<Type*, 8> EltTys;
173617a519f9SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
173717a519f9SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
173817a519f9SDimitry Andric           EltTys.push_back(T);
173917a519f9SDimitry Andric         else
174017a519f9SDimitry Andric           break;
174117a519f9SDimitry Andric       }
174217a519f9SDimitry Andric       if (EltTys.size() != Record.size()-1)
17438f0fd8f6SDimitry Andric         return error("Invalid type");
1744f22ef01cSRoman Divacky       ResultTy = StructType::get(Context, EltTys, Record[0]);
1745f22ef01cSRoman Divacky       break;
1746f22ef01cSRoman Divacky     }
174717a519f9SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
17488f0fd8f6SDimitry Andric       if (convertToString(Record, 0, TypeName))
17498f0fd8f6SDimitry Andric         return error("Invalid record");
175017a519f9SDimitry Andric       continue;
175117a519f9SDimitry Andric 
175217a519f9SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
175317a519f9SDimitry Andric       if (Record.size() < 1)
17548f0fd8f6SDimitry Andric         return error("Invalid record");
175517a519f9SDimitry Andric 
175617a519f9SDimitry Andric       if (NumRecords >= TypeList.size())
17578f0fd8f6SDimitry Andric         return error("Invalid TYPE table");
175817a519f9SDimitry Andric 
175917a519f9SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
176017a519f9SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
176117a519f9SDimitry Andric       if (Res) {
176217a519f9SDimitry Andric         Res->setName(TypeName);
176391bc56edSDimitry Andric         TypeList[NumRecords] = nullptr;
176417a519f9SDimitry Andric       } else  // Otherwise, create a new struct.
176539d628a0SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
176617a519f9SDimitry Andric       TypeName.clear();
176717a519f9SDimitry Andric 
176817a519f9SDimitry Andric       SmallVector<Type*, 8> EltTys;
176917a519f9SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
177017a519f9SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
177117a519f9SDimitry Andric           EltTys.push_back(T);
177217a519f9SDimitry Andric         else
177317a519f9SDimitry Andric           break;
177417a519f9SDimitry Andric       }
177517a519f9SDimitry Andric       if (EltTys.size() != Record.size()-1)
17768f0fd8f6SDimitry Andric         return error("Invalid record");
177717a519f9SDimitry Andric       Res->setBody(EltTys, Record[0]);
177817a519f9SDimitry Andric       ResultTy = Res;
177917a519f9SDimitry Andric       break;
178017a519f9SDimitry Andric     }
178117a519f9SDimitry Andric     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
178217a519f9SDimitry Andric       if (Record.size() != 1)
17838f0fd8f6SDimitry Andric         return error("Invalid record");
178417a519f9SDimitry Andric 
178517a519f9SDimitry Andric       if (NumRecords >= TypeList.size())
17868f0fd8f6SDimitry Andric         return error("Invalid TYPE table");
178717a519f9SDimitry Andric 
178817a519f9SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
178917a519f9SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
179017a519f9SDimitry Andric       if (Res) {
179117a519f9SDimitry Andric         Res->setName(TypeName);
179291bc56edSDimitry Andric         TypeList[NumRecords] = nullptr;
179317a519f9SDimitry Andric       } else  // Otherwise, create a new struct with no body.
179439d628a0SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
179517a519f9SDimitry Andric       TypeName.clear();
179617a519f9SDimitry Andric       ResultTy = Res;
179717a519f9SDimitry Andric       break;
179817a519f9SDimitry Andric     }
1799f22ef01cSRoman Divacky     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1800f22ef01cSRoman Divacky       if (Record.size() < 2)
18018f0fd8f6SDimitry Andric         return error("Invalid record");
1802ff0cc061SDimitry Andric       ResultTy = getTypeByID(Record[1]);
1803ff0cc061SDimitry Andric       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
18048f0fd8f6SDimitry Andric         return error("Invalid type");
1805ff0cc061SDimitry Andric       ResultTy = ArrayType::get(ResultTy, Record[0]);
1806f22ef01cSRoman Divacky       break;
1807f22ef01cSRoman Divacky     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
1808f22ef01cSRoman Divacky       if (Record.size() < 2)
18098f0fd8f6SDimitry Andric         return error("Invalid record");
181097bc6c73SDimitry Andric       if (Record[0] == 0)
18118f0fd8f6SDimitry Andric         return error("Invalid vector length");
1812ff0cc061SDimitry Andric       ResultTy = getTypeByID(Record[1]);
1813ff0cc061SDimitry Andric       if (!ResultTy || !StructType::isValidElementType(ResultTy))
18148f0fd8f6SDimitry Andric         return error("Invalid type");
1815ff0cc061SDimitry Andric       ResultTy = VectorType::get(ResultTy, Record[0]);
1816f22ef01cSRoman Divacky       break;
1817f22ef01cSRoman Divacky     }
1818f22ef01cSRoman Divacky 
181917a519f9SDimitry Andric     if (NumRecords >= TypeList.size())
18208f0fd8f6SDimitry Andric       return error("Invalid TYPE table");
1821ff0cc061SDimitry Andric     if (TypeList[NumRecords])
18228f0fd8f6SDimitry Andric       return error(
1823ff0cc061SDimitry Andric           "Invalid TYPE table: Only named structs can be forward referenced");
182417a519f9SDimitry Andric     assert(ResultTy && "Didn't read a type?");
182517a519f9SDimitry Andric     TypeList[NumRecords++] = ResultTy;
1826f22ef01cSRoman Divacky   }
1827f22ef01cSRoman Divacky }
182817a519f9SDimitry Andric 
18297d523365SDimitry Andric std::error_code BitcodeReader::parseOperandBundleTags() {
18307d523365SDimitry Andric   if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
18317d523365SDimitry Andric     return error("Invalid record");
18327d523365SDimitry Andric 
18337d523365SDimitry Andric   if (!BundleTags.empty())
18347d523365SDimitry Andric     return error("Invalid multiple blocks");
18357d523365SDimitry Andric 
18367d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
18377d523365SDimitry Andric 
18387d523365SDimitry Andric   while (1) {
18397d523365SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
18407d523365SDimitry Andric 
18417d523365SDimitry Andric     switch (Entry.Kind) {
18427d523365SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
18437d523365SDimitry Andric     case BitstreamEntry::Error:
18447d523365SDimitry Andric       return error("Malformed block");
18457d523365SDimitry Andric     case BitstreamEntry::EndBlock:
18467d523365SDimitry Andric       return std::error_code();
18477d523365SDimitry Andric     case BitstreamEntry::Record:
18487d523365SDimitry Andric       // The interesting case.
18497d523365SDimitry Andric       break;
18507d523365SDimitry Andric     }
18517d523365SDimitry Andric 
18527d523365SDimitry Andric     // Tags are implicitly mapped to integers by their order.
18537d523365SDimitry Andric 
18547d523365SDimitry Andric     if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
18557d523365SDimitry Andric       return error("Invalid record");
18567d523365SDimitry Andric 
18577d523365SDimitry Andric     // OPERAND_BUNDLE_TAG: [strchr x N]
18587d523365SDimitry Andric     BundleTags.emplace_back();
18597d523365SDimitry Andric     if (convertToString(Record, 0, BundleTags.back()))
18607d523365SDimitry Andric       return error("Invalid record");
18617d523365SDimitry Andric     Record.clear();
18627d523365SDimitry Andric   }
18637d523365SDimitry Andric }
18647d523365SDimitry Andric 
18657d523365SDimitry Andric /// Associate a value with its name from the given index in the provided record.
18667d523365SDimitry Andric ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
18677d523365SDimitry Andric                                             unsigned NameIndex, Triple &TT) {
18687d523365SDimitry Andric   SmallString<128> ValueName;
18697d523365SDimitry Andric   if (convertToString(Record, NameIndex, ValueName))
18707d523365SDimitry Andric     return error("Invalid record");
18717d523365SDimitry Andric   unsigned ValueID = Record[0];
18727d523365SDimitry Andric   if (ValueID >= ValueList.size() || !ValueList[ValueID])
18737d523365SDimitry Andric     return error("Invalid record");
18747d523365SDimitry Andric   Value *V = ValueList[ValueID];
18757d523365SDimitry Andric 
18767d523365SDimitry Andric   StringRef NameStr(ValueName.data(), ValueName.size());
18777d523365SDimitry Andric   if (NameStr.find_first_of(0) != StringRef::npos)
18787d523365SDimitry Andric     return error("Invalid value name");
18797d523365SDimitry Andric   V->setName(NameStr);
18807d523365SDimitry Andric   auto *GO = dyn_cast<GlobalObject>(V);
18817d523365SDimitry Andric   if (GO) {
18827d523365SDimitry Andric     if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
18837d523365SDimitry Andric       if (TT.isOSBinFormatMachO())
18847d523365SDimitry Andric         GO->setComdat(nullptr);
18857d523365SDimitry Andric       else
18867d523365SDimitry Andric         GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
18877d523365SDimitry Andric     }
18887d523365SDimitry Andric   }
18897d523365SDimitry Andric   return V;
18907d523365SDimitry Andric }
18917d523365SDimitry Andric 
18923ca95b02SDimitry Andric /// Helper to note and return the current location, and jump to the given
18933ca95b02SDimitry Andric /// offset.
18943ca95b02SDimitry Andric static uint64_t jumpToValueSymbolTable(uint64_t Offset,
18953ca95b02SDimitry Andric                                        BitstreamCursor &Stream) {
18967d523365SDimitry Andric   // Save the current parsing location so we can jump back at the end
18977d523365SDimitry Andric   // of the VST read.
18983ca95b02SDimitry Andric   uint64_t CurrentBit = Stream.GetCurrentBitNo();
18997d523365SDimitry Andric   Stream.JumpToBit(Offset * 32);
19007d523365SDimitry Andric #ifndef NDEBUG
19017d523365SDimitry Andric   // Do some checking if we are in debug mode.
19027d523365SDimitry Andric   BitstreamEntry Entry = Stream.advance();
19037d523365SDimitry Andric   assert(Entry.Kind == BitstreamEntry::SubBlock);
19047d523365SDimitry Andric   assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
19057d523365SDimitry Andric #else
19067d523365SDimitry Andric   // In NDEBUG mode ignore the output so we don't get an unused variable
19077d523365SDimitry Andric   // warning.
19087d523365SDimitry Andric   Stream.advance();
19097d523365SDimitry Andric #endif
19103ca95b02SDimitry Andric   return CurrentBit;
19117d523365SDimitry Andric }
19127d523365SDimitry Andric 
19133ca95b02SDimitry Andric /// Parse the value symbol table at either the current parsing location or
19143ca95b02SDimitry Andric /// at the given bit offset if provided.
19153ca95b02SDimitry Andric std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
19163ca95b02SDimitry Andric   uint64_t CurrentBit;
19173ca95b02SDimitry Andric   // Pass in the Offset to distinguish between calling for the module-level
19183ca95b02SDimitry Andric   // VST (where we want to jump to the VST offset) and the function-level
19193ca95b02SDimitry Andric   // VST (where we don't).
19203ca95b02SDimitry Andric   if (Offset > 0)
19213ca95b02SDimitry Andric     CurrentBit = jumpToValueSymbolTable(Offset, Stream);
19223ca95b02SDimitry Andric 
19237d523365SDimitry Andric   // Compute the delta between the bitcode indices in the VST (the word offset
19247d523365SDimitry Andric   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
19257d523365SDimitry Andric   // expected by the lazy reader. The reader's EnterSubBlock expects to have
19267d523365SDimitry Andric   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
19277d523365SDimitry Andric   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
19287d523365SDimitry Andric   // just before entering the VST subblock because: 1) the EnterSubBlock
19297d523365SDimitry Andric   // changes the AbbrevID width; 2) the VST block is nested within the same
19307d523365SDimitry Andric   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
19317d523365SDimitry Andric   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
19327d523365SDimitry Andric   // jump to the FUNCTION_BLOCK using this offset later, we don't want
19337d523365SDimitry Andric   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
19347d523365SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
19357d523365SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
19367d523365SDimitry Andric 
1937f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
19388f0fd8f6SDimitry Andric     return error("Invalid record");
1939f22ef01cSRoman Divacky 
1940f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
1941f22ef01cSRoman Divacky 
1942ff0cc061SDimitry Andric   Triple TT(TheModule->getTargetTriple());
1943ff0cc061SDimitry Andric 
1944f22ef01cSRoman Divacky   // Read all the records for this value table.
1945f22ef01cSRoman Divacky   SmallString<128> ValueName;
1946f22ef01cSRoman Divacky   while (1) {
1947139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1948f22ef01cSRoman Divacky 
1949139f7f9bSDimitry Andric     switch (Entry.Kind) {
1950139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1951139f7f9bSDimitry Andric     case BitstreamEntry::Error:
19528f0fd8f6SDimitry Andric       return error("Malformed block");
1953139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
19547d523365SDimitry Andric       if (Offset > 0)
19557d523365SDimitry Andric         Stream.JumpToBit(CurrentBit);
195691bc56edSDimitry Andric       return std::error_code();
1957139f7f9bSDimitry Andric     case BitstreamEntry::Record:
1958139f7f9bSDimitry Andric       // The interesting case.
1959139f7f9bSDimitry Andric       break;
1960f22ef01cSRoman Divacky     }
1961f22ef01cSRoman Divacky 
1962f22ef01cSRoman Divacky     // Read a record.
1963f22ef01cSRoman Divacky     Record.clear();
1964139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
1965f22ef01cSRoman Divacky     default:  // Default behavior: unknown type.
1966f22ef01cSRoman Divacky       break;
19673ca95b02SDimitry Andric     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
19687d523365SDimitry Andric       ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
19697d523365SDimitry Andric       if (std::error_code EC = ValOrErr.getError())
19707d523365SDimitry Andric         return EC;
19717d523365SDimitry Andric       ValOrErr.get();
19727d523365SDimitry Andric       break;
19737d523365SDimitry Andric     }
19747d523365SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
19753ca95b02SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
19767d523365SDimitry Andric       ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
19777d523365SDimitry Andric       if (std::error_code EC = ValOrErr.getError())
19787d523365SDimitry Andric         return EC;
19797d523365SDimitry Andric       Value *V = ValOrErr.get();
1980f22ef01cSRoman Divacky 
19817d523365SDimitry Andric       auto *GO = dyn_cast<GlobalObject>(V);
19827d523365SDimitry Andric       if (!GO) {
19837d523365SDimitry Andric         // If this is an alias, need to get the actual Function object
19847d523365SDimitry Andric         // it aliases, in order to set up the DeferredFunctionInfo entry below.
19857d523365SDimitry Andric         auto *GA = dyn_cast<GlobalAlias>(V);
19867d523365SDimitry Andric         if (GA)
19877d523365SDimitry Andric           GO = GA->getBaseObject();
19887d523365SDimitry Andric         assert(GO);
1989ff0cc061SDimitry Andric       }
19907d523365SDimitry Andric 
19917d523365SDimitry Andric       uint64_t FuncWordOffset = Record[1];
19927d523365SDimitry Andric       Function *F = dyn_cast<Function>(GO);
19937d523365SDimitry Andric       assert(F);
19947d523365SDimitry Andric       uint64_t FuncBitOffset = FuncWordOffset * 32;
19957d523365SDimitry Andric       DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
19967d523365SDimitry Andric       // Set the LastFunctionBlockBit to point to the last function block.
19977d523365SDimitry Andric       // Later when parsing is resumed after function materialization,
19987d523365SDimitry Andric       // we can simply skip that last function block.
19997d523365SDimitry Andric       if (FuncBitOffset > LastFunctionBlockBit)
20007d523365SDimitry Andric         LastFunctionBlockBit = FuncBitOffset;
2001f22ef01cSRoman Divacky       break;
2002f22ef01cSRoman Divacky     }
2003f22ef01cSRoman Divacky     case bitc::VST_CODE_BBENTRY: {
20048f0fd8f6SDimitry Andric       if (convertToString(Record, 1, ValueName))
20058f0fd8f6SDimitry Andric         return error("Invalid record");
2006f22ef01cSRoman Divacky       BasicBlock *BB = getBasicBlock(Record[0]);
200791bc56edSDimitry Andric       if (!BB)
20088f0fd8f6SDimitry Andric         return error("Invalid record");
2009f22ef01cSRoman Divacky 
2010f22ef01cSRoman Divacky       BB->setName(StringRef(ValueName.data(), ValueName.size()));
2011f22ef01cSRoman Divacky       ValueName.clear();
2012f22ef01cSRoman Divacky       break;
2013f22ef01cSRoman Divacky     }
2014f22ef01cSRoman Divacky     }
2015f22ef01cSRoman Divacky   }
2016f22ef01cSRoman Divacky }
2017f22ef01cSRoman Divacky 
20187d523365SDimitry Andric /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
20197d523365SDimitry Andric std::error_code
20207d523365SDimitry Andric BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
20217d523365SDimitry Andric   if (Record.size() < 2)
20227d523365SDimitry Andric     return error("Invalid record");
20237d523365SDimitry Andric 
20247d523365SDimitry Andric   unsigned Kind = Record[0];
20257d523365SDimitry Andric   SmallString<8> Name(Record.begin() + 1, Record.end());
20267d523365SDimitry Andric 
20277d523365SDimitry Andric   unsigned NewKind = TheModule->getMDKindID(Name.str());
20287d523365SDimitry Andric   if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
20297d523365SDimitry Andric     return error("Conflicting METADATA_KIND records");
20307d523365SDimitry Andric   return std::error_code();
20317d523365SDimitry Andric }
20327d523365SDimitry Andric 
2033ff0cc061SDimitry Andric static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
2034ff0cc061SDimitry Andric 
20353ca95b02SDimitry Andric std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
20363ca95b02SDimitry Andric                                                     StringRef Blob,
20373ca95b02SDimitry Andric                                                     unsigned &NextMetadataNo) {
20383ca95b02SDimitry Andric   // All the MDStrings in the block are emitted together in a single
20393ca95b02SDimitry Andric   // record.  The strings are concatenated and stored in a blob along with
20403ca95b02SDimitry Andric   // their sizes.
20413ca95b02SDimitry Andric   if (Record.size() != 2)
20423ca95b02SDimitry Andric     return error("Invalid record: metadata strings layout");
20433ca95b02SDimitry Andric 
20443ca95b02SDimitry Andric   unsigned NumStrings = Record[0];
20453ca95b02SDimitry Andric   unsigned StringsOffset = Record[1];
20463ca95b02SDimitry Andric   if (!NumStrings)
20473ca95b02SDimitry Andric     return error("Invalid record: metadata strings with no strings");
20483ca95b02SDimitry Andric   if (StringsOffset > Blob.size())
20493ca95b02SDimitry Andric     return error("Invalid record: metadata strings corrupt offset");
20503ca95b02SDimitry Andric 
20513ca95b02SDimitry Andric   StringRef Lengths = Blob.slice(0, StringsOffset);
20523ca95b02SDimitry Andric   SimpleBitstreamCursor R(*StreamFile);
20533ca95b02SDimitry Andric   R.jumpToPointer(Lengths.begin());
20543ca95b02SDimitry Andric 
20553ca95b02SDimitry Andric   // Ensure that Blob doesn't get invalidated, even if this is reading from
20563ca95b02SDimitry Andric   // a StreamingMemoryObject with corrupt data.
20573ca95b02SDimitry Andric   R.setArtificialByteLimit(R.getCurrentByteNo() + StringsOffset);
20583ca95b02SDimitry Andric 
20593ca95b02SDimitry Andric   StringRef Strings = Blob.drop_front(StringsOffset);
20603ca95b02SDimitry Andric   do {
20613ca95b02SDimitry Andric     if (R.AtEndOfStream())
20623ca95b02SDimitry Andric       return error("Invalid record: metadata strings bad length");
20633ca95b02SDimitry Andric 
20643ca95b02SDimitry Andric     unsigned Size = R.ReadVBR(6);
20653ca95b02SDimitry Andric     if (Strings.size() < Size)
20663ca95b02SDimitry Andric       return error("Invalid record: metadata strings truncated chars");
20673ca95b02SDimitry Andric 
20683ca95b02SDimitry Andric     MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
20693ca95b02SDimitry Andric                              NextMetadataNo++);
20703ca95b02SDimitry Andric     Strings = Strings.drop_front(Size);
20713ca95b02SDimitry Andric   } while (--NumStrings);
20723ca95b02SDimitry Andric 
20733ca95b02SDimitry Andric   return std::error_code();
20743ca95b02SDimitry Andric }
20753ca95b02SDimitry Andric 
20763ca95b02SDimitry Andric namespace {
20773ca95b02SDimitry Andric class PlaceholderQueue {
20783ca95b02SDimitry Andric   // Placeholders would thrash around when moved, so store in a std::deque
20793ca95b02SDimitry Andric   // instead of some sort of vector.
20803ca95b02SDimitry Andric   std::deque<DistinctMDOperandPlaceholder> PHs;
20813ca95b02SDimitry Andric 
20823ca95b02SDimitry Andric public:
20833ca95b02SDimitry Andric   DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
20843ca95b02SDimitry Andric   void flush(BitcodeReaderMetadataList &MetadataList);
20853ca95b02SDimitry Andric };
20863ca95b02SDimitry Andric } // end namespace
20873ca95b02SDimitry Andric 
20883ca95b02SDimitry Andric DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
20893ca95b02SDimitry Andric   PHs.emplace_back(ID);
20903ca95b02SDimitry Andric   return PHs.back();
20913ca95b02SDimitry Andric }
20923ca95b02SDimitry Andric 
20933ca95b02SDimitry Andric void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
20943ca95b02SDimitry Andric   while (!PHs.empty()) {
20953ca95b02SDimitry Andric     PHs.front().replaceUseWith(
20963ca95b02SDimitry Andric         MetadataList.getMetadataFwdRef(PHs.front().getID()));
20973ca95b02SDimitry Andric     PHs.pop_front();
20983ca95b02SDimitry Andric   }
20993ca95b02SDimitry Andric }
21003ca95b02SDimitry Andric 
21017d523365SDimitry Andric /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
21027d523365SDimitry Andric /// module level metadata.
21037d523365SDimitry Andric std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
21043ca95b02SDimitry Andric   assert((ModuleLevel || DeferredMetadataInfo.empty()) &&
21053ca95b02SDimitry Andric          "Must read all module-level metadata before function-level");
21063ca95b02SDimitry Andric 
2107ff0cc061SDimitry Andric   IsMetadataMaterialized = true;
21087d523365SDimitry Andric   unsigned NextMetadataNo = MetadataList.size();
21093ca95b02SDimitry Andric 
21103ca95b02SDimitry Andric   if (!ModuleLevel && MetadataList.hasFwdRefs())
21113ca95b02SDimitry Andric     return error("Invalid metadata: fwd refs into function blocks");
2112f22ef01cSRoman Divacky 
2113f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
21148f0fd8f6SDimitry Andric     return error("Invalid record");
2115f22ef01cSRoman Divacky 
21163ca95b02SDimitry Andric   std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
2117f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
2118f22ef01cSRoman Divacky 
21193ca95b02SDimitry Andric   PlaceholderQueue Placeholders;
21203ca95b02SDimitry Andric   bool IsDistinct;
21217d523365SDimitry Andric   auto getMD = [&](unsigned ID) -> Metadata * {
21223ca95b02SDimitry Andric     if (!IsDistinct)
21233ca95b02SDimitry Andric       return MetadataList.getMetadataFwdRef(ID);
21243ca95b02SDimitry Andric     if (auto *MD = MetadataList.getMetadataIfResolved(ID))
21253ca95b02SDimitry Andric       return MD;
21263ca95b02SDimitry Andric     return &Placeholders.getPlaceholderOp(ID);
21277d523365SDimitry Andric   };
2128ff0cc061SDimitry Andric   auto getMDOrNull = [&](unsigned ID) -> Metadata * {
2129ff0cc061SDimitry Andric     if (ID)
2130ff0cc061SDimitry Andric       return getMD(ID - 1);
2131ff0cc061SDimitry Andric     return nullptr;
2132ff0cc061SDimitry Andric   };
21333ca95b02SDimitry Andric   auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
21343ca95b02SDimitry Andric     if (ID)
21353ca95b02SDimitry Andric       return MetadataList.getMetadataFwdRef(ID - 1);
21363ca95b02SDimitry Andric     return nullptr;
21373ca95b02SDimitry Andric   };
2138ff0cc061SDimitry Andric   auto getMDString = [&](unsigned ID) -> MDString *{
2139ff0cc061SDimitry Andric     // This requires that the ID is not really a forward reference.  In
2140ff0cc061SDimitry Andric     // particular, the MDString must already have been resolved.
2141ff0cc061SDimitry Andric     return cast_or_null<MDString>(getMDOrNull(ID));
2142ff0cc061SDimitry Andric   };
2143ff0cc061SDimitry Andric 
21443ca95b02SDimitry Andric   // Support for old type refs.
21453ca95b02SDimitry Andric   auto getDITypeRefOrNull = [&](unsigned ID) {
21463ca95b02SDimitry Andric     return MetadataList.upgradeTypeRef(getMDOrNull(ID));
21473ca95b02SDimitry Andric   };
21483ca95b02SDimitry Andric 
21493ca95b02SDimitry Andric #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
21503ca95b02SDimitry Andric   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
2151ff0cc061SDimitry Andric 
2152f22ef01cSRoman Divacky   // Read all the records.
2153f22ef01cSRoman Divacky   while (1) {
2154139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2155139f7f9bSDimitry Andric 
2156139f7f9bSDimitry Andric     switch (Entry.Kind) {
2157139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2158139f7f9bSDimitry Andric     case BitstreamEntry::Error:
21598f0fd8f6SDimitry Andric       return error("Malformed block");
2160139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
21613ca95b02SDimitry Andric       // Upgrade old-style CU <-> SP pointers to point from SP to CU.
21623ca95b02SDimitry Andric       for (auto CU_SP : CUSubprograms)
21633ca95b02SDimitry Andric         if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
21643ca95b02SDimitry Andric           for (auto &Op : SPs->operands())
21653ca95b02SDimitry Andric             if (auto *SP = dyn_cast_or_null<MDNode>(Op))
21663ca95b02SDimitry Andric               SP->replaceOperandWith(7, CU_SP.first);
21673ca95b02SDimitry Andric 
21687d523365SDimitry Andric       MetadataList.tryToResolveCycles();
21693ca95b02SDimitry Andric       Placeholders.flush(MetadataList);
217091bc56edSDimitry Andric       return std::error_code();
2171139f7f9bSDimitry Andric     case BitstreamEntry::Record:
2172139f7f9bSDimitry Andric       // The interesting case.
2173139f7f9bSDimitry Andric       break;
2174f22ef01cSRoman Divacky     }
2175f22ef01cSRoman Divacky 
2176f22ef01cSRoman Divacky     // Read a record.
2177f22ef01cSRoman Divacky     Record.clear();
21783ca95b02SDimitry Andric     StringRef Blob;
21793ca95b02SDimitry Andric     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
21803ca95b02SDimitry Andric     IsDistinct = false;
2181e580952dSDimitry Andric     switch (Code) {
2182f22ef01cSRoman Divacky     default:  // Default behavior: ignore.
2183f22ef01cSRoman Divacky       break;
2184f22ef01cSRoman Divacky     case bitc::METADATA_NAME: {
2185139f7f9bSDimitry Andric       // Read name of the named metadata.
21867ae0e2c9SDimitry Andric       SmallString<8> Name(Record.begin(), Record.end());
2187f22ef01cSRoman Divacky       Record.clear();
2188f22ef01cSRoman Divacky       Code = Stream.ReadCode();
2189f22ef01cSRoman Divacky 
2190139f7f9bSDimitry Andric       unsigned NextBitCode = Stream.readRecord(Code, Record);
219197bc6c73SDimitry Andric       if (NextBitCode != bitc::METADATA_NAMED_NODE)
21928f0fd8f6SDimitry Andric         return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
2193f22ef01cSRoman Divacky 
2194f22ef01cSRoman Divacky       // Read named metadata elements.
2195f22ef01cSRoman Divacky       unsigned Size = Record.size();
2196e580952dSDimitry Andric       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
2197f22ef01cSRoman Divacky       for (unsigned i = 0; i != Size; ++i) {
21983ca95b02SDimitry Andric         MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
219991bc56edSDimitry Andric         if (!MD)
22008f0fd8f6SDimitry Andric           return error("Invalid record");
2201e580952dSDimitry Andric         NMD->addOperand(MD);
2202f22ef01cSRoman Divacky       }
2203f22ef01cSRoman Divacky       break;
2204f22ef01cSRoman Divacky     }
220539d628a0SDimitry Andric     case bitc::METADATA_OLD_FN_NODE: {
220639d628a0SDimitry Andric       // FIXME: Remove in 4.0.
220739d628a0SDimitry Andric       // This is a LocalAsMetadata record, the only type of function-local
220839d628a0SDimitry Andric       // metadata.
2209ffd1746dSEd Schouten       if (Record.size() % 2 == 1)
22108f0fd8f6SDimitry Andric         return error("Invalid record");
221139d628a0SDimitry Andric 
221239d628a0SDimitry Andric       // If this isn't a LocalAsMetadata record, we're dropping it.  This used
221339d628a0SDimitry Andric       // to be legal, but there's no upgrade path.
221439d628a0SDimitry Andric       auto dropRecord = [&] {
22157d523365SDimitry Andric         MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
221639d628a0SDimitry Andric       };
221739d628a0SDimitry Andric       if (Record.size() != 2) {
221839d628a0SDimitry Andric         dropRecord();
221939d628a0SDimitry Andric         break;
222039d628a0SDimitry Andric       }
222139d628a0SDimitry Andric 
222239d628a0SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
222339d628a0SDimitry Andric       if (Ty->isMetadataTy() || Ty->isVoidTy()) {
222439d628a0SDimitry Andric         dropRecord();
222539d628a0SDimitry Andric         break;
222639d628a0SDimitry Andric       }
222739d628a0SDimitry Andric 
22287d523365SDimitry Andric       MetadataList.assignValue(
222939d628a0SDimitry Andric           LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
22307d523365SDimitry Andric           NextMetadataNo++);
223139d628a0SDimitry Andric       break;
223239d628a0SDimitry Andric     }
223339d628a0SDimitry Andric     case bitc::METADATA_OLD_NODE: {
223439d628a0SDimitry Andric       // FIXME: Remove in 4.0.
223539d628a0SDimitry Andric       if (Record.size() % 2 == 1)
22368f0fd8f6SDimitry Andric         return error("Invalid record");
2237f22ef01cSRoman Divacky 
2238f22ef01cSRoman Divacky       unsigned Size = Record.size();
223939d628a0SDimitry Andric       SmallVector<Metadata *, 8> Elts;
2240f22ef01cSRoman Divacky       for (unsigned i = 0; i != Size; i += 2) {
22416122f3e6SDimitry Andric         Type *Ty = getTypeByID(Record[i]);
2242f785676fSDimitry Andric         if (!Ty)
22438f0fd8f6SDimitry Andric           return error("Invalid record");
2244f22ef01cSRoman Divacky         if (Ty->isMetadataTy())
22453ca95b02SDimitry Andric           Elts.push_back(getMD(Record[i + 1]));
224639d628a0SDimitry Andric         else if (!Ty->isVoidTy()) {
224739d628a0SDimitry Andric           auto *MD =
224839d628a0SDimitry Andric               ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
224939d628a0SDimitry Andric           assert(isa<ConstantAsMetadata>(MD) &&
225039d628a0SDimitry Andric                  "Expected non-function-local metadata");
225139d628a0SDimitry Andric           Elts.push_back(MD);
225239d628a0SDimitry Andric         } else
225391bc56edSDimitry Andric           Elts.push_back(nullptr);
2254f22ef01cSRoman Divacky       }
22557d523365SDimitry Andric       MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
225639d628a0SDimitry Andric       break;
225739d628a0SDimitry Andric     }
225839d628a0SDimitry Andric     case bitc::METADATA_VALUE: {
225939d628a0SDimitry Andric       if (Record.size() != 2)
22608f0fd8f6SDimitry Andric         return error("Invalid record");
226139d628a0SDimitry Andric 
226239d628a0SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
226339d628a0SDimitry Andric       if (Ty->isMetadataTy() || Ty->isVoidTy())
22648f0fd8f6SDimitry Andric         return error("Invalid record");
226539d628a0SDimitry Andric 
22667d523365SDimitry Andric       MetadataList.assignValue(
226739d628a0SDimitry Andric           ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
22687d523365SDimitry Andric           NextMetadataNo++);
226939d628a0SDimitry Andric       break;
227039d628a0SDimitry Andric     }
227139d628a0SDimitry Andric     case bitc::METADATA_DISTINCT_NODE:
227239d628a0SDimitry Andric       IsDistinct = true;
227339d628a0SDimitry Andric       // fallthrough...
227439d628a0SDimitry Andric     case bitc::METADATA_NODE: {
227539d628a0SDimitry Andric       SmallVector<Metadata *, 8> Elts;
227639d628a0SDimitry Andric       Elts.reserve(Record.size());
227739d628a0SDimitry Andric       for (unsigned ID : Record)
22783ca95b02SDimitry Andric         Elts.push_back(getMDOrNull(ID));
22797d523365SDimitry Andric       MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
228039d628a0SDimitry Andric                                           : MDNode::get(Context, Elts),
22817d523365SDimitry Andric                                NextMetadataNo++);
228239d628a0SDimitry Andric       break;
228339d628a0SDimitry Andric     }
228439d628a0SDimitry Andric     case bitc::METADATA_LOCATION: {
228539d628a0SDimitry Andric       if (Record.size() != 5)
22868f0fd8f6SDimitry Andric         return error("Invalid record");
228739d628a0SDimitry Andric 
22883ca95b02SDimitry Andric       IsDistinct = Record[0];
228939d628a0SDimitry Andric       unsigned Line = Record[1];
229039d628a0SDimitry Andric       unsigned Column = Record[2];
22913ca95b02SDimitry Andric       Metadata *Scope = getMD(Record[3]);
22923ca95b02SDimitry Andric       Metadata *InlinedAt = getMDOrNull(Record[4]);
22937d523365SDimitry Andric       MetadataList.assignValue(
22943ca95b02SDimitry Andric           GET_OR_DISTINCT(DILocation,
2295ff0cc061SDimitry Andric                           (Context, Line, Column, Scope, InlinedAt)),
22967d523365SDimitry Andric           NextMetadataNo++);
2297ff0cc061SDimitry Andric       break;
2298ff0cc061SDimitry Andric     }
2299ff0cc061SDimitry Andric     case bitc::METADATA_GENERIC_DEBUG: {
2300ff0cc061SDimitry Andric       if (Record.size() < 4)
23018f0fd8f6SDimitry Andric         return error("Invalid record");
2302ff0cc061SDimitry Andric 
23033ca95b02SDimitry Andric       IsDistinct = Record[0];
2304ff0cc061SDimitry Andric       unsigned Tag = Record[1];
2305ff0cc061SDimitry Andric       unsigned Version = Record[2];
2306ff0cc061SDimitry Andric 
2307ff0cc061SDimitry Andric       if (Tag >= 1u << 16 || Version != 0)
23088f0fd8f6SDimitry Andric         return error("Invalid record");
2309ff0cc061SDimitry Andric 
2310ff0cc061SDimitry Andric       auto *Header = getMDString(Record[3]);
2311ff0cc061SDimitry Andric       SmallVector<Metadata *, 8> DwarfOps;
2312ff0cc061SDimitry Andric       for (unsigned I = 4, E = Record.size(); I != E; ++I)
23133ca95b02SDimitry Andric         DwarfOps.push_back(getMDOrNull(Record[I]));
23147d523365SDimitry Andric       MetadataList.assignValue(
23153ca95b02SDimitry Andric           GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
23167d523365SDimitry Andric           NextMetadataNo++);
2317ff0cc061SDimitry Andric       break;
2318ff0cc061SDimitry Andric     }
2319ff0cc061SDimitry Andric     case bitc::METADATA_SUBRANGE: {
2320ff0cc061SDimitry Andric       if (Record.size() != 3)
23218f0fd8f6SDimitry Andric         return error("Invalid record");
2322ff0cc061SDimitry Andric 
23233ca95b02SDimitry Andric       IsDistinct = Record[0];
23247d523365SDimitry Andric       MetadataList.assignValue(
23253ca95b02SDimitry Andric           GET_OR_DISTINCT(DISubrange,
2326ff0cc061SDimitry Andric                           (Context, Record[1], unrotateSign(Record[2]))),
23277d523365SDimitry Andric           NextMetadataNo++);
2328ff0cc061SDimitry Andric       break;
2329ff0cc061SDimitry Andric     }
2330ff0cc061SDimitry Andric     case bitc::METADATA_ENUMERATOR: {
2331ff0cc061SDimitry Andric       if (Record.size() != 3)
23328f0fd8f6SDimitry Andric         return error("Invalid record");
2333ff0cc061SDimitry Andric 
23343ca95b02SDimitry Andric       IsDistinct = Record[0];
23357d523365SDimitry Andric       MetadataList.assignValue(
23363ca95b02SDimitry Andric           GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
23373ca95b02SDimitry Andric                                          getMDString(Record[2]))),
23387d523365SDimitry Andric           NextMetadataNo++);
2339ff0cc061SDimitry Andric       break;
2340ff0cc061SDimitry Andric     }
2341ff0cc061SDimitry Andric     case bitc::METADATA_BASIC_TYPE: {
2342ff0cc061SDimitry Andric       if (Record.size() != 6)
23438f0fd8f6SDimitry Andric         return error("Invalid record");
2344ff0cc061SDimitry Andric 
23453ca95b02SDimitry Andric       IsDistinct = Record[0];
23467d523365SDimitry Andric       MetadataList.assignValue(
23473ca95b02SDimitry Andric           GET_OR_DISTINCT(DIBasicType,
2348ff0cc061SDimitry Andric                           (Context, Record[1], getMDString(Record[2]),
2349ff0cc061SDimitry Andric                            Record[3], Record[4], Record[5])),
23507d523365SDimitry Andric           NextMetadataNo++);
2351ff0cc061SDimitry Andric       break;
2352ff0cc061SDimitry Andric     }
2353ff0cc061SDimitry Andric     case bitc::METADATA_DERIVED_TYPE: {
2354ff0cc061SDimitry Andric       if (Record.size() != 12)
23558f0fd8f6SDimitry Andric         return error("Invalid record");
2356ff0cc061SDimitry Andric 
23573ca95b02SDimitry Andric       IsDistinct = Record[0];
23587d523365SDimitry Andric       MetadataList.assignValue(
23593ca95b02SDimitry Andric           GET_OR_DISTINCT(
23603ca95b02SDimitry Andric               DIDerivedType,
2361ff0cc061SDimitry Andric               (Context, Record[1], getMDString(Record[2]),
23623ca95b02SDimitry Andric                getMDOrNull(Record[3]), Record[4], getDITypeRefOrNull(Record[5]),
23633ca95b02SDimitry Andric                getDITypeRefOrNull(Record[6]), Record[7], Record[8], Record[9],
23643ca95b02SDimitry Andric                Record[10], getDITypeRefOrNull(Record[11]))),
23657d523365SDimitry Andric           NextMetadataNo++);
2366ff0cc061SDimitry Andric       break;
2367ff0cc061SDimitry Andric     }
2368ff0cc061SDimitry Andric     case bitc::METADATA_COMPOSITE_TYPE: {
2369ff0cc061SDimitry Andric       if (Record.size() != 16)
23708f0fd8f6SDimitry Andric         return error("Invalid record");
2371ff0cc061SDimitry Andric 
23723ca95b02SDimitry Andric       // If we have a UUID and this is not a forward declaration, lookup the
23733ca95b02SDimitry Andric       // mapping.
23743ca95b02SDimitry Andric       IsDistinct = Record[0] & 0x1;
23753ca95b02SDimitry Andric       bool IsNotUsedInTypeRef = Record[0] >= 2;
23763ca95b02SDimitry Andric       unsigned Tag = Record[1];
23773ca95b02SDimitry Andric       MDString *Name = getMDString(Record[2]);
23783ca95b02SDimitry Andric       Metadata *File = getMDOrNull(Record[3]);
23793ca95b02SDimitry Andric       unsigned Line = Record[4];
23803ca95b02SDimitry Andric       Metadata *Scope = getDITypeRefOrNull(Record[5]);
23813ca95b02SDimitry Andric       Metadata *BaseType = getDITypeRefOrNull(Record[6]);
23823ca95b02SDimitry Andric       uint64_t SizeInBits = Record[7];
23833ca95b02SDimitry Andric       uint64_t AlignInBits = Record[8];
23843ca95b02SDimitry Andric       uint64_t OffsetInBits = Record[9];
23853ca95b02SDimitry Andric       unsigned Flags = Record[10];
23863ca95b02SDimitry Andric       Metadata *Elements = getMDOrNull(Record[11]);
23873ca95b02SDimitry Andric       unsigned RuntimeLang = Record[12];
23883ca95b02SDimitry Andric       Metadata *VTableHolder = getDITypeRefOrNull(Record[13]);
23893ca95b02SDimitry Andric       Metadata *TemplateParams = getMDOrNull(Record[14]);
23903ca95b02SDimitry Andric       auto *Identifier = getMDString(Record[15]);
23913ca95b02SDimitry Andric       DICompositeType *CT = nullptr;
23923ca95b02SDimitry Andric       if (Identifier)
23933ca95b02SDimitry Andric         CT = DICompositeType::buildODRType(
23943ca95b02SDimitry Andric             Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
23953ca95b02SDimitry Andric             SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
23963ca95b02SDimitry Andric             VTableHolder, TemplateParams);
23973ca95b02SDimitry Andric 
23983ca95b02SDimitry Andric       // Create a node if we didn't get a lazy ODR type.
23993ca95b02SDimitry Andric       if (!CT)
24003ca95b02SDimitry Andric         CT = GET_OR_DISTINCT(DICompositeType,
24013ca95b02SDimitry Andric                              (Context, Tag, Name, File, Line, Scope, BaseType,
24023ca95b02SDimitry Andric                               SizeInBits, AlignInBits, OffsetInBits, Flags,
24033ca95b02SDimitry Andric                               Elements, RuntimeLang, VTableHolder,
24043ca95b02SDimitry Andric                               TemplateParams, Identifier));
24053ca95b02SDimitry Andric       if (!IsNotUsedInTypeRef && Identifier)
24063ca95b02SDimitry Andric         MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
24073ca95b02SDimitry Andric 
24083ca95b02SDimitry Andric       MetadataList.assignValue(CT, NextMetadataNo++);
2409ff0cc061SDimitry Andric       break;
2410ff0cc061SDimitry Andric     }
2411ff0cc061SDimitry Andric     case bitc::METADATA_SUBROUTINE_TYPE: {
24123ca95b02SDimitry Andric       if (Record.size() < 3 || Record.size() > 4)
24138f0fd8f6SDimitry Andric         return error("Invalid record");
24143ca95b02SDimitry Andric       bool IsOldTypeRefArray = Record[0] < 2;
24153ca95b02SDimitry Andric       unsigned CC = (Record.size() > 3) ? Record[3] : 0;
24163ca95b02SDimitry Andric 
24173ca95b02SDimitry Andric       IsDistinct = Record[0] & 0x1;
24183ca95b02SDimitry Andric       Metadata *Types = getMDOrNull(Record[2]);
24193ca95b02SDimitry Andric       if (LLVM_UNLIKELY(IsOldTypeRefArray))
24203ca95b02SDimitry Andric         Types = MetadataList.upgradeTypeRefArray(Types);
2421ff0cc061SDimitry Andric 
24227d523365SDimitry Andric       MetadataList.assignValue(
24233ca95b02SDimitry Andric           GET_OR_DISTINCT(DISubroutineType, (Context, Record[1], CC, Types)),
24247d523365SDimitry Andric           NextMetadataNo++);
2425ff0cc061SDimitry Andric       break;
2426ff0cc061SDimitry Andric     }
24273dac3a9bSDimitry Andric 
24283dac3a9bSDimitry Andric     case bitc::METADATA_MODULE: {
24293dac3a9bSDimitry Andric       if (Record.size() != 6)
24303dac3a9bSDimitry Andric         return error("Invalid record");
24313dac3a9bSDimitry Andric 
24323ca95b02SDimitry Andric       IsDistinct = Record[0];
24337d523365SDimitry Andric       MetadataList.assignValue(
24343ca95b02SDimitry Andric           GET_OR_DISTINCT(DIModule,
24353dac3a9bSDimitry Andric                           (Context, getMDOrNull(Record[1]),
24363dac3a9bSDimitry Andric                            getMDString(Record[2]), getMDString(Record[3]),
24373dac3a9bSDimitry Andric                            getMDString(Record[4]), getMDString(Record[5]))),
24387d523365SDimitry Andric           NextMetadataNo++);
24393dac3a9bSDimitry Andric       break;
24403dac3a9bSDimitry Andric     }
24413dac3a9bSDimitry Andric 
2442ff0cc061SDimitry Andric     case bitc::METADATA_FILE: {
2443ff0cc061SDimitry Andric       if (Record.size() != 3)
24448f0fd8f6SDimitry Andric         return error("Invalid record");
2445ff0cc061SDimitry Andric 
24463ca95b02SDimitry Andric       IsDistinct = Record[0];
24477d523365SDimitry Andric       MetadataList.assignValue(
24483ca95b02SDimitry Andric           GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]),
2449ff0cc061SDimitry Andric                                    getMDString(Record[2]))),
24507d523365SDimitry Andric           NextMetadataNo++);
2451ff0cc061SDimitry Andric       break;
2452ff0cc061SDimitry Andric     }
2453ff0cc061SDimitry Andric     case bitc::METADATA_COMPILE_UNIT: {
24547d523365SDimitry Andric       if (Record.size() < 14 || Record.size() > 16)
24558f0fd8f6SDimitry Andric         return error("Invalid record");
2456ff0cc061SDimitry Andric 
24577d523365SDimitry Andric       // Ignore Record[0], which indicates whether this compile unit is
24587d523365SDimitry Andric       // distinct.  It's always distinct.
24593ca95b02SDimitry Andric       IsDistinct = true;
24603ca95b02SDimitry Andric       auto *CU = DICompileUnit::getDistinct(
24613ca95b02SDimitry Andric           Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
24623ca95b02SDimitry Andric           Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
24633ca95b02SDimitry Andric           Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
24643ca95b02SDimitry Andric           getMDOrNull(Record[12]), getMDOrNull(Record[13]),
24653ca95b02SDimitry Andric           Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
24663ca95b02SDimitry Andric           Record.size() <= 14 ? 0 : Record[14]);
24673ca95b02SDimitry Andric 
24683ca95b02SDimitry Andric       MetadataList.assignValue(CU, NextMetadataNo++);
24693ca95b02SDimitry Andric 
24703ca95b02SDimitry Andric       // Move the Upgrade the list of subprograms.
24713ca95b02SDimitry Andric       if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
24723ca95b02SDimitry Andric         CUSubprograms.push_back({CU, SPs});
2473ff0cc061SDimitry Andric       break;
2474ff0cc061SDimitry Andric     }
2475ff0cc061SDimitry Andric     case bitc::METADATA_SUBPROGRAM: {
24763ca95b02SDimitry Andric       if (Record.size() < 18 || Record.size() > 20)
24778f0fd8f6SDimitry Andric         return error("Invalid record");
2478ff0cc061SDimitry Andric 
24793ca95b02SDimitry Andric       IsDistinct =
24803ca95b02SDimitry Andric           (Record[0] & 1) || Record[8]; // All definitions should be distinct.
24813ca95b02SDimitry Andric       // Version 1 has a Function as Record[15].
24823ca95b02SDimitry Andric       // Version 2 has removed Record[15].
24833ca95b02SDimitry Andric       // Version 3 has the Unit as Record[15].
24843ca95b02SDimitry Andric       // Version 4 added thisAdjustment.
24853ca95b02SDimitry Andric       bool HasUnit = Record[0] >= 2;
24863ca95b02SDimitry Andric       if (HasUnit && Record.size() < 19)
24873ca95b02SDimitry Andric         return error("Invalid record");
24883ca95b02SDimitry Andric       Metadata *CUorFn = getMDOrNull(Record[15]);
24893ca95b02SDimitry Andric       unsigned Offset = Record.size() >= 19 ? 1 : 0;
24903ca95b02SDimitry Andric       bool HasFn = Offset && !HasUnit;
24913ca95b02SDimitry Andric       bool HasThisAdj = Record.size() >= 20;
24927d523365SDimitry Andric       DISubprogram *SP = GET_OR_DISTINCT(
24933ca95b02SDimitry Andric           DISubprogram, (Context,
24943ca95b02SDimitry Andric                          getDITypeRefOrNull(Record[1]),    // scope
24953ca95b02SDimitry Andric                          getMDString(Record[2]),           // name
24963ca95b02SDimitry Andric                          getMDString(Record[3]),           // linkageName
24973ca95b02SDimitry Andric                          getMDOrNull(Record[4]),           // file
24983ca95b02SDimitry Andric                          Record[5],                        // line
24993ca95b02SDimitry Andric                          getMDOrNull(Record[6]),           // type
25003ca95b02SDimitry Andric                          Record[7],                        // isLocal
25013ca95b02SDimitry Andric                          Record[8],                        // isDefinition
25023ca95b02SDimitry Andric                          Record[9],                        // scopeLine
25033ca95b02SDimitry Andric                          getDITypeRefOrNull(Record[10]),   // containingType
25043ca95b02SDimitry Andric                          Record[11],                       // virtuality
25053ca95b02SDimitry Andric                          Record[12],                       // virtualIndex
25063ca95b02SDimitry Andric                          HasThisAdj ? Record[19] : 0,      // thisAdjustment
25073ca95b02SDimitry Andric                          Record[13],                       // flags
25083ca95b02SDimitry Andric                          Record[14],                       // isOptimized
25093ca95b02SDimitry Andric                          HasUnit ? CUorFn : nullptr,       // unit
25103ca95b02SDimitry Andric                          getMDOrNull(Record[15 + Offset]), // templateParams
25113ca95b02SDimitry Andric                          getMDOrNull(Record[16 + Offset]), // declaration
25123ca95b02SDimitry Andric                          getMDOrNull(Record[17 + Offset])  // variables
25133ca95b02SDimitry Andric                          ));
25147d523365SDimitry Andric       MetadataList.assignValue(SP, NextMetadataNo++);
25157d523365SDimitry Andric 
25167d523365SDimitry Andric       // Upgrade sp->function mapping to function->sp mapping.
25173ca95b02SDimitry Andric       if (HasFn) {
25183ca95b02SDimitry Andric         if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
25197d523365SDimitry Andric           if (auto *F = dyn_cast<Function>(CMD->getValue())) {
25207d523365SDimitry Andric             if (F->isMaterializable())
25217d523365SDimitry Andric               // Defer until materialized; unmaterialized functions may not have
25227d523365SDimitry Andric               // metadata.
25237d523365SDimitry Andric               FunctionsWithSPs[F] = SP;
25247d523365SDimitry Andric             else if (!F->empty())
25257d523365SDimitry Andric               F->setSubprogram(SP);
25267d523365SDimitry Andric           }
25277d523365SDimitry Andric       }
2528ff0cc061SDimitry Andric       break;
2529ff0cc061SDimitry Andric     }
2530ff0cc061SDimitry Andric     case bitc::METADATA_LEXICAL_BLOCK: {
2531ff0cc061SDimitry Andric       if (Record.size() != 5)
25328f0fd8f6SDimitry Andric         return error("Invalid record");
2533ff0cc061SDimitry Andric 
25343ca95b02SDimitry Andric       IsDistinct = Record[0];
25357d523365SDimitry Andric       MetadataList.assignValue(
25363ca95b02SDimitry Andric           GET_OR_DISTINCT(DILexicalBlock,
2537ff0cc061SDimitry Andric                           (Context, getMDOrNull(Record[1]),
2538ff0cc061SDimitry Andric                            getMDOrNull(Record[2]), Record[3], Record[4])),
25397d523365SDimitry Andric           NextMetadataNo++);
2540ff0cc061SDimitry Andric       break;
2541ff0cc061SDimitry Andric     }
2542ff0cc061SDimitry Andric     case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2543ff0cc061SDimitry Andric       if (Record.size() != 4)
25448f0fd8f6SDimitry Andric         return error("Invalid record");
2545ff0cc061SDimitry Andric 
25463ca95b02SDimitry Andric       IsDistinct = Record[0];
25477d523365SDimitry Andric       MetadataList.assignValue(
25483ca95b02SDimitry Andric           GET_OR_DISTINCT(DILexicalBlockFile,
2549ff0cc061SDimitry Andric                           (Context, getMDOrNull(Record[1]),
2550ff0cc061SDimitry Andric                            getMDOrNull(Record[2]), Record[3])),
25517d523365SDimitry Andric           NextMetadataNo++);
2552ff0cc061SDimitry Andric       break;
2553ff0cc061SDimitry Andric     }
2554ff0cc061SDimitry Andric     case bitc::METADATA_NAMESPACE: {
2555ff0cc061SDimitry Andric       if (Record.size() != 5)
25568f0fd8f6SDimitry Andric         return error("Invalid record");
2557ff0cc061SDimitry Andric 
25583ca95b02SDimitry Andric       IsDistinct = Record[0];
25597d523365SDimitry Andric       MetadataList.assignValue(
25603ca95b02SDimitry Andric           GET_OR_DISTINCT(DINamespace, (Context, getMDOrNull(Record[1]),
25613ca95b02SDimitry Andric                                         getMDOrNull(Record[2]),
25623ca95b02SDimitry Andric                                         getMDString(Record[3]), Record[4])),
25637d523365SDimitry Andric           NextMetadataNo++);
25647d523365SDimitry Andric       break;
25657d523365SDimitry Andric     }
25667d523365SDimitry Andric     case bitc::METADATA_MACRO: {
25677d523365SDimitry Andric       if (Record.size() != 5)
25687d523365SDimitry Andric         return error("Invalid record");
25697d523365SDimitry Andric 
25703ca95b02SDimitry Andric       IsDistinct = Record[0];
25717d523365SDimitry Andric       MetadataList.assignValue(
25723ca95b02SDimitry Andric           GET_OR_DISTINCT(DIMacro,
25737d523365SDimitry Andric                           (Context, Record[1], Record[2],
25747d523365SDimitry Andric                            getMDString(Record[3]), getMDString(Record[4]))),
25757d523365SDimitry Andric           NextMetadataNo++);
25767d523365SDimitry Andric       break;
25777d523365SDimitry Andric     }
25787d523365SDimitry Andric     case bitc::METADATA_MACRO_FILE: {
25797d523365SDimitry Andric       if (Record.size() != 5)
25807d523365SDimitry Andric         return error("Invalid record");
25817d523365SDimitry Andric 
25823ca95b02SDimitry Andric       IsDistinct = Record[0];
25837d523365SDimitry Andric       MetadataList.assignValue(
25843ca95b02SDimitry Andric           GET_OR_DISTINCT(DIMacroFile,
25857d523365SDimitry Andric                           (Context, Record[1], Record[2],
25867d523365SDimitry Andric                            getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
25877d523365SDimitry Andric           NextMetadataNo++);
2588ff0cc061SDimitry Andric       break;
2589ff0cc061SDimitry Andric     }
2590ff0cc061SDimitry Andric     case bitc::METADATA_TEMPLATE_TYPE: {
2591ff0cc061SDimitry Andric       if (Record.size() != 3)
25928f0fd8f6SDimitry Andric         return error("Invalid record");
2593ff0cc061SDimitry Andric 
25943ca95b02SDimitry Andric       IsDistinct = Record[0];
25957d523365SDimitry Andric       MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2596ff0cc061SDimitry Andric                                                (Context, getMDString(Record[1]),
25973ca95b02SDimitry Andric                                                 getDITypeRefOrNull(Record[2]))),
25987d523365SDimitry Andric                                NextMetadataNo++);
2599ff0cc061SDimitry Andric       break;
2600ff0cc061SDimitry Andric     }
2601ff0cc061SDimitry Andric     case bitc::METADATA_TEMPLATE_VALUE: {
2602ff0cc061SDimitry Andric       if (Record.size() != 5)
26038f0fd8f6SDimitry Andric         return error("Invalid record");
2604ff0cc061SDimitry Andric 
26053ca95b02SDimitry Andric       IsDistinct = Record[0];
26067d523365SDimitry Andric       MetadataList.assignValue(
26073ca95b02SDimitry Andric           GET_OR_DISTINCT(DITemplateValueParameter,
2608ff0cc061SDimitry Andric                           (Context, Record[1], getMDString(Record[2]),
26093ca95b02SDimitry Andric                            getDITypeRefOrNull(Record[3]),
26103ca95b02SDimitry Andric                            getMDOrNull(Record[4]))),
26117d523365SDimitry Andric           NextMetadataNo++);
2612ff0cc061SDimitry Andric       break;
2613ff0cc061SDimitry Andric     }
2614ff0cc061SDimitry Andric     case bitc::METADATA_GLOBAL_VAR: {
2615ff0cc061SDimitry Andric       if (Record.size() != 11)
26168f0fd8f6SDimitry Andric         return error("Invalid record");
2617ff0cc061SDimitry Andric 
26183ca95b02SDimitry Andric       IsDistinct = Record[0];
26197d523365SDimitry Andric       MetadataList.assignValue(
26203ca95b02SDimitry Andric           GET_OR_DISTINCT(DIGlobalVariable,
2621ff0cc061SDimitry Andric                           (Context, getMDOrNull(Record[1]),
2622ff0cc061SDimitry Andric                            getMDString(Record[2]), getMDString(Record[3]),
2623ff0cc061SDimitry Andric                            getMDOrNull(Record[4]), Record[5],
26243ca95b02SDimitry Andric                            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2625ff0cc061SDimitry Andric                            getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
26267d523365SDimitry Andric           NextMetadataNo++);
2627ff0cc061SDimitry Andric       break;
2628ff0cc061SDimitry Andric     }
2629ff0cc061SDimitry Andric     case bitc::METADATA_LOCAL_VAR: {
2630ff0cc061SDimitry Andric       // 10th field is for the obseleted 'inlinedAt:' field.
26317d523365SDimitry Andric       if (Record.size() < 8 || Record.size() > 10)
26328f0fd8f6SDimitry Andric         return error("Invalid record");
2633ff0cc061SDimitry Andric 
26347d523365SDimitry Andric       // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
26357d523365SDimitry Andric       // DW_TAG_arg_variable.
26363ca95b02SDimitry Andric       IsDistinct = Record[0];
26377d523365SDimitry Andric       bool HasTag = Record.size() > 8;
26387d523365SDimitry Andric       MetadataList.assignValue(
26393ca95b02SDimitry Andric           GET_OR_DISTINCT(DILocalVariable,
26407d523365SDimitry Andric                           (Context, getMDOrNull(Record[1 + HasTag]),
26417d523365SDimitry Andric                            getMDString(Record[2 + HasTag]),
26427d523365SDimitry Andric                            getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
26433ca95b02SDimitry Andric                            getDITypeRefOrNull(Record[5 + HasTag]),
26443ca95b02SDimitry Andric                            Record[6 + HasTag], Record[7 + HasTag])),
26457d523365SDimitry Andric           NextMetadataNo++);
2646ff0cc061SDimitry Andric       break;
2647ff0cc061SDimitry Andric     }
2648ff0cc061SDimitry Andric     case bitc::METADATA_EXPRESSION: {
2649ff0cc061SDimitry Andric       if (Record.size() < 1)
26508f0fd8f6SDimitry Andric         return error("Invalid record");
2651ff0cc061SDimitry Andric 
26523ca95b02SDimitry Andric       IsDistinct = Record[0];
26537d523365SDimitry Andric       MetadataList.assignValue(
26543ca95b02SDimitry Andric           GET_OR_DISTINCT(DIExpression,
2655ff0cc061SDimitry Andric                           (Context, makeArrayRef(Record).slice(1))),
26567d523365SDimitry Andric           NextMetadataNo++);
2657ff0cc061SDimitry Andric       break;
2658ff0cc061SDimitry Andric     }
2659ff0cc061SDimitry Andric     case bitc::METADATA_OBJC_PROPERTY: {
2660ff0cc061SDimitry Andric       if (Record.size() != 8)
26618f0fd8f6SDimitry Andric         return error("Invalid record");
2662ff0cc061SDimitry Andric 
26633ca95b02SDimitry Andric       IsDistinct = Record[0];
26647d523365SDimitry Andric       MetadataList.assignValue(
26653ca95b02SDimitry Andric           GET_OR_DISTINCT(DIObjCProperty,
2666ff0cc061SDimitry Andric                           (Context, getMDString(Record[1]),
2667ff0cc061SDimitry Andric                            getMDOrNull(Record[2]), Record[3],
2668ff0cc061SDimitry Andric                            getMDString(Record[4]), getMDString(Record[5]),
26693ca95b02SDimitry Andric                            Record[6], getDITypeRefOrNull(Record[7]))),
26707d523365SDimitry Andric           NextMetadataNo++);
2671ff0cc061SDimitry Andric       break;
2672ff0cc061SDimitry Andric     }
2673ff0cc061SDimitry Andric     case bitc::METADATA_IMPORTED_ENTITY: {
2674ff0cc061SDimitry Andric       if (Record.size() != 6)
26758f0fd8f6SDimitry Andric         return error("Invalid record");
2676ff0cc061SDimitry Andric 
26773ca95b02SDimitry Andric       IsDistinct = Record[0];
26787d523365SDimitry Andric       MetadataList.assignValue(
26793ca95b02SDimitry Andric           GET_OR_DISTINCT(DIImportedEntity,
2680ff0cc061SDimitry Andric                           (Context, Record[1], getMDOrNull(Record[2]),
26813ca95b02SDimitry Andric                            getDITypeRefOrNull(Record[3]), Record[4],
2682ff0cc061SDimitry Andric                            getMDString(Record[5]))),
26837d523365SDimitry Andric           NextMetadataNo++);
2684f22ef01cSRoman Divacky       break;
2685f22ef01cSRoman Divacky     }
26863ca95b02SDimitry Andric     case bitc::METADATA_STRING_OLD: {
268791bc56edSDimitry Andric       std::string String(Record.begin(), Record.end());
26883ca95b02SDimitry Andric 
26893ca95b02SDimitry Andric       // Test for upgrading !llvm.loop.
26903ca95b02SDimitry Andric       HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
26913ca95b02SDimitry Andric 
269239d628a0SDimitry Andric       Metadata *MD = MDString::get(Context, String);
26937d523365SDimitry Andric       MetadataList.assignValue(MD, NextMetadataNo++);
2694f22ef01cSRoman Divacky       break;
2695f22ef01cSRoman Divacky     }
26963ca95b02SDimitry Andric     case bitc::METADATA_STRINGS:
26973ca95b02SDimitry Andric       if (std::error_code EC =
26983ca95b02SDimitry Andric               parseMetadataStrings(Record, Blob, NextMetadataNo))
26993ca95b02SDimitry Andric         return EC;
27003ca95b02SDimitry Andric       break;
27013ca95b02SDimitry Andric     case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
27023ca95b02SDimitry Andric       if (Record.size() % 2 == 0)
27033ca95b02SDimitry Andric         return error("Invalid record");
27043ca95b02SDimitry Andric       unsigned ValueID = Record[0];
27053ca95b02SDimitry Andric       if (ValueID >= ValueList.size())
27063ca95b02SDimitry Andric         return error("Invalid record");
27073ca95b02SDimitry Andric       if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
27083ca95b02SDimitry Andric         parseGlobalObjectAttachment(*GO, ArrayRef<uint64_t>(Record).slice(1));
27093ca95b02SDimitry Andric       break;
27103ca95b02SDimitry Andric     }
2711f22ef01cSRoman Divacky     case bitc::METADATA_KIND: {
27127d523365SDimitry Andric       // Support older bitcode files that had METADATA_KIND records in a
27137d523365SDimitry Andric       // block with METADATA_BLOCK_ID.
27147d523365SDimitry Andric       if (std::error_code EC = parseMetadataKindRecord(Record))
27157d523365SDimitry Andric         return EC;
2716f22ef01cSRoman Divacky       break;
2717f22ef01cSRoman Divacky     }
2718f22ef01cSRoman Divacky     }
2719f22ef01cSRoman Divacky   }
2720ff0cc061SDimitry Andric #undef GET_OR_DISTINCT
2721f22ef01cSRoman Divacky }
2722f22ef01cSRoman Divacky 
27237d523365SDimitry Andric /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
27247d523365SDimitry Andric std::error_code BitcodeReader::parseMetadataKinds() {
27257d523365SDimitry Andric   if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
27267d523365SDimitry Andric     return error("Invalid record");
27277d523365SDimitry Andric 
27287d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
27297d523365SDimitry Andric 
27307d523365SDimitry Andric   // Read all the records.
27317d523365SDimitry Andric   while (1) {
27327d523365SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
27337d523365SDimitry Andric 
27347d523365SDimitry Andric     switch (Entry.Kind) {
27357d523365SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
27367d523365SDimitry Andric     case BitstreamEntry::Error:
27377d523365SDimitry Andric       return error("Malformed block");
27387d523365SDimitry Andric     case BitstreamEntry::EndBlock:
27397d523365SDimitry Andric       return std::error_code();
27407d523365SDimitry Andric     case BitstreamEntry::Record:
27417d523365SDimitry Andric       // The interesting case.
27427d523365SDimitry Andric       break;
27437d523365SDimitry Andric     }
27447d523365SDimitry Andric 
27457d523365SDimitry Andric     // Read a record.
27467d523365SDimitry Andric     Record.clear();
27477d523365SDimitry Andric     unsigned Code = Stream.readRecord(Entry.ID, Record);
27487d523365SDimitry Andric     switch (Code) {
27497d523365SDimitry Andric     default: // Default behavior: ignore.
27507d523365SDimitry Andric       break;
27517d523365SDimitry Andric     case bitc::METADATA_KIND: {
27527d523365SDimitry Andric       if (std::error_code EC = parseMetadataKindRecord(Record))
27537d523365SDimitry Andric         return EC;
27547d523365SDimitry Andric       break;
27557d523365SDimitry Andric     }
27567d523365SDimitry Andric     }
27577d523365SDimitry Andric   }
27587d523365SDimitry Andric }
27597d523365SDimitry Andric 
27608f0fd8f6SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR
27618f0fd8f6SDimitry Andric /// encoding.
27623861d79fSDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2763f22ef01cSRoman Divacky   if ((V & 1) == 0)
2764f22ef01cSRoman Divacky     return V >> 1;
2765f22ef01cSRoman Divacky   if (V != 1)
2766f22ef01cSRoman Divacky     return -(V >> 1);
2767f22ef01cSRoman Divacky   // There is no such thing as -0 with integers.  "-0" really means MININT.
2768f22ef01cSRoman Divacky   return 1ULL << 63;
2769f22ef01cSRoman Divacky }
2770f22ef01cSRoman Divacky 
27718f0fd8f6SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can.
27723ca95b02SDimitry Andric std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2773f22ef01cSRoman Divacky   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
27743ca95b02SDimitry Andric   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
27753ca95b02SDimitry Andric       IndirectSymbolInitWorklist;
2776f785676fSDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
277739d628a0SDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
27788f0fd8f6SDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
2779f22ef01cSRoman Divacky 
2780f22ef01cSRoman Divacky   GlobalInitWorklist.swap(GlobalInits);
27813ca95b02SDimitry Andric   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2782f785676fSDimitry Andric   FunctionPrefixWorklist.swap(FunctionPrefixes);
278339d628a0SDimitry Andric   FunctionPrologueWorklist.swap(FunctionPrologues);
27848f0fd8f6SDimitry Andric   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2785f22ef01cSRoman Divacky 
2786f22ef01cSRoman Divacky   while (!GlobalInitWorklist.empty()) {
2787f22ef01cSRoman Divacky     unsigned ValID = GlobalInitWorklist.back().second;
2788f22ef01cSRoman Divacky     if (ValID >= ValueList.size()) {
2789f22ef01cSRoman Divacky       // Not ready to resolve this yet, it requires something later in the file.
2790f22ef01cSRoman Divacky       GlobalInits.push_back(GlobalInitWorklist.back());
2791f22ef01cSRoman Divacky     } else {
279291bc56edSDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2793f22ef01cSRoman Divacky         GlobalInitWorklist.back().first->setInitializer(C);
2794f22ef01cSRoman Divacky       else
27958f0fd8f6SDimitry Andric         return error("Expected a constant");
2796f22ef01cSRoman Divacky     }
2797f22ef01cSRoman Divacky     GlobalInitWorklist.pop_back();
2798f22ef01cSRoman Divacky   }
2799f22ef01cSRoman Divacky 
28003ca95b02SDimitry Andric   while (!IndirectSymbolInitWorklist.empty()) {
28013ca95b02SDimitry Andric     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2802f22ef01cSRoman Divacky     if (ValID >= ValueList.size()) {
28033ca95b02SDimitry Andric       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2804f22ef01cSRoman Divacky     } else {
280597bc6c73SDimitry Andric       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
280697bc6c73SDimitry Andric       if (!C)
28078f0fd8f6SDimitry Andric         return error("Expected a constant");
28083ca95b02SDimitry Andric       GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
28093ca95b02SDimitry Andric       if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
28108f0fd8f6SDimitry Andric         return error("Alias and aliasee types don't match");
28113ca95b02SDimitry Andric       GIS->setIndirectSymbol(C);
2812f22ef01cSRoman Divacky     }
28133ca95b02SDimitry Andric     IndirectSymbolInitWorklist.pop_back();
2814f22ef01cSRoman Divacky   }
2815f785676fSDimitry Andric 
2816f785676fSDimitry Andric   while (!FunctionPrefixWorklist.empty()) {
2817f785676fSDimitry Andric     unsigned ValID = FunctionPrefixWorklist.back().second;
2818f785676fSDimitry Andric     if (ValID >= ValueList.size()) {
2819f785676fSDimitry Andric       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2820f785676fSDimitry Andric     } else {
282191bc56edSDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2822f785676fSDimitry Andric         FunctionPrefixWorklist.back().first->setPrefixData(C);
2823f785676fSDimitry Andric       else
28248f0fd8f6SDimitry Andric         return error("Expected a constant");
2825f785676fSDimitry Andric     }
2826f785676fSDimitry Andric     FunctionPrefixWorklist.pop_back();
2827f785676fSDimitry Andric   }
2828f785676fSDimitry Andric 
282939d628a0SDimitry Andric   while (!FunctionPrologueWorklist.empty()) {
283039d628a0SDimitry Andric     unsigned ValID = FunctionPrologueWorklist.back().second;
283139d628a0SDimitry Andric     if (ValID >= ValueList.size()) {
283239d628a0SDimitry Andric       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
283339d628a0SDimitry Andric     } else {
283439d628a0SDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
283539d628a0SDimitry Andric         FunctionPrologueWorklist.back().first->setPrologueData(C);
283639d628a0SDimitry Andric       else
28378f0fd8f6SDimitry Andric         return error("Expected a constant");
283839d628a0SDimitry Andric     }
283939d628a0SDimitry Andric     FunctionPrologueWorklist.pop_back();
284039d628a0SDimitry Andric   }
284139d628a0SDimitry Andric 
28428f0fd8f6SDimitry Andric   while (!FunctionPersonalityFnWorklist.empty()) {
28438f0fd8f6SDimitry Andric     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
28448f0fd8f6SDimitry Andric     if (ValID >= ValueList.size()) {
28458f0fd8f6SDimitry Andric       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
28468f0fd8f6SDimitry Andric     } else {
28478f0fd8f6SDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
28488f0fd8f6SDimitry Andric         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
28498f0fd8f6SDimitry Andric       else
28508f0fd8f6SDimitry Andric         return error("Expected a constant");
28518f0fd8f6SDimitry Andric     }
28528f0fd8f6SDimitry Andric     FunctionPersonalityFnWorklist.pop_back();
28538f0fd8f6SDimitry Andric   }
28548f0fd8f6SDimitry Andric 
285591bc56edSDimitry Andric   return std::error_code();
2856f22ef01cSRoman Divacky }
2857f22ef01cSRoman Divacky 
28588f0fd8f6SDimitry Andric static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
28597ae0e2c9SDimitry Andric   SmallVector<uint64_t, 8> Words(Vals.size());
28607ae0e2c9SDimitry Andric   std::transform(Vals.begin(), Vals.end(), Words.begin(),
28613861d79fSDimitry Andric                  BitcodeReader::decodeSignRotatedValue);
28627ae0e2c9SDimitry Andric 
28637ae0e2c9SDimitry Andric   return APInt(TypeBits, Words);
28647ae0e2c9SDimitry Andric }
28657ae0e2c9SDimitry Andric 
28668f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseConstants() {
2867f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
28688f0fd8f6SDimitry Andric     return error("Invalid record");
2869f22ef01cSRoman Divacky 
2870f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
2871f22ef01cSRoman Divacky 
2872f22ef01cSRoman Divacky   // Read all the records for this value table.
28736122f3e6SDimitry Andric   Type *CurTy = Type::getInt32Ty(Context);
2874f22ef01cSRoman Divacky   unsigned NextCstNo = ValueList.size();
2875f22ef01cSRoman Divacky   while (1) {
2876139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2877139f7f9bSDimitry Andric 
2878139f7f9bSDimitry Andric     switch (Entry.Kind) {
2879139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2880139f7f9bSDimitry Andric     case BitstreamEntry::Error:
28818f0fd8f6SDimitry Andric       return error("Malformed block");
2882139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
2883139f7f9bSDimitry Andric       if (NextCstNo != ValueList.size())
28843ca95b02SDimitry Andric         return error("Invalid constant reference");
2885139f7f9bSDimitry Andric 
2886139f7f9bSDimitry Andric       // Once all the constants have been read, go through and resolve forward
2887139f7f9bSDimitry Andric       // references.
28888f0fd8f6SDimitry Andric       ValueList.resolveConstantForwardRefs();
288991bc56edSDimitry Andric       return std::error_code();
2890139f7f9bSDimitry Andric     case BitstreamEntry::Record:
2891139f7f9bSDimitry Andric       // The interesting case.
2892f22ef01cSRoman Divacky       break;
2893f22ef01cSRoman Divacky     }
2894f22ef01cSRoman Divacky 
2895f22ef01cSRoman Divacky     // Read a record.
2896f22ef01cSRoman Divacky     Record.clear();
28973ca95b02SDimitry Andric     Type *VoidType = Type::getVoidTy(Context);
289891bc56edSDimitry Andric     Value *V = nullptr;
2899139f7f9bSDimitry Andric     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2900f22ef01cSRoman Divacky     switch (BitCode) {
2901f22ef01cSRoman Divacky     default:  // Default behavior: unknown constant
2902f22ef01cSRoman Divacky     case bitc::CST_CODE_UNDEF:     // UNDEF
2903f22ef01cSRoman Divacky       V = UndefValue::get(CurTy);
2904f22ef01cSRoman Divacky       break;
2905f22ef01cSRoman Divacky     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2906f22ef01cSRoman Divacky       if (Record.empty())
29078f0fd8f6SDimitry Andric         return error("Invalid record");
290891bc56edSDimitry Andric       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
29098f0fd8f6SDimitry Andric         return error("Invalid record");
29103ca95b02SDimitry Andric       if (TypeList[Record[0]] == VoidType)
29113ca95b02SDimitry Andric         return error("Invalid constant type");
2912f22ef01cSRoman Divacky       CurTy = TypeList[Record[0]];
2913f22ef01cSRoman Divacky       continue;  // Skip the ValueList manipulation.
2914f22ef01cSRoman Divacky     case bitc::CST_CODE_NULL:      // NULL
2915f22ef01cSRoman Divacky       V = Constant::getNullValue(CurTy);
2916f22ef01cSRoman Divacky       break;
2917f22ef01cSRoman Divacky     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2918f22ef01cSRoman Divacky       if (!CurTy->isIntegerTy() || Record.empty())
29198f0fd8f6SDimitry Andric         return error("Invalid record");
29203861d79fSDimitry Andric       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2921f22ef01cSRoman Divacky       break;
2922f22ef01cSRoman Divacky     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2923f22ef01cSRoman Divacky       if (!CurTy->isIntegerTy() || Record.empty())
29248f0fd8f6SDimitry Andric         return error("Invalid record");
2925f22ef01cSRoman Divacky 
29268f0fd8f6SDimitry Andric       APInt VInt =
29278f0fd8f6SDimitry Andric           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
29287ae0e2c9SDimitry Andric       V = ConstantInt::get(Context, VInt);
29297ae0e2c9SDimitry Andric 
2930f22ef01cSRoman Divacky       break;
2931f22ef01cSRoman Divacky     }
2932f22ef01cSRoman Divacky     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2933f22ef01cSRoman Divacky       if (Record.empty())
29348f0fd8f6SDimitry Andric         return error("Invalid record");
2935dff0c46cSDimitry Andric       if (CurTy->isHalfTy())
2936139f7f9bSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2937139f7f9bSDimitry Andric                                              APInt(16, (uint16_t)Record[0])));
2938dff0c46cSDimitry Andric       else if (CurTy->isFloatTy())
2939139f7f9bSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2940139f7f9bSDimitry Andric                                              APInt(32, (uint32_t)Record[0])));
2941f22ef01cSRoman Divacky       else if (CurTy->isDoubleTy())
2942139f7f9bSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2943139f7f9bSDimitry Andric                                              APInt(64, Record[0])));
2944f22ef01cSRoman Divacky       else if (CurTy->isX86_FP80Ty()) {
2945f22ef01cSRoman Divacky         // Bits are not stored the same way as a normal i80 APInt, compensate.
2946f22ef01cSRoman Divacky         uint64_t Rearrange[2];
2947f22ef01cSRoman Divacky         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2948f22ef01cSRoman Divacky         Rearrange[1] = Record[0] >> 48;
2949139f7f9bSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2950139f7f9bSDimitry Andric                                              APInt(80, Rearrange)));
2951f22ef01cSRoman Divacky       } else if (CurTy->isFP128Ty())
2952139f7f9bSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2953139f7f9bSDimitry Andric                                              APInt(128, Record)));
2954f22ef01cSRoman Divacky       else if (CurTy->isPPC_FP128Ty())
2955139f7f9bSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2956139f7f9bSDimitry Andric                                              APInt(128, Record)));
2957f22ef01cSRoman Divacky       else
2958f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);
2959f22ef01cSRoman Divacky       break;
2960f22ef01cSRoman Divacky     }
2961f22ef01cSRoman Divacky 
2962f22ef01cSRoman Divacky     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2963f22ef01cSRoman Divacky       if (Record.empty())
29648f0fd8f6SDimitry Andric         return error("Invalid record");
2965f22ef01cSRoman Divacky 
2966f22ef01cSRoman Divacky       unsigned Size = Record.size();
2967dff0c46cSDimitry Andric       SmallVector<Constant*, 16> Elts;
2968f22ef01cSRoman Divacky 
29696122f3e6SDimitry Andric       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2970f22ef01cSRoman Divacky         for (unsigned i = 0; i != Size; ++i)
2971f22ef01cSRoman Divacky           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2972f22ef01cSRoman Divacky                                                      STy->getElementType(i)));
2973f22ef01cSRoman Divacky         V = ConstantStruct::get(STy, Elts);
29746122f3e6SDimitry Andric       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
29756122f3e6SDimitry Andric         Type *EltTy = ATy->getElementType();
2976f22ef01cSRoman Divacky         for (unsigned i = 0; i != Size; ++i)
2977f22ef01cSRoman Divacky           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2978f22ef01cSRoman Divacky         V = ConstantArray::get(ATy, Elts);
29796122f3e6SDimitry Andric       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
29806122f3e6SDimitry Andric         Type *EltTy = VTy->getElementType();
2981f22ef01cSRoman Divacky         for (unsigned i = 0; i != Size; ++i)
2982f22ef01cSRoman Divacky           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2983f22ef01cSRoman Divacky         V = ConstantVector::get(Elts);
2984f22ef01cSRoman Divacky       } else {
2985f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);
2986f22ef01cSRoman Divacky       }
2987f22ef01cSRoman Divacky       break;
2988f22ef01cSRoman Divacky     }
2989dff0c46cSDimitry Andric     case bitc::CST_CODE_STRING:    // STRING: [values]
2990f22ef01cSRoman Divacky     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2991f22ef01cSRoman Divacky       if (Record.empty())
29928f0fd8f6SDimitry Andric         return error("Invalid record");
2993f22ef01cSRoman Divacky 
29947ae0e2c9SDimitry Andric       SmallString<16> Elts(Record.begin(), Record.end());
2995dff0c46cSDimitry Andric       V = ConstantDataArray::getString(Context, Elts,
2996dff0c46cSDimitry Andric                                        BitCode == bitc::CST_CODE_CSTRING);
2997f22ef01cSRoman Divacky       break;
2998f22ef01cSRoman Divacky     }
2999dff0c46cSDimitry Andric     case bitc::CST_CODE_DATA: {// DATA: [n x value]
3000dff0c46cSDimitry Andric       if (Record.empty())
30018f0fd8f6SDimitry Andric         return error("Invalid record");
3002dff0c46cSDimitry Andric 
3003dff0c46cSDimitry Andric       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
3004dff0c46cSDimitry Andric       if (EltTy->isIntegerTy(8)) {
3005dff0c46cSDimitry Andric         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3006dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
3007dff0c46cSDimitry Andric           V = ConstantDataVector::get(Context, Elts);
3008dff0c46cSDimitry Andric         else
3009dff0c46cSDimitry Andric           V = ConstantDataArray::get(Context, Elts);
3010dff0c46cSDimitry Andric       } else if (EltTy->isIntegerTy(16)) {
3011dff0c46cSDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3012dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
3013dff0c46cSDimitry Andric           V = ConstantDataVector::get(Context, Elts);
3014dff0c46cSDimitry Andric         else
3015dff0c46cSDimitry Andric           V = ConstantDataArray::get(Context, Elts);
3016dff0c46cSDimitry Andric       } else if (EltTy->isIntegerTy(32)) {
3017dff0c46cSDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3018dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
3019dff0c46cSDimitry Andric           V = ConstantDataVector::get(Context, Elts);
3020dff0c46cSDimitry Andric         else
3021dff0c46cSDimitry Andric           V = ConstantDataArray::get(Context, Elts);
3022dff0c46cSDimitry Andric       } else if (EltTy->isIntegerTy(64)) {
3023dff0c46cSDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3024dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
3025dff0c46cSDimitry Andric           V = ConstantDataVector::get(Context, Elts);
3026dff0c46cSDimitry Andric         else
3027dff0c46cSDimitry Andric           V = ConstantDataArray::get(Context, Elts);
3028444ed5c5SDimitry Andric       } else if (EltTy->isHalfTy()) {
3029444ed5c5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3030444ed5c5SDimitry Andric         if (isa<VectorType>(CurTy))
3031444ed5c5SDimitry Andric           V = ConstantDataVector::getFP(Context, Elts);
3032444ed5c5SDimitry Andric         else
3033444ed5c5SDimitry Andric           V = ConstantDataArray::getFP(Context, Elts);
3034dff0c46cSDimitry Andric       } else if (EltTy->isFloatTy()) {
3035444ed5c5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3036dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
3037444ed5c5SDimitry Andric           V = ConstantDataVector::getFP(Context, Elts);
3038dff0c46cSDimitry Andric         else
3039444ed5c5SDimitry Andric           V = ConstantDataArray::getFP(Context, Elts);
3040dff0c46cSDimitry Andric       } else if (EltTy->isDoubleTy()) {
3041444ed5c5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3042dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
3043444ed5c5SDimitry Andric           V = ConstantDataVector::getFP(Context, Elts);
3044dff0c46cSDimitry Andric         else
3045444ed5c5SDimitry Andric           V = ConstantDataArray::getFP(Context, Elts);
3046dff0c46cSDimitry Andric       } else {
30478f0fd8f6SDimitry Andric         return error("Invalid type for value");
3048dff0c46cSDimitry Andric       }
3049dff0c46cSDimitry Andric       break;
3050dff0c46cSDimitry Andric     }
3051f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
3052f785676fSDimitry Andric       if (Record.size() < 3)
30538f0fd8f6SDimitry Andric         return error("Invalid record");
30548f0fd8f6SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3055f22ef01cSRoman Divacky       if (Opc < 0) {
3056f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);  // Unknown binop.
3057f22ef01cSRoman Divacky       } else {
3058f22ef01cSRoman Divacky         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
3059f22ef01cSRoman Divacky         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
3060f22ef01cSRoman Divacky         unsigned Flags = 0;
3061f22ef01cSRoman Divacky         if (Record.size() >= 4) {
3062f22ef01cSRoman Divacky           if (Opc == Instruction::Add ||
3063f22ef01cSRoman Divacky               Opc == Instruction::Sub ||
30642754fe60SDimitry Andric               Opc == Instruction::Mul ||
30652754fe60SDimitry Andric               Opc == Instruction::Shl) {
3066f22ef01cSRoman Divacky             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3067f22ef01cSRoman Divacky               Flags |= OverflowingBinaryOperator::NoSignedWrap;
3068f22ef01cSRoman Divacky             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3069f22ef01cSRoman Divacky               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
30702754fe60SDimitry Andric           } else if (Opc == Instruction::SDiv ||
30712754fe60SDimitry Andric                      Opc == Instruction::UDiv ||
30722754fe60SDimitry Andric                      Opc == Instruction::LShr ||
30732754fe60SDimitry Andric                      Opc == Instruction::AShr) {
30742754fe60SDimitry Andric             if (Record[3] & (1 << bitc::PEO_EXACT))
3075f22ef01cSRoman Divacky               Flags |= SDivOperator::IsExact;
3076f22ef01cSRoman Divacky           }
3077f22ef01cSRoman Divacky         }
3078f22ef01cSRoman Divacky         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
3079f22ef01cSRoman Divacky       }
3080f22ef01cSRoman Divacky       break;
3081f22ef01cSRoman Divacky     }
3082f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
3083f785676fSDimitry Andric       if (Record.size() < 3)
30848f0fd8f6SDimitry Andric         return error("Invalid record");
30858f0fd8f6SDimitry Andric       int Opc = getDecodedCastOpcode(Record[0]);
3086f22ef01cSRoman Divacky       if (Opc < 0) {
3087f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);  // Unknown cast.
3088f22ef01cSRoman Divacky       } else {
30896122f3e6SDimitry Andric         Type *OpTy = getTypeByID(Record[1]);
3090f785676fSDimitry Andric         if (!OpTy)
30918f0fd8f6SDimitry Andric           return error("Invalid record");
3092f22ef01cSRoman Divacky         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
3093f785676fSDimitry Andric         V = UpgradeBitCastExpr(Opc, Op, CurTy);
3094f785676fSDimitry Andric         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
3095f22ef01cSRoman Divacky       }
3096f22ef01cSRoman Divacky       break;
3097f22ef01cSRoman Divacky     }
3098f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_INBOUNDS_GEP:
3099f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
3100ff0cc061SDimitry Andric       unsigned OpNum = 0;
3101ff0cc061SDimitry Andric       Type *PointeeType = nullptr;
3102ff0cc061SDimitry Andric       if (Record.size() % 2)
3103ff0cc061SDimitry Andric         PointeeType = getTypeByID(Record[OpNum++]);
3104f22ef01cSRoman Divacky       SmallVector<Constant*, 16> Elts;
3105ff0cc061SDimitry Andric       while (OpNum != Record.size()) {
3106ff0cc061SDimitry Andric         Type *ElTy = getTypeByID(Record[OpNum++]);
3107f785676fSDimitry Andric         if (!ElTy)
31088f0fd8f6SDimitry Andric           return error("Invalid record");
3109ff0cc061SDimitry Andric         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
3110f22ef01cSRoman Divacky       }
3111ff0cc061SDimitry Andric 
3112ff0cc061SDimitry Andric       if (PointeeType &&
3113ff0cc061SDimitry Andric           PointeeType !=
3114ff0cc061SDimitry Andric               cast<SequentialType>(Elts[0]->getType()->getScalarType())
3115ff0cc061SDimitry Andric                   ->getElementType())
31168f0fd8f6SDimitry Andric         return error("Explicit gep operator type does not match pointee type "
3117ff0cc061SDimitry Andric                      "of pointer operand");
3118ff0cc061SDimitry Andric 
31193ca95b02SDimitry Andric       if (Elts.size() < 1)
31203ca95b02SDimitry Andric         return error("Invalid gep with no operands");
31213ca95b02SDimitry Andric 
31226122f3e6SDimitry Andric       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3123ff0cc061SDimitry Andric       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
31246122f3e6SDimitry Andric                                          BitCode ==
31256122f3e6SDimitry Andric                                              bitc::CST_CODE_CE_INBOUNDS_GEP);
3126f22ef01cSRoman Divacky       break;
3127f22ef01cSRoman Divacky     }
3128f785676fSDimitry Andric     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
3129f785676fSDimitry Andric       if (Record.size() < 3)
31308f0fd8f6SDimitry Andric         return error("Invalid record");
3131f785676fSDimitry Andric 
3132f785676fSDimitry Andric       Type *SelectorTy = Type::getInt1Ty(Context);
3133f785676fSDimitry Andric 
31347d523365SDimitry Andric       // The selector might be an i1 or an <n x i1>
31357d523365SDimitry Andric       // Get the type from the ValueList before getting a forward ref.
3136f785676fSDimitry Andric       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
31377d523365SDimitry Andric         if (Value *V = ValueList[Record[0]])
31387d523365SDimitry Andric           if (SelectorTy != V->getType())
31397d523365SDimitry Andric             SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
3140f785676fSDimitry Andric 
3141f785676fSDimitry Andric       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
3142f785676fSDimitry Andric                                                               SelectorTy),
3143f22ef01cSRoman Divacky                                   ValueList.getConstantFwdRef(Record[1],CurTy),
3144f22ef01cSRoman Divacky                                   ValueList.getConstantFwdRef(Record[2],CurTy));
3145f22ef01cSRoman Divacky       break;
3146f785676fSDimitry Andric     }
314791bc56edSDimitry Andric     case bitc::CST_CODE_CE_EXTRACTELT
314891bc56edSDimitry Andric         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3149f785676fSDimitry Andric       if (Record.size() < 3)
31508f0fd8f6SDimitry Andric         return error("Invalid record");
31516122f3e6SDimitry Andric       VectorType *OpTy =
3152f22ef01cSRoman Divacky         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
315391bc56edSDimitry Andric       if (!OpTy)
31548f0fd8f6SDimitry Andric         return error("Invalid record");
3155f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
315691bc56edSDimitry Andric       Constant *Op1 = nullptr;
315791bc56edSDimitry Andric       if (Record.size() == 4) {
315891bc56edSDimitry Andric         Type *IdxTy = getTypeByID(Record[2]);
315991bc56edSDimitry Andric         if (!IdxTy)
31608f0fd8f6SDimitry Andric           return error("Invalid record");
316191bc56edSDimitry Andric         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
316291bc56edSDimitry Andric       } else // TODO: Remove with llvm 4.0
316391bc56edSDimitry Andric         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
316491bc56edSDimitry Andric       if (!Op1)
31658f0fd8f6SDimitry Andric         return error("Invalid record");
3166f22ef01cSRoman Divacky       V = ConstantExpr::getExtractElement(Op0, Op1);
3167f22ef01cSRoman Divacky       break;
3168f22ef01cSRoman Divacky     }
316991bc56edSDimitry Andric     case bitc::CST_CODE_CE_INSERTELT
317091bc56edSDimitry Andric         : { // CE_INSERTELT: [opval, opval, opty, opval]
31716122f3e6SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
317291bc56edSDimitry Andric       if (Record.size() < 3 || !OpTy)
31738f0fd8f6SDimitry Andric         return error("Invalid record");
3174f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3175f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
3176f22ef01cSRoman Divacky                                                   OpTy->getElementType());
317791bc56edSDimitry Andric       Constant *Op2 = nullptr;
317891bc56edSDimitry Andric       if (Record.size() == 4) {
317991bc56edSDimitry Andric         Type *IdxTy = getTypeByID(Record[2]);
318091bc56edSDimitry Andric         if (!IdxTy)
31818f0fd8f6SDimitry Andric           return error("Invalid record");
318291bc56edSDimitry Andric         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
318391bc56edSDimitry Andric       } else // TODO: Remove with llvm 4.0
318491bc56edSDimitry Andric         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
318591bc56edSDimitry Andric       if (!Op2)
31868f0fd8f6SDimitry Andric         return error("Invalid record");
3187f22ef01cSRoman Divacky       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
3188f22ef01cSRoman Divacky       break;
3189f22ef01cSRoman Divacky     }
3190f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
31916122f3e6SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
319291bc56edSDimitry Andric       if (Record.size() < 3 || !OpTy)
31938f0fd8f6SDimitry Andric         return error("Invalid record");
3194f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3195f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
31966122f3e6SDimitry Andric       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
3197f22ef01cSRoman Divacky                                                  OpTy->getNumElements());
3198f22ef01cSRoman Divacky       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
3199f22ef01cSRoman Divacky       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
3200f22ef01cSRoman Divacky       break;
3201f22ef01cSRoman Divacky     }
3202f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
32036122f3e6SDimitry Andric       VectorType *RTy = dyn_cast<VectorType>(CurTy);
32046122f3e6SDimitry Andric       VectorType *OpTy =
32052754fe60SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
320691bc56edSDimitry Andric       if (Record.size() < 4 || !RTy || !OpTy)
32078f0fd8f6SDimitry Andric         return error("Invalid record");
3208f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3209f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
32106122f3e6SDimitry Andric       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
3211f22ef01cSRoman Divacky                                                  RTy->getNumElements());
3212f22ef01cSRoman Divacky       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
3213f22ef01cSRoman Divacky       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
3214f22ef01cSRoman Divacky       break;
3215f22ef01cSRoman Divacky     }
3216f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
3217f785676fSDimitry Andric       if (Record.size() < 4)
32188f0fd8f6SDimitry Andric         return error("Invalid record");
32196122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
322091bc56edSDimitry Andric       if (!OpTy)
32218f0fd8f6SDimitry Andric         return error("Invalid record");
3222f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3223f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3224f22ef01cSRoman Divacky 
3225f22ef01cSRoman Divacky       if (OpTy->isFPOrFPVectorTy())
3226f22ef01cSRoman Divacky         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
3227f22ef01cSRoman Divacky       else
3228f22ef01cSRoman Divacky         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
3229f22ef01cSRoman Divacky       break;
3230f22ef01cSRoman Divacky     }
32313861d79fSDimitry Andric     // This maintains backward compatibility, pre-asm dialect keywords.
32323861d79fSDimitry Andric     // FIXME: Remove with the 4.0 release.
32333861d79fSDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD: {
3234f785676fSDimitry Andric       if (Record.size() < 2)
32358f0fd8f6SDimitry Andric         return error("Invalid record");
3236f22ef01cSRoman Divacky       std::string AsmStr, ConstrStr;
3237f22ef01cSRoman Divacky       bool HasSideEffects = Record[0] & 1;
3238f22ef01cSRoman Divacky       bool IsAlignStack = Record[0] >> 1;
3239f22ef01cSRoman Divacky       unsigned AsmStrSize = Record[1];
3240f22ef01cSRoman Divacky       if (2+AsmStrSize >= Record.size())
32418f0fd8f6SDimitry Andric         return error("Invalid record");
3242f22ef01cSRoman Divacky       unsigned ConstStrSize = Record[2+AsmStrSize];
3243f22ef01cSRoman Divacky       if (3+AsmStrSize+ConstStrSize > Record.size())
32448f0fd8f6SDimitry Andric         return error("Invalid record");
3245f22ef01cSRoman Divacky 
3246f22ef01cSRoman Divacky       for (unsigned i = 0; i != AsmStrSize; ++i)
3247f22ef01cSRoman Divacky         AsmStr += (char)Record[2+i];
3248f22ef01cSRoman Divacky       for (unsigned i = 0; i != ConstStrSize; ++i)
3249f22ef01cSRoman Divacky         ConstrStr += (char)Record[3+AsmStrSize+i];
32506122f3e6SDimitry Andric       PointerType *PTy = cast<PointerType>(CurTy);
3251f22ef01cSRoman Divacky       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3252f22ef01cSRoman Divacky                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
3253f22ef01cSRoman Divacky       break;
3254f22ef01cSRoman Divacky     }
32553861d79fSDimitry Andric     // This version adds support for the asm dialect keywords (e.g.,
32563861d79fSDimitry Andric     // inteldialect).
32573861d79fSDimitry Andric     case bitc::CST_CODE_INLINEASM: {
3258f785676fSDimitry Andric       if (Record.size() < 2)
32598f0fd8f6SDimitry Andric         return error("Invalid record");
32603861d79fSDimitry Andric       std::string AsmStr, ConstrStr;
32613861d79fSDimitry Andric       bool HasSideEffects = Record[0] & 1;
32623861d79fSDimitry Andric       bool IsAlignStack = (Record[0] >> 1) & 1;
32633861d79fSDimitry Andric       unsigned AsmDialect = Record[0] >> 2;
32643861d79fSDimitry Andric       unsigned AsmStrSize = Record[1];
32653861d79fSDimitry Andric       if (2+AsmStrSize >= Record.size())
32668f0fd8f6SDimitry Andric         return error("Invalid record");
32673861d79fSDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
32683861d79fSDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
32698f0fd8f6SDimitry Andric         return error("Invalid record");
32703861d79fSDimitry Andric 
32713861d79fSDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
32723861d79fSDimitry Andric         AsmStr += (char)Record[2+i];
32733861d79fSDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
32743861d79fSDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
32753861d79fSDimitry Andric       PointerType *PTy = cast<PointerType>(CurTy);
32763861d79fSDimitry Andric       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
32773861d79fSDimitry Andric                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
32783861d79fSDimitry Andric                          InlineAsm::AsmDialect(AsmDialect));
32793861d79fSDimitry Andric       break;
32803861d79fSDimitry Andric     }
3281f22ef01cSRoman Divacky     case bitc::CST_CODE_BLOCKADDRESS:{
3282f785676fSDimitry Andric       if (Record.size() < 3)
32838f0fd8f6SDimitry Andric         return error("Invalid record");
32846122f3e6SDimitry Andric       Type *FnTy = getTypeByID(Record[0]);
328591bc56edSDimitry Andric       if (!FnTy)
32868f0fd8f6SDimitry Andric         return error("Invalid record");
3287f22ef01cSRoman Divacky       Function *Fn =
3288f22ef01cSRoman Divacky         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
328991bc56edSDimitry Andric       if (!Fn)
32908f0fd8f6SDimitry Andric         return error("Invalid record");
329139d628a0SDimitry Andric 
32923861d79fSDimitry Andric       // If the function is already parsed we can insert the block address right
32933861d79fSDimitry Andric       // away.
329439d628a0SDimitry Andric       BasicBlock *BB;
329539d628a0SDimitry Andric       unsigned BBID = Record[2];
329639d628a0SDimitry Andric       if (!BBID)
329739d628a0SDimitry Andric         // Invalid reference to entry block.
32988f0fd8f6SDimitry Andric         return error("Invalid ID");
32993861d79fSDimitry Andric       if (!Fn->empty()) {
33003861d79fSDimitry Andric         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
330139d628a0SDimitry Andric         for (size_t I = 0, E = BBID; I != E; ++I) {
33023861d79fSDimitry Andric           if (BBI == BBE)
33038f0fd8f6SDimitry Andric             return error("Invalid ID");
33043861d79fSDimitry Andric           ++BBI;
33053861d79fSDimitry Andric         }
33067d523365SDimitry Andric         BB = &*BBI;
33073861d79fSDimitry Andric       } else {
33083861d79fSDimitry Andric         // Otherwise insert a placeholder and remember it so it can be inserted
33093861d79fSDimitry Andric         // when the function is parsed.
331039d628a0SDimitry Andric         auto &FwdBBs = BasicBlockFwdRefs[Fn];
331139d628a0SDimitry Andric         if (FwdBBs.empty())
331239d628a0SDimitry Andric           BasicBlockFwdRefQueue.push_back(Fn);
331339d628a0SDimitry Andric         if (FwdBBs.size() < BBID + 1)
331439d628a0SDimitry Andric           FwdBBs.resize(BBID + 1);
331539d628a0SDimitry Andric         if (!FwdBBs[BBID])
331639d628a0SDimitry Andric           FwdBBs[BBID] = BasicBlock::Create(Context);
331739d628a0SDimitry Andric         BB = FwdBBs[BBID];
33183861d79fSDimitry Andric       }
331939d628a0SDimitry Andric       V = BlockAddress::get(Fn, BB);
3320f22ef01cSRoman Divacky       break;
3321f22ef01cSRoman Divacky     }
3322f22ef01cSRoman Divacky     }
3323f22ef01cSRoman Divacky 
33248f0fd8f6SDimitry Andric     ValueList.assignValue(V, NextCstNo);
3325f22ef01cSRoman Divacky     ++NextCstNo;
3326f22ef01cSRoman Divacky   }
3327f22ef01cSRoman Divacky }
3328f22ef01cSRoman Divacky 
33298f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseUseLists() {
3330dff0c46cSDimitry Andric   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
33318f0fd8f6SDimitry Andric     return error("Invalid record");
3332dff0c46cSDimitry Andric 
3333dff0c46cSDimitry Andric   // Read all the records.
333439d628a0SDimitry Andric   SmallVector<uint64_t, 64> Record;
3335dff0c46cSDimitry Andric   while (1) {
3336139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3337139f7f9bSDimitry Andric 
3338139f7f9bSDimitry Andric     switch (Entry.Kind) {
3339139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
3340139f7f9bSDimitry Andric     case BitstreamEntry::Error:
33418f0fd8f6SDimitry Andric       return error("Malformed block");
3342139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
334391bc56edSDimitry Andric       return std::error_code();
3344139f7f9bSDimitry Andric     case BitstreamEntry::Record:
3345139f7f9bSDimitry Andric       // The interesting case.
3346139f7f9bSDimitry Andric       break;
3347dff0c46cSDimitry Andric     }
3348dff0c46cSDimitry Andric 
3349dff0c46cSDimitry Andric     // Read a use list record.
3350dff0c46cSDimitry Andric     Record.clear();
335139d628a0SDimitry Andric     bool IsBB = false;
3352139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
3353dff0c46cSDimitry Andric     default:  // Default behavior: unknown type.
3354dff0c46cSDimitry Andric       break;
335539d628a0SDimitry Andric     case bitc::USELIST_CODE_BB:
335639d628a0SDimitry Andric       IsBB = true;
335739d628a0SDimitry Andric       // fallthrough
335839d628a0SDimitry Andric     case bitc::USELIST_CODE_DEFAULT: {
3359dff0c46cSDimitry Andric       unsigned RecordLength = Record.size();
336039d628a0SDimitry Andric       if (RecordLength < 3)
336139d628a0SDimitry Andric         // Records should have at least an ID and two indexes.
33628f0fd8f6SDimitry Andric         return error("Invalid record");
336339d628a0SDimitry Andric       unsigned ID = Record.back();
336439d628a0SDimitry Andric       Record.pop_back();
336539d628a0SDimitry Andric 
336639d628a0SDimitry Andric       Value *V;
336739d628a0SDimitry Andric       if (IsBB) {
336839d628a0SDimitry Andric         assert(ID < FunctionBBs.size() && "Basic block not found");
336939d628a0SDimitry Andric         V = FunctionBBs[ID];
337039d628a0SDimitry Andric       } else
337139d628a0SDimitry Andric         V = ValueList[ID];
337239d628a0SDimitry Andric       unsigned NumUses = 0;
337339d628a0SDimitry Andric       SmallDenseMap<const Use *, unsigned, 16> Order;
33747d523365SDimitry Andric       for (const Use &U : V->materialized_uses()) {
337539d628a0SDimitry Andric         if (++NumUses > Record.size())
337639d628a0SDimitry Andric           break;
337739d628a0SDimitry Andric         Order[&U] = Record[NumUses - 1];
337839d628a0SDimitry Andric       }
337939d628a0SDimitry Andric       if (Order.size() != Record.size() || NumUses > Record.size())
338039d628a0SDimitry Andric         // Mismatches can happen if the functions are being materialized lazily
338139d628a0SDimitry Andric         // (out-of-order), or a value has been upgraded.
338239d628a0SDimitry Andric         break;
338339d628a0SDimitry Andric 
338439d628a0SDimitry Andric       V->sortUseList([&](const Use &L, const Use &R) {
338539d628a0SDimitry Andric         return Order.lookup(&L) < Order.lookup(&R);
338639d628a0SDimitry Andric       });
3387dff0c46cSDimitry Andric       break;
3388dff0c46cSDimitry Andric     }
3389dff0c46cSDimitry Andric     }
3390dff0c46cSDimitry Andric   }
3391dff0c46cSDimitry Andric }
3392dff0c46cSDimitry Andric 
3393ff0cc061SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it.
3394ff0cc061SDimitry Andric /// This lets us lazily deserialize the metadata.
3395ff0cc061SDimitry Andric std::error_code BitcodeReader::rememberAndSkipMetadata() {
3396ff0cc061SDimitry Andric   // Save the current stream state.
3397ff0cc061SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
3398ff0cc061SDimitry Andric   DeferredMetadataInfo.push_back(CurBit);
3399ff0cc061SDimitry Andric 
3400ff0cc061SDimitry Andric   // Skip over the block for now.
3401ff0cc061SDimitry Andric   if (Stream.SkipBlock())
34028f0fd8f6SDimitry Andric     return error("Invalid record");
3403ff0cc061SDimitry Andric   return std::error_code();
3404ff0cc061SDimitry Andric }
3405ff0cc061SDimitry Andric 
3406ff0cc061SDimitry Andric std::error_code BitcodeReader::materializeMetadata() {
3407ff0cc061SDimitry Andric   for (uint64_t BitPos : DeferredMetadataInfo) {
3408ff0cc061SDimitry Andric     // Move the bit stream to the saved position.
3409ff0cc061SDimitry Andric     Stream.JumpToBit(BitPos);
34107d523365SDimitry Andric     if (std::error_code EC = parseMetadata(true))
3411ff0cc061SDimitry Andric       return EC;
3412ff0cc061SDimitry Andric   }
3413ff0cc061SDimitry Andric   DeferredMetadataInfo.clear();
3414ff0cc061SDimitry Andric   return std::error_code();
3415ff0cc061SDimitry Andric }
3416ff0cc061SDimitry Andric 
3417ff0cc061SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3418ff0cc061SDimitry Andric 
34198f0fd8f6SDimitry Andric /// When we see the block for a function body, remember where it is and then
34208f0fd8f6SDimitry Andric /// skip it.  This lets us lazily deserialize the functions.
34218f0fd8f6SDimitry Andric std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3422f22ef01cSRoman Divacky   // Get the function we are talking about.
3423f22ef01cSRoman Divacky   if (FunctionsWithBodies.empty())
34248f0fd8f6SDimitry Andric     return error("Insufficient function protos");
3425f22ef01cSRoman Divacky 
3426f22ef01cSRoman Divacky   Function *Fn = FunctionsWithBodies.back();
3427f22ef01cSRoman Divacky   FunctionsWithBodies.pop_back();
3428f22ef01cSRoman Divacky 
3429f22ef01cSRoman Divacky   // Save the current stream state.
3430f22ef01cSRoman Divacky   uint64_t CurBit = Stream.GetCurrentBitNo();
34317d523365SDimitry Andric   assert(
34327d523365SDimitry Andric       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
34337d523365SDimitry Andric       "Mismatch between VST and scanned function offsets");
3434f22ef01cSRoman Divacky   DeferredFunctionInfo[Fn] = CurBit;
3435f22ef01cSRoman Divacky 
3436f22ef01cSRoman Divacky   // Skip over the function block for now.
3437f22ef01cSRoman Divacky   if (Stream.SkipBlock())
34388f0fd8f6SDimitry Andric     return error("Invalid record");
343991bc56edSDimitry Andric   return std::error_code();
3440f22ef01cSRoman Divacky }
3441f22ef01cSRoman Divacky 
34428f0fd8f6SDimitry Andric std::error_code BitcodeReader::globalCleanup() {
3443f22ef01cSRoman Divacky   // Patch the initializers for globals and aliases up.
34443ca95b02SDimitry Andric   resolveGlobalAndIndirectSymbolInits();
34453ca95b02SDimitry Andric   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
34468f0fd8f6SDimitry Andric     return error("Malformed global initializer set");
3447f22ef01cSRoman Divacky 
3448f22ef01cSRoman Divacky   // Look for intrinsic functions which need to be upgraded at some point
34498f0fd8f6SDimitry Andric   for (Function &F : *TheModule) {
3450f22ef01cSRoman Divacky     Function *NewFn;
34518f0fd8f6SDimitry Andric     if (UpgradeIntrinsicFunction(&F, NewFn))
34523dac3a9bSDimitry Andric       UpgradedIntrinsics[&F] = NewFn;
34533ca95b02SDimitry Andric     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
34543ca95b02SDimitry Andric       // Some types could be renamed during loading if several modules are
34553ca95b02SDimitry Andric       // loaded in the same LLVMContext (LTO scenario). In this case we should
34563ca95b02SDimitry Andric       // remangle intrinsics names as well.
34573ca95b02SDimitry Andric       RemangledIntrinsics[&F] = Remangled.getValue();
3458f22ef01cSRoman Divacky   }
3459f22ef01cSRoman Divacky 
3460e580952dSDimitry Andric   // Look for global variables which need to be renamed.
34618f0fd8f6SDimitry Andric   for (GlobalVariable &GV : TheModule->globals())
34628f0fd8f6SDimitry Andric     UpgradeGlobalVariable(&GV);
346391bc56edSDimitry Andric 
3464f22ef01cSRoman Divacky   // Force deallocation of memory for these vectors to favor the client that
3465f22ef01cSRoman Divacky   // want lazy deserialization.
3466f22ef01cSRoman Divacky   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
34673ca95b02SDimitry Andric   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
34683ca95b02SDimitry Andric       IndirectSymbolInits);
346991bc56edSDimitry Andric   return std::error_code();
3470f22ef01cSRoman Divacky }
3471f22ef01cSRoman Divacky 
34727d523365SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we
34737d523365SDimitry Andric /// either have an old bitcode file without a VST forward declaration record,
34747d523365SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous
34757d523365SDimitry Andric /// functions do not have a name and are therefore not in the VST.
34767d523365SDimitry Andric std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3477dff0c46cSDimitry Andric   Stream.JumpToBit(NextUnreadBit);
34787d523365SDimitry Andric 
34797d523365SDimitry Andric   if (Stream.AtEndOfStream())
34807d523365SDimitry Andric     return error("Could not find function in stream");
34817d523365SDimitry Andric 
34827d523365SDimitry Andric   if (!SeenFirstFunctionBody)
34837d523365SDimitry Andric     return error("Trying to materialize functions before seeing function blocks");
34847d523365SDimitry Andric 
34857d523365SDimitry Andric   // An old bitcode file with the symbol table at the end would have
34867d523365SDimitry Andric   // finished the parse greedily.
34877d523365SDimitry Andric   assert(SeenValueSymbolTable);
34887d523365SDimitry Andric 
34897d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
34907d523365SDimitry Andric 
34917d523365SDimitry Andric   while (1) {
34927d523365SDimitry Andric     BitstreamEntry Entry = Stream.advance();
34937d523365SDimitry Andric     switch (Entry.Kind) {
34947d523365SDimitry Andric     default:
34957d523365SDimitry Andric       return error("Expect SubBlock");
34967d523365SDimitry Andric     case BitstreamEntry::SubBlock:
34977d523365SDimitry Andric       switch (Entry.ID) {
34987d523365SDimitry Andric       default:
34997d523365SDimitry Andric         return error("Expect function block");
35007d523365SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
35017d523365SDimitry Andric         if (std::error_code EC = rememberAndSkipFunctionBody())
35027d523365SDimitry Andric           return EC;
35037d523365SDimitry Andric         NextUnreadBit = Stream.GetCurrentBitNo();
35047d523365SDimitry Andric         return std::error_code();
35057d523365SDimitry Andric       }
35067d523365SDimitry Andric     }
35077d523365SDimitry Andric   }
35087d523365SDimitry Andric }
35097d523365SDimitry Andric 
35107d523365SDimitry Andric std::error_code BitcodeReader::parseBitcodeVersion() {
35117d523365SDimitry Andric   if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
35127d523365SDimitry Andric     return error("Invalid record");
35137d523365SDimitry Andric 
35147d523365SDimitry Andric   // Read all the records.
35157d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
35167d523365SDimitry Andric   while (1) {
35177d523365SDimitry Andric     BitstreamEntry Entry = Stream.advance();
35187d523365SDimitry Andric 
35197d523365SDimitry Andric     switch (Entry.Kind) {
35207d523365SDimitry Andric     default:
35217d523365SDimitry Andric     case BitstreamEntry::Error:
35227d523365SDimitry Andric       return error("Malformed block");
35237d523365SDimitry Andric     case BitstreamEntry::EndBlock:
35247d523365SDimitry Andric       return std::error_code();
35257d523365SDimitry Andric     case BitstreamEntry::Record:
35267d523365SDimitry Andric       // The interesting case.
35277d523365SDimitry Andric       break;
35287d523365SDimitry Andric     }
35297d523365SDimitry Andric 
35307d523365SDimitry Andric     // Read a record.
35317d523365SDimitry Andric     Record.clear();
35327d523365SDimitry Andric     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
35337d523365SDimitry Andric     switch (BitCode) {
35347d523365SDimitry Andric     default: // Default behavior: reject
35357d523365SDimitry Andric       return error("Invalid value");
35367d523365SDimitry Andric     case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION:      [strchr x
35377d523365SDimitry Andric                                              // N]
35387d523365SDimitry Andric       convertToString(Record, 0, ProducerIdentification);
35397d523365SDimitry Andric       break;
35407d523365SDimitry Andric     }
35417d523365SDimitry Andric     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH:      [epoch#]
35427d523365SDimitry Andric       unsigned epoch = (unsigned)Record[0];
35437d523365SDimitry Andric       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
35447d523365SDimitry Andric         return error(
35457d523365SDimitry Andric           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
35467d523365SDimitry Andric           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
35477d523365SDimitry Andric       }
35487d523365SDimitry Andric     }
35497d523365SDimitry Andric     }
35507d523365SDimitry Andric   }
35517d523365SDimitry Andric }
35527d523365SDimitry Andric 
35537d523365SDimitry Andric std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
35547d523365SDimitry Andric                                            bool ShouldLazyLoadMetadata) {
35557d523365SDimitry Andric   if (ResumeBit)
35567d523365SDimitry Andric     Stream.JumpToBit(ResumeBit);
3557dff0c46cSDimitry Andric   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
35588f0fd8f6SDimitry Andric     return error("Invalid record");
3559dff0c46cSDimitry Andric 
3560dff0c46cSDimitry Andric   SmallVector<uint64_t, 64> Record;
3561dff0c46cSDimitry Andric   std::vector<std::string> SectionTable;
3562dff0c46cSDimitry Andric   std::vector<std::string> GCTable;
3563dff0c46cSDimitry Andric 
3564dff0c46cSDimitry Andric   // Read all the records for this module.
3565139f7f9bSDimitry Andric   while (1) {
3566139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advance();
3567dff0c46cSDimitry Andric 
3568139f7f9bSDimitry Andric     switch (Entry.Kind) {
3569139f7f9bSDimitry Andric     case BitstreamEntry::Error:
35708f0fd8f6SDimitry Andric       return error("Malformed block");
3571139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
35728f0fd8f6SDimitry Andric       return globalCleanup();
3573dff0c46cSDimitry Andric 
3574139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock:
3575139f7f9bSDimitry Andric       switch (Entry.ID) {
3576f22ef01cSRoman Divacky       default:  // Skip unknown content.
3577f22ef01cSRoman Divacky         if (Stream.SkipBlock())
35788f0fd8f6SDimitry Andric           return error("Invalid record");
3579f22ef01cSRoman Divacky         break;
3580f22ef01cSRoman Divacky       case bitc::BLOCKINFO_BLOCK_ID:
3581f22ef01cSRoman Divacky         if (Stream.ReadBlockInfoBlock())
35828f0fd8f6SDimitry Andric           return error("Malformed block");
3583f22ef01cSRoman Divacky         break;
3584f22ef01cSRoman Divacky       case bitc::PARAMATTR_BLOCK_ID:
35858f0fd8f6SDimitry Andric         if (std::error_code EC = parseAttributeBlock())
3586f785676fSDimitry Andric           return EC;
3587f22ef01cSRoman Divacky         break;
3588139f7f9bSDimitry Andric       case bitc::PARAMATTR_GROUP_BLOCK_ID:
35898f0fd8f6SDimitry Andric         if (std::error_code EC = parseAttributeGroupBlock())
3590f785676fSDimitry Andric           return EC;
3591139f7f9bSDimitry Andric         break;
359217a519f9SDimitry Andric       case bitc::TYPE_BLOCK_ID_NEW:
35938f0fd8f6SDimitry Andric         if (std::error_code EC = parseTypeTable())
3594f785676fSDimitry Andric           return EC;
3595f22ef01cSRoman Divacky         break;
3596f22ef01cSRoman Divacky       case bitc::VALUE_SYMTAB_BLOCK_ID:
35977d523365SDimitry Andric         if (!SeenValueSymbolTable) {
35987d523365SDimitry Andric           // Either this is an old form VST without function index and an
35997d523365SDimitry Andric           // associated VST forward declaration record (which would have caused
36007d523365SDimitry Andric           // the VST to be jumped to and parsed before it was encountered
36017d523365SDimitry Andric           // normally in the stream), or there were no function blocks to
36027d523365SDimitry Andric           // trigger an earlier parsing of the VST.
36037d523365SDimitry Andric           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
36048f0fd8f6SDimitry Andric           if (std::error_code EC = parseValueSymbolTable())
3605f785676fSDimitry Andric             return EC;
3606dff0c46cSDimitry Andric           SeenValueSymbolTable = true;
36077d523365SDimitry Andric         } else {
36087d523365SDimitry Andric           // We must have had a VST forward declaration record, which caused
36097d523365SDimitry Andric           // the parser to jump to and parse the VST earlier.
36107d523365SDimitry Andric           assert(VSTOffset > 0);
36117d523365SDimitry Andric           if (Stream.SkipBlock())
36127d523365SDimitry Andric             return error("Invalid record");
36137d523365SDimitry Andric         }
3614f22ef01cSRoman Divacky         break;
3615f22ef01cSRoman Divacky       case bitc::CONSTANTS_BLOCK_ID:
36168f0fd8f6SDimitry Andric         if (std::error_code EC = parseConstants())
3617f785676fSDimitry Andric           return EC;
36183ca95b02SDimitry Andric         if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
3619f785676fSDimitry Andric           return EC;
3620f22ef01cSRoman Divacky         break;
3621f22ef01cSRoman Divacky       case bitc::METADATA_BLOCK_ID:
3622ff0cc061SDimitry Andric         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3623ff0cc061SDimitry Andric           if (std::error_code EC = rememberAndSkipMetadata())
3624ff0cc061SDimitry Andric             return EC;
3625ff0cc061SDimitry Andric           break;
3626ff0cc061SDimitry Andric         }
3627ff0cc061SDimitry Andric         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
36287d523365SDimitry Andric         if (std::error_code EC = parseMetadata(true))
36297d523365SDimitry Andric           return EC;
36307d523365SDimitry Andric         break;
36317d523365SDimitry Andric       case bitc::METADATA_KIND_BLOCK_ID:
36327d523365SDimitry Andric         if (std::error_code EC = parseMetadataKinds())
3633f785676fSDimitry Andric           return EC;
3634f22ef01cSRoman Divacky         break;
3635f22ef01cSRoman Divacky       case bitc::FUNCTION_BLOCK_ID:
3636f22ef01cSRoman Divacky         // If this is the first function body we've seen, reverse the
3637f22ef01cSRoman Divacky         // FunctionsWithBodies list.
3638dff0c46cSDimitry Andric         if (!SeenFirstFunctionBody) {
3639f22ef01cSRoman Divacky           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
36408f0fd8f6SDimitry Andric           if (std::error_code EC = globalCleanup())
3641f785676fSDimitry Andric             return EC;
3642dff0c46cSDimitry Andric           SeenFirstFunctionBody = true;
3643f22ef01cSRoman Divacky         }
3644f22ef01cSRoman Divacky 
36457d523365SDimitry Andric         if (VSTOffset > 0) {
36467d523365SDimitry Andric           // If we have a VST forward declaration record, make sure we
36477d523365SDimitry Andric           // parse the VST now if we haven't already. It is needed to
36487d523365SDimitry Andric           // set up the DeferredFunctionInfo vector for lazy reading.
36497d523365SDimitry Andric           if (!SeenValueSymbolTable) {
36507d523365SDimitry Andric             if (std::error_code EC =
36517d523365SDimitry Andric                     BitcodeReader::parseValueSymbolTable(VSTOffset))
36527d523365SDimitry Andric               return EC;
36537d523365SDimitry Andric             SeenValueSymbolTable = true;
36547d523365SDimitry Andric             // Fall through so that we record the NextUnreadBit below.
36557d523365SDimitry Andric             // This is necessary in case we have an anonymous function that
36567d523365SDimitry Andric             // is later materialized. Since it will not have a VST entry we
36577d523365SDimitry Andric             // need to fall back to the lazy parse to find its offset.
36587d523365SDimitry Andric           } else {
36597d523365SDimitry Andric             // If we have a VST forward declaration record, but have already
36607d523365SDimitry Andric             // parsed the VST (just above, when the first function body was
36617d523365SDimitry Andric             // encountered here), then we are resuming the parse after
36627d523365SDimitry Andric             // materializing functions. The ResumeBit points to the
36637d523365SDimitry Andric             // start of the last function block recorded in the
36647d523365SDimitry Andric             // DeferredFunctionInfo map. Skip it.
36657d523365SDimitry Andric             if (Stream.SkipBlock())
36667d523365SDimitry Andric               return error("Invalid record");
36677d523365SDimitry Andric             continue;
36687d523365SDimitry Andric           }
36697d523365SDimitry Andric         }
36707d523365SDimitry Andric 
36717d523365SDimitry Andric         // Support older bitcode files that did not have the function
36727d523365SDimitry Andric         // index in the VST, nor a VST forward declaration record, as
36737d523365SDimitry Andric         // well as anonymous functions that do not have VST entries.
36747d523365SDimitry Andric         // Build the DeferredFunctionInfo vector on the fly.
36758f0fd8f6SDimitry Andric         if (std::error_code EC = rememberAndSkipFunctionBody())
3676f785676fSDimitry Andric           return EC;
36777d523365SDimitry Andric 
36783dac3a9bSDimitry Andric         // Suspend parsing when we reach the function bodies. Subsequent
36793dac3a9bSDimitry Andric         // materialization calls will resume it when necessary. If the bitcode
36803dac3a9bSDimitry Andric         // file is old, the symbol table will be at the end instead and will not
36813dac3a9bSDimitry Andric         // have been seen yet. In this case, just finish the parse now.
36823dac3a9bSDimitry Andric         if (SeenValueSymbolTable) {
3683dff0c46cSDimitry Andric           NextUnreadBit = Stream.GetCurrentBitNo();
368491bc56edSDimitry Andric           return std::error_code();
3685dff0c46cSDimitry Andric         }
3686dff0c46cSDimitry Andric         break;
3687dff0c46cSDimitry Andric       case bitc::USELIST_BLOCK_ID:
36888f0fd8f6SDimitry Andric         if (std::error_code EC = parseUseLists())
3689f785676fSDimitry Andric           return EC;
3690f22ef01cSRoman Divacky         break;
36917d523365SDimitry Andric       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
36927d523365SDimitry Andric         if (std::error_code EC = parseOperandBundleTags())
36937d523365SDimitry Andric           return EC;
36947d523365SDimitry Andric         break;
3695f22ef01cSRoman Divacky       }
3696f22ef01cSRoman Divacky       continue;
3697139f7f9bSDimitry Andric 
3698139f7f9bSDimitry Andric     case BitstreamEntry::Record:
3699139f7f9bSDimitry Andric       // The interesting case.
3700139f7f9bSDimitry Andric       break;
3701f22ef01cSRoman Divacky     }
3702f22ef01cSRoman Divacky 
3703f22ef01cSRoman Divacky     // Read a record.
37047d523365SDimitry Andric     auto BitCode = Stream.readRecord(Entry.ID, Record);
37057d523365SDimitry Andric     switch (BitCode) {
3706f22ef01cSRoman Divacky     default: break;  // Default behavior, ignore unknown content.
37073861d79fSDimitry Andric     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
3708f22ef01cSRoman Divacky       if (Record.size() < 1)
37098f0fd8f6SDimitry Andric         return error("Invalid record");
37103861d79fSDimitry Andric       // Only version #0 and #1 are supported so far.
37113861d79fSDimitry Andric       unsigned module_version = Record[0];
37123861d79fSDimitry Andric       switch (module_version) {
3713f785676fSDimitry Andric         default:
37148f0fd8f6SDimitry Andric           return error("Invalid value");
37153861d79fSDimitry Andric         case 0:
37163861d79fSDimitry Andric           UseRelativeIDs = false;
3717f22ef01cSRoman Divacky           break;
37183861d79fSDimitry Andric         case 1:
37193861d79fSDimitry Andric           UseRelativeIDs = true;
37203861d79fSDimitry Andric           break;
37213861d79fSDimitry Andric       }
37223861d79fSDimitry Andric       break;
37233861d79fSDimitry Andric     }
3724f22ef01cSRoman Divacky     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3725f22ef01cSRoman Divacky       std::string S;
37268f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
37278f0fd8f6SDimitry Andric         return error("Invalid record");
3728f22ef01cSRoman Divacky       TheModule->setTargetTriple(S);
3729f22ef01cSRoman Divacky       break;
3730f22ef01cSRoman Divacky     }
3731f22ef01cSRoman Divacky     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3732f22ef01cSRoman Divacky       std::string S;
37338f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
37348f0fd8f6SDimitry Andric         return error("Invalid record");
3735f22ef01cSRoman Divacky       TheModule->setDataLayout(S);
3736f22ef01cSRoman Divacky       break;
3737f22ef01cSRoman Divacky     }
3738f22ef01cSRoman Divacky     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3739f22ef01cSRoman Divacky       std::string S;
37408f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
37418f0fd8f6SDimitry Andric         return error("Invalid record");
3742f22ef01cSRoman Divacky       TheModule->setModuleInlineAsm(S);
3743f22ef01cSRoman Divacky       break;
3744f22ef01cSRoman Divacky     }
3745f22ef01cSRoman Divacky     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3746139f7f9bSDimitry Andric       // FIXME: Remove in 4.0.
3747f22ef01cSRoman Divacky       std::string S;
37488f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
37498f0fd8f6SDimitry Andric         return error("Invalid record");
3750139f7f9bSDimitry Andric       // Ignore value.
3751f22ef01cSRoman Divacky       break;
3752f22ef01cSRoman Divacky     }
3753f22ef01cSRoman Divacky     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3754f22ef01cSRoman Divacky       std::string S;
37558f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
37568f0fd8f6SDimitry Andric         return error("Invalid record");
3757f22ef01cSRoman Divacky       SectionTable.push_back(S);
3758f22ef01cSRoman Divacky       break;
3759f22ef01cSRoman Divacky     }
3760f22ef01cSRoman Divacky     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3761f22ef01cSRoman Divacky       std::string S;
37628f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
37638f0fd8f6SDimitry Andric         return error("Invalid record");
3764f22ef01cSRoman Divacky       GCTable.push_back(S);
3765f22ef01cSRoman Divacky       break;
3766f22ef01cSRoman Divacky     }
376791bc56edSDimitry Andric     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
376891bc56edSDimitry Andric       if (Record.size() < 2)
37698f0fd8f6SDimitry Andric         return error("Invalid record");
377091bc56edSDimitry Andric       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
377191bc56edSDimitry Andric       unsigned ComdatNameSize = Record[1];
377291bc56edSDimitry Andric       std::string ComdatName;
377391bc56edSDimitry Andric       ComdatName.reserve(ComdatNameSize);
377491bc56edSDimitry Andric       for (unsigned i = 0; i != ComdatNameSize; ++i)
377591bc56edSDimitry Andric         ComdatName += (char)Record[2 + i];
377691bc56edSDimitry Andric       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
377791bc56edSDimitry Andric       C->setSelectionKind(SK);
377891bc56edSDimitry Andric       ComdatList.push_back(C);
377991bc56edSDimitry Andric       break;
378091bc56edSDimitry Andric     }
3781f22ef01cSRoman Divacky     // GLOBALVAR: [pointer type, isconst, initid,
37822754fe60SDimitry Andric     //             linkage, alignment, section, visibility, threadlocal,
3783ff0cc061SDimitry Andric     //             unnamed_addr, externally_initialized, dllstorageclass,
3784ff0cc061SDimitry Andric     //             comdat]
3785f22ef01cSRoman Divacky     case bitc::MODULE_CODE_GLOBALVAR: {
3786f22ef01cSRoman Divacky       if (Record.size() < 6)
37878f0fd8f6SDimitry Andric         return error("Invalid record");
37886122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
3789f785676fSDimitry Andric       if (!Ty)
37908f0fd8f6SDimitry Andric         return error("Invalid record");
3791ff0cc061SDimitry Andric       bool isConstant = Record[1] & 1;
3792ff0cc061SDimitry Andric       bool explicitType = Record[1] & 2;
3793ff0cc061SDimitry Andric       unsigned AddressSpace;
3794ff0cc061SDimitry Andric       if (explicitType) {
3795ff0cc061SDimitry Andric         AddressSpace = Record[1] >> 2;
3796ff0cc061SDimitry Andric       } else {
3797f22ef01cSRoman Divacky         if (!Ty->isPointerTy())
37988f0fd8f6SDimitry Andric           return error("Invalid type for value");
3799ff0cc061SDimitry Andric         AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3800f22ef01cSRoman Divacky         Ty = cast<PointerType>(Ty)->getElementType();
3801ff0cc061SDimitry Andric       }
3802f22ef01cSRoman Divacky 
3803ff0cc061SDimitry Andric       uint64_t RawLinkage = Record[3];
3804ff0cc061SDimitry Andric       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3805ff0cc061SDimitry Andric       unsigned Alignment;
3806ff0cc061SDimitry Andric       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3807ff0cc061SDimitry Andric         return EC;
3808f22ef01cSRoman Divacky       std::string Section;
3809f22ef01cSRoman Divacky       if (Record[5]) {
3810f22ef01cSRoman Divacky         if (Record[5]-1 >= SectionTable.size())
38118f0fd8f6SDimitry Andric           return error("Invalid ID");
3812f22ef01cSRoman Divacky         Section = SectionTable[Record[5]-1];
3813f22ef01cSRoman Divacky       }
3814f22ef01cSRoman Divacky       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
381591bc56edSDimitry Andric       // Local linkage must have default visibility.
381691bc56edSDimitry Andric       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
381791bc56edSDimitry Andric         // FIXME: Change to an error if non-default in 4.0.
38188f0fd8f6SDimitry Andric         Visibility = getDecodedVisibility(Record[6]);
38197ae0e2c9SDimitry Andric 
38207ae0e2c9SDimitry Andric       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3821f22ef01cSRoman Divacky       if (Record.size() > 7)
38228f0fd8f6SDimitry Andric         TLM = getDecodedThreadLocalMode(Record[7]);
3823f22ef01cSRoman Divacky 
38243ca95b02SDimitry Andric       GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
38252754fe60SDimitry Andric       if (Record.size() > 8)
38263ca95b02SDimitry Andric         UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
38272754fe60SDimitry Andric 
3828139f7f9bSDimitry Andric       bool ExternallyInitialized = false;
3829139f7f9bSDimitry Andric       if (Record.size() > 9)
3830139f7f9bSDimitry Andric         ExternallyInitialized = Record[9];
3831139f7f9bSDimitry Andric 
3832f22ef01cSRoman Divacky       GlobalVariable *NewGV =
383391bc56edSDimitry Andric         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3834139f7f9bSDimitry Andric                            TLM, AddressSpace, ExternallyInitialized);
3835f22ef01cSRoman Divacky       NewGV->setAlignment(Alignment);
3836f22ef01cSRoman Divacky       if (!Section.empty())
3837f22ef01cSRoman Divacky         NewGV->setSection(Section);
3838f22ef01cSRoman Divacky       NewGV->setVisibility(Visibility);
38392754fe60SDimitry Andric       NewGV->setUnnamedAddr(UnnamedAddr);
3840f22ef01cSRoman Divacky 
384191bc56edSDimitry Andric       if (Record.size() > 10)
38428f0fd8f6SDimitry Andric         NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
384391bc56edSDimitry Andric       else
38448f0fd8f6SDimitry Andric         upgradeDLLImportExportLinkage(NewGV, RawLinkage);
384591bc56edSDimitry Andric 
3846f22ef01cSRoman Divacky       ValueList.push_back(NewGV);
3847f22ef01cSRoman Divacky 
3848f22ef01cSRoman Divacky       // Remember which value to use for the global initializer.
3849f22ef01cSRoman Divacky       if (unsigned InitID = Record[2])
3850f22ef01cSRoman Divacky         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
385191bc56edSDimitry Andric 
3852ff0cc061SDimitry Andric       if (Record.size() > 11) {
385391bc56edSDimitry Andric         if (unsigned ComdatID = Record[11]) {
3854ff0cc061SDimitry Andric           if (ComdatID > ComdatList.size())
38558f0fd8f6SDimitry Andric             return error("Invalid global variable comdat ID");
385691bc56edSDimitry Andric           NewGV->setComdat(ComdatList[ComdatID - 1]);
385791bc56edSDimitry Andric         }
3858ff0cc061SDimitry Andric       } else if (hasImplicitComdat(RawLinkage)) {
3859ff0cc061SDimitry Andric         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3860ff0cc061SDimitry Andric       }
38613ca95b02SDimitry Andric 
3862f22ef01cSRoman Divacky       break;
3863f22ef01cSRoman Divacky     }
3864f22ef01cSRoman Divacky     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
386591bc56edSDimitry Andric     //             alignment, section, visibility, gc, unnamed_addr,
386639d628a0SDimitry Andric     //             prologuedata, dllstorageclass, comdat, prefixdata]
3867f22ef01cSRoman Divacky     case bitc::MODULE_CODE_FUNCTION: {
3868f22ef01cSRoman Divacky       if (Record.size() < 8)
38698f0fd8f6SDimitry Andric         return error("Invalid record");
38706122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
3871f785676fSDimitry Andric       if (!Ty)
38728f0fd8f6SDimitry Andric         return error("Invalid record");
3873ff0cc061SDimitry Andric       if (auto *PTy = dyn_cast<PointerType>(Ty))
3874ff0cc061SDimitry Andric         Ty = PTy->getElementType();
3875ff0cc061SDimitry Andric       auto *FTy = dyn_cast<FunctionType>(Ty);
3876f22ef01cSRoman Divacky       if (!FTy)
38778f0fd8f6SDimitry Andric         return error("Invalid type for value");
38787d523365SDimitry Andric       auto CC = static_cast<CallingConv::ID>(Record[1]);
38797d523365SDimitry Andric       if (CC & ~CallingConv::MaxID)
38807d523365SDimitry Andric         return error("Invalid calling convention ID");
3881f22ef01cSRoman Divacky 
3882f22ef01cSRoman Divacky       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3883f22ef01cSRoman Divacky                                         "", TheModule);
3884f22ef01cSRoman Divacky 
38857d523365SDimitry Andric       Func->setCallingConv(CC);
3886f22ef01cSRoman Divacky       bool isProto = Record[2];
3887ff0cc061SDimitry Andric       uint64_t RawLinkage = Record[3];
3888ff0cc061SDimitry Andric       Func->setLinkage(getDecodedLinkage(RawLinkage));
3889f22ef01cSRoman Divacky       Func->setAttributes(getAttributes(Record[4]));
3890f22ef01cSRoman Divacky 
3891ff0cc061SDimitry Andric       unsigned Alignment;
3892ff0cc061SDimitry Andric       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3893ff0cc061SDimitry Andric         return EC;
3894ff0cc061SDimitry Andric       Func->setAlignment(Alignment);
3895f22ef01cSRoman Divacky       if (Record[6]) {
3896f22ef01cSRoman Divacky         if (Record[6]-1 >= SectionTable.size())
38978f0fd8f6SDimitry Andric           return error("Invalid ID");
3898f22ef01cSRoman Divacky         Func->setSection(SectionTable[Record[6]-1]);
3899f22ef01cSRoman Divacky       }
390091bc56edSDimitry Andric       // Local linkage must have default visibility.
390191bc56edSDimitry Andric       if (!Func->hasLocalLinkage())
390291bc56edSDimitry Andric         // FIXME: Change to an error if non-default in 4.0.
39038f0fd8f6SDimitry Andric         Func->setVisibility(getDecodedVisibility(Record[7]));
3904f22ef01cSRoman Divacky       if (Record.size() > 8 && Record[8]) {
3905ff0cc061SDimitry Andric         if (Record[8]-1 >= GCTable.size())
39068f0fd8f6SDimitry Andric           return error("Invalid ID");
39073ca95b02SDimitry Andric         Func->setGC(GCTable[Record[8] - 1]);
3908f22ef01cSRoman Divacky       }
39093ca95b02SDimitry Andric       GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
39102754fe60SDimitry Andric       if (Record.size() > 9)
39113ca95b02SDimitry Andric         UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
39122754fe60SDimitry Andric       Func->setUnnamedAddr(UnnamedAddr);
3913f785676fSDimitry Andric       if (Record.size() > 10 && Record[10] != 0)
391439d628a0SDimitry Andric         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
391591bc56edSDimitry Andric 
391691bc56edSDimitry Andric       if (Record.size() > 11)
39178f0fd8f6SDimitry Andric         Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
391891bc56edSDimitry Andric       else
39198f0fd8f6SDimitry Andric         upgradeDLLImportExportLinkage(Func, RawLinkage);
392091bc56edSDimitry Andric 
3921ff0cc061SDimitry Andric       if (Record.size() > 12) {
392291bc56edSDimitry Andric         if (unsigned ComdatID = Record[12]) {
3923ff0cc061SDimitry Andric           if (ComdatID > ComdatList.size())
39248f0fd8f6SDimitry Andric             return error("Invalid function comdat ID");
392591bc56edSDimitry Andric           Func->setComdat(ComdatList[ComdatID - 1]);
392691bc56edSDimitry Andric         }
3927ff0cc061SDimitry Andric       } else if (hasImplicitComdat(RawLinkage)) {
3928ff0cc061SDimitry Andric         Func->setComdat(reinterpret_cast<Comdat *>(1));
3929ff0cc061SDimitry Andric       }
393091bc56edSDimitry Andric 
393139d628a0SDimitry Andric       if (Record.size() > 13 && Record[13] != 0)
393239d628a0SDimitry Andric         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
393339d628a0SDimitry Andric 
39348f0fd8f6SDimitry Andric       if (Record.size() > 14 && Record[14] != 0)
39358f0fd8f6SDimitry Andric         FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
39368f0fd8f6SDimitry Andric 
3937f22ef01cSRoman Divacky       ValueList.push_back(Func);
3938f22ef01cSRoman Divacky 
3939f22ef01cSRoman Divacky       // If this is a function with a body, remember the prototype we are
3940f22ef01cSRoman Divacky       // creating now, so that we can match up the body with them later.
3941dff0c46cSDimitry Andric       if (!isProto) {
394239d628a0SDimitry Andric         Func->setIsMaterializable(true);
3943f22ef01cSRoman Divacky         FunctionsWithBodies.push_back(Func);
394439d628a0SDimitry Andric         DeferredFunctionInfo[Func] = 0;
3945dff0c46cSDimitry Andric       }
3946f22ef01cSRoman Divacky       break;
3947f22ef01cSRoman Divacky     }
39487d523365SDimitry Andric     // ALIAS: [alias type, addrspace, aliasee val#, linkage]
39497d523365SDimitry Andric     // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
39503ca95b02SDimitry Andric     // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
39513ca95b02SDimitry Andric     case bitc::MODULE_CODE_IFUNC:
39527d523365SDimitry Andric     case bitc::MODULE_CODE_ALIAS:
39537d523365SDimitry Andric     case bitc::MODULE_CODE_ALIAS_OLD: {
39543ca95b02SDimitry Andric       bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
39557d523365SDimitry Andric       if (Record.size() < (3 + (unsigned)NewRecord))
39568f0fd8f6SDimitry Andric         return error("Invalid record");
39577d523365SDimitry Andric       unsigned OpNum = 0;
39587d523365SDimitry Andric       Type *Ty = getTypeByID(Record[OpNum++]);
3959f785676fSDimitry Andric       if (!Ty)
39608f0fd8f6SDimitry Andric         return error("Invalid record");
39617d523365SDimitry Andric 
39627d523365SDimitry Andric       unsigned AddrSpace;
39637d523365SDimitry Andric       if (!NewRecord) {
396491bc56edSDimitry Andric         auto *PTy = dyn_cast<PointerType>(Ty);
396591bc56edSDimitry Andric         if (!PTy)
39668f0fd8f6SDimitry Andric           return error("Invalid type for value");
39677d523365SDimitry Andric         Ty = PTy->getElementType();
39687d523365SDimitry Andric         AddrSpace = PTy->getAddressSpace();
39697d523365SDimitry Andric       } else {
39707d523365SDimitry Andric         AddrSpace = Record[OpNum++];
39717d523365SDimitry Andric       }
3972f22ef01cSRoman Divacky 
39737d523365SDimitry Andric       auto Val = Record[OpNum++];
39747d523365SDimitry Andric       auto Linkage = Record[OpNum++];
39753ca95b02SDimitry Andric       GlobalIndirectSymbol *NewGA;
39763ca95b02SDimitry Andric       if (BitCode == bitc::MODULE_CODE_ALIAS ||
39773ca95b02SDimitry Andric           BitCode == bitc::MODULE_CODE_ALIAS_OLD)
39783ca95b02SDimitry Andric         NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
39793ca95b02SDimitry Andric                                     "", TheModule);
39803ca95b02SDimitry Andric       else
39813ca95b02SDimitry Andric         NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
39823ca95b02SDimitry Andric                                     "", nullptr, TheModule);
3983f22ef01cSRoman Divacky       // Old bitcode files didn't have visibility field.
398491bc56edSDimitry Andric       // Local linkage must have default visibility.
39857d523365SDimitry Andric       if (OpNum != Record.size()) {
39867d523365SDimitry Andric         auto VisInd = OpNum++;
39877d523365SDimitry Andric         if (!NewGA->hasLocalLinkage())
398891bc56edSDimitry Andric           // FIXME: Change to an error if non-default in 4.0.
39897d523365SDimitry Andric           NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
39907d523365SDimitry Andric       }
39917d523365SDimitry Andric       if (OpNum != Record.size())
39927d523365SDimitry Andric         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
399391bc56edSDimitry Andric       else
39947d523365SDimitry Andric         upgradeDLLImportExportLinkage(NewGA, Linkage);
39957d523365SDimitry Andric       if (OpNum != Record.size())
39967d523365SDimitry Andric         NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
39977d523365SDimitry Andric       if (OpNum != Record.size())
39983ca95b02SDimitry Andric         NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3999f22ef01cSRoman Divacky       ValueList.push_back(NewGA);
40003ca95b02SDimitry Andric       IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4001f22ef01cSRoman Divacky       break;
4002f22ef01cSRoman Divacky     }
4003f22ef01cSRoman Divacky     /// MODULE_CODE_PURGEVALS: [numvals]
4004f22ef01cSRoman Divacky     case bitc::MODULE_CODE_PURGEVALS:
4005f22ef01cSRoman Divacky       // Trim down the value list to the specified size.
4006f22ef01cSRoman Divacky       if (Record.size() < 1 || Record[0] > ValueList.size())
40078f0fd8f6SDimitry Andric         return error("Invalid record");
4008f22ef01cSRoman Divacky       ValueList.shrinkTo(Record[0]);
4009f22ef01cSRoman Divacky       break;
40107d523365SDimitry Andric     /// MODULE_CODE_VSTOFFSET: [offset]
40117d523365SDimitry Andric     case bitc::MODULE_CODE_VSTOFFSET:
40127d523365SDimitry Andric       if (Record.size() < 1)
40137d523365SDimitry Andric         return error("Invalid record");
40147d523365SDimitry Andric       VSTOffset = Record[0];
40157d523365SDimitry Andric       break;
40163ca95b02SDimitry Andric     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
40173ca95b02SDimitry Andric     case bitc::MODULE_CODE_SOURCE_FILENAME:
40183ca95b02SDimitry Andric       SmallString<128> ValueName;
40193ca95b02SDimitry Andric       if (convertToString(Record, 0, ValueName))
40207d523365SDimitry Andric         return error("Invalid record");
40213ca95b02SDimitry Andric       TheModule->setSourceFileName(ValueName);
40227d523365SDimitry Andric       break;
4023f22ef01cSRoman Divacky     }
4024f22ef01cSRoman Divacky     Record.clear();
4025f22ef01cSRoman Divacky   }
4026f22ef01cSRoman Divacky }
4027f22ef01cSRoman Divacky 
40287d523365SDimitry Andric /// Helper to read the header common to all bitcode files.
40297d523365SDimitry Andric static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
40307d523365SDimitry Andric   // Sniff for the signature.
40317d523365SDimitry Andric   if (Stream.Read(8) != 'B' ||
40327d523365SDimitry Andric       Stream.Read(8) != 'C' ||
40337d523365SDimitry Andric       Stream.Read(4) != 0x0 ||
40347d523365SDimitry Andric       Stream.Read(4) != 0xC ||
40357d523365SDimitry Andric       Stream.Read(4) != 0xE ||
40367d523365SDimitry Andric       Stream.Read(4) != 0xD)
40377d523365SDimitry Andric     return false;
40387d523365SDimitry Andric   return true;
40397d523365SDimitry Andric }
40407d523365SDimitry Andric 
40418f0fd8f6SDimitry Andric std::error_code
40428f0fd8f6SDimitry Andric BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
40438f0fd8f6SDimitry Andric                                 Module *M, bool ShouldLazyLoadMetadata) {
40448f0fd8f6SDimitry Andric   TheModule = M;
4045f22ef01cSRoman Divacky 
40468f0fd8f6SDimitry Andric   if (std::error_code EC = initStream(std::move(Streamer)))
4047f785676fSDimitry Andric     return EC;
4048f22ef01cSRoman Divacky 
4049f22ef01cSRoman Divacky   // Sniff for the signature.
40507d523365SDimitry Andric   if (!hasValidBitcodeHeader(Stream))
40518f0fd8f6SDimitry Andric     return error("Invalid bitcode signature");
4052f22ef01cSRoman Divacky 
4053f22ef01cSRoman Divacky   // We expect a number of well-defined blocks, though we don't necessarily
4054f22ef01cSRoman Divacky   // need to understand them all.
4055139f7f9bSDimitry Andric   while (1) {
4056ff0cc061SDimitry Andric     if (Stream.AtEndOfStream()) {
4057ff0cc061SDimitry Andric       // We didn't really read a proper Module.
40588f0fd8f6SDimitry Andric       return error("Malformed IR file");
4059ff0cc061SDimitry Andric     }
4060bd5abe19SDimitry Andric 
4061139f7f9bSDimitry Andric     BitstreamEntry Entry =
4062139f7f9bSDimitry Andric       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
4063f22ef01cSRoman Divacky 
40648f0fd8f6SDimitry Andric     if (Entry.Kind != BitstreamEntry::SubBlock)
40658f0fd8f6SDimitry Andric       return error("Malformed block");
4066f22ef01cSRoman Divacky 
40677d523365SDimitry Andric     if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
40687d523365SDimitry Andric       parseBitcodeVersion();
40697d523365SDimitry Andric       continue;
40707d523365SDimitry Andric     }
40717d523365SDimitry Andric 
40728f0fd8f6SDimitry Andric     if (Entry.ID == bitc::MODULE_BLOCK_ID)
40737d523365SDimitry Andric       return parseModule(0, ShouldLazyLoadMetadata);
40748f0fd8f6SDimitry Andric 
4075f22ef01cSRoman Divacky     if (Stream.SkipBlock())
40768f0fd8f6SDimitry Andric       return error("Invalid record");
4077139f7f9bSDimitry Andric   }
4078f22ef01cSRoman Divacky }
4079f22ef01cSRoman Divacky 
408091bc56edSDimitry Andric ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
40812754fe60SDimitry Andric   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
40828f0fd8f6SDimitry Andric     return error("Invalid record");
40832754fe60SDimitry Andric 
40842754fe60SDimitry Andric   SmallVector<uint64_t, 64> Record;
40852754fe60SDimitry Andric 
408691bc56edSDimitry Andric   std::string Triple;
40872754fe60SDimitry Andric   // Read all the records for this module.
4088139f7f9bSDimitry Andric   while (1) {
4089139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
40902754fe60SDimitry Andric 
4091139f7f9bSDimitry Andric     switch (Entry.Kind) {
4092139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
4093139f7f9bSDimitry Andric     case BitstreamEntry::Error:
40948f0fd8f6SDimitry Andric       return error("Malformed block");
4095139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
409691bc56edSDimitry Andric       return Triple;
4097139f7f9bSDimitry Andric     case BitstreamEntry::Record:
4098139f7f9bSDimitry Andric       // The interesting case.
40992754fe60SDimitry Andric       break;
41002754fe60SDimitry Andric     }
41012754fe60SDimitry Andric 
41022754fe60SDimitry Andric     // Read a record.
4103139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
41042754fe60SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
41052754fe60SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
41062754fe60SDimitry Andric       std::string S;
41078f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
41088f0fd8f6SDimitry Andric         return error("Invalid record");
41092754fe60SDimitry Andric       Triple = S;
41102754fe60SDimitry Andric       break;
41112754fe60SDimitry Andric     }
41122754fe60SDimitry Andric     }
41132754fe60SDimitry Andric     Record.clear();
41142754fe60SDimitry Andric   }
411591bc56edSDimitry Andric   llvm_unreachable("Exit infinite loop");
41162754fe60SDimitry Andric }
41172754fe60SDimitry Andric 
411891bc56edSDimitry Andric ErrorOr<std::string> BitcodeReader::parseTriple() {
41198f0fd8f6SDimitry Andric   if (std::error_code EC = initStream(nullptr))
4120f785676fSDimitry Andric     return EC;
41212754fe60SDimitry Andric 
41222754fe60SDimitry Andric   // Sniff for the signature.
41237d523365SDimitry Andric   if (!hasValidBitcodeHeader(Stream))
41248f0fd8f6SDimitry Andric     return error("Invalid bitcode signature");
41252754fe60SDimitry Andric 
41262754fe60SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
41272754fe60SDimitry Andric   // need to understand them all.
4128139f7f9bSDimitry Andric   while (1) {
4129139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advance();
41302754fe60SDimitry Andric 
4131139f7f9bSDimitry Andric     switch (Entry.Kind) {
4132139f7f9bSDimitry Andric     case BitstreamEntry::Error:
41338f0fd8f6SDimitry Andric       return error("Malformed block");
4134139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
413591bc56edSDimitry Andric       return std::error_code();
4136139f7f9bSDimitry Andric 
4137139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock:
4138139f7f9bSDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
413991bc56edSDimitry Andric         return parseModuleTriple();
4140139f7f9bSDimitry Andric 
4141139f7f9bSDimitry Andric       // Ignore other sub-blocks.
4142f785676fSDimitry Andric       if (Stream.SkipBlock())
41438f0fd8f6SDimitry Andric         return error("Malformed block");
4144139f7f9bSDimitry Andric       continue;
4145139f7f9bSDimitry Andric 
4146139f7f9bSDimitry Andric     case BitstreamEntry::Record:
4147139f7f9bSDimitry Andric       Stream.skipRecord(Entry.ID);
4148139f7f9bSDimitry Andric       continue;
4149139f7f9bSDimitry Andric     }
4150139f7f9bSDimitry Andric   }
41512754fe60SDimitry Andric }
41522754fe60SDimitry Andric 
41537d523365SDimitry Andric ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
41547d523365SDimitry Andric   if (std::error_code EC = initStream(nullptr))
41557d523365SDimitry Andric     return EC;
41567d523365SDimitry Andric 
41577d523365SDimitry Andric   // Sniff for the signature.
41587d523365SDimitry Andric   if (!hasValidBitcodeHeader(Stream))
41597d523365SDimitry Andric     return error("Invalid bitcode signature");
41607d523365SDimitry Andric 
41617d523365SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
41627d523365SDimitry Andric   // need to understand them all.
41637d523365SDimitry Andric   while (1) {
41647d523365SDimitry Andric     BitstreamEntry Entry = Stream.advance();
41657d523365SDimitry Andric     switch (Entry.Kind) {
41667d523365SDimitry Andric     case BitstreamEntry::Error:
41677d523365SDimitry Andric       return error("Malformed block");
41687d523365SDimitry Andric     case BitstreamEntry::EndBlock:
41697d523365SDimitry Andric       return std::error_code();
41707d523365SDimitry Andric 
41717d523365SDimitry Andric     case BitstreamEntry::SubBlock:
41727d523365SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
41737d523365SDimitry Andric         if (std::error_code EC = parseBitcodeVersion())
41747d523365SDimitry Andric           return EC;
41757d523365SDimitry Andric         return ProducerIdentification;
41767d523365SDimitry Andric       }
41777d523365SDimitry Andric       // Ignore other sub-blocks.
41787d523365SDimitry Andric       if (Stream.SkipBlock())
41797d523365SDimitry Andric         return error("Malformed block");
41807d523365SDimitry Andric       continue;
41817d523365SDimitry Andric     case BitstreamEntry::Record:
41827d523365SDimitry Andric       Stream.skipRecord(Entry.ID);
41837d523365SDimitry Andric       continue;
41847d523365SDimitry Andric     }
41857d523365SDimitry Andric   }
41867d523365SDimitry Andric }
41877d523365SDimitry Andric 
41883ca95b02SDimitry Andric std::error_code BitcodeReader::parseGlobalObjectAttachment(
41893ca95b02SDimitry Andric     GlobalObject &GO, ArrayRef<uint64_t> Record) {
41903ca95b02SDimitry Andric   assert(Record.size() % 2 == 0);
41913ca95b02SDimitry Andric   for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
41923ca95b02SDimitry Andric     auto K = MDKindMap.find(Record[I]);
41933ca95b02SDimitry Andric     if (K == MDKindMap.end())
41943ca95b02SDimitry Andric       return error("Invalid ID");
41953ca95b02SDimitry Andric     MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
41963ca95b02SDimitry Andric     if (!MD)
41973ca95b02SDimitry Andric       return error("Invalid metadata attachment");
41983ca95b02SDimitry Andric     GO.addMetadata(K->second, *MD);
41993ca95b02SDimitry Andric   }
42003ca95b02SDimitry Andric   return std::error_code();
42013ca95b02SDimitry Andric }
42023ca95b02SDimitry Andric 
42033ca95b02SDimitry Andric ErrorOr<bool> BitcodeReader::hasObjCCategory() {
42043ca95b02SDimitry Andric   if (std::error_code EC = initStream(nullptr))
42053ca95b02SDimitry Andric     return EC;
42063ca95b02SDimitry Andric 
42073ca95b02SDimitry Andric   // Sniff for the signature.
42083ca95b02SDimitry Andric   if (!hasValidBitcodeHeader(Stream))
42093ca95b02SDimitry Andric     return error("Invalid bitcode signature");
42103ca95b02SDimitry Andric 
42113ca95b02SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
42123ca95b02SDimitry Andric   // need to understand them all.
42133ca95b02SDimitry Andric   while (1) {
42143ca95b02SDimitry Andric     BitstreamEntry Entry = Stream.advance();
42153ca95b02SDimitry Andric 
42163ca95b02SDimitry Andric     switch (Entry.Kind) {
42173ca95b02SDimitry Andric     case BitstreamEntry::Error:
42183ca95b02SDimitry Andric       return error("Malformed block");
42193ca95b02SDimitry Andric     case BitstreamEntry::EndBlock:
42203ca95b02SDimitry Andric       return std::error_code();
42213ca95b02SDimitry Andric 
42223ca95b02SDimitry Andric     case BitstreamEntry::SubBlock:
42233ca95b02SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
42243ca95b02SDimitry Andric         return hasObjCCategoryInModule();
42253ca95b02SDimitry Andric 
42263ca95b02SDimitry Andric       // Ignore other sub-blocks.
42273ca95b02SDimitry Andric       if (Stream.SkipBlock())
42283ca95b02SDimitry Andric         return error("Malformed block");
42293ca95b02SDimitry Andric       continue;
42303ca95b02SDimitry Andric 
42313ca95b02SDimitry Andric     case BitstreamEntry::Record:
42323ca95b02SDimitry Andric       Stream.skipRecord(Entry.ID);
42333ca95b02SDimitry Andric       continue;
42343ca95b02SDimitry Andric     }
42353ca95b02SDimitry Andric   }
42363ca95b02SDimitry Andric }
42373ca95b02SDimitry Andric 
42383ca95b02SDimitry Andric ErrorOr<bool> BitcodeReader::hasObjCCategoryInModule() {
42393ca95b02SDimitry Andric   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
42403ca95b02SDimitry Andric     return error("Invalid record");
42413ca95b02SDimitry Andric 
42423ca95b02SDimitry Andric   SmallVector<uint64_t, 64> Record;
42433ca95b02SDimitry Andric   // Read all the records for this module.
42443ca95b02SDimitry Andric   while (1) {
42453ca95b02SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
42463ca95b02SDimitry Andric 
42473ca95b02SDimitry Andric     switch (Entry.Kind) {
42483ca95b02SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
42493ca95b02SDimitry Andric     case BitstreamEntry::Error:
42503ca95b02SDimitry Andric       return error("Malformed block");
42513ca95b02SDimitry Andric     case BitstreamEntry::EndBlock:
42523ca95b02SDimitry Andric       return false;
42533ca95b02SDimitry Andric     case BitstreamEntry::Record:
42543ca95b02SDimitry Andric       // The interesting case.
42553ca95b02SDimitry Andric       break;
42563ca95b02SDimitry Andric     }
42573ca95b02SDimitry Andric 
42583ca95b02SDimitry Andric     // Read a record.
42593ca95b02SDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
42603ca95b02SDimitry Andric     default:
42613ca95b02SDimitry Andric       break; // Default behavior, ignore unknown content.
42623ca95b02SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
42633ca95b02SDimitry Andric       std::string S;
42643ca95b02SDimitry Andric       if (convertToString(Record, 0, S))
42653ca95b02SDimitry Andric         return error("Invalid record");
42663ca95b02SDimitry Andric       // Check for the i386 and other (x86_64, ARM) conventions
42673ca95b02SDimitry Andric       if (S.find("__DATA, __objc_catlist") != std::string::npos ||
42683ca95b02SDimitry Andric           S.find("__OBJC,__category") != std::string::npos)
42693ca95b02SDimitry Andric         return true;
42703ca95b02SDimitry Andric       break;
42713ca95b02SDimitry Andric     }
42723ca95b02SDimitry Andric     }
42733ca95b02SDimitry Andric     Record.clear();
42743ca95b02SDimitry Andric   }
42753ca95b02SDimitry Andric   llvm_unreachable("Exit infinite loop");
42763ca95b02SDimitry Andric }
42773ca95b02SDimitry Andric 
42788f0fd8f6SDimitry Andric /// Parse metadata attachments.
42798f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
4280f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
42818f0fd8f6SDimitry Andric     return error("Invalid record");
4282f22ef01cSRoman Divacky 
4283f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
4284f22ef01cSRoman Divacky   while (1) {
4285139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4286139f7f9bSDimitry Andric 
4287139f7f9bSDimitry Andric     switch (Entry.Kind) {
4288139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
4289139f7f9bSDimitry Andric     case BitstreamEntry::Error:
42908f0fd8f6SDimitry Andric       return error("Malformed block");
4291139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
429291bc56edSDimitry Andric       return std::error_code();
4293139f7f9bSDimitry Andric     case BitstreamEntry::Record:
4294139f7f9bSDimitry Andric       // The interesting case.
4295f22ef01cSRoman Divacky       break;
4296f22ef01cSRoman Divacky     }
4297139f7f9bSDimitry Andric 
4298f22ef01cSRoman Divacky     // Read a metadata attachment record.
4299f22ef01cSRoman Divacky     Record.clear();
4300139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
4301f22ef01cSRoman Divacky     default:  // Default behavior: ignore.
4302f22ef01cSRoman Divacky       break;
430317a519f9SDimitry Andric     case bitc::METADATA_ATTACHMENT: {
4304f22ef01cSRoman Divacky       unsigned RecordLength = Record.size();
4305ff0cc061SDimitry Andric       if (Record.empty())
43068f0fd8f6SDimitry Andric         return error("Invalid record");
4307ff0cc061SDimitry Andric       if (RecordLength % 2 == 0) {
4308ff0cc061SDimitry Andric         // A function attachment.
43093ca95b02SDimitry Andric         if (std::error_code EC = parseGlobalObjectAttachment(F, Record))
43103ca95b02SDimitry Andric           return EC;
4311ff0cc061SDimitry Andric         continue;
4312ff0cc061SDimitry Andric       }
4313ff0cc061SDimitry Andric 
4314ff0cc061SDimitry Andric       // An instruction attachment.
4315f22ef01cSRoman Divacky       Instruction *Inst = InstructionList[Record[0]];
4316f22ef01cSRoman Divacky       for (unsigned i = 1; i != RecordLength; i = i+2) {
4317f22ef01cSRoman Divacky         unsigned Kind = Record[i];
4318e580952dSDimitry Andric         DenseMap<unsigned, unsigned>::iterator I =
4319e580952dSDimitry Andric           MDKindMap.find(Kind);
4320e580952dSDimitry Andric         if (I == MDKindMap.end())
43218f0fd8f6SDimitry Andric           return error("Invalid ID");
43223ca95b02SDimitry Andric         Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
432339d628a0SDimitry Andric         if (isa<LocalAsMetadata>(Node))
432439d628a0SDimitry Andric           // Drop the attachment.  This used to be legal, but there's no
432539d628a0SDimitry Andric           // upgrade path.
432639d628a0SDimitry Andric           break;
43273ca95b02SDimitry Andric         MDNode *MD = dyn_cast_or_null<MDNode>(Node);
43283ca95b02SDimitry Andric         if (!MD)
43293ca95b02SDimitry Andric           return error("Invalid metadata attachment");
43303ca95b02SDimitry Andric 
43313ca95b02SDimitry Andric         if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
43323ca95b02SDimitry Andric           MD = upgradeInstructionLoopAttachment(*MD);
43333ca95b02SDimitry Andric 
43343ca95b02SDimitry Andric         Inst->setMetadata(I->second, MD);
43353ca95b02SDimitry Andric         if (I->second == LLVMContext::MD_tbaa) {
4336f785676fSDimitry Andric           InstsWithTBAATag.push_back(Inst);
43373ca95b02SDimitry Andric           continue;
43383ca95b02SDimitry Andric         }
4339f22ef01cSRoman Divacky       }
4340f22ef01cSRoman Divacky       break;
4341f22ef01cSRoman Divacky     }
4342f22ef01cSRoman Divacky     }
4343f22ef01cSRoman Divacky   }
4344f22ef01cSRoman Divacky }
4345f22ef01cSRoman Divacky 
43467d523365SDimitry Andric static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
43477d523365SDimitry Andric   LLVMContext &Context = PtrType->getContext();
4348ff0cc061SDimitry Andric   if (!isa<PointerType>(PtrType))
43497d523365SDimitry Andric     return error(Context, "Load/Store operand is not a pointer type");
4350ff0cc061SDimitry Andric   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
4351ff0cc061SDimitry Andric 
4352ff0cc061SDimitry Andric   if (ValType && ValType != ElemType)
43537d523365SDimitry Andric     return error(Context, "Explicit load/store type does not match pointee "
43547d523365SDimitry Andric                           "type of pointer operand");
4355ff0cc061SDimitry Andric   if (!PointerType::isLoadableOrStorableType(ElemType))
43567d523365SDimitry Andric     return error(Context, "Cannot load/store from pointer");
4357ff0cc061SDimitry Andric   return std::error_code();
4358ff0cc061SDimitry Andric }
4359ff0cc061SDimitry Andric 
43608f0fd8f6SDimitry Andric /// Lazily parse the specified function body block.
43618f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseFunctionBody(Function *F) {
4362f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
43638f0fd8f6SDimitry Andric     return error("Invalid record");
4364f22ef01cSRoman Divacky 
43653ca95b02SDimitry Andric   // Unexpected unresolved metadata when parsing function.
43663ca95b02SDimitry Andric   if (MetadataList.hasFwdRefs())
43673ca95b02SDimitry Andric     return error("Invalid function metadata: incoming forward references");
43683ca95b02SDimitry Andric 
4369f22ef01cSRoman Divacky   InstructionList.clear();
4370f22ef01cSRoman Divacky   unsigned ModuleValueListSize = ValueList.size();
43717d523365SDimitry Andric   unsigned ModuleMetadataListSize = MetadataList.size();
4372f22ef01cSRoman Divacky 
4373f22ef01cSRoman Divacky   // Add all the function arguments to the value table.
43747d523365SDimitry Andric   for (Argument &I : F->args())
43757d523365SDimitry Andric     ValueList.push_back(&I);
4376f22ef01cSRoman Divacky 
4377f22ef01cSRoman Divacky   unsigned NextValueNo = ValueList.size();
437891bc56edSDimitry Andric   BasicBlock *CurBB = nullptr;
4379f22ef01cSRoman Divacky   unsigned CurBBNo = 0;
4380f22ef01cSRoman Divacky 
4381f22ef01cSRoman Divacky   DebugLoc LastLoc;
438239d628a0SDimitry Andric   auto getLastInstruction = [&]() -> Instruction * {
438339d628a0SDimitry Andric     if (CurBB && !CurBB->empty())
438439d628a0SDimitry Andric       return &CurBB->back();
438539d628a0SDimitry Andric     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
438639d628a0SDimitry Andric              !FunctionBBs[CurBBNo - 1]->empty())
438739d628a0SDimitry Andric       return &FunctionBBs[CurBBNo - 1]->back();
438839d628a0SDimitry Andric     return nullptr;
438939d628a0SDimitry Andric   };
4390f22ef01cSRoman Divacky 
43917d523365SDimitry Andric   std::vector<OperandBundleDef> OperandBundles;
43927d523365SDimitry Andric 
4393f22ef01cSRoman Divacky   // Read all the records.
4394f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
4395f22ef01cSRoman Divacky   while (1) {
4396139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advance();
4397f22ef01cSRoman Divacky 
4398139f7f9bSDimitry Andric     switch (Entry.Kind) {
4399139f7f9bSDimitry Andric     case BitstreamEntry::Error:
44008f0fd8f6SDimitry Andric       return error("Malformed block");
4401139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
4402139f7f9bSDimitry Andric       goto OutOfRecordLoop;
4403139f7f9bSDimitry Andric 
4404139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock:
4405139f7f9bSDimitry Andric       switch (Entry.ID) {
4406f22ef01cSRoman Divacky       default:  // Skip unknown content.
4407f22ef01cSRoman Divacky         if (Stream.SkipBlock())
44088f0fd8f6SDimitry Andric           return error("Invalid record");
4409f22ef01cSRoman Divacky         break;
4410f22ef01cSRoman Divacky       case bitc::CONSTANTS_BLOCK_ID:
44118f0fd8f6SDimitry Andric         if (std::error_code EC = parseConstants())
4412f785676fSDimitry Andric           return EC;
4413f22ef01cSRoman Divacky         NextValueNo = ValueList.size();
4414f22ef01cSRoman Divacky         break;
4415f22ef01cSRoman Divacky       case bitc::VALUE_SYMTAB_BLOCK_ID:
44168f0fd8f6SDimitry Andric         if (std::error_code EC = parseValueSymbolTable())
4417f785676fSDimitry Andric           return EC;
4418f22ef01cSRoman Divacky         break;
4419f22ef01cSRoman Divacky       case bitc::METADATA_ATTACHMENT_ID:
44208f0fd8f6SDimitry Andric         if (std::error_code EC = parseMetadataAttachment(*F))
4421f785676fSDimitry Andric           return EC;
4422f22ef01cSRoman Divacky         break;
4423f22ef01cSRoman Divacky       case bitc::METADATA_BLOCK_ID:
44248f0fd8f6SDimitry Andric         if (std::error_code EC = parseMetadata())
4425f785676fSDimitry Andric           return EC;
4426f22ef01cSRoman Divacky         break;
442739d628a0SDimitry Andric       case bitc::USELIST_BLOCK_ID:
44288f0fd8f6SDimitry Andric         if (std::error_code EC = parseUseLists())
442939d628a0SDimitry Andric           return EC;
443039d628a0SDimitry Andric         break;
4431f22ef01cSRoman Divacky       }
4432f22ef01cSRoman Divacky       continue;
4433f22ef01cSRoman Divacky 
4434139f7f9bSDimitry Andric     case BitstreamEntry::Record:
4435139f7f9bSDimitry Andric       // The interesting case.
4436139f7f9bSDimitry Andric       break;
4437f22ef01cSRoman Divacky     }
4438f22ef01cSRoman Divacky 
4439f22ef01cSRoman Divacky     // Read a record.
4440f22ef01cSRoman Divacky     Record.clear();
444191bc56edSDimitry Andric     Instruction *I = nullptr;
4442139f7f9bSDimitry Andric     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
4443f22ef01cSRoman Divacky     switch (BitCode) {
4444f22ef01cSRoman Divacky     default: // Default behavior: reject
44458f0fd8f6SDimitry Andric       return error("Invalid value");
444639d628a0SDimitry Andric     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4447f22ef01cSRoman Divacky       if (Record.size() < 1 || Record[0] == 0)
44488f0fd8f6SDimitry Andric         return error("Invalid record");
4449f22ef01cSRoman Divacky       // Create all the basic blocks for the function.
4450f22ef01cSRoman Divacky       FunctionBBs.resize(Record[0]);
445139d628a0SDimitry Andric 
445239d628a0SDimitry Andric       // See if anything took the address of blocks in this function.
445339d628a0SDimitry Andric       auto BBFRI = BasicBlockFwdRefs.find(F);
445439d628a0SDimitry Andric       if (BBFRI == BasicBlockFwdRefs.end()) {
4455f22ef01cSRoman Divacky         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4456f22ef01cSRoman Divacky           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
445739d628a0SDimitry Andric       } else {
445839d628a0SDimitry Andric         auto &BBRefs = BBFRI->second;
445939d628a0SDimitry Andric         // Check for invalid basic block references.
446039d628a0SDimitry Andric         if (BBRefs.size() > FunctionBBs.size())
44618f0fd8f6SDimitry Andric           return error("Invalid ID");
446239d628a0SDimitry Andric         assert(!BBRefs.empty() && "Unexpected empty array");
446339d628a0SDimitry Andric         assert(!BBRefs.front() && "Invalid reference to entry block");
446439d628a0SDimitry Andric         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
446539d628a0SDimitry Andric              ++I)
446639d628a0SDimitry Andric           if (I < RE && BBRefs[I]) {
446739d628a0SDimitry Andric             BBRefs[I]->insertInto(F);
446839d628a0SDimitry Andric             FunctionBBs[I] = BBRefs[I];
446939d628a0SDimitry Andric           } else {
447039d628a0SDimitry Andric             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
447139d628a0SDimitry Andric           }
447239d628a0SDimitry Andric 
447339d628a0SDimitry Andric         // Erase from the table.
447439d628a0SDimitry Andric         BasicBlockFwdRefs.erase(BBFRI);
447539d628a0SDimitry Andric       }
447639d628a0SDimitry Andric 
4477f22ef01cSRoman Divacky       CurBB = FunctionBBs[0];
4478f22ef01cSRoman Divacky       continue;
447939d628a0SDimitry Andric     }
4480f22ef01cSRoman Divacky 
4481f22ef01cSRoman Divacky     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4482f22ef01cSRoman Divacky       // This record indicates that the last instruction is at the same
4483f22ef01cSRoman Divacky       // location as the previous instruction with a location.
448439d628a0SDimitry Andric       I = getLastInstruction();
4485f22ef01cSRoman Divacky 
448691bc56edSDimitry Andric       if (!I)
44878f0fd8f6SDimitry Andric         return error("Invalid record");
4488f22ef01cSRoman Divacky       I->setDebugLoc(LastLoc);
448991bc56edSDimitry Andric       I = nullptr;
4490f22ef01cSRoman Divacky       continue;
4491f22ef01cSRoman Divacky 
449217a519f9SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
449339d628a0SDimitry Andric       I = getLastInstruction();
449491bc56edSDimitry Andric       if (!I || Record.size() < 4)
44958f0fd8f6SDimitry Andric         return error("Invalid record");
4496f22ef01cSRoman Divacky 
4497f22ef01cSRoman Divacky       unsigned Line = Record[0], Col = Record[1];
4498f22ef01cSRoman Divacky       unsigned ScopeID = Record[2], IAID = Record[3];
4499f22ef01cSRoman Divacky 
450091bc56edSDimitry Andric       MDNode *Scope = nullptr, *IA = nullptr;
45013ca95b02SDimitry Andric       if (ScopeID) {
45023ca95b02SDimitry Andric         Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
45033ca95b02SDimitry Andric         if (!Scope)
45043ca95b02SDimitry Andric           return error("Invalid record");
45053ca95b02SDimitry Andric       }
45063ca95b02SDimitry Andric       if (IAID) {
45073ca95b02SDimitry Andric         IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
45083ca95b02SDimitry Andric         if (!IA)
45093ca95b02SDimitry Andric           return error("Invalid record");
45103ca95b02SDimitry Andric       }
4511f22ef01cSRoman Divacky       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4512f22ef01cSRoman Divacky       I->setDebugLoc(LastLoc);
451391bc56edSDimitry Andric       I = nullptr;
4514f22ef01cSRoman Divacky       continue;
4515f22ef01cSRoman Divacky     }
4516f22ef01cSRoman Divacky 
4517f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4518f22ef01cSRoman Divacky       unsigned OpNum = 0;
4519f22ef01cSRoman Divacky       Value *LHS, *RHS;
4520f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
45213861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4522f22ef01cSRoman Divacky           OpNum+1 > Record.size())
45238f0fd8f6SDimitry Andric         return error("Invalid record");
4524f22ef01cSRoman Divacky 
45258f0fd8f6SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4526f785676fSDimitry Andric       if (Opc == -1)
45278f0fd8f6SDimitry Andric         return error("Invalid record");
4528f22ef01cSRoman Divacky       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4529f22ef01cSRoman Divacky       InstructionList.push_back(I);
4530f22ef01cSRoman Divacky       if (OpNum < Record.size()) {
4531f22ef01cSRoman Divacky         if (Opc == Instruction::Add ||
4532f22ef01cSRoman Divacky             Opc == Instruction::Sub ||
45332754fe60SDimitry Andric             Opc == Instruction::Mul ||
45342754fe60SDimitry Andric             Opc == Instruction::Shl) {
4535f22ef01cSRoman Divacky           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4536f22ef01cSRoman Divacky             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4537f22ef01cSRoman Divacky           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4538f22ef01cSRoman Divacky             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
45392754fe60SDimitry Andric         } else if (Opc == Instruction::SDiv ||
45402754fe60SDimitry Andric                    Opc == Instruction::UDiv ||
45412754fe60SDimitry Andric                    Opc == Instruction::LShr ||
45422754fe60SDimitry Andric                    Opc == Instruction::AShr) {
45432754fe60SDimitry Andric           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4544f22ef01cSRoman Divacky             cast<BinaryOperator>(I)->setIsExact(true);
4545139f7f9bSDimitry Andric         } else if (isa<FPMathOperator>(I)) {
4546875ed548SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4547139f7f9bSDimitry Andric           if (FMF.any())
4548139f7f9bSDimitry Andric             I->setFastMathFlags(FMF);
4549f22ef01cSRoman Divacky         }
4550139f7f9bSDimitry Andric 
4551f22ef01cSRoman Divacky       }
4552f22ef01cSRoman Divacky       break;
4553f22ef01cSRoman Divacky     }
4554f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4555f22ef01cSRoman Divacky       unsigned OpNum = 0;
4556f22ef01cSRoman Divacky       Value *Op;
4557f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4558f22ef01cSRoman Divacky           OpNum+2 != Record.size())
45598f0fd8f6SDimitry Andric         return error("Invalid record");
4560f22ef01cSRoman Divacky 
45616122f3e6SDimitry Andric       Type *ResTy = getTypeByID(Record[OpNum]);
45628f0fd8f6SDimitry Andric       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
456391bc56edSDimitry Andric       if (Opc == -1 || !ResTy)
45648f0fd8f6SDimitry Andric         return error("Invalid record");
456591bc56edSDimitry Andric       Instruction *Temp = nullptr;
4566f785676fSDimitry Andric       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4567f785676fSDimitry Andric         if (Temp) {
4568f785676fSDimitry Andric           InstructionList.push_back(Temp);
4569f785676fSDimitry Andric           CurBB->getInstList().push_back(Temp);
4570f785676fSDimitry Andric         }
4571f785676fSDimitry Andric       } else {
45727d523365SDimitry Andric         auto CastOp = (Instruction::CastOps)Opc;
45737d523365SDimitry Andric         if (!CastInst::castIsValid(CastOp, Op, ResTy))
45747d523365SDimitry Andric           return error("Invalid cast");
45757d523365SDimitry Andric         I = CastInst::Create(CastOp, Op, ResTy);
4576f785676fSDimitry Andric       }
4577f22ef01cSRoman Divacky       InstructionList.push_back(I);
4578f22ef01cSRoman Divacky       break;
4579f22ef01cSRoman Divacky     }
4580ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4581ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_GEP_OLD:
4582ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4583f22ef01cSRoman Divacky       unsigned OpNum = 0;
4584ff0cc061SDimitry Andric 
4585ff0cc061SDimitry Andric       Type *Ty;
4586ff0cc061SDimitry Andric       bool InBounds;
4587ff0cc061SDimitry Andric 
4588ff0cc061SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4589ff0cc061SDimitry Andric         InBounds = Record[OpNum++];
4590ff0cc061SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
4591ff0cc061SDimitry Andric       } else {
4592ff0cc061SDimitry Andric         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4593ff0cc061SDimitry Andric         Ty = nullptr;
4594ff0cc061SDimitry Andric       }
4595ff0cc061SDimitry Andric 
4596f22ef01cSRoman Divacky       Value *BasePtr;
4597f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
45988f0fd8f6SDimitry Andric         return error("Invalid record");
4599f22ef01cSRoman Divacky 
4600ff0cc061SDimitry Andric       if (!Ty)
4601ff0cc061SDimitry Andric         Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4602ff0cc061SDimitry Andric                  ->getElementType();
4603ff0cc061SDimitry Andric       else if (Ty !=
4604ff0cc061SDimitry Andric                cast<SequentialType>(BasePtr->getType()->getScalarType())
4605ff0cc061SDimitry Andric                    ->getElementType())
46068f0fd8f6SDimitry Andric         return error(
4607ff0cc061SDimitry Andric             "Explicit gep type does not match pointee type of pointer operand");
4608ff0cc061SDimitry Andric 
4609f22ef01cSRoman Divacky       SmallVector<Value*, 16> GEPIdx;
4610f22ef01cSRoman Divacky       while (OpNum != Record.size()) {
4611f22ef01cSRoman Divacky         Value *Op;
4612f22ef01cSRoman Divacky         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
46138f0fd8f6SDimitry Andric           return error("Invalid record");
4614f22ef01cSRoman Divacky         GEPIdx.push_back(Op);
4615f22ef01cSRoman Divacky       }
4616f22ef01cSRoman Divacky 
4617ff0cc061SDimitry Andric       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4618ff0cc061SDimitry Andric 
4619f22ef01cSRoman Divacky       InstructionList.push_back(I);
4620ff0cc061SDimitry Andric       if (InBounds)
4621f22ef01cSRoman Divacky         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4622f22ef01cSRoman Divacky       break;
4623f22ef01cSRoman Divacky     }
4624f22ef01cSRoman Divacky 
4625f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4626f22ef01cSRoman Divacky                                        // EXTRACTVAL: [opty, opval, n x indices]
4627f22ef01cSRoman Divacky       unsigned OpNum = 0;
4628f22ef01cSRoman Divacky       Value *Agg;
4629f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
46308f0fd8f6SDimitry Andric         return error("Invalid record");
4631f22ef01cSRoman Divacky 
4632ff0cc061SDimitry Andric       unsigned RecSize = Record.size();
4633ff0cc061SDimitry Andric       if (OpNum == RecSize)
46348f0fd8f6SDimitry Andric         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4635ff0cc061SDimitry Andric 
4636f22ef01cSRoman Divacky       SmallVector<unsigned, 4> EXTRACTVALIdx;
4637ff0cc061SDimitry Andric       Type *CurTy = Agg->getType();
4638ff0cc061SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
4639ff0cc061SDimitry Andric         bool IsArray = CurTy->isArrayTy();
4640ff0cc061SDimitry Andric         bool IsStruct = CurTy->isStructTy();
4641f22ef01cSRoman Divacky         uint64_t Index = Record[OpNum];
4642ff0cc061SDimitry Andric 
4643ff0cc061SDimitry Andric         if (!IsStruct && !IsArray)
46448f0fd8f6SDimitry Andric           return error("EXTRACTVAL: Invalid type");
4645f22ef01cSRoman Divacky         if ((unsigned)Index != Index)
46468f0fd8f6SDimitry Andric           return error("Invalid value");
4647ff0cc061SDimitry Andric         if (IsStruct && Index >= CurTy->subtypes().size())
46488f0fd8f6SDimitry Andric           return error("EXTRACTVAL: Invalid struct index");
4649ff0cc061SDimitry Andric         if (IsArray && Index >= CurTy->getArrayNumElements())
46508f0fd8f6SDimitry Andric           return error("EXTRACTVAL: Invalid array index");
4651f22ef01cSRoman Divacky         EXTRACTVALIdx.push_back((unsigned)Index);
4652ff0cc061SDimitry Andric 
4653ff0cc061SDimitry Andric         if (IsStruct)
4654ff0cc061SDimitry Andric           CurTy = CurTy->subtypes()[Index];
4655ff0cc061SDimitry Andric         else
4656ff0cc061SDimitry Andric           CurTy = CurTy->subtypes()[0];
4657f22ef01cSRoman Divacky       }
4658f22ef01cSRoman Divacky 
465917a519f9SDimitry Andric       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4660f22ef01cSRoman Divacky       InstructionList.push_back(I);
4661f22ef01cSRoman Divacky       break;
4662f22ef01cSRoman Divacky     }
4663f22ef01cSRoman Divacky 
4664f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INSERTVAL: {
4665f22ef01cSRoman Divacky                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4666f22ef01cSRoman Divacky       unsigned OpNum = 0;
4667f22ef01cSRoman Divacky       Value *Agg;
4668f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
46698f0fd8f6SDimitry Andric         return error("Invalid record");
4670f22ef01cSRoman Divacky       Value *Val;
4671f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
46728f0fd8f6SDimitry Andric         return error("Invalid record");
4673f22ef01cSRoman Divacky 
4674ff0cc061SDimitry Andric       unsigned RecSize = Record.size();
4675ff0cc061SDimitry Andric       if (OpNum == RecSize)
46768f0fd8f6SDimitry Andric         return error("INSERTVAL: Invalid instruction with 0 indices");
4677ff0cc061SDimitry Andric 
4678f22ef01cSRoman Divacky       SmallVector<unsigned, 4> INSERTVALIdx;
4679ff0cc061SDimitry Andric       Type *CurTy = Agg->getType();
4680ff0cc061SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
4681ff0cc061SDimitry Andric         bool IsArray = CurTy->isArrayTy();
4682ff0cc061SDimitry Andric         bool IsStruct = CurTy->isStructTy();
4683f22ef01cSRoman Divacky         uint64_t Index = Record[OpNum];
4684ff0cc061SDimitry Andric 
4685ff0cc061SDimitry Andric         if (!IsStruct && !IsArray)
46868f0fd8f6SDimitry Andric           return error("INSERTVAL: Invalid type");
4687f22ef01cSRoman Divacky         if ((unsigned)Index != Index)
46888f0fd8f6SDimitry Andric           return error("Invalid value");
4689ff0cc061SDimitry Andric         if (IsStruct && Index >= CurTy->subtypes().size())
46908f0fd8f6SDimitry Andric           return error("INSERTVAL: Invalid struct index");
4691ff0cc061SDimitry Andric         if (IsArray && Index >= CurTy->getArrayNumElements())
46928f0fd8f6SDimitry Andric           return error("INSERTVAL: Invalid array index");
4693ff0cc061SDimitry Andric 
4694f22ef01cSRoman Divacky         INSERTVALIdx.push_back((unsigned)Index);
4695ff0cc061SDimitry Andric         if (IsStruct)
4696ff0cc061SDimitry Andric           CurTy = CurTy->subtypes()[Index];
4697ff0cc061SDimitry Andric         else
4698ff0cc061SDimitry Andric           CurTy = CurTy->subtypes()[0];
4699f22ef01cSRoman Divacky       }
4700f22ef01cSRoman Divacky 
4701ff0cc061SDimitry Andric       if (CurTy != Val->getType())
47028f0fd8f6SDimitry Andric         return error("Inserted value type doesn't match aggregate type");
4703ff0cc061SDimitry Andric 
470417a519f9SDimitry Andric       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4705f22ef01cSRoman Divacky       InstructionList.push_back(I);
4706f22ef01cSRoman Divacky       break;
4707f22ef01cSRoman Divacky     }
4708f22ef01cSRoman Divacky 
4709f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4710f22ef01cSRoman Divacky       // obsolete form of select
4711f22ef01cSRoman Divacky       // handles select i1 ... in old bitcode
4712f22ef01cSRoman Divacky       unsigned OpNum = 0;
4713f22ef01cSRoman Divacky       Value *TrueVal, *FalseVal, *Cond;
4714f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
47153861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
47163861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
47178f0fd8f6SDimitry Andric         return error("Invalid record");
4718f22ef01cSRoman Divacky 
4719f22ef01cSRoman Divacky       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4720f22ef01cSRoman Divacky       InstructionList.push_back(I);
4721f22ef01cSRoman Divacky       break;
4722f22ef01cSRoman Divacky     }
4723f22ef01cSRoman Divacky 
4724f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4725f22ef01cSRoman Divacky       // new form of select
4726f22ef01cSRoman Divacky       // handles select i1 or select [N x i1]
4727f22ef01cSRoman Divacky       unsigned OpNum = 0;
4728f22ef01cSRoman Divacky       Value *TrueVal, *FalseVal, *Cond;
4729f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
47303861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4731f22ef01cSRoman Divacky           getValueTypePair(Record, OpNum, NextValueNo, Cond))
47328f0fd8f6SDimitry Andric         return error("Invalid record");
4733f22ef01cSRoman Divacky 
4734f22ef01cSRoman Divacky       // select condition can be either i1 or [N x i1]
47356122f3e6SDimitry Andric       if (VectorType* vector_type =
47366122f3e6SDimitry Andric           dyn_cast<VectorType>(Cond->getType())) {
4737f22ef01cSRoman Divacky         // expect <n x i1>
4738f22ef01cSRoman Divacky         if (vector_type->getElementType() != Type::getInt1Ty(Context))
47398f0fd8f6SDimitry Andric           return error("Invalid type for value");
4740f22ef01cSRoman Divacky       } else {
4741f22ef01cSRoman Divacky         // expect i1
4742f22ef01cSRoman Divacky         if (Cond->getType() != Type::getInt1Ty(Context))
47438f0fd8f6SDimitry Andric           return error("Invalid type for value");
4744f22ef01cSRoman Divacky       }
4745f22ef01cSRoman Divacky 
4746f22ef01cSRoman Divacky       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4747f22ef01cSRoman Divacky       InstructionList.push_back(I);
4748f22ef01cSRoman Divacky       break;
4749f22ef01cSRoman Divacky     }
4750f22ef01cSRoman Divacky 
4751f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4752f22ef01cSRoman Divacky       unsigned OpNum = 0;
4753f22ef01cSRoman Divacky       Value *Vec, *Idx;
4754f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
475591bc56edSDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx))
47568f0fd8f6SDimitry Andric         return error("Invalid record");
4757ff0cc061SDimitry Andric       if (!Vec->getType()->isVectorTy())
47588f0fd8f6SDimitry Andric         return error("Invalid type for value");
4759f22ef01cSRoman Divacky       I = ExtractElementInst::Create(Vec, Idx);
4760f22ef01cSRoman Divacky       InstructionList.push_back(I);
4761f22ef01cSRoman Divacky       break;
4762f22ef01cSRoman Divacky     }
4763f22ef01cSRoman Divacky 
4764f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4765f22ef01cSRoman Divacky       unsigned OpNum = 0;
4766f22ef01cSRoman Divacky       Value *Vec, *Elt, *Idx;
4767ff0cc061SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
47688f0fd8f6SDimitry Andric         return error("Invalid record");
4769ff0cc061SDimitry Andric       if (!Vec->getType()->isVectorTy())
47708f0fd8f6SDimitry Andric         return error("Invalid type for value");
4771ff0cc061SDimitry Andric       if (popValue(Record, OpNum, NextValueNo,
4772f22ef01cSRoman Divacky                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
477391bc56edSDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx))
47748f0fd8f6SDimitry Andric         return error("Invalid record");
4775f22ef01cSRoman Divacky       I = InsertElementInst::Create(Vec, Elt, Idx);
4776f22ef01cSRoman Divacky       InstructionList.push_back(I);
4777f22ef01cSRoman Divacky       break;
4778f22ef01cSRoman Divacky     }
4779f22ef01cSRoman Divacky 
4780f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4781f22ef01cSRoman Divacky       unsigned OpNum = 0;
4782f22ef01cSRoman Divacky       Value *Vec1, *Vec2, *Mask;
4783f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
47843861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
47858f0fd8f6SDimitry Andric         return error("Invalid record");
4786f22ef01cSRoman Divacky 
4787f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
47888f0fd8f6SDimitry Andric         return error("Invalid record");
4789ff0cc061SDimitry Andric       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
47908f0fd8f6SDimitry Andric         return error("Invalid type for value");
4791f22ef01cSRoman Divacky       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4792f22ef01cSRoman Divacky       InstructionList.push_back(I);
4793f22ef01cSRoman Divacky       break;
4794f22ef01cSRoman Divacky     }
4795f22ef01cSRoman Divacky 
4796f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
4797f22ef01cSRoman Divacky       // Old form of ICmp/FCmp returning bool
4798f22ef01cSRoman Divacky       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4799f22ef01cSRoman Divacky       // both legal on vectors but had different behaviour.
4800f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4801f22ef01cSRoman Divacky       // FCmp/ICmp returning bool or vector of bool
4802f22ef01cSRoman Divacky 
4803f22ef01cSRoman Divacky       unsigned OpNum = 0;
4804f22ef01cSRoman Divacky       Value *LHS, *RHS;
4805f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4806875ed548SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4807875ed548SDimitry Andric         return error("Invalid record");
4808875ed548SDimitry Andric 
4809875ed548SDimitry Andric       unsigned PredVal = Record[OpNum];
4810875ed548SDimitry Andric       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4811875ed548SDimitry Andric       FastMathFlags FMF;
4812875ed548SDimitry Andric       if (IsFP && Record.size() > OpNum+1)
4813875ed548SDimitry Andric         FMF = getDecodedFastMathFlags(Record[++OpNum]);
4814875ed548SDimitry Andric 
4815875ed548SDimitry Andric       if (OpNum+1 != Record.size())
48168f0fd8f6SDimitry Andric         return error("Invalid record");
4817f22ef01cSRoman Divacky 
4818f22ef01cSRoman Divacky       if (LHS->getType()->isFPOrFPVectorTy())
4819875ed548SDimitry Andric         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4820f22ef01cSRoman Divacky       else
4821875ed548SDimitry Andric         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4822875ed548SDimitry Andric 
4823875ed548SDimitry Andric       if (FMF.any())
4824875ed548SDimitry Andric         I->setFastMathFlags(FMF);
4825f22ef01cSRoman Divacky       InstructionList.push_back(I);
4826f22ef01cSRoman Divacky       break;
4827f22ef01cSRoman Divacky     }
4828f22ef01cSRoman Divacky 
4829f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4830f22ef01cSRoman Divacky       {
4831f22ef01cSRoman Divacky         unsigned Size = Record.size();
4832f22ef01cSRoman Divacky         if (Size == 0) {
4833f22ef01cSRoman Divacky           I = ReturnInst::Create(Context);
4834f22ef01cSRoman Divacky           InstructionList.push_back(I);
4835f22ef01cSRoman Divacky           break;
4836f22ef01cSRoman Divacky         }
4837f22ef01cSRoman Divacky 
4838f22ef01cSRoman Divacky         unsigned OpNum = 0;
483991bc56edSDimitry Andric         Value *Op = nullptr;
4840f22ef01cSRoman Divacky         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
48418f0fd8f6SDimitry Andric           return error("Invalid record");
484217a519f9SDimitry Andric         if (OpNum != Record.size())
48438f0fd8f6SDimitry Andric           return error("Invalid record");
4844f22ef01cSRoman Divacky 
484517a519f9SDimitry Andric         I = ReturnInst::Create(Context, Op);
4846f22ef01cSRoman Divacky         InstructionList.push_back(I);
4847f22ef01cSRoman Divacky         break;
4848f22ef01cSRoman Divacky       }
4849f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4850f22ef01cSRoman Divacky       if (Record.size() != 1 && Record.size() != 3)
48518f0fd8f6SDimitry Andric         return error("Invalid record");
4852f22ef01cSRoman Divacky       BasicBlock *TrueDest = getBasicBlock(Record[0]);
485391bc56edSDimitry Andric       if (!TrueDest)
48548f0fd8f6SDimitry Andric         return error("Invalid record");
4855f22ef01cSRoman Divacky 
4856f22ef01cSRoman Divacky       if (Record.size() == 1) {
4857f22ef01cSRoman Divacky         I = BranchInst::Create(TrueDest);
4858f22ef01cSRoman Divacky         InstructionList.push_back(I);
4859f22ef01cSRoman Divacky       }
4860f22ef01cSRoman Divacky       else {
4861f22ef01cSRoman Divacky         BasicBlock *FalseDest = getBasicBlock(Record[1]);
48623861d79fSDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo,
48633861d79fSDimitry Andric                                Type::getInt1Ty(Context));
486491bc56edSDimitry Andric         if (!FalseDest || !Cond)
48658f0fd8f6SDimitry Andric           return error("Invalid record");
4866f22ef01cSRoman Divacky         I = BranchInst::Create(TrueDest, FalseDest, Cond);
4867f22ef01cSRoman Divacky         InstructionList.push_back(I);
4868f22ef01cSRoman Divacky       }
4869f22ef01cSRoman Divacky       break;
4870f22ef01cSRoman Divacky     }
48717d523365SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
48727d523365SDimitry Andric       if (Record.size() != 1 && Record.size() != 2)
48737d523365SDimitry Andric         return error("Invalid record");
48747d523365SDimitry Andric       unsigned Idx = 0;
48757d523365SDimitry Andric       Value *CleanupPad =
48767d523365SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
48777d523365SDimitry Andric       if (!CleanupPad)
48787d523365SDimitry Andric         return error("Invalid record");
48797d523365SDimitry Andric       BasicBlock *UnwindDest = nullptr;
48807d523365SDimitry Andric       if (Record.size() == 2) {
48817d523365SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
48827d523365SDimitry Andric         if (!UnwindDest)
48837d523365SDimitry Andric           return error("Invalid record");
48847d523365SDimitry Andric       }
48857d523365SDimitry Andric 
48867d523365SDimitry Andric       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
48877d523365SDimitry Andric       InstructionList.push_back(I);
48887d523365SDimitry Andric       break;
48897d523365SDimitry Andric     }
48907d523365SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
48917d523365SDimitry Andric       if (Record.size() != 2)
48927d523365SDimitry Andric         return error("Invalid record");
48937d523365SDimitry Andric       unsigned Idx = 0;
48947d523365SDimitry Andric       Value *CatchPad =
48957d523365SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
48967d523365SDimitry Andric       if (!CatchPad)
48977d523365SDimitry Andric         return error("Invalid record");
48987d523365SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[Idx++]);
48997d523365SDimitry Andric       if (!BB)
49007d523365SDimitry Andric         return error("Invalid record");
49017d523365SDimitry Andric 
49027d523365SDimitry Andric       I = CatchReturnInst::Create(CatchPad, BB);
49037d523365SDimitry Andric       InstructionList.push_back(I);
49047d523365SDimitry Andric       break;
49057d523365SDimitry Andric     }
49067d523365SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
49077d523365SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
49087d523365SDimitry Andric       if (Record.size() < 2)
49097d523365SDimitry Andric         return error("Invalid record");
49107d523365SDimitry Andric 
49117d523365SDimitry Andric       unsigned Idx = 0;
49127d523365SDimitry Andric 
49137d523365SDimitry Andric       Value *ParentPad =
49147d523365SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
49157d523365SDimitry Andric 
49167d523365SDimitry Andric       unsigned NumHandlers = Record[Idx++];
49177d523365SDimitry Andric 
49187d523365SDimitry Andric       SmallVector<BasicBlock *, 2> Handlers;
49197d523365SDimitry Andric       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
49207d523365SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[Idx++]);
49217d523365SDimitry Andric         if (!BB)
49227d523365SDimitry Andric           return error("Invalid record");
49237d523365SDimitry Andric         Handlers.push_back(BB);
49247d523365SDimitry Andric       }
49257d523365SDimitry Andric 
49267d523365SDimitry Andric       BasicBlock *UnwindDest = nullptr;
49277d523365SDimitry Andric       if (Idx + 1 == Record.size()) {
49287d523365SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
49297d523365SDimitry Andric         if (!UnwindDest)
49307d523365SDimitry Andric           return error("Invalid record");
49317d523365SDimitry Andric       }
49327d523365SDimitry Andric 
49337d523365SDimitry Andric       if (Record.size() != Idx)
49347d523365SDimitry Andric         return error("Invalid record");
49357d523365SDimitry Andric 
49367d523365SDimitry Andric       auto *CatchSwitch =
49377d523365SDimitry Andric           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
49387d523365SDimitry Andric       for (BasicBlock *Handler : Handlers)
49397d523365SDimitry Andric         CatchSwitch->addHandler(Handler);
49407d523365SDimitry Andric       I = CatchSwitch;
49417d523365SDimitry Andric       InstructionList.push_back(I);
49427d523365SDimitry Andric       break;
49437d523365SDimitry Andric     }
49447d523365SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHPAD:
49457d523365SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
49467d523365SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
49477d523365SDimitry Andric       if (Record.size() < 2)
49487d523365SDimitry Andric         return error("Invalid record");
49497d523365SDimitry Andric 
49507d523365SDimitry Andric       unsigned Idx = 0;
49517d523365SDimitry Andric 
49527d523365SDimitry Andric       Value *ParentPad =
49537d523365SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
49547d523365SDimitry Andric 
49557d523365SDimitry Andric       unsigned NumArgOperands = Record[Idx++];
49567d523365SDimitry Andric 
49577d523365SDimitry Andric       SmallVector<Value *, 2> Args;
49587d523365SDimitry Andric       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
49597d523365SDimitry Andric         Value *Val;
49607d523365SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val))
49617d523365SDimitry Andric           return error("Invalid record");
49627d523365SDimitry Andric         Args.push_back(Val);
49637d523365SDimitry Andric       }
49647d523365SDimitry Andric 
49657d523365SDimitry Andric       if (Record.size() != Idx)
49667d523365SDimitry Andric         return error("Invalid record");
49677d523365SDimitry Andric 
49687d523365SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
49697d523365SDimitry Andric         I = CleanupPadInst::Create(ParentPad, Args);
49707d523365SDimitry Andric       else
49717d523365SDimitry Andric         I = CatchPadInst::Create(ParentPad, Args);
49727d523365SDimitry Andric       InstructionList.push_back(I);
49737d523365SDimitry Andric       break;
49747d523365SDimitry Andric     }
4975f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
49767ae0e2c9SDimitry Andric       // Check magic
49777ae0e2c9SDimitry Andric       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4978f785676fSDimitry Andric         // "New" SwitchInst format with case ranges. The changes to write this
4979f785676fSDimitry Andric         // format were reverted but we still recognize bitcode that uses it.
4980f785676fSDimitry Andric         // Hopefully someday we will have support for case ranges and can use
4981f785676fSDimitry Andric         // this format again.
49827ae0e2c9SDimitry Andric 
49837ae0e2c9SDimitry Andric         Type *OpTy = getTypeByID(Record[1]);
49847ae0e2c9SDimitry Andric         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
49857ae0e2c9SDimitry Andric 
49863861d79fSDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
49877ae0e2c9SDimitry Andric         BasicBlock *Default = getBasicBlock(Record[3]);
498891bc56edSDimitry Andric         if (!OpTy || !Cond || !Default)
49898f0fd8f6SDimitry Andric           return error("Invalid record");
49907ae0e2c9SDimitry Andric 
49917ae0e2c9SDimitry Andric         unsigned NumCases = Record[4];
49927ae0e2c9SDimitry Andric 
49937ae0e2c9SDimitry Andric         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
49947ae0e2c9SDimitry Andric         InstructionList.push_back(SI);
49957ae0e2c9SDimitry Andric 
49967ae0e2c9SDimitry Andric         unsigned CurIdx = 5;
49977ae0e2c9SDimitry Andric         for (unsigned i = 0; i != NumCases; ++i) {
4998f785676fSDimitry Andric           SmallVector<ConstantInt*, 1> CaseVals;
49997ae0e2c9SDimitry Andric           unsigned NumItems = Record[CurIdx++];
50007ae0e2c9SDimitry Andric           for (unsigned ci = 0; ci != NumItems; ++ci) {
50017ae0e2c9SDimitry Andric             bool isSingleNumber = Record[CurIdx++];
50027ae0e2c9SDimitry Andric 
50037ae0e2c9SDimitry Andric             APInt Low;
50047ae0e2c9SDimitry Andric             unsigned ActiveWords = 1;
50057ae0e2c9SDimitry Andric             if (ValueBitWidth > 64)
50067ae0e2c9SDimitry Andric               ActiveWords = Record[CurIdx++];
50078f0fd8f6SDimitry Andric             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
50087ae0e2c9SDimitry Andric                                 ValueBitWidth);
50097ae0e2c9SDimitry Andric             CurIdx += ActiveWords;
50107ae0e2c9SDimitry Andric 
50117ae0e2c9SDimitry Andric             if (!isSingleNumber) {
50127ae0e2c9SDimitry Andric               ActiveWords = 1;
50137ae0e2c9SDimitry Andric               if (ValueBitWidth > 64)
50147ae0e2c9SDimitry Andric                 ActiveWords = Record[CurIdx++];
50158f0fd8f6SDimitry Andric               APInt High = readWideAPInt(
50168f0fd8f6SDimitry Andric                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
50177ae0e2c9SDimitry Andric               CurIdx += ActiveWords;
5018f785676fSDimitry Andric 
5019f785676fSDimitry Andric               // FIXME: It is not clear whether values in the range should be
5020f785676fSDimitry Andric               // compared as signed or unsigned values. The partially
5021f785676fSDimitry Andric               // implemented changes that used this format in the past used
5022f785676fSDimitry Andric               // unsigned comparisons.
5023f785676fSDimitry Andric               for ( ; Low.ule(High); ++Low)
5024f785676fSDimitry Andric                 CaseVals.push_back(ConstantInt::get(Context, Low));
50257ae0e2c9SDimitry Andric             } else
5026f785676fSDimitry Andric               CaseVals.push_back(ConstantInt::get(Context, Low));
50277ae0e2c9SDimitry Andric           }
50287ae0e2c9SDimitry Andric           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5029f785676fSDimitry Andric           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
5030f785676fSDimitry Andric                  cve = CaseVals.end(); cvi != cve; ++cvi)
5031f785676fSDimitry Andric             SI->addCase(*cvi, DestBB);
50327ae0e2c9SDimitry Andric         }
50337ae0e2c9SDimitry Andric         I = SI;
50347ae0e2c9SDimitry Andric         break;
50357ae0e2c9SDimitry Andric       }
50367ae0e2c9SDimitry Andric 
50377ae0e2c9SDimitry Andric       // Old SwitchInst format without case ranges.
50387ae0e2c9SDimitry Andric 
5039f22ef01cSRoman Divacky       if (Record.size() < 3 || (Record.size() & 1) == 0)
50408f0fd8f6SDimitry Andric         return error("Invalid record");
50416122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
50423861d79fSDimitry Andric       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
5043f22ef01cSRoman Divacky       BasicBlock *Default = getBasicBlock(Record[2]);
504491bc56edSDimitry Andric       if (!OpTy || !Cond || !Default)
50458f0fd8f6SDimitry Andric         return error("Invalid record");
5046f22ef01cSRoman Divacky       unsigned NumCases = (Record.size()-3)/2;
5047f22ef01cSRoman Divacky       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5048f22ef01cSRoman Divacky       InstructionList.push_back(SI);
5049f22ef01cSRoman Divacky       for (unsigned i = 0, e = NumCases; i != e; ++i) {
5050f22ef01cSRoman Divacky         ConstantInt *CaseVal =
5051f22ef01cSRoman Divacky           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
5052f22ef01cSRoman Divacky         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
505391bc56edSDimitry Andric         if (!CaseVal || !DestBB) {
5054f22ef01cSRoman Divacky           delete SI;
50558f0fd8f6SDimitry Andric           return error("Invalid record");
5056f22ef01cSRoman Divacky         }
5057f22ef01cSRoman Divacky         SI->addCase(CaseVal, DestBB);
5058f22ef01cSRoman Divacky       }
5059f22ef01cSRoman Divacky       I = SI;
5060f22ef01cSRoman Divacky       break;
5061f22ef01cSRoman Divacky     }
5062f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5063f22ef01cSRoman Divacky       if (Record.size() < 2)
50648f0fd8f6SDimitry Andric         return error("Invalid record");
50656122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
50663861d79fSDimitry Andric       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
506791bc56edSDimitry Andric       if (!OpTy || !Address)
50688f0fd8f6SDimitry Andric         return error("Invalid record");
5069f22ef01cSRoman Divacky       unsigned NumDests = Record.size()-2;
5070f22ef01cSRoman Divacky       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5071f22ef01cSRoman Divacky       InstructionList.push_back(IBI);
5072f22ef01cSRoman Divacky       for (unsigned i = 0, e = NumDests; i != e; ++i) {
5073f22ef01cSRoman Divacky         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5074f22ef01cSRoman Divacky           IBI->addDestination(DestBB);
5075f22ef01cSRoman Divacky         } else {
5076f22ef01cSRoman Divacky           delete IBI;
50778f0fd8f6SDimitry Andric           return error("Invalid record");
5078f22ef01cSRoman Divacky         }
5079f22ef01cSRoman Divacky       }
5080f22ef01cSRoman Divacky       I = IBI;
5081f22ef01cSRoman Divacky       break;
5082f22ef01cSRoman Divacky     }
5083f22ef01cSRoman Divacky 
5084f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INVOKE: {
5085f22ef01cSRoman Divacky       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5086f785676fSDimitry Andric       if (Record.size() < 4)
50878f0fd8f6SDimitry Andric         return error("Invalid record");
5088ff0cc061SDimitry Andric       unsigned OpNum = 0;
5089ff0cc061SDimitry Andric       AttributeSet PAL = getAttributes(Record[OpNum++]);
5090ff0cc061SDimitry Andric       unsigned CCInfo = Record[OpNum++];
5091ff0cc061SDimitry Andric       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5092ff0cc061SDimitry Andric       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5093f22ef01cSRoman Divacky 
5094ff0cc061SDimitry Andric       FunctionType *FTy = nullptr;
5095ff0cc061SDimitry Andric       if (CCInfo >> 13 & 1 &&
5096ff0cc061SDimitry Andric           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
50978f0fd8f6SDimitry Andric         return error("Explicit invoke type is not a function type");
5098ff0cc061SDimitry Andric 
5099f22ef01cSRoman Divacky       Value *Callee;
5100f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
51018f0fd8f6SDimitry Andric         return error("Invalid record");
5102f22ef01cSRoman Divacky 
51036122f3e6SDimitry Andric       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5104ff0cc061SDimitry Andric       if (!CalleeTy)
51058f0fd8f6SDimitry Andric         return error("Callee is not a pointer");
5106ff0cc061SDimitry Andric       if (!FTy) {
5107ff0cc061SDimitry Andric         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
5108ff0cc061SDimitry Andric         if (!FTy)
51098f0fd8f6SDimitry Andric           return error("Callee is not of pointer to function type");
5110ff0cc061SDimitry Andric       } else if (CalleeTy->getElementType() != FTy)
51118f0fd8f6SDimitry Andric         return error("Explicit invoke type does not match pointee type of "
5112ff0cc061SDimitry Andric                      "callee operand");
5113ff0cc061SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
51148f0fd8f6SDimitry Andric         return error("Insufficient operands to call");
5115f22ef01cSRoman Divacky 
5116f22ef01cSRoman Divacky       SmallVector<Value*, 16> Ops;
5117f22ef01cSRoman Divacky       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
51183861d79fSDimitry Andric         Ops.push_back(getValue(Record, OpNum, NextValueNo,
51193861d79fSDimitry Andric                                FTy->getParamType(i)));
512091bc56edSDimitry Andric         if (!Ops.back())
51218f0fd8f6SDimitry Andric           return error("Invalid record");
5122f22ef01cSRoman Divacky       }
5123f22ef01cSRoman Divacky 
5124f22ef01cSRoman Divacky       if (!FTy->isVarArg()) {
5125f22ef01cSRoman Divacky         if (Record.size() != OpNum)
51268f0fd8f6SDimitry Andric           return error("Invalid record");
5127f22ef01cSRoman Divacky       } else {
5128f22ef01cSRoman Divacky         // Read type/value pairs for varargs params.
5129f22ef01cSRoman Divacky         while (OpNum != Record.size()) {
5130f22ef01cSRoman Divacky           Value *Op;
5131f22ef01cSRoman Divacky           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
51328f0fd8f6SDimitry Andric             return error("Invalid record");
5133f22ef01cSRoman Divacky           Ops.push_back(Op);
5134f22ef01cSRoman Divacky         }
5135f22ef01cSRoman Divacky       }
5136f22ef01cSRoman Divacky 
51377d523365SDimitry Andric       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
51387d523365SDimitry Andric       OperandBundles.clear();
5139f22ef01cSRoman Divacky       InstructionList.push_back(I);
51407d523365SDimitry Andric       cast<InvokeInst>(I)->setCallingConv(
51417d523365SDimitry Andric           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5142f22ef01cSRoman Divacky       cast<InvokeInst>(I)->setAttributes(PAL);
5143f22ef01cSRoman Divacky       break;
5144f22ef01cSRoman Divacky     }
51456122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
51466122f3e6SDimitry Andric       unsigned Idx = 0;
514791bc56edSDimitry Andric       Value *Val = nullptr;
51486122f3e6SDimitry Andric       if (getValueTypePair(Record, Idx, NextValueNo, Val))
51498f0fd8f6SDimitry Andric         return error("Invalid record");
51506122f3e6SDimitry Andric       I = ResumeInst::Create(Val);
51516122f3e6SDimitry Andric       InstructionList.push_back(I);
51526122f3e6SDimitry Andric       break;
51536122f3e6SDimitry Andric     }
5154f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
5155f22ef01cSRoman Divacky       I = new UnreachableInst(Context);
5156f22ef01cSRoman Divacky       InstructionList.push_back(I);
5157f22ef01cSRoman Divacky       break;
5158f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5159f22ef01cSRoman Divacky       if (Record.size() < 1 || ((Record.size()-1)&1))
51608f0fd8f6SDimitry Andric         return error("Invalid record");
51616122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
5162f785676fSDimitry Andric       if (!Ty)
51638f0fd8f6SDimitry Andric         return error("Invalid record");
5164f22ef01cSRoman Divacky 
51653b0f4066SDimitry Andric       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
5166f22ef01cSRoman Divacky       InstructionList.push_back(PN);
5167f22ef01cSRoman Divacky 
5168f22ef01cSRoman Divacky       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
51693861d79fSDimitry Andric         Value *V;
51703861d79fSDimitry Andric         // With the new function encoding, it is possible that operands have
51713861d79fSDimitry Andric         // negative IDs (for forward references).  Use a signed VBR
51723861d79fSDimitry Andric         // representation to keep the encoding small.
51733861d79fSDimitry Andric         if (UseRelativeIDs)
51743861d79fSDimitry Andric           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
51753861d79fSDimitry Andric         else
51763861d79fSDimitry Andric           V = getValue(Record, 1+i, NextValueNo, Ty);
5177f22ef01cSRoman Divacky         BasicBlock *BB = getBasicBlock(Record[2+i]);
5178f785676fSDimitry Andric         if (!V || !BB)
51798f0fd8f6SDimitry Andric           return error("Invalid record");
5180f22ef01cSRoman Divacky         PN->addIncoming(V, BB);
5181f22ef01cSRoman Divacky       }
5182f22ef01cSRoman Divacky       I = PN;
5183f22ef01cSRoman Divacky       break;
5184f22ef01cSRoman Divacky     }
5185f22ef01cSRoman Divacky 
51868f0fd8f6SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD:
51878f0fd8f6SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
51886122f3e6SDimitry Andric       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
51896122f3e6SDimitry Andric       unsigned Idx = 0;
51908f0fd8f6SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
51918f0fd8f6SDimitry Andric         if (Record.size() < 3)
51928f0fd8f6SDimitry Andric           return error("Invalid record");
51938f0fd8f6SDimitry Andric       } else {
51948f0fd8f6SDimitry Andric         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
51956122f3e6SDimitry Andric         if (Record.size() < 4)
51968f0fd8f6SDimitry Andric           return error("Invalid record");
51978f0fd8f6SDimitry Andric       }
51986122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[Idx++]);
5199f785676fSDimitry Andric       if (!Ty)
52008f0fd8f6SDimitry Andric         return error("Invalid record");
52018f0fd8f6SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
520291bc56edSDimitry Andric         Value *PersFn = nullptr;
52036122f3e6SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
52048f0fd8f6SDimitry Andric           return error("Invalid record");
52058f0fd8f6SDimitry Andric 
52068f0fd8f6SDimitry Andric         if (!F->hasPersonalityFn())
52078f0fd8f6SDimitry Andric           F->setPersonalityFn(cast<Constant>(PersFn));
52088f0fd8f6SDimitry Andric         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
52098f0fd8f6SDimitry Andric           return error("Personality function mismatch");
52108f0fd8f6SDimitry Andric       }
52116122f3e6SDimitry Andric 
52126122f3e6SDimitry Andric       bool IsCleanup = !!Record[Idx++];
52136122f3e6SDimitry Andric       unsigned NumClauses = Record[Idx++];
52148f0fd8f6SDimitry Andric       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
52156122f3e6SDimitry Andric       LP->setCleanup(IsCleanup);
52166122f3e6SDimitry Andric       for (unsigned J = 0; J != NumClauses; ++J) {
52176122f3e6SDimitry Andric         LandingPadInst::ClauseType CT =
52186122f3e6SDimitry Andric           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
52196122f3e6SDimitry Andric         Value *Val;
52206122f3e6SDimitry Andric 
52216122f3e6SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
52226122f3e6SDimitry Andric           delete LP;
52238f0fd8f6SDimitry Andric           return error("Invalid record");
52246122f3e6SDimitry Andric         }
52256122f3e6SDimitry Andric 
52266122f3e6SDimitry Andric         assert((CT != LandingPadInst::Catch ||
52276122f3e6SDimitry Andric                 !isa<ArrayType>(Val->getType())) &&
52286122f3e6SDimitry Andric                "Catch clause has a invalid type!");
52296122f3e6SDimitry Andric         assert((CT != LandingPadInst::Filter ||
52306122f3e6SDimitry Andric                 isa<ArrayType>(Val->getType())) &&
52316122f3e6SDimitry Andric                "Filter clause has invalid type!");
523291bc56edSDimitry Andric         LP->addClause(cast<Constant>(Val));
52336122f3e6SDimitry Andric       }
52346122f3e6SDimitry Andric 
52356122f3e6SDimitry Andric       I = LP;
52366122f3e6SDimitry Andric       InstructionList.push_back(I);
52376122f3e6SDimitry Andric       break;
52386122f3e6SDimitry Andric     }
52396122f3e6SDimitry Andric 
524017a519f9SDimitry Andric     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
524117a519f9SDimitry Andric       if (Record.size() != 4)
52428f0fd8f6SDimitry Andric         return error("Invalid record");
5243ff0cc061SDimitry Andric       uint64_t AlignRecord = Record[3];
5244ff0cc061SDimitry Andric       const uint64_t InAllocaMask = uint64_t(1) << 5;
5245ff0cc061SDimitry Andric       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
52463ca95b02SDimitry Andric       const uint64_t SwiftErrorMask = uint64_t(1) << 7;
52473ca95b02SDimitry Andric       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
52483ca95b02SDimitry Andric                                 SwiftErrorMask;
5249ff0cc061SDimitry Andric       bool InAlloca = AlignRecord & InAllocaMask;
52503ca95b02SDimitry Andric       bool SwiftError = AlignRecord & SwiftErrorMask;
5251ff0cc061SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
5252ff0cc061SDimitry Andric       if ((AlignRecord & ExplicitTypeMask) == 0) {
5253ff0cc061SDimitry Andric         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
5254ff0cc061SDimitry Andric         if (!PTy)
52558f0fd8f6SDimitry Andric           return error("Old-style alloca with a non-pointer type");
5256ff0cc061SDimitry Andric         Ty = PTy->getElementType();
5257ff0cc061SDimitry Andric       }
52586122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[1]);
525917a519f9SDimitry Andric       Value *Size = getFnValueByID(Record[2], OpTy);
5260ff0cc061SDimitry Andric       unsigned Align;
5261ff0cc061SDimitry Andric       if (std::error_code EC =
5262ff0cc061SDimitry Andric               parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
5263ff0cc061SDimitry Andric         return EC;
5264ff0cc061SDimitry Andric       }
5265f785676fSDimitry Andric       if (!Ty || !Size)
52668f0fd8f6SDimitry Andric         return error("Invalid record");
5267ff0cc061SDimitry Andric       AllocaInst *AI = new AllocaInst(Ty, Size, Align);
526891bc56edSDimitry Andric       AI->setUsedWithInAlloca(InAlloca);
52693ca95b02SDimitry Andric       AI->setSwiftError(SwiftError);
527091bc56edSDimitry Andric       I = AI;
5271f22ef01cSRoman Divacky       InstructionList.push_back(I);
5272f22ef01cSRoman Divacky       break;
5273f22ef01cSRoman Divacky     }
5274f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5275f22ef01cSRoman Divacky       unsigned OpNum = 0;
5276f22ef01cSRoman Divacky       Value *Op;
5277f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5278ff0cc061SDimitry Andric           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
52798f0fd8f6SDimitry Andric         return error("Invalid record");
5280f22ef01cSRoman Divacky 
5281ff0cc061SDimitry Andric       Type *Ty = nullptr;
5282ff0cc061SDimitry Andric       if (OpNum + 3 == Record.size())
5283ff0cc061SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
52847d523365SDimitry Andric       if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
5285ff0cc061SDimitry Andric         return EC;
5286ff0cc061SDimitry Andric       if (!Ty)
5287ff0cc061SDimitry Andric         Ty = cast<PointerType>(Op->getType())->getElementType();
5288ff0cc061SDimitry Andric 
5289ff0cc061SDimitry Andric       unsigned Align;
5290ff0cc061SDimitry Andric       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5291ff0cc061SDimitry Andric         return EC;
5292ff0cc061SDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
5293ff0cc061SDimitry Andric 
5294f22ef01cSRoman Divacky       InstructionList.push_back(I);
5295f22ef01cSRoman Divacky       break;
5296f22ef01cSRoman Divacky     }
52976122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_LOADATOMIC: {
52986122f3e6SDimitry Andric        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
52996122f3e6SDimitry Andric       unsigned OpNum = 0;
53006122f3e6SDimitry Andric       Value *Op;
53016122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5302ff0cc061SDimitry Andric           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
53038f0fd8f6SDimitry Andric         return error("Invalid record");
53046122f3e6SDimitry Andric 
5305ff0cc061SDimitry Andric       Type *Ty = nullptr;
5306ff0cc061SDimitry Andric       if (OpNum + 5 == Record.size())
5307ff0cc061SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
53087d523365SDimitry Andric       if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
5309ff0cc061SDimitry Andric         return EC;
5310ff0cc061SDimitry Andric       if (!Ty)
5311ff0cc061SDimitry Andric         Ty = cast<PointerType>(Op->getType())->getElementType();
5312ff0cc061SDimitry Andric 
53138f0fd8f6SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
53143ca95b02SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
53153ca95b02SDimitry Andric           Ordering == AtomicOrdering::Release ||
53163ca95b02SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
53178f0fd8f6SDimitry Andric         return error("Invalid record");
53183ca95b02SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
53198f0fd8f6SDimitry Andric         return error("Invalid record");
53208f0fd8f6SDimitry Andric       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
53216122f3e6SDimitry Andric 
5322ff0cc061SDimitry Andric       unsigned Align;
5323ff0cc061SDimitry Andric       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5324ff0cc061SDimitry Andric         return EC;
5325ff0cc061SDimitry Andric       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
5326ff0cc061SDimitry Andric 
53276122f3e6SDimitry Andric       InstructionList.push_back(I);
53286122f3e6SDimitry Andric       break;
53296122f3e6SDimitry Andric     }
5330ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_STORE:
5331ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5332f22ef01cSRoman Divacky       unsigned OpNum = 0;
5333f22ef01cSRoman Divacky       Value *Val, *Ptr;
5334f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5335ff0cc061SDimitry Andric           (BitCode == bitc::FUNC_CODE_INST_STORE
5336ff0cc061SDimitry Andric                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5337ff0cc061SDimitry Andric                : popValue(Record, OpNum, NextValueNo,
5338ff0cc061SDimitry Andric                           cast<PointerType>(Ptr->getType())->getElementType(),
5339ff0cc061SDimitry Andric                           Val)) ||
5340f22ef01cSRoman Divacky           OpNum + 2 != Record.size())
53418f0fd8f6SDimitry Andric         return error("Invalid record");
5342f22ef01cSRoman Divacky 
53437d523365SDimitry Andric       if (std::error_code EC =
53447d523365SDimitry Andric               typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5345ff0cc061SDimitry Andric         return EC;
5346ff0cc061SDimitry Andric       unsigned Align;
5347ff0cc061SDimitry Andric       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5348ff0cc061SDimitry Andric         return EC;
5349ff0cc061SDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
5350f22ef01cSRoman Divacky       InstructionList.push_back(I);
5351f22ef01cSRoman Divacky       break;
5352f22ef01cSRoman Divacky     }
5353ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC:
5354ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
53556122f3e6SDimitry Andric       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
53566122f3e6SDimitry Andric       unsigned OpNum = 0;
53576122f3e6SDimitry Andric       Value *Val, *Ptr;
53586122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
53593ca95b02SDimitry Andric           !isa<PointerType>(Ptr->getType()) ||
5360ff0cc061SDimitry Andric           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5361ff0cc061SDimitry Andric                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5362ff0cc061SDimitry Andric                : popValue(Record, OpNum, NextValueNo,
5363ff0cc061SDimitry Andric                           cast<PointerType>(Ptr->getType())->getElementType(),
5364ff0cc061SDimitry Andric                           Val)) ||
53656122f3e6SDimitry Andric           OpNum + 4 != Record.size())
53668f0fd8f6SDimitry Andric         return error("Invalid record");
53676122f3e6SDimitry Andric 
53687d523365SDimitry Andric       if (std::error_code EC =
53697d523365SDimitry Andric               typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5370ff0cc061SDimitry Andric         return EC;
53718f0fd8f6SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
53723ca95b02SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
53733ca95b02SDimitry Andric           Ordering == AtomicOrdering::Acquire ||
53743ca95b02SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
53758f0fd8f6SDimitry Andric         return error("Invalid record");
53768f0fd8f6SDimitry Andric       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
53773ca95b02SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
53788f0fd8f6SDimitry Andric         return error("Invalid record");
53796122f3e6SDimitry Andric 
5380ff0cc061SDimitry Andric       unsigned Align;
5381ff0cc061SDimitry Andric       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5382ff0cc061SDimitry Andric         return EC;
5383ff0cc061SDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
53846122f3e6SDimitry Andric       InstructionList.push_back(I);
53856122f3e6SDimitry Andric       break;
53866122f3e6SDimitry Andric     }
5387ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
53886122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG: {
538991bc56edSDimitry Andric       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
539091bc56edSDimitry Andric       //          failureordering?, isweak?]
53916122f3e6SDimitry Andric       unsigned OpNum = 0;
53926122f3e6SDimitry Andric       Value *Ptr, *Cmp, *New;
53936122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5394ff0cc061SDimitry Andric           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5395ff0cc061SDimitry Andric                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5396ff0cc061SDimitry Andric                : popValue(Record, OpNum, NextValueNo,
5397ff0cc061SDimitry Andric                           cast<PointerType>(Ptr->getType())->getElementType(),
5398ff0cc061SDimitry Andric                           Cmp)) ||
5399ff0cc061SDimitry Andric           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5400ff0cc061SDimitry Andric           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
54018f0fd8f6SDimitry Andric         return error("Invalid record");
54028f0fd8f6SDimitry Andric       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
54033ca95b02SDimitry Andric       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
54043ca95b02SDimitry Andric           SuccessOrdering == AtomicOrdering::Unordered)
54058f0fd8f6SDimitry Andric         return error("Invalid record");
54068f0fd8f6SDimitry Andric       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
540791bc56edSDimitry Andric 
54087d523365SDimitry Andric       if (std::error_code EC =
54097d523365SDimitry Andric               typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5410ff0cc061SDimitry Andric         return EC;
541191bc56edSDimitry Andric       AtomicOrdering FailureOrdering;
541291bc56edSDimitry Andric       if (Record.size() < 7)
541391bc56edSDimitry Andric         FailureOrdering =
541491bc56edSDimitry Andric             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
541591bc56edSDimitry Andric       else
54168f0fd8f6SDimitry Andric         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
541791bc56edSDimitry Andric 
541891bc56edSDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
541991bc56edSDimitry Andric                                 SynchScope);
54206122f3e6SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
542191bc56edSDimitry Andric 
542291bc56edSDimitry Andric       if (Record.size() < 8) {
542391bc56edSDimitry Andric         // Before weak cmpxchgs existed, the instruction simply returned the
542491bc56edSDimitry Andric         // value loaded from memory, so bitcode files from that era will be
542591bc56edSDimitry Andric         // expecting the first component of a modern cmpxchg.
542691bc56edSDimitry Andric         CurBB->getInstList().push_back(I);
542791bc56edSDimitry Andric         I = ExtractValueInst::Create(I, 0);
542891bc56edSDimitry Andric       } else {
542991bc56edSDimitry Andric         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
543091bc56edSDimitry Andric       }
543191bc56edSDimitry Andric 
54326122f3e6SDimitry Andric       InstructionList.push_back(I);
54336122f3e6SDimitry Andric       break;
54346122f3e6SDimitry Andric     }
54356122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW: {
54366122f3e6SDimitry Andric       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
54376122f3e6SDimitry Andric       unsigned OpNum = 0;
54386122f3e6SDimitry Andric       Value *Ptr, *Val;
54396122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
54403ca95b02SDimitry Andric           !isa<PointerType>(Ptr->getType()) ||
54413861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo,
54426122f3e6SDimitry Andric                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
54436122f3e6SDimitry Andric           OpNum+4 != Record.size())
54448f0fd8f6SDimitry Andric         return error("Invalid record");
54458f0fd8f6SDimitry Andric       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
54466122f3e6SDimitry Andric       if (Operation < AtomicRMWInst::FIRST_BINOP ||
54476122f3e6SDimitry Andric           Operation > AtomicRMWInst::LAST_BINOP)
54488f0fd8f6SDimitry Andric         return error("Invalid record");
54498f0fd8f6SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
54503ca95b02SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
54513ca95b02SDimitry Andric           Ordering == AtomicOrdering::Unordered)
54528f0fd8f6SDimitry Andric         return error("Invalid record");
54538f0fd8f6SDimitry Andric       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
54546122f3e6SDimitry Andric       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
54556122f3e6SDimitry Andric       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
54566122f3e6SDimitry Andric       InstructionList.push_back(I);
54576122f3e6SDimitry Andric       break;
54586122f3e6SDimitry Andric     }
54596122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
54606122f3e6SDimitry Andric       if (2 != Record.size())
54618f0fd8f6SDimitry Andric         return error("Invalid record");
54628f0fd8f6SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
54633ca95b02SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
54643ca95b02SDimitry Andric           Ordering == AtomicOrdering::Unordered ||
54653ca95b02SDimitry Andric           Ordering == AtomicOrdering::Monotonic)
54668f0fd8f6SDimitry Andric         return error("Invalid record");
54678f0fd8f6SDimitry Andric       SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
54686122f3e6SDimitry Andric       I = new FenceInst(Context, Ordering, SynchScope);
54696122f3e6SDimitry Andric       InstructionList.push_back(I);
54706122f3e6SDimitry Andric       break;
54716122f3e6SDimitry Andric     }
547217a519f9SDimitry Andric     case bitc::FUNC_CODE_INST_CALL: {
54737d523365SDimitry Andric       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5474f22ef01cSRoman Divacky       if (Record.size() < 3)
54758f0fd8f6SDimitry Andric         return error("Invalid record");
5476f22ef01cSRoman Divacky 
5477ff0cc061SDimitry Andric       unsigned OpNum = 0;
5478ff0cc061SDimitry Andric       AttributeSet PAL = getAttributes(Record[OpNum++]);
5479ff0cc061SDimitry Andric       unsigned CCInfo = Record[OpNum++];
5480f22ef01cSRoman Divacky 
54817d523365SDimitry Andric       FastMathFlags FMF;
54827d523365SDimitry Andric       if ((CCInfo >> bitc::CALL_FMF) & 1) {
54837d523365SDimitry Andric         FMF = getDecodedFastMathFlags(Record[OpNum++]);
54847d523365SDimitry Andric         if (!FMF.any())
54857d523365SDimitry Andric           return error("Fast math flags indicator set for call with no FMF");
54867d523365SDimitry Andric       }
54877d523365SDimitry Andric 
5488ff0cc061SDimitry Andric       FunctionType *FTy = nullptr;
54897d523365SDimitry Andric       if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5490ff0cc061SDimitry Andric           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
54918f0fd8f6SDimitry Andric         return error("Explicit call type is not a function type");
5492ff0cc061SDimitry Andric 
5493f22ef01cSRoman Divacky       Value *Callee;
5494f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
54958f0fd8f6SDimitry Andric         return error("Invalid record");
5496f22ef01cSRoman Divacky 
54976122f3e6SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5498ff0cc061SDimitry Andric       if (!OpTy)
54998f0fd8f6SDimitry Andric         return error("Callee is not a pointer type");
5500ff0cc061SDimitry Andric       if (!FTy) {
5501ff0cc061SDimitry Andric         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5502ff0cc061SDimitry Andric         if (!FTy)
55038f0fd8f6SDimitry Andric           return error("Callee is not of pointer to function type");
5504ff0cc061SDimitry Andric       } else if (OpTy->getElementType() != FTy)
55058f0fd8f6SDimitry Andric         return error("Explicit call type does not match pointee type of "
5506ff0cc061SDimitry Andric                      "callee operand");
5507ff0cc061SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
55088f0fd8f6SDimitry Andric         return error("Insufficient operands to call");
5509f22ef01cSRoman Divacky 
5510f22ef01cSRoman Divacky       SmallVector<Value*, 16> Args;
5511f22ef01cSRoman Divacky       // Read the fixed params.
5512f22ef01cSRoman Divacky       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
551317a519f9SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
5514f22ef01cSRoman Divacky           Args.push_back(getBasicBlock(Record[OpNum]));
5515f22ef01cSRoman Divacky         else
55163861d79fSDimitry Andric           Args.push_back(getValue(Record, OpNum, NextValueNo,
55173861d79fSDimitry Andric                                   FTy->getParamType(i)));
551891bc56edSDimitry Andric         if (!Args.back())
55198f0fd8f6SDimitry Andric           return error("Invalid record");
5520f22ef01cSRoman Divacky       }
5521f22ef01cSRoman Divacky 
5522f22ef01cSRoman Divacky       // Read type/value pairs for varargs params.
5523f22ef01cSRoman Divacky       if (!FTy->isVarArg()) {
5524f22ef01cSRoman Divacky         if (OpNum != Record.size())
55258f0fd8f6SDimitry Andric           return error("Invalid record");
5526f22ef01cSRoman Divacky       } else {
5527f22ef01cSRoman Divacky         while (OpNum != Record.size()) {
5528f22ef01cSRoman Divacky           Value *Op;
5529f22ef01cSRoman Divacky           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
55308f0fd8f6SDimitry Andric             return error("Invalid record");
5531f22ef01cSRoman Divacky           Args.push_back(Op);
5532f22ef01cSRoman Divacky         }
5533f22ef01cSRoman Divacky       }
5534f22ef01cSRoman Divacky 
55357d523365SDimitry Andric       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
55367d523365SDimitry Andric       OperandBundles.clear();
5537f22ef01cSRoman Divacky       InstructionList.push_back(I);
5538f22ef01cSRoman Divacky       cast<CallInst>(I)->setCallingConv(
55397d523365SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
554091bc56edSDimitry Andric       CallInst::TailCallKind TCK = CallInst::TCK_None;
55417d523365SDimitry Andric       if (CCInfo & 1 << bitc::CALL_TAIL)
554291bc56edSDimitry Andric         TCK = CallInst::TCK_Tail;
55437d523365SDimitry Andric       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
554491bc56edSDimitry Andric         TCK = CallInst::TCK_MustTail;
55457d523365SDimitry Andric       if (CCInfo & (1 << bitc::CALL_NOTAIL))
55467d523365SDimitry Andric         TCK = CallInst::TCK_NoTail;
554791bc56edSDimitry Andric       cast<CallInst>(I)->setTailCallKind(TCK);
5548f22ef01cSRoman Divacky       cast<CallInst>(I)->setAttributes(PAL);
55497d523365SDimitry Andric       if (FMF.any()) {
55507d523365SDimitry Andric         if (!isa<FPMathOperator>(I))
55517d523365SDimitry Andric           return error("Fast-math-flags specified for call without "
55527d523365SDimitry Andric                        "floating-point scalar or vector return type");
55537d523365SDimitry Andric         I->setFastMathFlags(FMF);
55547d523365SDimitry Andric       }
5555f22ef01cSRoman Divacky       break;
5556f22ef01cSRoman Divacky     }
5557f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5558f22ef01cSRoman Divacky       if (Record.size() < 3)
55598f0fd8f6SDimitry Andric         return error("Invalid record");
55606122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
55613861d79fSDimitry Andric       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
55626122f3e6SDimitry Andric       Type *ResTy = getTypeByID(Record[2]);
5563f22ef01cSRoman Divacky       if (!OpTy || !Op || !ResTy)
55648f0fd8f6SDimitry Andric         return error("Invalid record");
5565f22ef01cSRoman Divacky       I = new VAArgInst(Op, ResTy);
5566f22ef01cSRoman Divacky       InstructionList.push_back(I);
5567f22ef01cSRoman Divacky       break;
5568f22ef01cSRoman Divacky     }
55697d523365SDimitry Andric 
55707d523365SDimitry Andric     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
55717d523365SDimitry Andric       // A call or an invoke can be optionally prefixed with some variable
55727d523365SDimitry Andric       // number of operand bundle blocks.  These blocks are read into
55737d523365SDimitry Andric       // OperandBundles and consumed at the next call or invoke instruction.
55747d523365SDimitry Andric 
55757d523365SDimitry Andric       if (Record.size() < 1 || Record[0] >= BundleTags.size())
55767d523365SDimitry Andric         return error("Invalid record");
55777d523365SDimitry Andric 
55787d523365SDimitry Andric       std::vector<Value *> Inputs;
55797d523365SDimitry Andric 
55807d523365SDimitry Andric       unsigned OpNum = 1;
55817d523365SDimitry Andric       while (OpNum != Record.size()) {
55827d523365SDimitry Andric         Value *Op;
55837d523365SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
55847d523365SDimitry Andric           return error("Invalid record");
55857d523365SDimitry Andric         Inputs.push_back(Op);
55867d523365SDimitry Andric       }
55877d523365SDimitry Andric 
55887d523365SDimitry Andric       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
55897d523365SDimitry Andric       continue;
55907d523365SDimitry Andric     }
5591f22ef01cSRoman Divacky     }
5592f22ef01cSRoman Divacky 
5593f22ef01cSRoman Divacky     // Add instruction to end of current BB.  If there is no current BB, reject
5594f22ef01cSRoman Divacky     // this file.
559591bc56edSDimitry Andric     if (!CurBB) {
5596f22ef01cSRoman Divacky       delete I;
55978f0fd8f6SDimitry Andric       return error("Invalid instruction with no BB");
5598f22ef01cSRoman Divacky     }
55997d523365SDimitry Andric     if (!OperandBundles.empty()) {
56007d523365SDimitry Andric       delete I;
56017d523365SDimitry Andric       return error("Operand bundles found with no consumer");
56027d523365SDimitry Andric     }
5603f22ef01cSRoman Divacky     CurBB->getInstList().push_back(I);
5604f22ef01cSRoman Divacky 
5605f22ef01cSRoman Divacky     // If this was a terminator instruction, move to the next block.
5606f22ef01cSRoman Divacky     if (isa<TerminatorInst>(I)) {
5607f22ef01cSRoman Divacky       ++CurBBNo;
560891bc56edSDimitry Andric       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5609f22ef01cSRoman Divacky     }
5610f22ef01cSRoman Divacky 
5611f22ef01cSRoman Divacky     // Non-void values get registered in the value table for future use.
5612f22ef01cSRoman Divacky     if (I && !I->getType()->isVoidTy())
56138f0fd8f6SDimitry Andric       ValueList.assignValue(I, NextValueNo++);
5614f22ef01cSRoman Divacky   }
5615f22ef01cSRoman Divacky 
5616139f7f9bSDimitry Andric OutOfRecordLoop:
5617139f7f9bSDimitry Andric 
56187d523365SDimitry Andric   if (!OperandBundles.empty())
56197d523365SDimitry Andric     return error("Operand bundles found with no consumer");
56207d523365SDimitry Andric 
5621f22ef01cSRoman Divacky   // Check the function list for unresolved values.
5622f22ef01cSRoman Divacky   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
562391bc56edSDimitry Andric     if (!A->getParent()) {
5624f22ef01cSRoman Divacky       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5625f22ef01cSRoman Divacky       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
562691bc56edSDimitry Andric         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5627f22ef01cSRoman Divacky           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5628f22ef01cSRoman Divacky           delete A;
5629f22ef01cSRoman Divacky         }
5630f22ef01cSRoman Divacky       }
56318f0fd8f6SDimitry Andric       return error("Never resolved value found in function");
5632f22ef01cSRoman Divacky     }
5633f22ef01cSRoman Divacky   }
5634f22ef01cSRoman Divacky 
56353ca95b02SDimitry Andric   // Unexpected unresolved metadata about to be dropped.
56363ca95b02SDimitry Andric   if (MetadataList.hasFwdRefs())
56373ca95b02SDimitry Andric     return error("Invalid function metadata: outgoing forward refs");
5638e580952dSDimitry Andric 
5639f22ef01cSRoman Divacky   // Trim the value list down to the size it was before we parsed this function.
5640f22ef01cSRoman Divacky   ValueList.shrinkTo(ModuleValueListSize);
56417d523365SDimitry Andric   MetadataList.shrinkTo(ModuleMetadataListSize);
5642f22ef01cSRoman Divacky   std::vector<BasicBlock*>().swap(FunctionBBs);
564391bc56edSDimitry Andric   return std::error_code();
5644f22ef01cSRoman Divacky }
5645f22ef01cSRoman Divacky 
5646f785676fSDimitry Andric /// Find the function body in the bitcode stream
56478f0fd8f6SDimitry Andric std::error_code BitcodeReader::findFunctionInStream(
564891bc56edSDimitry Andric     Function *F,
5649dff0c46cSDimitry Andric     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5650dff0c46cSDimitry Andric   while (DeferredFunctionInfoIterator->second == 0) {
56517d523365SDimitry Andric     // This is the fallback handling for the old format bitcode that
56527d523365SDimitry Andric     // didn't contain the function index in the VST, or when we have
56537d523365SDimitry Andric     // an anonymous function which would not have a VST entry.
56547d523365SDimitry Andric     // Assert that we have one of those two cases.
56557d523365SDimitry Andric     assert(VSTOffset == 0 || !F->hasName());
56567d523365SDimitry Andric     // Parse the next body in the stream and set its position in the
56577d523365SDimitry Andric     // DeferredFunctionInfo map.
56587d523365SDimitry Andric     if (std::error_code EC = rememberAndSkipFunctionBodies())
5659f785676fSDimitry Andric       return EC;
5660dff0c46cSDimitry Andric   }
566191bc56edSDimitry Andric   return std::error_code();
5662dff0c46cSDimitry Andric }
5663dff0c46cSDimitry Andric 
5664f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
5665f22ef01cSRoman Divacky // GVMaterializer implementation
5666f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
5667f22ef01cSRoman Divacky 
566891bc56edSDimitry Andric void BitcodeReader::releaseBuffer() { Buffer.release(); }
5669f22ef01cSRoman Divacky 
567039d628a0SDimitry Andric std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5671f22ef01cSRoman Divacky   Function *F = dyn_cast<Function>(GV);
5672f22ef01cSRoman Divacky   // If it's not a function or is already material, ignore the request.
5673f785676fSDimitry Andric   if (!F || !F->isMaterializable())
567491bc56edSDimitry Andric     return std::error_code();
5675f22ef01cSRoman Divacky 
5676f22ef01cSRoman Divacky   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5677f22ef01cSRoman Divacky   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5678dff0c46cSDimitry Andric   // If its position is recorded as 0, its body is somewhere in the stream
5679dff0c46cSDimitry Andric   // but we haven't seen it yet.
56803dac3a9bSDimitry Andric   if (DFII->second == 0)
56818f0fd8f6SDimitry Andric     if (std::error_code EC = findFunctionInStream(F, DFII))
5682f785676fSDimitry Andric       return EC;
5683f22ef01cSRoman Divacky 
56843ca95b02SDimitry Andric   // Materialize metadata before parsing any function bodies.
56853ca95b02SDimitry Andric   if (std::error_code EC = materializeMetadata())
56863ca95b02SDimitry Andric     return EC;
56873ca95b02SDimitry Andric 
5688f22ef01cSRoman Divacky   // Move the bit stream to the saved position of the deferred function body.
5689f22ef01cSRoman Divacky   Stream.JumpToBit(DFII->second);
5690f22ef01cSRoman Divacky 
56918f0fd8f6SDimitry Andric   if (std::error_code EC = parseFunctionBody(F))
5692f785676fSDimitry Andric     return EC;
569339d628a0SDimitry Andric   F->setIsMaterializable(false);
5694f22ef01cSRoman Divacky 
5695ff0cc061SDimitry Andric   if (StripDebugInfo)
5696ff0cc061SDimitry Andric     stripDebugInfo(*F);
5697ff0cc061SDimitry Andric 
5698f22ef01cSRoman Divacky   // Upgrade any old intrinsic calls in the function.
56993dac3a9bSDimitry Andric   for (auto &I : UpgradedIntrinsics) {
57007d523365SDimitry Andric     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
57017d523365SDimitry Andric          UI != UE;) {
57023dac3a9bSDimitry Andric       User *U = *UI;
57033dac3a9bSDimitry Andric       ++UI;
57043dac3a9bSDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
57053dac3a9bSDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
5706f22ef01cSRoman Divacky     }
5707f22ef01cSRoman Divacky   }
5708f22ef01cSRoman Divacky 
57093ca95b02SDimitry Andric   // Update calls to the remangled intrinsics
57103ca95b02SDimitry Andric   for (auto &I : RemangledIntrinsics)
57113ca95b02SDimitry Andric     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
57123ca95b02SDimitry Andric          UI != UE;)
57133ca95b02SDimitry Andric       // Don't expect any other users than call sites
57143ca95b02SDimitry Andric       CallSite(*UI++).setCalledFunction(I.second);
57153ca95b02SDimitry Andric 
57167d523365SDimitry Andric   // Finish fn->subprogram upgrade for materialized functions.
57177d523365SDimitry Andric   if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
57187d523365SDimitry Andric     F->setSubprogram(SP);
57197d523365SDimitry Andric 
572039d628a0SDimitry Andric   // Bring in any functions that this function forward-referenced via
572139d628a0SDimitry Andric   // blockaddresses.
572239d628a0SDimitry Andric   return materializeForwardReferencedFunctions();
5723f22ef01cSRoman Divacky }
5724f22ef01cSRoman Divacky 
57257d523365SDimitry Andric std::error_code BitcodeReader::materializeModule() {
5726ff0cc061SDimitry Andric   if (std::error_code EC = materializeMetadata())
5727ff0cc061SDimitry Andric     return EC;
5728ff0cc061SDimitry Andric 
572939d628a0SDimitry Andric   // Promise to materialize all forward references.
573039d628a0SDimitry Andric   WillMaterializeAllForwardRefs = true;
573139d628a0SDimitry Andric 
5732f22ef01cSRoman Divacky   // Iterate over the module, deserializing any functions that are still on
5733f22ef01cSRoman Divacky   // disk.
57347d523365SDimitry Andric   for (Function &F : *TheModule) {
57357d523365SDimitry Andric     if (std::error_code EC = materialize(&F))
5736f785676fSDimitry Andric       return EC;
5737f785676fSDimitry Andric   }
57387d523365SDimitry Andric   // At this point, if there are any function bodies, parse the rest of
57397d523365SDimitry Andric   // the bits in the module past the last function block we have recorded
57407d523365SDimitry Andric   // through either lazy scanning or the VST.
57417d523365SDimitry Andric   if (LastFunctionBlockBit || NextUnreadBit)
57427d523365SDimitry Andric     parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
57437d523365SDimitry Andric                                                      : NextUnreadBit);
5744dff0c46cSDimitry Andric 
574539d628a0SDimitry Andric   // Check that all block address forward references got resolved (as we
574639d628a0SDimitry Andric   // promised above).
574739d628a0SDimitry Andric   if (!BasicBlockFwdRefs.empty())
57488f0fd8f6SDimitry Andric     return error("Never resolved function from blockaddress");
574939d628a0SDimitry Andric 
57503ca95b02SDimitry Andric   // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
57513ca95b02SDimitry Andric   // to prevent this instructions with TBAA tags should be upgraded first.
57523ca95b02SDimitry Andric   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
57533ca95b02SDimitry Andric     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
57543ca95b02SDimitry Andric 
5755f22ef01cSRoman Divacky   // Upgrade any intrinsic calls that slipped through (should not happen!) and
5756f22ef01cSRoman Divacky   // delete the old functions to clean up. We can't do this unless the entire
5757f22ef01cSRoman Divacky   // module is materialized because there could always be another function body
5758f22ef01cSRoman Divacky   // with calls to the old function.
57593dac3a9bSDimitry Andric   for (auto &I : UpgradedIntrinsics) {
57603dac3a9bSDimitry Andric     for (auto *U : I.first->users()) {
57613dac3a9bSDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
57623dac3a9bSDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
5763f22ef01cSRoman Divacky     }
57643dac3a9bSDimitry Andric     if (!I.first->use_empty())
57653dac3a9bSDimitry Andric       I.first->replaceAllUsesWith(I.second);
57663dac3a9bSDimitry Andric     I.first->eraseFromParent();
5767f22ef01cSRoman Divacky   }
57683dac3a9bSDimitry Andric   UpgradedIntrinsics.clear();
57693ca95b02SDimitry Andric   // Do the same for remangled intrinsics
57703ca95b02SDimitry Andric   for (auto &I : RemangledIntrinsics) {
57713ca95b02SDimitry Andric     I.first->replaceAllUsesWith(I.second);
57723ca95b02SDimitry Andric     I.first->eraseFromParent();
57733ca95b02SDimitry Andric   }
57743ca95b02SDimitry Andric   RemangledIntrinsics.clear();
5775f785676fSDimitry Andric 
57767d523365SDimitry Andric   UpgradeDebugInfo(*TheModule);
57773ca95b02SDimitry Andric 
57783ca95b02SDimitry Andric   UpgradeModuleFlags(*TheModule);
577991bc56edSDimitry Andric   return std::error_code();
5780dff0c46cSDimitry Andric }
57816122f3e6SDimitry Andric 
578239d628a0SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
578339d628a0SDimitry Andric   return IdentifiedStructTypes;
578439d628a0SDimitry Andric }
578539d628a0SDimitry Andric 
57868f0fd8f6SDimitry Andric std::error_code
57878f0fd8f6SDimitry Andric BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
57888f0fd8f6SDimitry Andric   if (Streamer)
57898f0fd8f6SDimitry Andric     return initLazyStream(std::move(Streamer));
57908f0fd8f6SDimitry Andric   return initStreamFromBuffer();
5791dff0c46cSDimitry Andric }
5792dff0c46cSDimitry Andric 
57938f0fd8f6SDimitry Andric std::error_code BitcodeReader::initStreamFromBuffer() {
57943861d79fSDimitry Andric   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5795dff0c46cSDimitry Andric   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5796dff0c46cSDimitry Andric 
579739d628a0SDimitry Andric   if (Buffer->getBufferSize() & 3)
57988f0fd8f6SDimitry Andric     return error("Invalid bitcode signature");
5799dff0c46cSDimitry Andric 
5800dff0c46cSDimitry Andric   // If we have a wrapper header, parse it and ignore the non-bc file contents.
5801dff0c46cSDimitry Andric   // The magic number is 0x0B17C0DE stored in little endian.
5802dff0c46cSDimitry Andric   if (isBitcodeWrapper(BufPtr, BufEnd))
5803dff0c46cSDimitry Andric     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
58048f0fd8f6SDimitry Andric       return error("Invalid bitcode wrapper header");
5805dff0c46cSDimitry Andric 
5806dff0c46cSDimitry Andric   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
580739d628a0SDimitry Andric   Stream.init(&*StreamFile);
5808f22ef01cSRoman Divacky 
580991bc56edSDimitry Andric   return std::error_code();
5810f22ef01cSRoman Divacky }
5811f22ef01cSRoman Divacky 
58128f0fd8f6SDimitry Andric std::error_code
58138f0fd8f6SDimitry Andric BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5814dff0c46cSDimitry Andric   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5815dff0c46cSDimitry Andric   // see it.
58168f0fd8f6SDimitry Andric   auto OwnedBytes =
58178f0fd8f6SDimitry Andric       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
581839d628a0SDimitry Andric   StreamingMemoryObject &Bytes = *OwnedBytes;
581939d628a0SDimitry Andric   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
582039d628a0SDimitry Andric   Stream.init(&*StreamFile);
5821dff0c46cSDimitry Andric 
5822dff0c46cSDimitry Andric   unsigned char buf[16];
582339d628a0SDimitry Andric   if (Bytes.readBytes(buf, 16, 0) != 16)
58248f0fd8f6SDimitry Andric     return error("Invalid bitcode signature");
5825dff0c46cSDimitry Andric 
5826dff0c46cSDimitry Andric   if (!isBitcode(buf, buf + 16))
58278f0fd8f6SDimitry Andric     return error("Invalid bitcode signature");
5828dff0c46cSDimitry Andric 
5829dff0c46cSDimitry Andric   if (isBitcodeWrapper(buf, buf + 4)) {
5830dff0c46cSDimitry Andric     const unsigned char *bitcodeStart = buf;
5831dff0c46cSDimitry Andric     const unsigned char *bitcodeEnd = buf + 16;
5832dff0c46cSDimitry Andric     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
583339d628a0SDimitry Andric     Bytes.dropLeadingBytes(bitcodeStart - buf);
583439d628a0SDimitry Andric     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5835dff0c46cSDimitry Andric   }
583691bc56edSDimitry Andric   return std::error_code();
5837f785676fSDimitry Andric }
5838f785676fSDimitry Andric 
58393ca95b02SDimitry Andric std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
58407d523365SDimitry Andric   return ::error(DiagnosticHandler,
58417d523365SDimitry Andric                  make_error_code(BitcodeError::CorruptedBitcode), Message);
58427d523365SDimitry Andric }
58437d523365SDimitry Andric 
58443ca95b02SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
58453ca95b02SDimitry Andric     MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
58463ca95b02SDimitry Andric     bool CheckGlobalValSummaryPresenceOnly)
58473ca95b02SDimitry Andric     : DiagnosticHandler(std::move(DiagnosticHandler)), Buffer(Buffer),
58483ca95b02SDimitry Andric       CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
58493ca95b02SDimitry Andric 
58503ca95b02SDimitry Andric void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
58513ca95b02SDimitry Andric 
58523ca95b02SDimitry Andric void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
58533ca95b02SDimitry Andric 
58543ca95b02SDimitry Andric std::pair<GlobalValue::GUID, GlobalValue::GUID>
58553ca95b02SDimitry Andric ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
58563ca95b02SDimitry Andric   auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
58573ca95b02SDimitry Andric   assert(VGI != ValueIdToCallGraphGUIDMap.end());
58583ca95b02SDimitry Andric   return VGI->second;
58597d523365SDimitry Andric }
58607d523365SDimitry Andric 
58613ca95b02SDimitry Andric // Specialized value symbol table parser used when reading module index
58623ca95b02SDimitry Andric // blocks where we don't actually create global values. The parsed information
58633ca95b02SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries.
58643ca95b02SDimitry Andric std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
58653ca95b02SDimitry Andric     uint64_t Offset,
58663ca95b02SDimitry Andric     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
58673ca95b02SDimitry Andric   assert(Offset > 0 && "Expected non-zero VST offset");
58683ca95b02SDimitry Andric   uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
58697d523365SDimitry Andric 
58707d523365SDimitry Andric   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
58717d523365SDimitry Andric     return error("Invalid record");
58727d523365SDimitry Andric 
58737d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
58747d523365SDimitry Andric 
58757d523365SDimitry Andric   // Read all the records for this value table.
58767d523365SDimitry Andric   SmallString<128> ValueName;
58777d523365SDimitry Andric   while (1) {
58787d523365SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
58797d523365SDimitry Andric 
58807d523365SDimitry Andric     switch (Entry.Kind) {
58817d523365SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
58827d523365SDimitry Andric     case BitstreamEntry::Error:
58837d523365SDimitry Andric       return error("Malformed block");
58847d523365SDimitry Andric     case BitstreamEntry::EndBlock:
58853ca95b02SDimitry Andric       // Done parsing VST, jump back to wherever we came from.
58863ca95b02SDimitry Andric       Stream.JumpToBit(CurrentBit);
58877d523365SDimitry Andric       return std::error_code();
58887d523365SDimitry Andric     case BitstreamEntry::Record:
58897d523365SDimitry Andric       // The interesting case.
58907d523365SDimitry Andric       break;
58917d523365SDimitry Andric     }
58927d523365SDimitry Andric 
58937d523365SDimitry Andric     // Read a record.
58947d523365SDimitry Andric     Record.clear();
58957d523365SDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
58967d523365SDimitry Andric     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
58977d523365SDimitry Andric       break;
58983ca95b02SDimitry Andric     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
58993ca95b02SDimitry Andric       if (convertToString(Record, 1, ValueName))
59003ca95b02SDimitry Andric         return error("Invalid record");
59013ca95b02SDimitry Andric       unsigned ValueID = Record[0];
59023ca95b02SDimitry Andric       assert(!SourceFileName.empty());
59033ca95b02SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
59043ca95b02SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
59053ca95b02SDimitry Andric              "No linkage found for VST entry?");
59063ca95b02SDimitry Andric       auto Linkage = VLI->second;
59073ca95b02SDimitry Andric       std::string GlobalId =
59083ca95b02SDimitry Andric           GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
59093ca95b02SDimitry Andric       auto ValueGUID = GlobalValue::getGUID(GlobalId);
59103ca95b02SDimitry Andric       auto OriginalNameID = ValueGUID;
59113ca95b02SDimitry Andric       if (GlobalValue::isLocalLinkage(Linkage))
59123ca95b02SDimitry Andric         OriginalNameID = GlobalValue::getGUID(ValueName);
59133ca95b02SDimitry Andric       if (PrintSummaryGUIDs)
59143ca95b02SDimitry Andric         dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
59153ca95b02SDimitry Andric                << ValueName << "\n";
59163ca95b02SDimitry Andric       ValueIdToCallGraphGUIDMap[ValueID] =
59173ca95b02SDimitry Andric           std::make_pair(ValueGUID, OriginalNameID);
59183ca95b02SDimitry Andric       ValueName.clear();
59193ca95b02SDimitry Andric       break;
59203ca95b02SDimitry Andric     }
59217d523365SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
59223ca95b02SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
59237d523365SDimitry Andric       if (convertToString(Record, 2, ValueName))
59247d523365SDimitry Andric         return error("Invalid record");
59257d523365SDimitry Andric       unsigned ValueID = Record[0];
59263ca95b02SDimitry Andric       assert(!SourceFileName.empty());
59273ca95b02SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
59283ca95b02SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
59293ca95b02SDimitry Andric              "No linkage found for VST entry?");
59303ca95b02SDimitry Andric       auto Linkage = VLI->second;
59313ca95b02SDimitry Andric       std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
59323ca95b02SDimitry Andric           ValueName, VLI->second, SourceFileName);
59333ca95b02SDimitry Andric       auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
59343ca95b02SDimitry Andric       auto OriginalNameID = FunctionGUID;
59353ca95b02SDimitry Andric       if (GlobalValue::isLocalLinkage(Linkage))
59363ca95b02SDimitry Andric         OriginalNameID = GlobalValue::getGUID(ValueName);
59373ca95b02SDimitry Andric       if (PrintSummaryGUIDs)
59383ca95b02SDimitry Andric         dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
59393ca95b02SDimitry Andric                << ValueName << "\n";
59403ca95b02SDimitry Andric       ValueIdToCallGraphGUIDMap[ValueID] =
59413ca95b02SDimitry Andric           std::make_pair(FunctionGUID, OriginalNameID);
59427d523365SDimitry Andric 
59437d523365SDimitry Andric       ValueName.clear();
59447d523365SDimitry Andric       break;
59457d523365SDimitry Andric     }
59463ca95b02SDimitry Andric     case bitc::VST_CODE_COMBINED_ENTRY: {
59473ca95b02SDimitry Andric       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
59483ca95b02SDimitry Andric       unsigned ValueID = Record[0];
59493ca95b02SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
59503ca95b02SDimitry Andric       // The "original name", which is the second value of the pair will be
59513ca95b02SDimitry Andric       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
59523ca95b02SDimitry Andric       ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
59537d523365SDimitry Andric       break;
59547d523365SDimitry Andric     }
59557d523365SDimitry Andric     }
59567d523365SDimitry Andric   }
59577d523365SDimitry Andric }
59587d523365SDimitry Andric 
59593ca95b02SDimitry Andric // Parse just the blocks needed for building the index out of the module.
59603ca95b02SDimitry Andric // At the end of this routine the module Index is populated with a map
59613ca95b02SDimitry Andric // from global value id to GlobalValueSummary objects.
59623ca95b02SDimitry Andric std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
59637d523365SDimitry Andric   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
59647d523365SDimitry Andric     return error("Invalid record");
59657d523365SDimitry Andric 
59663ca95b02SDimitry Andric   SmallVector<uint64_t, 64> Record;
59673ca95b02SDimitry Andric   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
59683ca95b02SDimitry Andric   unsigned ValueId = 0;
59693ca95b02SDimitry Andric 
59703ca95b02SDimitry Andric   // Read the index for this module.
59717d523365SDimitry Andric   while (1) {
59727d523365SDimitry Andric     BitstreamEntry Entry = Stream.advance();
59737d523365SDimitry Andric 
59747d523365SDimitry Andric     switch (Entry.Kind) {
59757d523365SDimitry Andric     case BitstreamEntry::Error:
59767d523365SDimitry Andric       return error("Malformed block");
59777d523365SDimitry Andric     case BitstreamEntry::EndBlock:
59787d523365SDimitry Andric       return std::error_code();
59797d523365SDimitry Andric 
59807d523365SDimitry Andric     case BitstreamEntry::SubBlock:
59813ca95b02SDimitry Andric       if (CheckGlobalValSummaryPresenceOnly) {
59823ca95b02SDimitry Andric         if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
59833ca95b02SDimitry Andric           SeenGlobalValSummary = true;
59847d523365SDimitry Andric           // No need to parse the rest since we found the summary.
59857d523365SDimitry Andric           return std::error_code();
59867d523365SDimitry Andric         }
59877d523365SDimitry Andric         if (Stream.SkipBlock())
59887d523365SDimitry Andric           return error("Invalid record");
59897d523365SDimitry Andric         continue;
59907d523365SDimitry Andric       }
59917d523365SDimitry Andric       switch (Entry.ID) {
59927d523365SDimitry Andric       default: // Skip unknown content.
59937d523365SDimitry Andric         if (Stream.SkipBlock())
59947d523365SDimitry Andric           return error("Invalid record");
59957d523365SDimitry Andric         break;
59967d523365SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
59977d523365SDimitry Andric         // Need to parse these to get abbrev ids (e.g. for VST)
59987d523365SDimitry Andric         if (Stream.ReadBlockInfoBlock())
59997d523365SDimitry Andric           return error("Malformed block");
60007d523365SDimitry Andric         break;
60017d523365SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
60023ca95b02SDimitry Andric         // Should have been parsed earlier via VSTOffset, unless there
60033ca95b02SDimitry Andric         // is no summary section.
60043ca95b02SDimitry Andric         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
60053ca95b02SDimitry Andric                 !SeenGlobalValSummary) &&
60063ca95b02SDimitry Andric                "Expected early VST parse via VSTOffset record");
60077d523365SDimitry Andric         if (Stream.SkipBlock())
60087d523365SDimitry Andric           return error("Invalid record");
60093ca95b02SDimitry Andric         break;
60103ca95b02SDimitry Andric       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
60113ca95b02SDimitry Andric         assert(VSTOffset > 0 && "Expected non-zero VST offset");
60123ca95b02SDimitry Andric         assert(!SeenValueSymbolTable &&
60133ca95b02SDimitry Andric                "Already read VST when parsing summary block?");
60143ca95b02SDimitry Andric         if (std::error_code EC =
60153ca95b02SDimitry Andric                 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
60163ca95b02SDimitry Andric           return EC;
60173ca95b02SDimitry Andric         SeenValueSymbolTable = true;
60183ca95b02SDimitry Andric         SeenGlobalValSummary = true;
60193ca95b02SDimitry Andric         if (std::error_code EC = parseEntireSummary())
60207d523365SDimitry Andric           return EC;
60217d523365SDimitry Andric         break;
60227d523365SDimitry Andric       case bitc::MODULE_STRTAB_BLOCK_ID:
60237d523365SDimitry Andric         if (std::error_code EC = parseModuleStringTable())
60247d523365SDimitry Andric           return EC;
60257d523365SDimitry Andric         break;
60267d523365SDimitry Andric       }
60277d523365SDimitry Andric       continue;
60287d523365SDimitry Andric 
60293ca95b02SDimitry Andric     case BitstreamEntry::Record: {
60303ca95b02SDimitry Andric         Record.clear();
60313ca95b02SDimitry Andric         auto BitCode = Stream.readRecord(Entry.ID, Record);
60323ca95b02SDimitry Andric         switch (BitCode) {
60333ca95b02SDimitry Andric         default:
60343ca95b02SDimitry Andric           break; // Default behavior, ignore unknown content.
60353ca95b02SDimitry Andric         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
60363ca95b02SDimitry Andric         case bitc::MODULE_CODE_SOURCE_FILENAME: {
60373ca95b02SDimitry Andric           SmallString<128> ValueName;
60383ca95b02SDimitry Andric           if (convertToString(Record, 0, ValueName))
60393ca95b02SDimitry Andric             return error("Invalid record");
60403ca95b02SDimitry Andric           SourceFileName = ValueName.c_str();
60413ca95b02SDimitry Andric           break;
60423ca95b02SDimitry Andric         }
60433ca95b02SDimitry Andric         /// MODULE_CODE_HASH: [5*i32]
60443ca95b02SDimitry Andric         case bitc::MODULE_CODE_HASH: {
60453ca95b02SDimitry Andric           if (Record.size() != 5)
60463ca95b02SDimitry Andric             return error("Invalid hash length " + Twine(Record.size()).str());
60473ca95b02SDimitry Andric           if (!TheIndex)
60483ca95b02SDimitry Andric             break;
60493ca95b02SDimitry Andric           if (TheIndex->modulePaths().empty())
60503ca95b02SDimitry Andric             // Does not have any summary emitted.
60513ca95b02SDimitry Andric             break;
60523ca95b02SDimitry Andric           if (TheIndex->modulePaths().size() != 1)
60533ca95b02SDimitry Andric             return error("Don't expect multiple modules defined?");
60543ca95b02SDimitry Andric           auto &Hash = TheIndex->modulePaths().begin()->second.second;
60553ca95b02SDimitry Andric           int Pos = 0;
60563ca95b02SDimitry Andric           for (auto &Val : Record) {
60573ca95b02SDimitry Andric             assert(!(Val >> 32) && "Unexpected high bits set");
60583ca95b02SDimitry Andric             Hash[Pos++] = Val;
60593ca95b02SDimitry Andric           }
60603ca95b02SDimitry Andric           break;
60613ca95b02SDimitry Andric         }
60623ca95b02SDimitry Andric         /// MODULE_CODE_VSTOFFSET: [offset]
60633ca95b02SDimitry Andric         case bitc::MODULE_CODE_VSTOFFSET:
60643ca95b02SDimitry Andric           if (Record.size() < 1)
60653ca95b02SDimitry Andric             return error("Invalid record");
60663ca95b02SDimitry Andric           VSTOffset = Record[0];
60673ca95b02SDimitry Andric           break;
60683ca95b02SDimitry Andric         // GLOBALVAR: [pointer type, isconst, initid,
60693ca95b02SDimitry Andric         //             linkage, alignment, section, visibility, threadlocal,
60703ca95b02SDimitry Andric         //             unnamed_addr, externally_initialized, dllstorageclass,
60713ca95b02SDimitry Andric         //             comdat]
60723ca95b02SDimitry Andric         case bitc::MODULE_CODE_GLOBALVAR: {
60733ca95b02SDimitry Andric           if (Record.size() < 6)
60743ca95b02SDimitry Andric             return error("Invalid record");
60753ca95b02SDimitry Andric           uint64_t RawLinkage = Record[3];
60763ca95b02SDimitry Andric           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
60773ca95b02SDimitry Andric           ValueIdToLinkageMap[ValueId++] = Linkage;
60783ca95b02SDimitry Andric           break;
60793ca95b02SDimitry Andric         }
60803ca95b02SDimitry Andric         // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
60813ca95b02SDimitry Andric         //             alignment, section, visibility, gc, unnamed_addr,
60823ca95b02SDimitry Andric         //             prologuedata, dllstorageclass, comdat, prefixdata]
60833ca95b02SDimitry Andric         case bitc::MODULE_CODE_FUNCTION: {
60843ca95b02SDimitry Andric           if (Record.size() < 8)
60853ca95b02SDimitry Andric             return error("Invalid record");
60863ca95b02SDimitry Andric           uint64_t RawLinkage = Record[3];
60873ca95b02SDimitry Andric           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
60883ca95b02SDimitry Andric           ValueIdToLinkageMap[ValueId++] = Linkage;
60893ca95b02SDimitry Andric           break;
60903ca95b02SDimitry Andric         }
60913ca95b02SDimitry Andric         // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
60923ca95b02SDimitry Andric         // dllstorageclass]
60933ca95b02SDimitry Andric         case bitc::MODULE_CODE_ALIAS: {
60943ca95b02SDimitry Andric           if (Record.size() < 6)
60953ca95b02SDimitry Andric             return error("Invalid record");
60963ca95b02SDimitry Andric           uint64_t RawLinkage = Record[3];
60973ca95b02SDimitry Andric           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
60983ca95b02SDimitry Andric           ValueIdToLinkageMap[ValueId++] = Linkage;
60993ca95b02SDimitry Andric           break;
61003ca95b02SDimitry Andric         }
61013ca95b02SDimitry Andric         }
61023ca95b02SDimitry Andric       }
61037d523365SDimitry Andric       continue;
61047d523365SDimitry Andric     }
61057d523365SDimitry Andric   }
61067d523365SDimitry Andric }
61077d523365SDimitry Andric 
61083ca95b02SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary
61093ca95b02SDimitry Andric // objects in the index.
61103ca95b02SDimitry Andric std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
61113ca95b02SDimitry Andric   if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
61127d523365SDimitry Andric     return error("Invalid record");
61137d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
61147d523365SDimitry Andric 
61153ca95b02SDimitry Andric   // Parse version
61163ca95b02SDimitry Andric   {
61173ca95b02SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
61183ca95b02SDimitry Andric     if (Entry.Kind != BitstreamEntry::Record)
61193ca95b02SDimitry Andric       return error("Invalid Summary Block: record for version expected");
61203ca95b02SDimitry Andric     if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
61213ca95b02SDimitry Andric       return error("Invalid Summary Block: version expected");
61223ca95b02SDimitry Andric   }
61233ca95b02SDimitry Andric   const uint64_t Version = Record[0];
61243ca95b02SDimitry Andric   if (Version != 1)
61253ca95b02SDimitry Andric     return error("Invalid summary version " + Twine(Version) + ", 1 expected");
61263ca95b02SDimitry Andric   Record.clear();
61273ca95b02SDimitry Andric 
61283ca95b02SDimitry Andric   // Keep around the last seen summary to be used when we see an optional
61293ca95b02SDimitry Andric   // "OriginalName" attachement.
61303ca95b02SDimitry Andric   GlobalValueSummary *LastSeenSummary = nullptr;
61313ca95b02SDimitry Andric   bool Combined = false;
61327d523365SDimitry Andric   while (1) {
61337d523365SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
61347d523365SDimitry Andric 
61357d523365SDimitry Andric     switch (Entry.Kind) {
61367d523365SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
61377d523365SDimitry Andric     case BitstreamEntry::Error:
61387d523365SDimitry Andric       return error("Malformed block");
61397d523365SDimitry Andric     case BitstreamEntry::EndBlock:
61403ca95b02SDimitry Andric       // For a per-module index, remove any entries that still have empty
61413ca95b02SDimitry Andric       // summaries. The VST parsing creates entries eagerly for all symbols,
61423ca95b02SDimitry Andric       // but not all have associated summaries (e.g. it doesn't know how to
61433ca95b02SDimitry Andric       // distinguish between VST_CODE_ENTRY for function declarations vs global
61443ca95b02SDimitry Andric       // variables with initializers that end up with a summary). Remove those
61453ca95b02SDimitry Andric       // entries now so that we don't need to rely on the combined index merger
61463ca95b02SDimitry Andric       // to clean them up (especially since that may not run for the first
61473ca95b02SDimitry Andric       // module's index if we merge into that).
61483ca95b02SDimitry Andric       if (!Combined)
61493ca95b02SDimitry Andric         TheIndex->removeEmptySummaryEntries();
61507d523365SDimitry Andric       return std::error_code();
61517d523365SDimitry Andric     case BitstreamEntry::Record:
61527d523365SDimitry Andric       // The interesting case.
61537d523365SDimitry Andric       break;
61547d523365SDimitry Andric     }
61557d523365SDimitry Andric 
61567d523365SDimitry Andric     // Read a record. The record format depends on whether this
61577d523365SDimitry Andric     // is a per-module index or a combined index file. In the per-module
61587d523365SDimitry Andric     // case the records contain the associated value's ID for correlation
61597d523365SDimitry Andric     // with VST entries. In the combined index the correlation is done
61607d523365SDimitry Andric     // via the bitcode offset of the summary records (which were saved
61617d523365SDimitry Andric     // in the combined index VST entries). The records also contain
61627d523365SDimitry Andric     // information used for ThinLTO renaming and importing.
61637d523365SDimitry Andric     Record.clear();
61643ca95b02SDimitry Andric     auto BitCode = Stream.readRecord(Entry.ID, Record);
61653ca95b02SDimitry Andric     switch (BitCode) {
61667d523365SDimitry Andric     default: // Default behavior: ignore.
61677d523365SDimitry Andric       break;
61683ca95b02SDimitry Andric     // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
61693ca95b02SDimitry Andric     //                n x (valueid, callsitecount)]
61703ca95b02SDimitry Andric     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
61713ca95b02SDimitry Andric     //                        numrefs x valueid,
61723ca95b02SDimitry Andric     //                        n x (valueid, callsitecount, profilecount)]
61733ca95b02SDimitry Andric     case bitc::FS_PERMODULE:
61743ca95b02SDimitry Andric     case bitc::FS_PERMODULE_PROFILE: {
61757d523365SDimitry Andric       unsigned ValueID = Record[0];
61763ca95b02SDimitry Andric       uint64_t RawFlags = Record[1];
61777d523365SDimitry Andric       unsigned InstCount = Record[2];
61783ca95b02SDimitry Andric       unsigned NumRefs = Record[3];
61793ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
61807d523365SDimitry Andric       std::unique_ptr<FunctionSummary> FS =
61813ca95b02SDimitry Andric           llvm::make_unique<FunctionSummary>(Flags, InstCount);
61827d523365SDimitry Andric       // The module path string ref set in the summary must be owned by the
61837d523365SDimitry Andric       // index's module string table. Since we don't have a module path
61847d523365SDimitry Andric       // string table section in the per-module index, we create a single
61857d523365SDimitry Andric       // module path string table entry with an empty (0) ID to take
61867d523365SDimitry Andric       // ownership.
61877d523365SDimitry Andric       FS->setModulePath(
61883ca95b02SDimitry Andric           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
61893ca95b02SDimitry Andric       static int RefListStartIndex = 4;
61903ca95b02SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
61913ca95b02SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
61923ca95b02SDimitry Andric              "Record size inconsistent with number of references");
61933ca95b02SDimitry Andric       for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
61943ca95b02SDimitry Andric         unsigned RefValueId = Record[I];
61953ca95b02SDimitry Andric         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
61963ca95b02SDimitry Andric         FS->addRefEdge(RefGUID);
61977d523365SDimitry Andric       }
61983ca95b02SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
61993ca95b02SDimitry Andric       for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
62003ca95b02SDimitry Andric            ++I) {
62013ca95b02SDimitry Andric         unsigned CalleeValueId = Record[I];
62023ca95b02SDimitry Andric         unsigned CallsiteCount = Record[++I];
62033ca95b02SDimitry Andric         uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
62043ca95b02SDimitry Andric         GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
62053ca95b02SDimitry Andric         FS->addCallGraphEdge(CalleeGUID,
62063ca95b02SDimitry Andric                              CalleeInfo(CallsiteCount, ProfileCount));
62073ca95b02SDimitry Andric       }
62083ca95b02SDimitry Andric       auto GUID = getGUIDFromValueId(ValueID);
62093ca95b02SDimitry Andric       FS->setOriginalName(GUID.second);
62103ca95b02SDimitry Andric       TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
62113ca95b02SDimitry Andric       break;
62123ca95b02SDimitry Andric     }
62133ca95b02SDimitry Andric     // FS_ALIAS: [valueid, flags, valueid]
62143ca95b02SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
62153ca95b02SDimitry Andric     // they expect all aliasee summaries to be available.
62163ca95b02SDimitry Andric     case bitc::FS_ALIAS: {
62173ca95b02SDimitry Andric       unsigned ValueID = Record[0];
62183ca95b02SDimitry Andric       uint64_t RawFlags = Record[1];
62193ca95b02SDimitry Andric       unsigned AliaseeID = Record[2];
62203ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
62213ca95b02SDimitry Andric       std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
62223ca95b02SDimitry Andric       // The module path string ref set in the summary must be owned by the
62233ca95b02SDimitry Andric       // index's module string table. Since we don't have a module path
62243ca95b02SDimitry Andric       // string table section in the per-module index, we create a single
62253ca95b02SDimitry Andric       // module path string table entry with an empty (0) ID to take
62263ca95b02SDimitry Andric       // ownership.
62273ca95b02SDimitry Andric       AS->setModulePath(
62283ca95b02SDimitry Andric           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
62293ca95b02SDimitry Andric 
62303ca95b02SDimitry Andric       GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
62313ca95b02SDimitry Andric       auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID);
62323ca95b02SDimitry Andric       if (!AliaseeSummary)
62333ca95b02SDimitry Andric         return error("Alias expects aliasee summary to be parsed");
62343ca95b02SDimitry Andric       AS->setAliasee(AliaseeSummary);
62353ca95b02SDimitry Andric 
62363ca95b02SDimitry Andric       auto GUID = getGUIDFromValueId(ValueID);
62373ca95b02SDimitry Andric       AS->setOriginalName(GUID.second);
62383ca95b02SDimitry Andric       TheIndex->addGlobalValueSummary(GUID.first, std::move(AS));
62393ca95b02SDimitry Andric       break;
62403ca95b02SDimitry Andric     }
62413ca95b02SDimitry Andric     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
62423ca95b02SDimitry Andric     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
62433ca95b02SDimitry Andric       unsigned ValueID = Record[0];
62443ca95b02SDimitry Andric       uint64_t RawFlags = Record[1];
62453ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
62463ca95b02SDimitry Andric       std::unique_ptr<GlobalVarSummary> FS =
62473ca95b02SDimitry Andric           llvm::make_unique<GlobalVarSummary>(Flags);
62483ca95b02SDimitry Andric       FS->setModulePath(
62493ca95b02SDimitry Andric           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
62503ca95b02SDimitry Andric       for (unsigned I = 2, E = Record.size(); I != E; ++I) {
62513ca95b02SDimitry Andric         unsigned RefValueId = Record[I];
62523ca95b02SDimitry Andric         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
62533ca95b02SDimitry Andric         FS->addRefEdge(RefGUID);
62543ca95b02SDimitry Andric       }
62553ca95b02SDimitry Andric       auto GUID = getGUIDFromValueId(ValueID);
62563ca95b02SDimitry Andric       FS->setOriginalName(GUID.second);
62573ca95b02SDimitry Andric       TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
62583ca95b02SDimitry Andric       break;
62593ca95b02SDimitry Andric     }
62603ca95b02SDimitry Andric     // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
62613ca95b02SDimitry Andric     //               numrefs x valueid, n x (valueid, callsitecount)]
62623ca95b02SDimitry Andric     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
62633ca95b02SDimitry Andric     //                       numrefs x valueid,
62643ca95b02SDimitry Andric     //                       n x (valueid, callsitecount, profilecount)]
62653ca95b02SDimitry Andric     case bitc::FS_COMBINED:
62663ca95b02SDimitry Andric     case bitc::FS_COMBINED_PROFILE: {
62673ca95b02SDimitry Andric       unsigned ValueID = Record[0];
62683ca95b02SDimitry Andric       uint64_t ModuleId = Record[1];
62693ca95b02SDimitry Andric       uint64_t RawFlags = Record[2];
62703ca95b02SDimitry Andric       unsigned InstCount = Record[3];
62713ca95b02SDimitry Andric       unsigned NumRefs = Record[4];
62723ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
62737d523365SDimitry Andric       std::unique_ptr<FunctionSummary> FS =
62743ca95b02SDimitry Andric           llvm::make_unique<FunctionSummary>(Flags, InstCount);
62753ca95b02SDimitry Andric       LastSeenSummary = FS.get();
62767d523365SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
62773ca95b02SDimitry Andric       static int RefListStartIndex = 5;
62783ca95b02SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
62793ca95b02SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
62803ca95b02SDimitry Andric              "Record size inconsistent with number of references");
62813ca95b02SDimitry Andric       for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E;
62823ca95b02SDimitry Andric            ++I) {
62833ca95b02SDimitry Andric         unsigned RefValueId = Record[I];
62843ca95b02SDimitry Andric         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
62853ca95b02SDimitry Andric         FS->addRefEdge(RefGUID);
62863ca95b02SDimitry Andric       }
62873ca95b02SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
62883ca95b02SDimitry Andric       for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
62893ca95b02SDimitry Andric            ++I) {
62903ca95b02SDimitry Andric         unsigned CalleeValueId = Record[I];
62913ca95b02SDimitry Andric         unsigned CallsiteCount = Record[++I];
62923ca95b02SDimitry Andric         uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
62933ca95b02SDimitry Andric         GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
62943ca95b02SDimitry Andric         FS->addCallGraphEdge(CalleeGUID,
62953ca95b02SDimitry Andric                              CalleeInfo(CallsiteCount, ProfileCount));
62963ca95b02SDimitry Andric       }
62973ca95b02SDimitry Andric       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
62983ca95b02SDimitry Andric       TheIndex->addGlobalValueSummary(GUID, std::move(FS));
62993ca95b02SDimitry Andric       Combined = true;
63003ca95b02SDimitry Andric       break;
63013ca95b02SDimitry Andric     }
63023ca95b02SDimitry Andric     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
63033ca95b02SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
63043ca95b02SDimitry Andric     // they expect all aliasee summaries to be available.
63053ca95b02SDimitry Andric     case bitc::FS_COMBINED_ALIAS: {
63063ca95b02SDimitry Andric       unsigned ValueID = Record[0];
63073ca95b02SDimitry Andric       uint64_t ModuleId = Record[1];
63083ca95b02SDimitry Andric       uint64_t RawFlags = Record[2];
63093ca95b02SDimitry Andric       unsigned AliaseeValueId = Record[3];
63103ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
63113ca95b02SDimitry Andric       std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
63123ca95b02SDimitry Andric       LastSeenSummary = AS.get();
63133ca95b02SDimitry Andric       AS->setModulePath(ModuleIdMap[ModuleId]);
63143ca95b02SDimitry Andric 
63153ca95b02SDimitry Andric       auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
63163ca95b02SDimitry Andric       auto AliaseeInModule =
63173ca95b02SDimitry Andric           TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath());
63183ca95b02SDimitry Andric       if (!AliaseeInModule)
63193ca95b02SDimitry Andric         return error("Alias expects aliasee summary to be parsed");
63203ca95b02SDimitry Andric       AS->setAliasee(AliaseeInModule);
63213ca95b02SDimitry Andric 
63223ca95b02SDimitry Andric       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
63233ca95b02SDimitry Andric       TheIndex->addGlobalValueSummary(GUID, std::move(AS));
63243ca95b02SDimitry Andric       Combined = true;
63253ca95b02SDimitry Andric       break;
63263ca95b02SDimitry Andric     }
63273ca95b02SDimitry Andric     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
63283ca95b02SDimitry Andric     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
63293ca95b02SDimitry Andric       unsigned ValueID = Record[0];
63303ca95b02SDimitry Andric       uint64_t ModuleId = Record[1];
63313ca95b02SDimitry Andric       uint64_t RawFlags = Record[2];
63323ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
63333ca95b02SDimitry Andric       std::unique_ptr<GlobalVarSummary> FS =
63343ca95b02SDimitry Andric           llvm::make_unique<GlobalVarSummary>(Flags);
63353ca95b02SDimitry Andric       LastSeenSummary = FS.get();
63363ca95b02SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
63373ca95b02SDimitry Andric       for (unsigned I = 3, E = Record.size(); I != E; ++I) {
63383ca95b02SDimitry Andric         unsigned RefValueId = Record[I];
63393ca95b02SDimitry Andric         GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
63403ca95b02SDimitry Andric         FS->addRefEdge(RefGUID);
63413ca95b02SDimitry Andric       }
63423ca95b02SDimitry Andric       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
63433ca95b02SDimitry Andric       TheIndex->addGlobalValueSummary(GUID, std::move(FS));
63443ca95b02SDimitry Andric       Combined = true;
63453ca95b02SDimitry Andric       break;
63463ca95b02SDimitry Andric     }
63473ca95b02SDimitry Andric     // FS_COMBINED_ORIGINAL_NAME: [original_name]
63483ca95b02SDimitry Andric     case bitc::FS_COMBINED_ORIGINAL_NAME: {
63493ca95b02SDimitry Andric       uint64_t OriginalName = Record[0];
63503ca95b02SDimitry Andric       if (!LastSeenSummary)
63513ca95b02SDimitry Andric         return error("Name attachment that does not follow a combined record");
63523ca95b02SDimitry Andric       LastSeenSummary->setOriginalName(OriginalName);
63533ca95b02SDimitry Andric       // Reset the LastSeenSummary
63543ca95b02SDimitry Andric       LastSeenSummary = nullptr;
63557d523365SDimitry Andric     }
63567d523365SDimitry Andric     }
63577d523365SDimitry Andric   }
63587d523365SDimitry Andric   llvm_unreachable("Exit infinite loop");
63597d523365SDimitry Andric }
63607d523365SDimitry Andric 
63617d523365SDimitry Andric // Parse the  module string table block into the Index.
63627d523365SDimitry Andric // This populates the ModulePathStringTable map in the index.
63633ca95b02SDimitry Andric std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
63647d523365SDimitry Andric   if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
63657d523365SDimitry Andric     return error("Invalid record");
63667d523365SDimitry Andric 
63677d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
63687d523365SDimitry Andric 
63697d523365SDimitry Andric   SmallString<128> ModulePath;
63703ca95b02SDimitry Andric   ModulePathStringTableTy::iterator LastSeenModulePath;
63717d523365SDimitry Andric   while (1) {
63727d523365SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
63737d523365SDimitry Andric 
63747d523365SDimitry Andric     switch (Entry.Kind) {
63757d523365SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
63767d523365SDimitry Andric     case BitstreamEntry::Error:
63777d523365SDimitry Andric       return error("Malformed block");
63787d523365SDimitry Andric     case BitstreamEntry::EndBlock:
63797d523365SDimitry Andric       return std::error_code();
63807d523365SDimitry Andric     case BitstreamEntry::Record:
63817d523365SDimitry Andric       // The interesting case.
63827d523365SDimitry Andric       break;
63837d523365SDimitry Andric     }
63847d523365SDimitry Andric 
63857d523365SDimitry Andric     Record.clear();
63867d523365SDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
63877d523365SDimitry Andric     default: // Default behavior: ignore.
63887d523365SDimitry Andric       break;
63897d523365SDimitry Andric     case bitc::MST_CODE_ENTRY: {
63907d523365SDimitry Andric       // MST_ENTRY: [modid, namechar x N]
63913ca95b02SDimitry Andric       uint64_t ModuleId = Record[0];
63923ca95b02SDimitry Andric 
63937d523365SDimitry Andric       if (convertToString(Record, 1, ModulePath))
63947d523365SDimitry Andric         return error("Invalid record");
63953ca95b02SDimitry Andric 
63963ca95b02SDimitry Andric       LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
63973ca95b02SDimitry Andric       ModuleIdMap[ModuleId] = LastSeenModulePath->first();
63983ca95b02SDimitry Andric 
63997d523365SDimitry Andric       ModulePath.clear();
64007d523365SDimitry Andric       break;
64017d523365SDimitry Andric     }
64023ca95b02SDimitry Andric     /// MST_CODE_HASH: [5*i32]
64033ca95b02SDimitry Andric     case bitc::MST_CODE_HASH: {
64043ca95b02SDimitry Andric       if (Record.size() != 5)
64053ca95b02SDimitry Andric         return error("Invalid hash length " + Twine(Record.size()).str());
64063ca95b02SDimitry Andric       if (LastSeenModulePath == TheIndex->modulePaths().end())
64073ca95b02SDimitry Andric         return error("Invalid hash that does not follow a module path");
64083ca95b02SDimitry Andric       int Pos = 0;
64093ca95b02SDimitry Andric       for (auto &Val : Record) {
64103ca95b02SDimitry Andric         assert(!(Val >> 32) && "Unexpected high bits set");
64113ca95b02SDimitry Andric         LastSeenModulePath->second.second[Pos++] = Val;
64123ca95b02SDimitry Andric       }
64133ca95b02SDimitry Andric       // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
64143ca95b02SDimitry Andric       LastSeenModulePath = TheIndex->modulePaths().end();
64153ca95b02SDimitry Andric       break;
64163ca95b02SDimitry Andric     }
64177d523365SDimitry Andric     }
64187d523365SDimitry Andric   }
64197d523365SDimitry Andric   llvm_unreachable("Exit infinite loop");
64207d523365SDimitry Andric }
64217d523365SDimitry Andric 
64227d523365SDimitry Andric // Parse the function info index from the bitcode streamer into the given index.
64233ca95b02SDimitry Andric std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
64243ca95b02SDimitry Andric     std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
64257d523365SDimitry Andric   TheIndex = I;
64267d523365SDimitry Andric 
64277d523365SDimitry Andric   if (std::error_code EC = initStream(std::move(Streamer)))
64287d523365SDimitry Andric     return EC;
64297d523365SDimitry Andric 
64307d523365SDimitry Andric   // Sniff for the signature.
64317d523365SDimitry Andric   if (!hasValidBitcodeHeader(Stream))
64327d523365SDimitry Andric     return error("Invalid bitcode signature");
64337d523365SDimitry Andric 
64347d523365SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
64357d523365SDimitry Andric   // need to understand them all.
64367d523365SDimitry Andric   while (1) {
64377d523365SDimitry Andric     if (Stream.AtEndOfStream()) {
64387d523365SDimitry Andric       // We didn't really read a proper Module block.
64397d523365SDimitry Andric       return error("Malformed block");
64407d523365SDimitry Andric     }
64417d523365SDimitry Andric 
64427d523365SDimitry Andric     BitstreamEntry Entry =
64437d523365SDimitry Andric         Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
64447d523365SDimitry Andric 
64457d523365SDimitry Andric     if (Entry.Kind != BitstreamEntry::SubBlock)
64467d523365SDimitry Andric       return error("Malformed block");
64477d523365SDimitry Andric 
64487d523365SDimitry Andric     // If we see a MODULE_BLOCK, parse it to find the blocks needed for
64497d523365SDimitry Andric     // building the function summary index.
64507d523365SDimitry Andric     if (Entry.ID == bitc::MODULE_BLOCK_ID)
64517d523365SDimitry Andric       return parseModule();
64527d523365SDimitry Andric 
64537d523365SDimitry Andric     if (Stream.SkipBlock())
64547d523365SDimitry Andric       return error("Invalid record");
64557d523365SDimitry Andric   }
64567d523365SDimitry Andric }
64577d523365SDimitry Andric 
64583ca95b02SDimitry Andric std::error_code ModuleSummaryIndexBitcodeReader::initStream(
64593ca95b02SDimitry Andric     std::unique_ptr<DataStreamer> Streamer) {
64607d523365SDimitry Andric   if (Streamer)
64617d523365SDimitry Andric     return initLazyStream(std::move(Streamer));
64627d523365SDimitry Andric   return initStreamFromBuffer();
64637d523365SDimitry Andric }
64647d523365SDimitry Andric 
64653ca95b02SDimitry Andric std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
64667d523365SDimitry Andric   const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
64677d523365SDimitry Andric   const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
64687d523365SDimitry Andric 
64697d523365SDimitry Andric   if (Buffer->getBufferSize() & 3)
64707d523365SDimitry Andric     return error("Invalid bitcode signature");
64717d523365SDimitry Andric 
64727d523365SDimitry Andric   // If we have a wrapper header, parse it and ignore the non-bc file contents.
64737d523365SDimitry Andric   // The magic number is 0x0B17C0DE stored in little endian.
64747d523365SDimitry Andric   if (isBitcodeWrapper(BufPtr, BufEnd))
64757d523365SDimitry Andric     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
64767d523365SDimitry Andric       return error("Invalid bitcode wrapper header");
64777d523365SDimitry Andric 
64787d523365SDimitry Andric   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
64797d523365SDimitry Andric   Stream.init(&*StreamFile);
64807d523365SDimitry Andric 
64817d523365SDimitry Andric   return std::error_code();
64827d523365SDimitry Andric }
64837d523365SDimitry Andric 
64843ca95b02SDimitry Andric std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
64857d523365SDimitry Andric     std::unique_ptr<DataStreamer> Streamer) {
64867d523365SDimitry Andric   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
64877d523365SDimitry Andric   // see it.
64887d523365SDimitry Andric   auto OwnedBytes =
64897d523365SDimitry Andric       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
64907d523365SDimitry Andric   StreamingMemoryObject &Bytes = *OwnedBytes;
64917d523365SDimitry Andric   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
64927d523365SDimitry Andric   Stream.init(&*StreamFile);
64937d523365SDimitry Andric 
64947d523365SDimitry Andric   unsigned char buf[16];
64957d523365SDimitry Andric   if (Bytes.readBytes(buf, 16, 0) != 16)
64967d523365SDimitry Andric     return error("Invalid bitcode signature");
64977d523365SDimitry Andric 
64987d523365SDimitry Andric   if (!isBitcode(buf, buf + 16))
64997d523365SDimitry Andric     return error("Invalid bitcode signature");
65007d523365SDimitry Andric 
65017d523365SDimitry Andric   if (isBitcodeWrapper(buf, buf + 4)) {
65027d523365SDimitry Andric     const unsigned char *bitcodeStart = buf;
65037d523365SDimitry Andric     const unsigned char *bitcodeEnd = buf + 16;
65047d523365SDimitry Andric     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
65057d523365SDimitry Andric     Bytes.dropLeadingBytes(bitcodeStart - buf);
65067d523365SDimitry Andric     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
65077d523365SDimitry Andric   }
65087d523365SDimitry Andric   return std::error_code();
65097d523365SDimitry Andric }
65107d523365SDimitry Andric 
6511f785676fSDimitry Andric namespace {
65123ca95b02SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
65133ca95b02SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
65143ca95b02SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
651591bc56edSDimitry Andric class BitcodeErrorCategoryType : public std::error_category {
651691bc56edSDimitry Andric   const char *name() const LLVM_NOEXCEPT override {
6517f785676fSDimitry Andric     return "llvm.bitcode";
6518f785676fSDimitry Andric   }
651991bc56edSDimitry Andric   std::string message(int IE) const override {
652039d628a0SDimitry Andric     BitcodeError E = static_cast<BitcodeError>(IE);
6521f785676fSDimitry Andric     switch (E) {
652239d628a0SDimitry Andric     case BitcodeError::InvalidBitcodeSignature:
6523f785676fSDimitry Andric       return "Invalid bitcode signature";
652439d628a0SDimitry Andric     case BitcodeError::CorruptedBitcode:
652539d628a0SDimitry Andric       return "Corrupted bitcode";
6526f785676fSDimitry Andric     }
6527f785676fSDimitry Andric     llvm_unreachable("Unknown error type!");
6528f785676fSDimitry Andric   }
6529f785676fSDimitry Andric };
65303ca95b02SDimitry Andric } // end anonymous namespace
6531f785676fSDimitry Andric 
653239d628a0SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
653339d628a0SDimitry Andric 
653439d628a0SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() {
653539d628a0SDimitry Andric   return *ErrorCategory;
6536dff0c46cSDimitry Andric }
6537f22ef01cSRoman Divacky 
6538f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
6539f22ef01cSRoman Divacky // External interface
6540f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
6541f22ef01cSRoman Divacky 
65428f0fd8f6SDimitry Andric static ErrorOr<std::unique_ptr<Module>>
65438f0fd8f6SDimitry Andric getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
65448f0fd8f6SDimitry Andric                      BitcodeReader *R, LLVMContext &Context,
65458f0fd8f6SDimitry Andric                      bool MaterializeAll, bool ShouldLazyLoadMetadata) {
65468f0fd8f6SDimitry Andric   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
65478f0fd8f6SDimitry Andric   M->setMaterializer(R);
65488f0fd8f6SDimitry Andric 
65498f0fd8f6SDimitry Andric   auto cleanupOnError = [&](std::error_code EC) {
65508f0fd8f6SDimitry Andric     R->releaseBuffer(); // Never take ownership on error.
65518f0fd8f6SDimitry Andric     return EC;
65528f0fd8f6SDimitry Andric   };
65538f0fd8f6SDimitry Andric 
65548f0fd8f6SDimitry Andric   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
65558f0fd8f6SDimitry Andric   if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
65568f0fd8f6SDimitry Andric                                                ShouldLazyLoadMetadata))
65578f0fd8f6SDimitry Andric     return cleanupOnError(EC);
65588f0fd8f6SDimitry Andric 
65598f0fd8f6SDimitry Andric   if (MaterializeAll) {
65608f0fd8f6SDimitry Andric     // Read in the entire module, and destroy the BitcodeReader.
65617d523365SDimitry Andric     if (std::error_code EC = M->materializeAll())
65628f0fd8f6SDimitry Andric       return cleanupOnError(EC);
65638f0fd8f6SDimitry Andric   } else {
65648f0fd8f6SDimitry Andric     // Resolve forward references from blockaddresses.
65658f0fd8f6SDimitry Andric     if (std::error_code EC = R->materializeForwardReferencedFunctions())
65668f0fd8f6SDimitry Andric       return cleanupOnError(EC);
65678f0fd8f6SDimitry Andric   }
65688f0fd8f6SDimitry Andric   return std::move(M);
65698f0fd8f6SDimitry Andric }
65708f0fd8f6SDimitry Andric 
657139d628a0SDimitry Andric /// \brief Get a lazy one-at-time loading module from bitcode.
6572f22ef01cSRoman Divacky ///
657339d628a0SDimitry Andric /// This isn't always used in a lazy context.  In particular, it's also used by
657439d628a0SDimitry Andric /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
657539d628a0SDimitry Andric /// in forward-referenced functions from block address references.
657639d628a0SDimitry Andric ///
65778f0fd8f6SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize
65788f0fd8f6SDimitry Andric /// everything.
65798f0fd8f6SDimitry Andric static ErrorOr<std::unique_ptr<Module>>
658039d628a0SDimitry Andric getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
65818f0fd8f6SDimitry Andric                          LLVMContext &Context, bool MaterializeAll,
6582ff0cc061SDimitry Andric                          bool ShouldLazyLoadMetadata = false) {
65837d523365SDimitry Andric   BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
658439d628a0SDimitry Andric 
65858f0fd8f6SDimitry Andric   ErrorOr<std::unique_ptr<Module>> Ret =
65868f0fd8f6SDimitry Andric       getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
65878f0fd8f6SDimitry Andric                            MaterializeAll, ShouldLazyLoadMetadata);
65888f0fd8f6SDimitry Andric   if (!Ret)
65898f0fd8f6SDimitry Andric     return Ret;
659039d628a0SDimitry Andric 
659139d628a0SDimitry Andric   Buffer.release(); // The BitcodeReader owns it now.
65928f0fd8f6SDimitry Andric   return Ret;
6593dff0c46cSDimitry Andric }
6594dff0c46cSDimitry Andric 
65957d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>>
65967d523365SDimitry Andric llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
65977d523365SDimitry Andric                            LLVMContext &Context, bool ShouldLazyLoadMetadata) {
659839d628a0SDimitry Andric   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
65997d523365SDimitry Andric                                   ShouldLazyLoadMetadata);
6600f22ef01cSRoman Divacky }
6601f22ef01cSRoman Divacky 
66027d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>>
66037d523365SDimitry Andric llvm::getStreamedBitcodeModule(StringRef Name,
66047d523365SDimitry Andric                                std::unique_ptr<DataStreamer> Streamer,
66057d523365SDimitry Andric                                LLVMContext &Context) {
660639d628a0SDimitry Andric   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
66077d523365SDimitry Andric   BitcodeReader *R = new BitcodeReader(Context);
66088f0fd8f6SDimitry Andric 
66098f0fd8f6SDimitry Andric   return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
66108f0fd8f6SDimitry Andric                               false);
661139d628a0SDimitry Andric }
661239d628a0SDimitry Andric 
66137d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
66147d523365SDimitry Andric                                                         LLVMContext &Context) {
661539d628a0SDimitry Andric   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
66167d523365SDimitry Andric   return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
6617dff0c46cSDimitry Andric   // TODO: Restore the use-lists to the in-memory state when the bitcode was
6618dff0c46cSDimitry Andric   // written.  We must defer until the Module has been fully materialized.
6619f22ef01cSRoman Divacky }
66202754fe60SDimitry Andric 
66217d523365SDimitry Andric std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
66227d523365SDimitry Andric                                          LLVMContext &Context) {
662339d628a0SDimitry Andric   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
66247d523365SDimitry Andric   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
662591bc56edSDimitry Andric   ErrorOr<std::string> Triple = R->parseTriple();
662691bc56edSDimitry Andric   if (Triple.getError())
662791bc56edSDimitry Andric     return "";
662891bc56edSDimitry Andric   return Triple.get();
66292754fe60SDimitry Andric }
66307d523365SDimitry Andric 
66313ca95b02SDimitry Andric bool llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer,
66323ca95b02SDimitry Andric                                            LLVMContext &Context) {
66333ca95b02SDimitry Andric   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
66343ca95b02SDimitry Andric   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
66353ca95b02SDimitry Andric   ErrorOr<bool> hasObjCCategory = R->hasObjCCategory();
66363ca95b02SDimitry Andric   if (hasObjCCategory.getError())
66373ca95b02SDimitry Andric     return false;
66383ca95b02SDimitry Andric   return hasObjCCategory.get();
66393ca95b02SDimitry Andric }
66403ca95b02SDimitry Andric 
66417d523365SDimitry Andric std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
66427d523365SDimitry Andric                                            LLVMContext &Context) {
66437d523365SDimitry Andric   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
66447d523365SDimitry Andric   BitcodeReader R(Buf.release(), Context);
66457d523365SDimitry Andric   ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
66467d523365SDimitry Andric   if (ProducerString.getError())
66477d523365SDimitry Andric     return "";
66487d523365SDimitry Andric   return ProducerString.get();
66497d523365SDimitry Andric }
66507d523365SDimitry Andric 
66517d523365SDimitry Andric // Parse the specified bitcode buffer, returning the function info index.
66523ca95b02SDimitry Andric ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex(
66533ca95b02SDimitry Andric     MemoryBufferRef Buffer,
66543ca95b02SDimitry Andric     const DiagnosticHandlerFunction &DiagnosticHandler) {
66557d523365SDimitry Andric   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
66563ca95b02SDimitry Andric   ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
66577d523365SDimitry Andric 
66583ca95b02SDimitry Andric   auto Index = llvm::make_unique<ModuleSummaryIndex>();
66597d523365SDimitry Andric 
66607d523365SDimitry Andric   auto cleanupOnError = [&](std::error_code EC) {
66617d523365SDimitry Andric     R.releaseBuffer(); // Never take ownership on error.
66627d523365SDimitry Andric     return EC;
66637d523365SDimitry Andric   };
66647d523365SDimitry Andric 
66657d523365SDimitry Andric   if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
66667d523365SDimitry Andric     return cleanupOnError(EC);
66677d523365SDimitry Andric 
66683ca95b02SDimitry Andric   Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
66697d523365SDimitry Andric   return std::move(Index);
66707d523365SDimitry Andric }
66717d523365SDimitry Andric 
66723ca95b02SDimitry Andric // Check if the given bitcode buffer contains a global value summary block.
66733ca95b02SDimitry Andric bool llvm::hasGlobalValueSummary(
66743ca95b02SDimitry Andric     MemoryBufferRef Buffer,
66753ca95b02SDimitry Andric     const DiagnosticHandlerFunction &DiagnosticHandler) {
66767d523365SDimitry Andric   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
66773ca95b02SDimitry Andric   ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, true);
66787d523365SDimitry Andric 
66797d523365SDimitry Andric   auto cleanupOnError = [&](std::error_code EC) {
66807d523365SDimitry Andric     R.releaseBuffer(); // Never take ownership on error.
66817d523365SDimitry Andric     return false;
66827d523365SDimitry Andric   };
66837d523365SDimitry Andric 
66847d523365SDimitry Andric   if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
66857d523365SDimitry Andric     return cleanupOnError(EC);
66867d523365SDimitry Andric 
66873ca95b02SDimitry Andric   Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
66883ca95b02SDimitry Andric   return R.foundGlobalValSummary();
66897d523365SDimitry Andric }
6690