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 10f22ef01cSRoman Divacky #include "llvm/Bitcode/ReaderWriter.h" 11ff0cc061SDimitry Andric #include "llvm/ADT/STLExtras.h" 12f22ef01cSRoman Divacky #include "llvm/ADT/SmallString.h" 13f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h" 14ff0cc061SDimitry Andric #include "llvm/ADT/Triple.h" 15ff0cc061SDimitry Andric #include "llvm/Bitcode/BitstreamReader.h" 16f785676fSDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h" 1791bc56edSDimitry Andric #include "llvm/IR/AutoUpgrade.h" 18139f7f9bSDimitry Andric #include "llvm/IR/Constants.h" 19ff0cc061SDimitry Andric #include "llvm/IR/DebugInfo.h" 20ff0cc061SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 21139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h" 2239d628a0SDimitry Andric #include "llvm/IR/DiagnosticPrinter.h" 23ff0cc061SDimitry Andric #include "llvm/IR/GVMaterializer.h" 24139f7f9bSDimitry Andric #include "llvm/IR/InlineAsm.h" 25139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h" 26f785676fSDimitry Andric #include "llvm/IR/LLVMContext.h" 27139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 28139f7f9bSDimitry Andric #include "llvm/IR/OperandTraits.h" 29139f7f9bSDimitry Andric #include "llvm/IR/Operator.h" 307d523365SDimitry Andric #include "llvm/IR/FunctionInfo.h" 31ff0cc061SDimitry Andric #include "llvm/IR/ValueHandle.h" 32dff0c46cSDimitry Andric #include "llvm/Support/DataStream.h" 3339d628a0SDimitry Andric #include "llvm/Support/ManagedStatic.h" 34f22ef01cSRoman Divacky #include "llvm/Support/MathExtras.h" 35f22ef01cSRoman Divacky #include "llvm/Support/MemoryBuffer.h" 36f785676fSDimitry Andric #include "llvm/Support/raw_ostream.h" 37ff0cc061SDimitry Andric #include <deque> 38f22ef01cSRoman Divacky using namespace llvm; 39f22ef01cSRoman Divacky 40ff0cc061SDimitry Andric namespace { 417ae0e2c9SDimitry Andric enum { 427ae0e2c9SDimitry Andric SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 437ae0e2c9SDimitry Andric }; 447ae0e2c9SDimitry Andric 45ff0cc061SDimitry Andric class BitcodeReaderValueList { 46ff0cc061SDimitry Andric std::vector<WeakVH> ValuePtrs; 47ff0cc061SDimitry Andric 488f0fd8f6SDimitry Andric /// As we resolve forward-referenced constants, we add information about them 498f0fd8f6SDimitry Andric /// to this vector. This allows us to resolve them in bulk instead of 508f0fd8f6SDimitry Andric /// resolving each reference at a time. See the code in 51ff0cc061SDimitry Andric /// ResolveConstantForwardRefs for more information about this. 52ff0cc061SDimitry Andric /// 53ff0cc061SDimitry Andric /// The key of this vector is the placeholder constant, the value is the slot 54ff0cc061SDimitry Andric /// number that holds the resolved value. 55ff0cc061SDimitry Andric typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy; 56ff0cc061SDimitry Andric ResolveConstantsTy ResolveConstants; 57ff0cc061SDimitry Andric LLVMContext &Context; 58ff0cc061SDimitry Andric public: 59ff0cc061SDimitry Andric BitcodeReaderValueList(LLVMContext &C) : Context(C) {} 60ff0cc061SDimitry Andric ~BitcodeReaderValueList() { 61ff0cc061SDimitry Andric assert(ResolveConstants.empty() && "Constants not resolved?"); 62ff0cc061SDimitry Andric } 63ff0cc061SDimitry Andric 64ff0cc061SDimitry Andric // vector compatibility methods 65ff0cc061SDimitry Andric unsigned size() const { return ValuePtrs.size(); } 66ff0cc061SDimitry Andric void resize(unsigned N) { ValuePtrs.resize(N); } 6797bc6c73SDimitry Andric void push_back(Value *V) { ValuePtrs.emplace_back(V); } 68ff0cc061SDimitry Andric 69ff0cc061SDimitry Andric void clear() { 70ff0cc061SDimitry Andric assert(ResolveConstants.empty() && "Constants not resolved?"); 71ff0cc061SDimitry Andric ValuePtrs.clear(); 72ff0cc061SDimitry Andric } 73ff0cc061SDimitry Andric 74ff0cc061SDimitry Andric Value *operator[](unsigned i) const { 75ff0cc061SDimitry Andric assert(i < ValuePtrs.size()); 76ff0cc061SDimitry Andric return ValuePtrs[i]; 77ff0cc061SDimitry Andric } 78ff0cc061SDimitry Andric 79ff0cc061SDimitry Andric Value *back() const { return ValuePtrs.back(); } 80ff0cc061SDimitry Andric void pop_back() { ValuePtrs.pop_back(); } 81ff0cc061SDimitry Andric bool empty() const { return ValuePtrs.empty(); } 82ff0cc061SDimitry Andric void shrinkTo(unsigned N) { 83ff0cc061SDimitry Andric assert(N <= size() && "Invalid shrinkTo request!"); 84ff0cc061SDimitry Andric ValuePtrs.resize(N); 85ff0cc061SDimitry Andric } 86ff0cc061SDimitry Andric 87ff0cc061SDimitry Andric Constant *getConstantFwdRef(unsigned Idx, Type *Ty); 88ff0cc061SDimitry Andric Value *getValueFwdRef(unsigned Idx, Type *Ty); 89ff0cc061SDimitry Andric 908f0fd8f6SDimitry Andric void assignValue(Value *V, unsigned Idx); 91ff0cc061SDimitry Andric 928f0fd8f6SDimitry Andric /// Once all constants are read, this method bulk resolves any forward 938f0fd8f6SDimitry Andric /// references. 948f0fd8f6SDimitry Andric void resolveConstantForwardRefs(); 95ff0cc061SDimitry Andric }; 96ff0cc061SDimitry Andric 977d523365SDimitry Andric class BitcodeReaderMetadataList { 98ff0cc061SDimitry Andric unsigned NumFwdRefs; 99ff0cc061SDimitry Andric bool AnyFwdRefs; 100ff0cc061SDimitry Andric unsigned MinFwdRef; 101ff0cc061SDimitry Andric unsigned MaxFwdRef; 1027d523365SDimitry Andric std::vector<TrackingMDRef> MetadataPtrs; 103ff0cc061SDimitry Andric 104ff0cc061SDimitry Andric LLVMContext &Context; 105ff0cc061SDimitry Andric public: 1067d523365SDimitry Andric BitcodeReaderMetadataList(LLVMContext &C) 107ff0cc061SDimitry Andric : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {} 108ff0cc061SDimitry Andric 109ff0cc061SDimitry Andric // vector compatibility methods 1107d523365SDimitry Andric unsigned size() const { return MetadataPtrs.size(); } 1117d523365SDimitry Andric void resize(unsigned N) { MetadataPtrs.resize(N); } 1127d523365SDimitry Andric void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); } 1137d523365SDimitry Andric void clear() { MetadataPtrs.clear(); } 1147d523365SDimitry Andric Metadata *back() const { return MetadataPtrs.back(); } 1157d523365SDimitry Andric void pop_back() { MetadataPtrs.pop_back(); } 1167d523365SDimitry Andric bool empty() const { return MetadataPtrs.empty(); } 117ff0cc061SDimitry Andric 118ff0cc061SDimitry Andric Metadata *operator[](unsigned i) const { 1197d523365SDimitry Andric assert(i < MetadataPtrs.size()); 1207d523365SDimitry Andric return MetadataPtrs[i]; 121ff0cc061SDimitry Andric } 122ff0cc061SDimitry Andric 123ff0cc061SDimitry Andric void shrinkTo(unsigned N) { 124ff0cc061SDimitry Andric assert(N <= size() && "Invalid shrinkTo request!"); 1257d523365SDimitry Andric MetadataPtrs.resize(N); 126ff0cc061SDimitry Andric } 127ff0cc061SDimitry Andric 128ff0cc061SDimitry Andric Metadata *getValueFwdRef(unsigned Idx); 1298f0fd8f6SDimitry Andric void assignValue(Metadata *MD, unsigned Idx); 130ff0cc061SDimitry Andric void tryToResolveCycles(); 131ff0cc061SDimitry Andric }; 132ff0cc061SDimitry Andric 133ff0cc061SDimitry Andric class BitcodeReader : public GVMaterializer { 134ff0cc061SDimitry Andric LLVMContext &Context; 1358f0fd8f6SDimitry Andric Module *TheModule = nullptr; 136ff0cc061SDimitry Andric std::unique_ptr<MemoryBuffer> Buffer; 137ff0cc061SDimitry Andric std::unique_ptr<BitstreamReader> StreamFile; 138ff0cc061SDimitry Andric BitstreamCursor Stream; 1397d523365SDimitry Andric // Next offset to start scanning for lazy parsing of function bodies. 1408f0fd8f6SDimitry Andric uint64_t NextUnreadBit = 0; 1417d523365SDimitry Andric // Last function offset found in the VST. 1427d523365SDimitry Andric uint64_t LastFunctionBlockBit = 0; 1438f0fd8f6SDimitry Andric bool SeenValueSymbolTable = false; 1447d523365SDimitry Andric uint64_t VSTOffset = 0; 1457d523365SDimitry Andric // Contains an arbitrary and optional string identifying the bitcode producer 1467d523365SDimitry Andric std::string ProducerIdentification; 1477d523365SDimitry Andric // Number of module level metadata records specified by the 1487d523365SDimitry Andric // MODULE_CODE_METADATA_VALUES record. 1497d523365SDimitry Andric unsigned NumModuleMDs = 0; 1507d523365SDimitry Andric // Support older bitcode without the MODULE_CODE_METADATA_VALUES record. 1517d523365SDimitry Andric bool SeenModuleValuesRecord = false; 152ff0cc061SDimitry Andric 153ff0cc061SDimitry Andric std::vector<Type*> TypeList; 154ff0cc061SDimitry Andric BitcodeReaderValueList ValueList; 1557d523365SDimitry Andric BitcodeReaderMetadataList MetadataList; 156ff0cc061SDimitry Andric std::vector<Comdat *> ComdatList; 157ff0cc061SDimitry Andric SmallVector<Instruction *, 64> InstructionList; 158ff0cc061SDimitry Andric 159ff0cc061SDimitry Andric std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits; 160ff0cc061SDimitry Andric std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits; 161ff0cc061SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrefixes; 162ff0cc061SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrologues; 1638f0fd8f6SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns; 164ff0cc061SDimitry Andric 165ff0cc061SDimitry Andric SmallVector<Instruction*, 64> InstsWithTBAATag; 166ff0cc061SDimitry Andric 1678f0fd8f6SDimitry Andric /// The set of attributes by index. Index zero in the file is for null, and 1688f0fd8f6SDimitry Andric /// is thus not represented here. As such all indices are off by one. 169ff0cc061SDimitry Andric std::vector<AttributeSet> MAttributes; 170ff0cc061SDimitry Andric 1717d523365SDimitry Andric /// The set of attribute groups. 172ff0cc061SDimitry Andric std::map<unsigned, AttributeSet> MAttributeGroups; 173ff0cc061SDimitry Andric 1748f0fd8f6SDimitry Andric /// While parsing a function body, this is a list of the basic blocks for the 1758f0fd8f6SDimitry Andric /// function. 176ff0cc061SDimitry Andric std::vector<BasicBlock*> FunctionBBs; 177ff0cc061SDimitry Andric 178ff0cc061SDimitry Andric // When reading the module header, this list is populated with functions that 179ff0cc061SDimitry Andric // have bodies later in the file. 180ff0cc061SDimitry Andric std::vector<Function*> FunctionsWithBodies; 181ff0cc061SDimitry Andric 182ff0cc061SDimitry Andric // When intrinsic functions are encountered which require upgrading they are 183ff0cc061SDimitry Andric // stored here with their replacement function. 1843dac3a9bSDimitry Andric typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap; 185ff0cc061SDimitry Andric UpgradedIntrinsicMap UpgradedIntrinsics; 186ff0cc061SDimitry Andric 187ff0cc061SDimitry Andric // Map the bitcode's custom MDKind ID to the Module's MDKind ID. 188ff0cc061SDimitry Andric DenseMap<unsigned, unsigned> MDKindMap; 189ff0cc061SDimitry Andric 190ff0cc061SDimitry Andric // Several operations happen after the module header has been read, but 191ff0cc061SDimitry Andric // before function bodies are processed. This keeps track of whether 192ff0cc061SDimitry Andric // we've done this yet. 1938f0fd8f6SDimitry Andric bool SeenFirstFunctionBody = false; 194ff0cc061SDimitry Andric 1958f0fd8f6SDimitry Andric /// When function bodies are initially scanned, this map contains info about 1968f0fd8f6SDimitry Andric /// where to find deferred function body in the stream. 197ff0cc061SDimitry Andric DenseMap<Function*, uint64_t> DeferredFunctionInfo; 198ff0cc061SDimitry Andric 199ff0cc061SDimitry Andric /// When Metadata block is initially scanned when parsing the module, we may 200ff0cc061SDimitry Andric /// choose to defer parsing of the metadata. This vector contains info about 201ff0cc061SDimitry Andric /// which Metadata blocks are deferred. 202ff0cc061SDimitry Andric std::vector<uint64_t> DeferredMetadataInfo; 203ff0cc061SDimitry Andric 204ff0cc061SDimitry Andric /// These are basic blocks forward-referenced by block addresses. They are 205ff0cc061SDimitry Andric /// inserted lazily into functions when they're loaded. The basic block ID is 206ff0cc061SDimitry Andric /// its index into the vector. 207ff0cc061SDimitry Andric DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; 208ff0cc061SDimitry Andric std::deque<Function *> BasicBlockFwdRefQueue; 209ff0cc061SDimitry Andric 2108f0fd8f6SDimitry Andric /// Indicates that we are using a new encoding for instruction operands where 2118f0fd8f6SDimitry Andric /// most operands in the current FUNCTION_BLOCK are encoded relative to the 2128f0fd8f6SDimitry Andric /// instruction number, for a more compact encoding. Some instruction 2138f0fd8f6SDimitry Andric /// operands are not relative to the instruction ID: basic block numbers, and 2148f0fd8f6SDimitry Andric /// types. Once the old style function blocks have been phased out, we would 215ff0cc061SDimitry Andric /// not need this flag. 2168f0fd8f6SDimitry Andric bool UseRelativeIDs = false; 217ff0cc061SDimitry Andric 218ff0cc061SDimitry Andric /// True if all functions will be materialized, negating the need to process 219ff0cc061SDimitry Andric /// (e.g.) blockaddress forward references. 2208f0fd8f6SDimitry Andric bool WillMaterializeAllForwardRefs = false; 221ff0cc061SDimitry Andric 222ff0cc061SDimitry Andric /// True if any Metadata block has been materialized. 2238f0fd8f6SDimitry Andric bool IsMetadataMaterialized = false; 224ff0cc061SDimitry Andric 225ff0cc061SDimitry Andric bool StripDebugInfo = false; 226ff0cc061SDimitry Andric 2277d523365SDimitry Andric /// Functions that need to be matched with subprograms when upgrading old 2287d523365SDimitry Andric /// metadata. 2297d523365SDimitry Andric SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs; 2307d523365SDimitry Andric 2317d523365SDimitry Andric std::vector<std::string> BundleTags; 2327d523365SDimitry Andric 233ff0cc061SDimitry Andric public: 2348f0fd8f6SDimitry Andric std::error_code error(BitcodeError E, const Twine &Message); 2358f0fd8f6SDimitry Andric std::error_code error(BitcodeError E); 2368f0fd8f6SDimitry Andric std::error_code error(const Twine &Message); 237ff0cc061SDimitry Andric 2387d523365SDimitry Andric BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context); 2397d523365SDimitry Andric BitcodeReader(LLVMContext &Context); 2408f0fd8f6SDimitry Andric ~BitcodeReader() override { freeState(); } 241ff0cc061SDimitry Andric 242ff0cc061SDimitry Andric std::error_code materializeForwardReferencedFunctions(); 243ff0cc061SDimitry Andric 2448f0fd8f6SDimitry Andric void freeState(); 245ff0cc061SDimitry Andric 246ff0cc061SDimitry Andric void releaseBuffer(); 247ff0cc061SDimitry Andric 248ff0cc061SDimitry Andric std::error_code materialize(GlobalValue *GV) override; 2497d523365SDimitry Andric std::error_code materializeModule() override; 250ff0cc061SDimitry Andric std::vector<StructType *> getIdentifiedStructTypes() const override; 251ff0cc061SDimitry Andric 2528f0fd8f6SDimitry Andric /// \brief Main interface to parsing a bitcode buffer. 2538f0fd8f6SDimitry Andric /// \returns true if an error occurred. 2548f0fd8f6SDimitry Andric std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer, 2558f0fd8f6SDimitry Andric Module *M, 256ff0cc061SDimitry Andric bool ShouldLazyLoadMetadata = false); 257ff0cc061SDimitry Andric 2588f0fd8f6SDimitry Andric /// \brief Cheap mechanism to just extract module triple 2598f0fd8f6SDimitry Andric /// \returns true if an error occurred. 260ff0cc061SDimitry Andric ErrorOr<std::string> parseTriple(); 261ff0cc061SDimitry Andric 2627d523365SDimitry Andric /// Cheap mechanism to just extract the identification block out of bitcode. 2637d523365SDimitry Andric ErrorOr<std::string> parseIdentificationBlock(); 2647d523365SDimitry Andric 265ff0cc061SDimitry Andric static uint64_t decodeSignRotatedValue(uint64_t V); 266ff0cc061SDimitry Andric 267ff0cc061SDimitry Andric /// Materialize any deferred Metadata block. 268ff0cc061SDimitry Andric std::error_code materializeMetadata() override; 269ff0cc061SDimitry Andric 270ff0cc061SDimitry Andric void setStripDebugInfo() override; 271ff0cc061SDimitry Andric 2727d523365SDimitry Andric /// Save the mapping between the metadata values and the corresponding 2737d523365SDimitry Andric /// value id that were recorded in the MetadataList during parsing. If 2747d523365SDimitry Andric /// OnlyTempMD is true, then only record those entries that are still 2757d523365SDimitry Andric /// temporary metadata. This interface is used when metadata linking is 2767d523365SDimitry Andric /// performed as a postpass, such as during function importing. 2777d523365SDimitry Andric void saveMetadataList(DenseMap<const Metadata *, unsigned> &MetadataToIDs, 2787d523365SDimitry Andric bool OnlyTempMD) override; 2797d523365SDimitry Andric 280ff0cc061SDimitry Andric private: 2817d523365SDimitry Andric /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the 2827d523365SDimitry Andric // ProducerIdentification data member, and do some basic enforcement on the 2837d523365SDimitry Andric // "epoch" encoded in the bitcode. 2847d523365SDimitry Andric std::error_code parseBitcodeVersion(); 2857d523365SDimitry Andric 286ff0cc061SDimitry Andric std::vector<StructType *> IdentifiedStructTypes; 287ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 288ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context); 289ff0cc061SDimitry Andric 290ff0cc061SDimitry Andric Type *getTypeByID(unsigned ID); 291ff0cc061SDimitry Andric Value *getFnValueByID(unsigned ID, Type *Ty) { 292ff0cc061SDimitry Andric if (Ty && Ty->isMetadataTy()) 293ff0cc061SDimitry Andric return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 294ff0cc061SDimitry Andric return ValueList.getValueFwdRef(ID, Ty); 295ff0cc061SDimitry Andric } 296ff0cc061SDimitry Andric Metadata *getFnMetadataByID(unsigned ID) { 2977d523365SDimitry Andric return MetadataList.getValueFwdRef(ID); 298ff0cc061SDimitry Andric } 299ff0cc061SDimitry Andric BasicBlock *getBasicBlock(unsigned ID) const { 300ff0cc061SDimitry Andric if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 301ff0cc061SDimitry Andric return FunctionBBs[ID]; 302ff0cc061SDimitry Andric } 303ff0cc061SDimitry Andric AttributeSet getAttributes(unsigned i) const { 304ff0cc061SDimitry Andric if (i-1 < MAttributes.size()) 305ff0cc061SDimitry Andric return MAttributes[i-1]; 306ff0cc061SDimitry Andric return AttributeSet(); 307ff0cc061SDimitry Andric } 308ff0cc061SDimitry Andric 3098f0fd8f6SDimitry Andric /// Read a value/type pair out of the specified record from slot 'Slot'. 3108f0fd8f6SDimitry Andric /// Increment Slot past the number of slots used in the record. Return true on 3118f0fd8f6SDimitry Andric /// failure. 312ff0cc061SDimitry Andric bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 313ff0cc061SDimitry Andric unsigned InstNum, Value *&ResVal) { 314ff0cc061SDimitry Andric if (Slot == Record.size()) return true; 315ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot++]; 316ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 317ff0cc061SDimitry Andric if (UseRelativeIDs) 318ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 319ff0cc061SDimitry Andric if (ValNo < InstNum) { 320ff0cc061SDimitry Andric // If this is not a forward reference, just return the value we already 321ff0cc061SDimitry Andric // have. 322ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, nullptr); 323ff0cc061SDimitry Andric return ResVal == nullptr; 324ff0cc061SDimitry Andric } 325ff0cc061SDimitry Andric if (Slot == Record.size()) 326ff0cc061SDimitry Andric return true; 327ff0cc061SDimitry Andric 328ff0cc061SDimitry Andric unsigned TypeNo = (unsigned)Record[Slot++]; 329ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo)); 330ff0cc061SDimitry Andric return ResVal == nullptr; 331ff0cc061SDimitry Andric } 332ff0cc061SDimitry Andric 3338f0fd8f6SDimitry Andric /// Read a value out of the specified record from slot 'Slot'. Increment Slot 3348f0fd8f6SDimitry Andric /// past the number of slots used by the value in the record. Return true if 3358f0fd8f6SDimitry Andric /// there is an error. 336ff0cc061SDimitry Andric bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 337ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) { 338ff0cc061SDimitry Andric if (getValue(Record, Slot, InstNum, Ty, ResVal)) 339ff0cc061SDimitry Andric return true; 340ff0cc061SDimitry Andric // All values currently take a single record slot. 341ff0cc061SDimitry Andric ++Slot; 342ff0cc061SDimitry Andric return false; 343ff0cc061SDimitry Andric } 344ff0cc061SDimitry Andric 3458f0fd8f6SDimitry Andric /// Like popValue, but does not increment the Slot number. 346ff0cc061SDimitry Andric bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 347ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) { 348ff0cc061SDimitry Andric ResVal = getValue(Record, Slot, InstNum, Ty); 349ff0cc061SDimitry Andric return ResVal == nullptr; 350ff0cc061SDimitry Andric } 351ff0cc061SDimitry Andric 3528f0fd8f6SDimitry Andric /// Version of getValue that returns ResVal directly, or 0 if there is an 3538f0fd8f6SDimitry Andric /// error. 354ff0cc061SDimitry Andric Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 355ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) { 356ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr; 357ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot]; 358ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 359ff0cc061SDimitry Andric if (UseRelativeIDs) 360ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 361ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty); 362ff0cc061SDimitry Andric } 363ff0cc061SDimitry Andric 3648f0fd8f6SDimitry Andric /// Like getValue, but decodes signed VBRs. 365ff0cc061SDimitry Andric Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 366ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) { 367ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr; 368ff0cc061SDimitry Andric unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); 369ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum. 370ff0cc061SDimitry Andric if (UseRelativeIDs) 371ff0cc061SDimitry Andric ValNo = InstNum - ValNo; 372ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty); 373ff0cc061SDimitry Andric } 374ff0cc061SDimitry Andric 375ff0cc061SDimitry Andric /// Converts alignment exponent (i.e. power of two (or zero)) to the 376ff0cc061SDimitry Andric /// corresponding alignment to use. If alignment is too large, returns 377ff0cc061SDimitry Andric /// a corresponding error code. 378ff0cc061SDimitry Andric std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment); 3798f0fd8f6SDimitry Andric std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); 3807d523365SDimitry Andric std::error_code parseModule(uint64_t ResumeBit, 3817d523365SDimitry Andric bool ShouldLazyLoadMetadata = false); 3828f0fd8f6SDimitry Andric std::error_code parseAttributeBlock(); 3838f0fd8f6SDimitry Andric std::error_code parseAttributeGroupBlock(); 3848f0fd8f6SDimitry Andric std::error_code parseTypeTable(); 3858f0fd8f6SDimitry Andric std::error_code parseTypeTableBody(); 3867d523365SDimitry Andric std::error_code parseOperandBundleTags(); 387ff0cc061SDimitry Andric 3887d523365SDimitry Andric ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, 3897d523365SDimitry Andric unsigned NameIndex, Triple &TT); 3907d523365SDimitry Andric std::error_code parseValueSymbolTable(uint64_t Offset = 0); 3918f0fd8f6SDimitry Andric std::error_code parseConstants(); 3927d523365SDimitry Andric std::error_code rememberAndSkipFunctionBodies(); 3938f0fd8f6SDimitry Andric std::error_code rememberAndSkipFunctionBody(); 394ff0cc061SDimitry Andric /// Save the positions of the Metadata blocks and skip parsing the blocks. 395ff0cc061SDimitry Andric std::error_code rememberAndSkipMetadata(); 3968f0fd8f6SDimitry Andric std::error_code parseFunctionBody(Function *F); 3978f0fd8f6SDimitry Andric std::error_code globalCleanup(); 3988f0fd8f6SDimitry Andric std::error_code resolveGlobalAndAliasInits(); 3997d523365SDimitry Andric std::error_code parseMetadata(bool ModuleLevel = false); 4007d523365SDimitry Andric std::error_code parseMetadataKinds(); 4017d523365SDimitry Andric std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record); 4028f0fd8f6SDimitry Andric std::error_code parseMetadataAttachment(Function &F); 403ff0cc061SDimitry Andric ErrorOr<std::string> parseModuleTriple(); 4048f0fd8f6SDimitry Andric std::error_code parseUseLists(); 4058f0fd8f6SDimitry Andric std::error_code initStream(std::unique_ptr<DataStreamer> Streamer); 4068f0fd8f6SDimitry Andric std::error_code initStreamFromBuffer(); 4078f0fd8f6SDimitry Andric std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer); 4088f0fd8f6SDimitry Andric std::error_code findFunctionInStream( 409ff0cc061SDimitry Andric Function *F, 410ff0cc061SDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); 411ff0cc061SDimitry Andric }; 4127d523365SDimitry Andric 4137d523365SDimitry Andric /// Class to manage reading and parsing function summary index bitcode 4147d523365SDimitry Andric /// files/sections. 4157d523365SDimitry Andric class FunctionIndexBitcodeReader { 4167d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler; 4177d523365SDimitry Andric 4187d523365SDimitry Andric /// Eventually points to the function index built during parsing. 4197d523365SDimitry Andric FunctionInfoIndex *TheIndex = nullptr; 4207d523365SDimitry Andric 4217d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buffer; 4227d523365SDimitry Andric std::unique_ptr<BitstreamReader> StreamFile; 4237d523365SDimitry Andric BitstreamCursor Stream; 4247d523365SDimitry Andric 4257d523365SDimitry Andric /// \brief Used to indicate whether we are doing lazy parsing of summary data. 4267d523365SDimitry Andric /// 4277d523365SDimitry Andric /// If false, the summary section is fully parsed into the index during 4287d523365SDimitry Andric /// the initial parse. Otherwise, if true, the caller is expected to 4297d523365SDimitry Andric /// invoke \a readFunctionSummary for each summary needed, and the summary 4307d523365SDimitry Andric /// section is thus parsed lazily. 4317d523365SDimitry Andric bool IsLazy = false; 4327d523365SDimitry Andric 4337d523365SDimitry Andric /// Used to indicate whether caller only wants to check for the presence 4347d523365SDimitry Andric /// of the function summary bitcode section. All blocks are skipped, 4357d523365SDimitry Andric /// but the SeenFuncSummary boolean is set. 4367d523365SDimitry Andric bool CheckFuncSummaryPresenceOnly = false; 4377d523365SDimitry Andric 4387d523365SDimitry Andric /// Indicates whether we have encountered a function summary section 4397d523365SDimitry Andric /// yet during parsing, used when checking if file contains function 4407d523365SDimitry Andric /// summary section. 4417d523365SDimitry Andric bool SeenFuncSummary = false; 4427d523365SDimitry Andric 4437d523365SDimitry Andric /// \brief Map populated during function summary section parsing, and 4447d523365SDimitry Andric /// consumed during ValueSymbolTable parsing. 4457d523365SDimitry Andric /// 4467d523365SDimitry Andric /// Used to correlate summary records with VST entries. For the per-module 4477d523365SDimitry Andric /// index this maps the ValueID to the parsed function summary, and 4487d523365SDimitry Andric /// for the combined index this maps the summary record's bitcode 4497d523365SDimitry Andric /// offset to the function summary (since in the combined index the 4507d523365SDimitry Andric /// VST records do not hold value IDs but rather hold the function 4517d523365SDimitry Andric /// summary record offset). 4527d523365SDimitry Andric DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap; 4537d523365SDimitry Andric 4547d523365SDimitry Andric /// Map populated during module path string table parsing, from the 4557d523365SDimitry Andric /// module ID to a string reference owned by the index's module 4567d523365SDimitry Andric /// path string table, used to correlate with combined index function 4577d523365SDimitry Andric /// summary records. 4587d523365SDimitry Andric DenseMap<uint64_t, StringRef> ModuleIdMap; 4597d523365SDimitry Andric 4607d523365SDimitry Andric public: 4617d523365SDimitry Andric std::error_code error(BitcodeError E, const Twine &Message); 4627d523365SDimitry Andric std::error_code error(BitcodeError E); 4637d523365SDimitry Andric std::error_code error(const Twine &Message); 4647d523365SDimitry Andric 4657d523365SDimitry Andric FunctionIndexBitcodeReader(MemoryBuffer *Buffer, 4667d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler, 4677d523365SDimitry Andric bool IsLazy = false, 4687d523365SDimitry Andric bool CheckFuncSummaryPresenceOnly = false); 4697d523365SDimitry Andric FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler, 4707d523365SDimitry Andric bool IsLazy = false, 4717d523365SDimitry Andric bool CheckFuncSummaryPresenceOnly = false); 4727d523365SDimitry Andric ~FunctionIndexBitcodeReader() { freeState(); } 4737d523365SDimitry Andric 4747d523365SDimitry Andric void freeState(); 4757d523365SDimitry Andric 4767d523365SDimitry Andric void releaseBuffer(); 4777d523365SDimitry Andric 4787d523365SDimitry Andric /// Check if the parser has encountered a function summary section. 4797d523365SDimitry Andric bool foundFuncSummary() { return SeenFuncSummary; } 4807d523365SDimitry Andric 4817d523365SDimitry Andric /// \brief Main interface to parsing a bitcode buffer. 4827d523365SDimitry Andric /// \returns true if an error occurred. 4837d523365SDimitry Andric std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer, 4847d523365SDimitry Andric FunctionInfoIndex *I); 4857d523365SDimitry Andric 4867d523365SDimitry Andric /// \brief Interface for parsing a function summary lazily. 4877d523365SDimitry Andric std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer, 4887d523365SDimitry Andric FunctionInfoIndex *I, 4897d523365SDimitry Andric size_t FunctionSummaryOffset); 4907d523365SDimitry Andric 4917d523365SDimitry Andric private: 4927d523365SDimitry Andric std::error_code parseModule(); 4937d523365SDimitry Andric std::error_code parseValueSymbolTable(); 4947d523365SDimitry Andric std::error_code parseEntireSummary(); 4957d523365SDimitry Andric std::error_code parseModuleStringTable(); 4967d523365SDimitry Andric std::error_code initStream(std::unique_ptr<DataStreamer> Streamer); 4977d523365SDimitry Andric std::error_code initStreamFromBuffer(); 4987d523365SDimitry Andric std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer); 4997d523365SDimitry Andric }; 500ff0cc061SDimitry Andric } // namespace 501ff0cc061SDimitry Andric 50239d628a0SDimitry Andric BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC, 50339d628a0SDimitry Andric DiagnosticSeverity Severity, 50439d628a0SDimitry Andric const Twine &Msg) 50539d628a0SDimitry Andric : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {} 50639d628a0SDimitry Andric 50739d628a0SDimitry Andric void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 50839d628a0SDimitry Andric 5098f0fd8f6SDimitry Andric static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler, 51039d628a0SDimitry Andric std::error_code EC, const Twine &Message) { 51139d628a0SDimitry Andric BitcodeDiagnosticInfo DI(EC, DS_Error, Message); 51239d628a0SDimitry Andric DiagnosticHandler(DI); 51339d628a0SDimitry Andric return EC; 514dff0c46cSDimitry Andric } 51539d628a0SDimitry Andric 5168f0fd8f6SDimitry Andric static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler, 51739d628a0SDimitry Andric std::error_code EC) { 5188f0fd8f6SDimitry Andric return error(DiagnosticHandler, EC, EC.message()); 51939d628a0SDimitry Andric } 52039d628a0SDimitry Andric 5217d523365SDimitry Andric static std::error_code error(LLVMContext &Context, std::error_code EC, 522ff0cc061SDimitry Andric const Twine &Message) { 5237d523365SDimitry Andric return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC, 5247d523365SDimitry Andric Message); 5257d523365SDimitry Andric } 5267d523365SDimitry Andric 5277d523365SDimitry Andric static std::error_code error(LLVMContext &Context, std::error_code EC) { 5287d523365SDimitry Andric return error(Context, EC, EC.message()); 5297d523365SDimitry Andric } 5307d523365SDimitry Andric 5317d523365SDimitry Andric static std::error_code error(LLVMContext &Context, const Twine &Message) { 5327d523365SDimitry Andric return error(Context, make_error_code(BitcodeError::CorruptedBitcode), 5337d523365SDimitry Andric Message); 534ff0cc061SDimitry Andric } 535ff0cc061SDimitry Andric 5368f0fd8f6SDimitry Andric std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) { 5377d523365SDimitry Andric if (!ProducerIdentification.empty()) { 5387d523365SDimitry Andric return ::error(Context, make_error_code(E), 5397d523365SDimitry Andric Message + " (Producer: '" + ProducerIdentification + 5407d523365SDimitry Andric "' Reader: 'LLVM " + LLVM_VERSION_STRING "')"); 5417d523365SDimitry Andric } 5427d523365SDimitry Andric return ::error(Context, make_error_code(E), Message); 54339d628a0SDimitry Andric } 54439d628a0SDimitry Andric 5458f0fd8f6SDimitry Andric std::error_code BitcodeReader::error(const Twine &Message) { 5467d523365SDimitry Andric if (!ProducerIdentification.empty()) { 5477d523365SDimitry Andric return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode), 5487d523365SDimitry Andric Message + " (Producer: '" + ProducerIdentification + 5497d523365SDimitry Andric "' Reader: 'LLVM " + LLVM_VERSION_STRING "')"); 5507d523365SDimitry Andric } 5517d523365SDimitry Andric return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode), 5527d523365SDimitry Andric Message); 55339d628a0SDimitry Andric } 55439d628a0SDimitry Andric 5558f0fd8f6SDimitry Andric std::error_code BitcodeReader::error(BitcodeError E) { 5567d523365SDimitry Andric return ::error(Context, make_error_code(E)); 55739d628a0SDimitry Andric } 55839d628a0SDimitry Andric 5597d523365SDimitry Andric BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context) 5607d523365SDimitry Andric : Context(Context), Buffer(Buffer), ValueList(Context), 5617d523365SDimitry Andric MetadataList(Context) {} 56239d628a0SDimitry Andric 5637d523365SDimitry Andric BitcodeReader::BitcodeReader(LLVMContext &Context) 5647d523365SDimitry Andric : Context(Context), Buffer(nullptr), ValueList(Context), 5657d523365SDimitry Andric MetadataList(Context) {} 56639d628a0SDimitry Andric 56739d628a0SDimitry Andric std::error_code BitcodeReader::materializeForwardReferencedFunctions() { 56839d628a0SDimitry Andric if (WillMaterializeAllForwardRefs) 56939d628a0SDimitry Andric return std::error_code(); 57039d628a0SDimitry Andric 57139d628a0SDimitry Andric // Prevent recursion. 57239d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 57339d628a0SDimitry Andric 57439d628a0SDimitry Andric while (!BasicBlockFwdRefQueue.empty()) { 57539d628a0SDimitry Andric Function *F = BasicBlockFwdRefQueue.front(); 57639d628a0SDimitry Andric BasicBlockFwdRefQueue.pop_front(); 57739d628a0SDimitry Andric assert(F && "Expected valid function"); 57839d628a0SDimitry Andric if (!BasicBlockFwdRefs.count(F)) 57939d628a0SDimitry Andric // Already materialized. 58039d628a0SDimitry Andric continue; 58139d628a0SDimitry Andric 58239d628a0SDimitry Andric // Check for a function that isn't materializable to prevent an infinite 58339d628a0SDimitry Andric // loop. When parsing a blockaddress stored in a global variable, there 58439d628a0SDimitry Andric // isn't a trivial way to check if a function will have a body without a 58539d628a0SDimitry Andric // linear search through FunctionsWithBodies, so just check it here. 58639d628a0SDimitry Andric if (!F->isMaterializable()) 5878f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 58839d628a0SDimitry Andric 58939d628a0SDimitry Andric // Try to materialize F. 59039d628a0SDimitry Andric if (std::error_code EC = materialize(F)) 59139d628a0SDimitry Andric return EC; 59239d628a0SDimitry Andric } 59339d628a0SDimitry Andric assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 59439d628a0SDimitry Andric 59539d628a0SDimitry Andric // Reset state. 59639d628a0SDimitry Andric WillMaterializeAllForwardRefs = false; 59739d628a0SDimitry Andric return std::error_code(); 598dff0c46cSDimitry Andric } 599dff0c46cSDimitry Andric 6008f0fd8f6SDimitry Andric void BitcodeReader::freeState() { 60191bc56edSDimitry Andric Buffer = nullptr; 60217a519f9SDimitry Andric std::vector<Type*>().swap(TypeList); 603f22ef01cSRoman Divacky ValueList.clear(); 6047d523365SDimitry Andric MetadataList.clear(); 60591bc56edSDimitry Andric std::vector<Comdat *>().swap(ComdatList); 606f22ef01cSRoman Divacky 607139f7f9bSDimitry Andric std::vector<AttributeSet>().swap(MAttributes); 608f22ef01cSRoman Divacky std::vector<BasicBlock*>().swap(FunctionBBs); 609f22ef01cSRoman Divacky std::vector<Function*>().swap(FunctionsWithBodies); 610f22ef01cSRoman Divacky DeferredFunctionInfo.clear(); 611ff0cc061SDimitry Andric DeferredMetadataInfo.clear(); 612e580952dSDimitry Andric MDKindMap.clear(); 6133861d79fSDimitry Andric 61439d628a0SDimitry Andric assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references"); 61539d628a0SDimitry Andric BasicBlockFwdRefQueue.clear(); 616f22ef01cSRoman Divacky } 617f22ef01cSRoman Divacky 618f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 619f22ef01cSRoman Divacky // Helper functions to implement forward reference resolution, etc. 620f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 621f22ef01cSRoman Divacky 6228f0fd8f6SDimitry Andric /// Convert a string from a record into an std::string, return true on failure. 623f22ef01cSRoman Divacky template <typename StrTy> 6248f0fd8f6SDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, 625f22ef01cSRoman Divacky StrTy &Result) { 626f22ef01cSRoman Divacky if (Idx > Record.size()) 627f22ef01cSRoman Divacky return true; 628f22ef01cSRoman Divacky 629f22ef01cSRoman Divacky for (unsigned i = Idx, e = Record.size(); i != e; ++i) 630f22ef01cSRoman Divacky Result += (char)Record[i]; 631f22ef01cSRoman Divacky return false; 632f22ef01cSRoman Divacky } 633f22ef01cSRoman Divacky 634ff0cc061SDimitry Andric static bool hasImplicitComdat(size_t Val) { 635ff0cc061SDimitry Andric switch (Val) { 636ff0cc061SDimitry Andric default: 637ff0cc061SDimitry Andric return false; 638ff0cc061SDimitry Andric case 1: // Old WeakAnyLinkage 639ff0cc061SDimitry Andric case 4: // Old LinkOnceAnyLinkage 640ff0cc061SDimitry Andric case 10: // Old WeakODRLinkage 641ff0cc061SDimitry Andric case 11: // Old LinkOnceODRLinkage 642ff0cc061SDimitry Andric return true; 643ff0cc061SDimitry Andric } 644ff0cc061SDimitry Andric } 645ff0cc061SDimitry Andric 64639d628a0SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 647f22ef01cSRoman Divacky switch (Val) { 648f22ef01cSRoman Divacky default: // Map unknown/new linkages to external 64939d628a0SDimitry Andric case 0: 65039d628a0SDimitry Andric return GlobalValue::ExternalLinkage; 65139d628a0SDimitry Andric case 2: 65239d628a0SDimitry Andric return GlobalValue::AppendingLinkage; 65339d628a0SDimitry Andric case 3: 65439d628a0SDimitry Andric return GlobalValue::InternalLinkage; 65539d628a0SDimitry Andric case 5: 65639d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 65739d628a0SDimitry Andric case 6: 65839d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 65939d628a0SDimitry Andric case 7: 66039d628a0SDimitry Andric return GlobalValue::ExternalWeakLinkage; 66139d628a0SDimitry Andric case 8: 66239d628a0SDimitry Andric return GlobalValue::CommonLinkage; 66339d628a0SDimitry Andric case 9: 66439d628a0SDimitry Andric return GlobalValue::PrivateLinkage; 66539d628a0SDimitry Andric case 12: 66639d628a0SDimitry Andric return GlobalValue::AvailableExternallyLinkage; 66791bc56edSDimitry Andric case 13: 66891bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 66991bc56edSDimitry Andric case 14: 67091bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 67139d628a0SDimitry Andric case 15: 67239d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 673ff0cc061SDimitry Andric case 1: // Old value with implicit comdat. 674ff0cc061SDimitry Andric case 16: 675ff0cc061SDimitry Andric return GlobalValue::WeakAnyLinkage; 676ff0cc061SDimitry Andric case 10: // Old value with implicit comdat. 677ff0cc061SDimitry Andric case 17: 678ff0cc061SDimitry Andric return GlobalValue::WeakODRLinkage; 679ff0cc061SDimitry Andric case 4: // Old value with implicit comdat. 680ff0cc061SDimitry Andric case 18: 681ff0cc061SDimitry Andric return GlobalValue::LinkOnceAnyLinkage; 682ff0cc061SDimitry Andric case 11: // Old value with implicit comdat. 683ff0cc061SDimitry Andric case 19: 684ff0cc061SDimitry Andric return GlobalValue::LinkOnceODRLinkage; 685f22ef01cSRoman Divacky } 686f22ef01cSRoman Divacky } 687f22ef01cSRoman Divacky 6888f0fd8f6SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { 689f22ef01cSRoman Divacky switch (Val) { 690f22ef01cSRoman Divacky default: // Map unknown visibilities to default. 691f22ef01cSRoman Divacky case 0: return GlobalValue::DefaultVisibility; 692f22ef01cSRoman Divacky case 1: return GlobalValue::HiddenVisibility; 693f22ef01cSRoman Divacky case 2: return GlobalValue::ProtectedVisibility; 694f22ef01cSRoman Divacky } 695f22ef01cSRoman Divacky } 696f22ef01cSRoman Divacky 69791bc56edSDimitry Andric static GlobalValue::DLLStorageClassTypes 6988f0fd8f6SDimitry Andric getDecodedDLLStorageClass(unsigned Val) { 69991bc56edSDimitry Andric switch (Val) { 70091bc56edSDimitry Andric default: // Map unknown values to default. 70191bc56edSDimitry Andric case 0: return GlobalValue::DefaultStorageClass; 70291bc56edSDimitry Andric case 1: return GlobalValue::DLLImportStorageClass; 70391bc56edSDimitry Andric case 2: return GlobalValue::DLLExportStorageClass; 70491bc56edSDimitry Andric } 70591bc56edSDimitry Andric } 70691bc56edSDimitry Andric 7078f0fd8f6SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { 7087ae0e2c9SDimitry Andric switch (Val) { 7097ae0e2c9SDimitry Andric case 0: return GlobalVariable::NotThreadLocal; 7107ae0e2c9SDimitry Andric default: // Map unknown non-zero value to general dynamic. 7117ae0e2c9SDimitry Andric case 1: return GlobalVariable::GeneralDynamicTLSModel; 7127ae0e2c9SDimitry Andric case 2: return GlobalVariable::LocalDynamicTLSModel; 7137ae0e2c9SDimitry Andric case 3: return GlobalVariable::InitialExecTLSModel; 7147ae0e2c9SDimitry Andric case 4: return GlobalVariable::LocalExecTLSModel; 7157ae0e2c9SDimitry Andric } 7167ae0e2c9SDimitry Andric } 7177ae0e2c9SDimitry Andric 7188f0fd8f6SDimitry Andric static int getDecodedCastOpcode(unsigned Val) { 719f22ef01cSRoman Divacky switch (Val) { 720f22ef01cSRoman Divacky default: return -1; 721f22ef01cSRoman Divacky case bitc::CAST_TRUNC : return Instruction::Trunc; 722f22ef01cSRoman Divacky case bitc::CAST_ZEXT : return Instruction::ZExt; 723f22ef01cSRoman Divacky case bitc::CAST_SEXT : return Instruction::SExt; 724f22ef01cSRoman Divacky case bitc::CAST_FPTOUI : return Instruction::FPToUI; 725f22ef01cSRoman Divacky case bitc::CAST_FPTOSI : return Instruction::FPToSI; 726f22ef01cSRoman Divacky case bitc::CAST_UITOFP : return Instruction::UIToFP; 727f22ef01cSRoman Divacky case bitc::CAST_SITOFP : return Instruction::SIToFP; 728f22ef01cSRoman Divacky case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 729f22ef01cSRoman Divacky case bitc::CAST_FPEXT : return Instruction::FPExt; 730f22ef01cSRoman Divacky case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 731f22ef01cSRoman Divacky case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 732f22ef01cSRoman Divacky case bitc::CAST_BITCAST : return Instruction::BitCast; 733f785676fSDimitry Andric case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 734f22ef01cSRoman Divacky } 735f22ef01cSRoman Divacky } 736ff0cc061SDimitry Andric 7378f0fd8f6SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { 738ff0cc061SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy(); 739ff0cc061SDimitry Andric // BinOps are only valid for int/fp or vector of int/fp types 740ff0cc061SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy()) 741ff0cc061SDimitry Andric return -1; 742ff0cc061SDimitry Andric 743f22ef01cSRoman Divacky switch (Val) { 744ff0cc061SDimitry Andric default: 745ff0cc061SDimitry Andric return -1; 746f22ef01cSRoman Divacky case bitc::BINOP_ADD: 747ff0cc061SDimitry Andric return IsFP ? Instruction::FAdd : Instruction::Add; 748f22ef01cSRoman Divacky case bitc::BINOP_SUB: 749ff0cc061SDimitry Andric return IsFP ? Instruction::FSub : Instruction::Sub; 750f22ef01cSRoman Divacky case bitc::BINOP_MUL: 751ff0cc061SDimitry Andric return IsFP ? Instruction::FMul : Instruction::Mul; 752ff0cc061SDimitry Andric case bitc::BINOP_UDIV: 753ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::UDiv; 754f22ef01cSRoman Divacky case bitc::BINOP_SDIV: 755ff0cc061SDimitry Andric return IsFP ? Instruction::FDiv : Instruction::SDiv; 756ff0cc061SDimitry Andric case bitc::BINOP_UREM: 757ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::URem; 758f22ef01cSRoman Divacky case bitc::BINOP_SREM: 759ff0cc061SDimitry Andric return IsFP ? Instruction::FRem : Instruction::SRem; 760ff0cc061SDimitry Andric case bitc::BINOP_SHL: 761ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Shl; 762ff0cc061SDimitry Andric case bitc::BINOP_LSHR: 763ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::LShr; 764ff0cc061SDimitry Andric case bitc::BINOP_ASHR: 765ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::AShr; 766ff0cc061SDimitry Andric case bitc::BINOP_AND: 767ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::And; 768ff0cc061SDimitry Andric case bitc::BINOP_OR: 769ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Or; 770ff0cc061SDimitry Andric case bitc::BINOP_XOR: 771ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Xor; 772f22ef01cSRoman Divacky } 773f22ef01cSRoman Divacky } 774f22ef01cSRoman Divacky 7758f0fd8f6SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { 7766122f3e6SDimitry Andric switch (Val) { 7776122f3e6SDimitry Andric default: return AtomicRMWInst::BAD_BINOP; 7786122f3e6SDimitry Andric case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 7796122f3e6SDimitry Andric case bitc::RMW_ADD: return AtomicRMWInst::Add; 7806122f3e6SDimitry Andric case bitc::RMW_SUB: return AtomicRMWInst::Sub; 7816122f3e6SDimitry Andric case bitc::RMW_AND: return AtomicRMWInst::And; 7826122f3e6SDimitry Andric case bitc::RMW_NAND: return AtomicRMWInst::Nand; 7836122f3e6SDimitry Andric case bitc::RMW_OR: return AtomicRMWInst::Or; 7846122f3e6SDimitry Andric case bitc::RMW_XOR: return AtomicRMWInst::Xor; 7856122f3e6SDimitry Andric case bitc::RMW_MAX: return AtomicRMWInst::Max; 7866122f3e6SDimitry Andric case bitc::RMW_MIN: return AtomicRMWInst::Min; 7876122f3e6SDimitry Andric case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 7886122f3e6SDimitry Andric case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 7896122f3e6SDimitry Andric } 7906122f3e6SDimitry Andric } 7916122f3e6SDimitry Andric 7928f0fd8f6SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) { 7936122f3e6SDimitry Andric switch (Val) { 7946122f3e6SDimitry Andric case bitc::ORDERING_NOTATOMIC: return NotAtomic; 7956122f3e6SDimitry Andric case bitc::ORDERING_UNORDERED: return Unordered; 7966122f3e6SDimitry Andric case bitc::ORDERING_MONOTONIC: return Monotonic; 7976122f3e6SDimitry Andric case bitc::ORDERING_ACQUIRE: return Acquire; 7986122f3e6SDimitry Andric case bitc::ORDERING_RELEASE: return Release; 7996122f3e6SDimitry Andric case bitc::ORDERING_ACQREL: return AcquireRelease; 8006122f3e6SDimitry Andric default: // Map unknown orderings to sequentially-consistent. 8016122f3e6SDimitry Andric case bitc::ORDERING_SEQCST: return SequentiallyConsistent; 8026122f3e6SDimitry Andric } 8036122f3e6SDimitry Andric } 8046122f3e6SDimitry Andric 8058f0fd8f6SDimitry Andric static SynchronizationScope getDecodedSynchScope(unsigned Val) { 8066122f3e6SDimitry Andric switch (Val) { 8076122f3e6SDimitry Andric case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread; 8086122f3e6SDimitry Andric default: // Map unknown scopes to cross-thread. 8096122f3e6SDimitry Andric case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread; 8106122f3e6SDimitry Andric } 8116122f3e6SDimitry Andric } 8126122f3e6SDimitry Andric 81391bc56edSDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 81491bc56edSDimitry Andric switch (Val) { 81591bc56edSDimitry Andric default: // Map unknown selection kinds to any. 81691bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_ANY: 81791bc56edSDimitry Andric return Comdat::Any; 81891bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 81991bc56edSDimitry Andric return Comdat::ExactMatch; 82091bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_LARGEST: 82191bc56edSDimitry Andric return Comdat::Largest; 82291bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 82391bc56edSDimitry Andric return Comdat::NoDuplicates; 82491bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 82591bc56edSDimitry Andric return Comdat::SameSize; 82691bc56edSDimitry Andric } 82791bc56edSDimitry Andric } 82891bc56edSDimitry Andric 829875ed548SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) { 830875ed548SDimitry Andric FastMathFlags FMF; 831875ed548SDimitry Andric if (0 != (Val & FastMathFlags::UnsafeAlgebra)) 832875ed548SDimitry Andric FMF.setUnsafeAlgebra(); 833875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoNaNs)) 834875ed548SDimitry Andric FMF.setNoNaNs(); 835875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoInfs)) 836875ed548SDimitry Andric FMF.setNoInfs(); 837875ed548SDimitry Andric if (0 != (Val & FastMathFlags::NoSignedZeros)) 838875ed548SDimitry Andric FMF.setNoSignedZeros(); 839875ed548SDimitry Andric if (0 != (Val & FastMathFlags::AllowReciprocal)) 840875ed548SDimitry Andric FMF.setAllowReciprocal(); 841875ed548SDimitry Andric return FMF; 842875ed548SDimitry Andric } 843875ed548SDimitry Andric 8448f0fd8f6SDimitry Andric static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) { 84591bc56edSDimitry Andric switch (Val) { 84691bc56edSDimitry Andric case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 84791bc56edSDimitry Andric case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 84891bc56edSDimitry Andric } 84991bc56edSDimitry Andric } 85091bc56edSDimitry Andric 851f22ef01cSRoman Divacky namespace llvm { 852f22ef01cSRoman Divacky namespace { 8538f0fd8f6SDimitry Andric /// \brief A class for maintaining the slot number definition 854f22ef01cSRoman Divacky /// as a placeholder for the actual definition for forward constants defs. 855f22ef01cSRoman Divacky class ConstantPlaceHolder : public ConstantExpr { 856ff0cc061SDimitry Andric void operator=(const ConstantPlaceHolder &) = delete; 8578f0fd8f6SDimitry Andric 858f22ef01cSRoman Divacky public: 859f22ef01cSRoman Divacky // allocate space for exactly one operand 8608f0fd8f6SDimitry Andric void *operator new(size_t s) { return User::operator new(s, 1); } 8616122f3e6SDimitry Andric explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context) 862f22ef01cSRoman Divacky : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 863f22ef01cSRoman Divacky Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 864f22ef01cSRoman Divacky } 865f22ef01cSRoman Divacky 8668f0fd8f6SDimitry Andric /// \brief Methods to support type inquiry through isa, cast, and dyn_cast. 867f22ef01cSRoman Divacky static bool classof(const Value *V) { 868f22ef01cSRoman Divacky return isa<ConstantExpr>(V) && 869f22ef01cSRoman Divacky cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 870f22ef01cSRoman Divacky } 871f22ef01cSRoman Divacky 872f22ef01cSRoman Divacky /// Provide fast operand accessors 87339d628a0SDimitry Andric DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 874f22ef01cSRoman Divacky }; 8753dac3a9bSDimitry Andric } 876f22ef01cSRoman Divacky 877f22ef01cSRoman Divacky // FIXME: can we inherit this from ConstantExpr? 878f22ef01cSRoman Divacky template <> 8792754fe60SDimitry Andric struct OperandTraits<ConstantPlaceHolder> : 8802754fe60SDimitry Andric public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 881f22ef01cSRoman Divacky }; 88239d628a0SDimitry Andric DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value) 8833dac3a9bSDimitry Andric } 884f22ef01cSRoman Divacky 8858f0fd8f6SDimitry Andric void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) { 886f22ef01cSRoman Divacky if (Idx == size()) { 887f22ef01cSRoman Divacky push_back(V); 888f22ef01cSRoman Divacky return; 889f22ef01cSRoman Divacky } 890f22ef01cSRoman Divacky 891f22ef01cSRoman Divacky if (Idx >= size()) 892f22ef01cSRoman Divacky resize(Idx+1); 893f22ef01cSRoman Divacky 894f22ef01cSRoman Divacky WeakVH &OldV = ValuePtrs[Idx]; 89591bc56edSDimitry Andric if (!OldV) { 896f22ef01cSRoman Divacky OldV = V; 897f22ef01cSRoman Divacky return; 898f22ef01cSRoman Divacky } 899f22ef01cSRoman Divacky 900f22ef01cSRoman Divacky // Handle constants and non-constants (e.g. instrs) differently for 901f22ef01cSRoman Divacky // efficiency. 902f22ef01cSRoman Divacky if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 903f22ef01cSRoman Divacky ResolveConstants.push_back(std::make_pair(PHC, Idx)); 904f22ef01cSRoman Divacky OldV = V; 905f22ef01cSRoman Divacky } else { 906f22ef01cSRoman Divacky // If there was a forward reference to this value, replace it. 907f22ef01cSRoman Divacky Value *PrevVal = OldV; 908f22ef01cSRoman Divacky OldV->replaceAllUsesWith(V); 909f22ef01cSRoman Divacky delete PrevVal; 910f22ef01cSRoman Divacky } 9117d523365SDimitry Andric 9127d523365SDimitry Andric return; 913f22ef01cSRoman Divacky } 914f22ef01cSRoman Divacky 915f22ef01cSRoman Divacky 916f22ef01cSRoman Divacky Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 9176122f3e6SDimitry Andric Type *Ty) { 918f22ef01cSRoman Divacky if (Idx >= size()) 919f22ef01cSRoman Divacky resize(Idx + 1); 920f22ef01cSRoman Divacky 921f22ef01cSRoman Divacky if (Value *V = ValuePtrs[Idx]) { 922ff0cc061SDimitry Andric if (Ty != V->getType()) 923ff0cc061SDimitry Andric report_fatal_error("Type mismatch in constant table!"); 924f22ef01cSRoman Divacky return cast<Constant>(V); 925f22ef01cSRoman Divacky } 926f22ef01cSRoman Divacky 927f22ef01cSRoman Divacky // Create and return a placeholder, which will later be RAUW'd. 928f22ef01cSRoman Divacky Constant *C = new ConstantPlaceHolder(Ty, Context); 929f22ef01cSRoman Divacky ValuePtrs[Idx] = C; 930f22ef01cSRoman Divacky return C; 931f22ef01cSRoman Divacky } 932f22ef01cSRoman Divacky 9336122f3e6SDimitry Andric Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 934ff0cc061SDimitry Andric // Bail out for a clearly invalid value. This would make us call resize(0) 935ff0cc061SDimitry Andric if (Idx == UINT_MAX) 936ff0cc061SDimitry Andric return nullptr; 937ff0cc061SDimitry Andric 938f22ef01cSRoman Divacky if (Idx >= size()) 939f22ef01cSRoman Divacky resize(Idx + 1); 940f22ef01cSRoman Divacky 941f22ef01cSRoman Divacky if (Value *V = ValuePtrs[Idx]) { 942ff0cc061SDimitry Andric // If the types don't match, it's invalid. 943ff0cc061SDimitry Andric if (Ty && Ty != V->getType()) 944ff0cc061SDimitry Andric return nullptr; 945f22ef01cSRoman Divacky return V; 946f22ef01cSRoman Divacky } 947f22ef01cSRoman Divacky 948f22ef01cSRoman Divacky // No type specified, must be invalid reference. 94991bc56edSDimitry Andric if (!Ty) return nullptr; 950f22ef01cSRoman Divacky 951f22ef01cSRoman Divacky // Create and return a placeholder, which will later be RAUW'd. 952f22ef01cSRoman Divacky Value *V = new Argument(Ty); 953f22ef01cSRoman Divacky ValuePtrs[Idx] = V; 954f22ef01cSRoman Divacky return V; 955f22ef01cSRoman Divacky } 956f22ef01cSRoman Divacky 9578f0fd8f6SDimitry Andric /// Once all constants are read, this method bulk resolves any forward 9588f0fd8f6SDimitry Andric /// references. The idea behind this is that we sometimes get constants (such 9598f0fd8f6SDimitry Andric /// as large arrays) which reference *many* forward ref constants. Replacing 9608f0fd8f6SDimitry Andric /// each of these causes a lot of thrashing when building/reuniquing the 9618f0fd8f6SDimitry Andric /// constant. Instead of doing this, we look at all the uses and rewrite all 9628f0fd8f6SDimitry Andric /// the place holders at once for any constant that uses a placeholder. 9638f0fd8f6SDimitry Andric void BitcodeReaderValueList::resolveConstantForwardRefs() { 964f22ef01cSRoman Divacky // Sort the values by-pointer so that they are efficient to look up with a 965f22ef01cSRoman Divacky // binary search. 966f22ef01cSRoman Divacky std::sort(ResolveConstants.begin(), ResolveConstants.end()); 967f22ef01cSRoman Divacky 968f22ef01cSRoman Divacky SmallVector<Constant*, 64> NewOps; 969f22ef01cSRoman Divacky 970f22ef01cSRoman Divacky while (!ResolveConstants.empty()) { 971f22ef01cSRoman Divacky Value *RealVal = operator[](ResolveConstants.back().second); 972f22ef01cSRoman Divacky Constant *Placeholder = ResolveConstants.back().first; 973f22ef01cSRoman Divacky ResolveConstants.pop_back(); 974f22ef01cSRoman Divacky 975f22ef01cSRoman Divacky // Loop over all users of the placeholder, updating them to reference the 976f22ef01cSRoman Divacky // new value. If they reference more than one placeholder, update them all 977f22ef01cSRoman Divacky // at once. 978f22ef01cSRoman Divacky while (!Placeholder->use_empty()) { 97991bc56edSDimitry Andric auto UI = Placeholder->user_begin(); 980ffd1746dSEd Schouten User *U = *UI; 981f22ef01cSRoman Divacky 982f22ef01cSRoman Divacky // If the using object isn't uniqued, just update the operands. This 983f22ef01cSRoman Divacky // handles instructions and initializers for global variables. 984ffd1746dSEd Schouten if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 985f22ef01cSRoman Divacky UI.getUse().set(RealVal); 986f22ef01cSRoman Divacky continue; 987f22ef01cSRoman Divacky } 988f22ef01cSRoman Divacky 989f22ef01cSRoman Divacky // Otherwise, we have a constant that uses the placeholder. Replace that 990f22ef01cSRoman Divacky // constant with a new constant that has *all* placeholder uses updated. 991ffd1746dSEd Schouten Constant *UserC = cast<Constant>(U); 992f22ef01cSRoman Divacky for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 993f22ef01cSRoman Divacky I != E; ++I) { 994f22ef01cSRoman Divacky Value *NewOp; 995f22ef01cSRoman Divacky if (!isa<ConstantPlaceHolder>(*I)) { 996f22ef01cSRoman Divacky // Not a placeholder reference. 997f22ef01cSRoman Divacky NewOp = *I; 998f22ef01cSRoman Divacky } else if (*I == Placeholder) { 999f22ef01cSRoman Divacky // Common case is that it just references this one placeholder. 1000f22ef01cSRoman Divacky NewOp = RealVal; 1001f22ef01cSRoman Divacky } else { 1002f22ef01cSRoman Divacky // Otherwise, look up the placeholder in ResolveConstants. 1003f22ef01cSRoman Divacky ResolveConstantsTy::iterator It = 1004f22ef01cSRoman Divacky std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 1005f22ef01cSRoman Divacky std::pair<Constant*, unsigned>(cast<Constant>(*I), 1006f22ef01cSRoman Divacky 0)); 1007f22ef01cSRoman Divacky assert(It != ResolveConstants.end() && It->first == *I); 1008f22ef01cSRoman Divacky NewOp = operator[](It->second); 1009f22ef01cSRoman Divacky } 1010f22ef01cSRoman Divacky 1011f22ef01cSRoman Divacky NewOps.push_back(cast<Constant>(NewOp)); 1012f22ef01cSRoman Divacky } 1013f22ef01cSRoman Divacky 1014f22ef01cSRoman Divacky // Make the new constant. 1015f22ef01cSRoman Divacky Constant *NewC; 1016f22ef01cSRoman Divacky if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 101717a519f9SDimitry Andric NewC = ConstantArray::get(UserCA->getType(), NewOps); 1018f22ef01cSRoman Divacky } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 101917a519f9SDimitry Andric NewC = ConstantStruct::get(UserCS->getType(), NewOps); 1020f22ef01cSRoman Divacky } else if (isa<ConstantVector>(UserC)) { 10212754fe60SDimitry Andric NewC = ConstantVector::get(NewOps); 1022f22ef01cSRoman Divacky } else { 1023f22ef01cSRoman Divacky assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 10243b0f4066SDimitry Andric NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 1025f22ef01cSRoman Divacky } 1026f22ef01cSRoman Divacky 1027f22ef01cSRoman Divacky UserC->replaceAllUsesWith(NewC); 1028f22ef01cSRoman Divacky UserC->destroyConstant(); 1029f22ef01cSRoman Divacky NewOps.clear(); 1030f22ef01cSRoman Divacky } 1031f22ef01cSRoman Divacky 1032f22ef01cSRoman Divacky // Update all ValueHandles, they should be the only users at this point. 1033f22ef01cSRoman Divacky Placeholder->replaceAllUsesWith(RealVal); 1034f22ef01cSRoman Divacky delete Placeholder; 1035f22ef01cSRoman Divacky } 1036f22ef01cSRoman Divacky } 1037f22ef01cSRoman Divacky 10387d523365SDimitry Andric void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) { 1039f22ef01cSRoman Divacky if (Idx == size()) { 104039d628a0SDimitry Andric push_back(MD); 1041f22ef01cSRoman Divacky return; 1042f22ef01cSRoman Divacky } 1043f22ef01cSRoman Divacky 1044f22ef01cSRoman Divacky if (Idx >= size()) 1045f22ef01cSRoman Divacky resize(Idx+1); 1046f22ef01cSRoman Divacky 10477d523365SDimitry Andric TrackingMDRef &OldMD = MetadataPtrs[Idx]; 104839d628a0SDimitry Andric if (!OldMD) { 104939d628a0SDimitry Andric OldMD.reset(MD); 1050f22ef01cSRoman Divacky return; 1051f22ef01cSRoman Divacky } 1052f22ef01cSRoman Divacky 1053f22ef01cSRoman Divacky // If there was a forward reference to this value, replace it. 1054ff0cc061SDimitry Andric TempMDTuple PrevMD(cast<MDTuple>(OldMD.get())); 105539d628a0SDimitry Andric PrevMD->replaceAllUsesWith(MD); 105639d628a0SDimitry Andric --NumFwdRefs; 1057f22ef01cSRoman Divacky } 1058f22ef01cSRoman Divacky 10597d523365SDimitry Andric Metadata *BitcodeReaderMetadataList::getValueFwdRef(unsigned Idx) { 1060f22ef01cSRoman Divacky if (Idx >= size()) 1061f22ef01cSRoman Divacky resize(Idx + 1); 1062f22ef01cSRoman Divacky 10637d523365SDimitry Andric if (Metadata *MD = MetadataPtrs[Idx]) 106439d628a0SDimitry Andric return MD; 1065f22ef01cSRoman Divacky 1066b09980d1SDimitry Andric // Track forward refs to be resolved later. 1067b09980d1SDimitry Andric if (AnyFwdRefs) { 1068b09980d1SDimitry Andric MinFwdRef = std::min(MinFwdRef, Idx); 1069b09980d1SDimitry Andric MaxFwdRef = std::max(MaxFwdRef, Idx); 1070b09980d1SDimitry Andric } else { 107139d628a0SDimitry Andric AnyFwdRefs = true; 1072b09980d1SDimitry Andric MinFwdRef = MaxFwdRef = Idx; 1073b09980d1SDimitry Andric } 107439d628a0SDimitry Andric ++NumFwdRefs; 1075b09980d1SDimitry Andric 1076b09980d1SDimitry Andric // Create and return a placeholder, which will later be RAUW'd. 1077ff0cc061SDimitry Andric Metadata *MD = MDNode::getTemporary(Context, None).release(); 10787d523365SDimitry Andric MetadataPtrs[Idx].reset(MD); 107939d628a0SDimitry Andric return MD; 108039d628a0SDimitry Andric } 108139d628a0SDimitry Andric 10827d523365SDimitry Andric void BitcodeReaderMetadataList::tryToResolveCycles() { 108339d628a0SDimitry Andric if (!AnyFwdRefs) 108439d628a0SDimitry Andric // Nothing to do. 108539d628a0SDimitry Andric return; 108639d628a0SDimitry Andric 108739d628a0SDimitry Andric if (NumFwdRefs) 108839d628a0SDimitry Andric // Still forward references... can't resolve cycles. 108939d628a0SDimitry Andric return; 109039d628a0SDimitry Andric 109139d628a0SDimitry Andric // Resolve any cycles. 1092b09980d1SDimitry Andric for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) { 10937d523365SDimitry Andric auto &MD = MetadataPtrs[I]; 1094ff0cc061SDimitry Andric auto *N = dyn_cast_or_null<MDNode>(MD); 1095ff0cc061SDimitry Andric if (!N) 1096ff0cc061SDimitry Andric continue; 1097ff0cc061SDimitry Andric 1098ff0cc061SDimitry Andric assert(!N->isTemporary() && "Unexpected forward reference"); 109939d628a0SDimitry Andric N->resolveCycles(); 110039d628a0SDimitry Andric } 1101b09980d1SDimitry Andric 1102b09980d1SDimitry Andric // Make sure we return early again until there's another forward ref. 1103b09980d1SDimitry Andric AnyFwdRefs = false; 1104f22ef01cSRoman Divacky } 1105f22ef01cSRoman Divacky 110617a519f9SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) { 110717a519f9SDimitry Andric // The type table size is always specified correctly. 110817a519f9SDimitry Andric if (ID >= TypeList.size()) 110991bc56edSDimitry Andric return nullptr; 1110f22ef01cSRoman Divacky 111117a519f9SDimitry Andric if (Type *Ty = TypeList[ID]) 111217a519f9SDimitry Andric return Ty; 111317a519f9SDimitry Andric 111417a519f9SDimitry Andric // If we have a forward reference, the only possible case is when it is to a 111517a519f9SDimitry Andric // named struct. Just create a placeholder for now. 111639d628a0SDimitry Andric return TypeList[ID] = createIdentifiedStructType(Context); 111739d628a0SDimitry Andric } 111839d628a0SDimitry Andric 111939d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 112039d628a0SDimitry Andric StringRef Name) { 112139d628a0SDimitry Andric auto *Ret = StructType::create(Context, Name); 112239d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret); 112339d628a0SDimitry Andric return Ret; 112439d628a0SDimitry Andric } 112539d628a0SDimitry Andric 112639d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 112739d628a0SDimitry Andric auto *Ret = StructType::create(Context); 112839d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret); 112939d628a0SDimitry Andric return Ret; 1130f22ef01cSRoman Divacky } 1131f22ef01cSRoman Divacky 113217a519f9SDimitry Andric 1133f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 1134f22ef01cSRoman Divacky // Functions for parsing blocks from the bitcode file 1135f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 1136f22ef01cSRoman Divacky 1137139f7f9bSDimitry Andric 1138139f7f9bSDimitry Andric /// \brief This fills an AttrBuilder object with the LLVM attributes that have 1139139f7f9bSDimitry Andric /// been decoded from the given integer. This function must stay in sync with 1140139f7f9bSDimitry Andric /// 'encodeLLVMAttributesForBitcode'. 1141139f7f9bSDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 1142139f7f9bSDimitry Andric uint64_t EncodedAttrs) { 1143139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 1144139f7f9bSDimitry Andric 1145139f7f9bSDimitry Andric // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 1146139f7f9bSDimitry Andric // the bits above 31 down by 11 bits. 1147139f7f9bSDimitry Andric unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 1148139f7f9bSDimitry Andric assert((!Alignment || isPowerOf2_32(Alignment)) && 1149139f7f9bSDimitry Andric "Alignment must be a power of two."); 1150139f7f9bSDimitry Andric 1151139f7f9bSDimitry Andric if (Alignment) 1152139f7f9bSDimitry Andric B.addAlignmentAttr(Alignment); 1153139f7f9bSDimitry Andric B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 1154139f7f9bSDimitry Andric (EncodedAttrs & 0xffff)); 1155139f7f9bSDimitry Andric } 1156139f7f9bSDimitry Andric 11578f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseAttributeBlock() { 1158f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 11598f0fd8f6SDimitry Andric return error("Invalid record"); 1160f22ef01cSRoman Divacky 1161f22ef01cSRoman Divacky if (!MAttributes.empty()) 11628f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1163f22ef01cSRoman Divacky 1164f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1165f22ef01cSRoman Divacky 1166139f7f9bSDimitry Andric SmallVector<AttributeSet, 8> Attrs; 1167f22ef01cSRoman Divacky 1168f22ef01cSRoman Divacky // Read all the records. 1169f22ef01cSRoman Divacky while (1) { 1170139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1171139f7f9bSDimitry Andric 1172139f7f9bSDimitry Andric switch (Entry.Kind) { 1173139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1174139f7f9bSDimitry Andric case BitstreamEntry::Error: 11758f0fd8f6SDimitry Andric return error("Malformed block"); 1176139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 117791bc56edSDimitry Andric return std::error_code(); 1178139f7f9bSDimitry Andric case BitstreamEntry::Record: 1179139f7f9bSDimitry Andric // The interesting case. 1180139f7f9bSDimitry Andric break; 1181f22ef01cSRoman Divacky } 1182f22ef01cSRoman Divacky 1183f22ef01cSRoman Divacky // Read a record. 1184f22ef01cSRoman Divacky Record.clear(); 1185139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1186f22ef01cSRoman Divacky default: // Default behavior: ignore. 1187f22ef01cSRoman Divacky break; 1188139f7f9bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 1189139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 1190f22ef01cSRoman Divacky if (Record.size() & 1) 11918f0fd8f6SDimitry Andric return error("Invalid record"); 1192f22ef01cSRoman Divacky 1193f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1194139f7f9bSDimitry Andric AttrBuilder B; 1195139f7f9bSDimitry Andric decodeLLVMAttributesForBitcode(B, Record[i+1]); 1196139f7f9bSDimitry Andric Attrs.push_back(AttributeSet::get(Context, Record[i], B)); 1197f22ef01cSRoman Divacky } 1198f22ef01cSRoman Divacky 1199139f7f9bSDimitry Andric MAttributes.push_back(AttributeSet::get(Context, Attrs)); 1200f22ef01cSRoman Divacky Attrs.clear(); 1201f22ef01cSRoman Divacky break; 1202f22ef01cSRoman Divacky } 1203139f7f9bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 1204139f7f9bSDimitry Andric for (unsigned i = 0, e = Record.size(); i != e; ++i) 1205139f7f9bSDimitry Andric Attrs.push_back(MAttributeGroups[Record[i]]); 1206139f7f9bSDimitry Andric 1207139f7f9bSDimitry Andric MAttributes.push_back(AttributeSet::get(Context, Attrs)); 1208139f7f9bSDimitry Andric Attrs.clear(); 1209139f7f9bSDimitry Andric break; 1210139f7f9bSDimitry Andric } 1211139f7f9bSDimitry Andric } 1212139f7f9bSDimitry Andric } 1213139f7f9bSDimitry Andric } 1214139f7f9bSDimitry Andric 1215f785676fSDimitry Andric // Returns Attribute::None on unrecognized codes. 12168f0fd8f6SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) { 1217f785676fSDimitry Andric switch (Code) { 1218f785676fSDimitry Andric default: 1219f785676fSDimitry Andric return Attribute::None; 1220f785676fSDimitry Andric case bitc::ATTR_KIND_ALIGNMENT: 1221f785676fSDimitry Andric return Attribute::Alignment; 1222f785676fSDimitry Andric case bitc::ATTR_KIND_ALWAYS_INLINE: 1223f785676fSDimitry Andric return Attribute::AlwaysInline; 1224875ed548SDimitry Andric case bitc::ATTR_KIND_ARGMEMONLY: 1225875ed548SDimitry Andric return Attribute::ArgMemOnly; 1226f785676fSDimitry Andric case bitc::ATTR_KIND_BUILTIN: 1227f785676fSDimitry Andric return Attribute::Builtin; 1228f785676fSDimitry Andric case bitc::ATTR_KIND_BY_VAL: 1229f785676fSDimitry Andric return Attribute::ByVal; 123091bc56edSDimitry Andric case bitc::ATTR_KIND_IN_ALLOCA: 123191bc56edSDimitry Andric return Attribute::InAlloca; 1232f785676fSDimitry Andric case bitc::ATTR_KIND_COLD: 1233f785676fSDimitry Andric return Attribute::Cold; 1234ff0cc061SDimitry Andric case bitc::ATTR_KIND_CONVERGENT: 1235ff0cc061SDimitry Andric return Attribute::Convergent; 12367d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: 12377d523365SDimitry Andric return Attribute::InaccessibleMemOnly; 12387d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: 12397d523365SDimitry Andric return Attribute::InaccessibleMemOrArgMemOnly; 1240f785676fSDimitry Andric case bitc::ATTR_KIND_INLINE_HINT: 1241f785676fSDimitry Andric return Attribute::InlineHint; 1242f785676fSDimitry Andric case bitc::ATTR_KIND_IN_REG: 1243f785676fSDimitry Andric return Attribute::InReg; 124491bc56edSDimitry Andric case bitc::ATTR_KIND_JUMP_TABLE: 124591bc56edSDimitry Andric return Attribute::JumpTable; 1246f785676fSDimitry Andric case bitc::ATTR_KIND_MIN_SIZE: 1247f785676fSDimitry Andric return Attribute::MinSize; 1248f785676fSDimitry Andric case bitc::ATTR_KIND_NAKED: 1249f785676fSDimitry Andric return Attribute::Naked; 1250f785676fSDimitry Andric case bitc::ATTR_KIND_NEST: 1251f785676fSDimitry Andric return Attribute::Nest; 1252f785676fSDimitry Andric case bitc::ATTR_KIND_NO_ALIAS: 1253f785676fSDimitry Andric return Attribute::NoAlias; 1254f785676fSDimitry Andric case bitc::ATTR_KIND_NO_BUILTIN: 1255f785676fSDimitry Andric return Attribute::NoBuiltin; 1256f785676fSDimitry Andric case bitc::ATTR_KIND_NO_CAPTURE: 1257f785676fSDimitry Andric return Attribute::NoCapture; 1258f785676fSDimitry Andric case bitc::ATTR_KIND_NO_DUPLICATE: 1259f785676fSDimitry Andric return Attribute::NoDuplicate; 1260f785676fSDimitry Andric case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 1261f785676fSDimitry Andric return Attribute::NoImplicitFloat; 1262f785676fSDimitry Andric case bitc::ATTR_KIND_NO_INLINE: 1263f785676fSDimitry Andric return Attribute::NoInline; 12647d523365SDimitry Andric case bitc::ATTR_KIND_NO_RECURSE: 12657d523365SDimitry Andric return Attribute::NoRecurse; 1266f785676fSDimitry Andric case bitc::ATTR_KIND_NON_LAZY_BIND: 1267f785676fSDimitry Andric return Attribute::NonLazyBind; 126891bc56edSDimitry Andric case bitc::ATTR_KIND_NON_NULL: 126991bc56edSDimitry Andric return Attribute::NonNull; 127091bc56edSDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE: 127191bc56edSDimitry Andric return Attribute::Dereferenceable; 1272ff0cc061SDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: 1273ff0cc061SDimitry Andric return Attribute::DereferenceableOrNull; 1274f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RED_ZONE: 1275f785676fSDimitry Andric return Attribute::NoRedZone; 1276f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RETURN: 1277f785676fSDimitry Andric return Attribute::NoReturn; 1278f785676fSDimitry Andric case bitc::ATTR_KIND_NO_UNWIND: 1279f785676fSDimitry Andric return Attribute::NoUnwind; 1280f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 1281f785676fSDimitry Andric return Attribute::OptimizeForSize; 1282f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_NONE: 1283f785676fSDimitry Andric return Attribute::OptimizeNone; 1284f785676fSDimitry Andric case bitc::ATTR_KIND_READ_NONE: 1285f785676fSDimitry Andric return Attribute::ReadNone; 1286f785676fSDimitry Andric case bitc::ATTR_KIND_READ_ONLY: 1287f785676fSDimitry Andric return Attribute::ReadOnly; 1288f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNED: 1289f785676fSDimitry Andric return Attribute::Returned; 1290f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNS_TWICE: 1291f785676fSDimitry Andric return Attribute::ReturnsTwice; 1292f785676fSDimitry Andric case bitc::ATTR_KIND_S_EXT: 1293f785676fSDimitry Andric return Attribute::SExt; 1294f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_ALIGNMENT: 1295f785676fSDimitry Andric return Attribute::StackAlignment; 1296f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT: 1297f785676fSDimitry Andric return Attribute::StackProtect; 1298f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_REQ: 1299f785676fSDimitry Andric return Attribute::StackProtectReq; 1300f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 1301f785676fSDimitry Andric return Attribute::StackProtectStrong; 13028f0fd8f6SDimitry Andric case bitc::ATTR_KIND_SAFESTACK: 13038f0fd8f6SDimitry Andric return Attribute::SafeStack; 1304f785676fSDimitry Andric case bitc::ATTR_KIND_STRUCT_RET: 1305f785676fSDimitry Andric return Attribute::StructRet; 1306f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_ADDRESS: 1307f785676fSDimitry Andric return Attribute::SanitizeAddress; 1308f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_THREAD: 1309f785676fSDimitry Andric return Attribute::SanitizeThread; 1310f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_MEMORY: 1311f785676fSDimitry Andric return Attribute::SanitizeMemory; 1312f785676fSDimitry Andric case bitc::ATTR_KIND_UW_TABLE: 1313f785676fSDimitry Andric return Attribute::UWTable; 1314f785676fSDimitry Andric case bitc::ATTR_KIND_Z_EXT: 1315f785676fSDimitry Andric return Attribute::ZExt; 1316f785676fSDimitry Andric } 1317f785676fSDimitry Andric } 1318f785676fSDimitry Andric 1319ff0cc061SDimitry Andric std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent, 1320ff0cc061SDimitry Andric unsigned &Alignment) { 1321ff0cc061SDimitry Andric // Note: Alignment in bitcode files is incremented by 1, so that zero 1322ff0cc061SDimitry Andric // can be used for default alignment. 1323ff0cc061SDimitry Andric if (Exponent > Value::MaxAlignmentExponent + 1) 13248f0fd8f6SDimitry Andric return error("Invalid alignment value"); 1325ff0cc061SDimitry Andric Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1; 1326ff0cc061SDimitry Andric return std::error_code(); 1327ff0cc061SDimitry Andric } 1328ff0cc061SDimitry Andric 13298f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseAttrKind(uint64_t Code, 1330f785676fSDimitry Andric Attribute::AttrKind *Kind) { 13318f0fd8f6SDimitry Andric *Kind = getAttrFromCode(Code); 1332f785676fSDimitry Andric if (*Kind == Attribute::None) 13338f0fd8f6SDimitry Andric return error(BitcodeError::CorruptedBitcode, 133439d628a0SDimitry Andric "Unknown attribute kind (" + Twine(Code) + ")"); 133591bc56edSDimitry Andric return std::error_code(); 1336f785676fSDimitry Andric } 1337f785676fSDimitry Andric 13388f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseAttributeGroupBlock() { 1339139f7f9bSDimitry Andric if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 13408f0fd8f6SDimitry Andric return error("Invalid record"); 1341139f7f9bSDimitry Andric 1342139f7f9bSDimitry Andric if (!MAttributeGroups.empty()) 13438f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1344139f7f9bSDimitry Andric 1345139f7f9bSDimitry Andric SmallVector<uint64_t, 64> Record; 1346139f7f9bSDimitry Andric 1347139f7f9bSDimitry Andric // Read all the records. 1348139f7f9bSDimitry Andric while (1) { 1349139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1350139f7f9bSDimitry Andric 1351139f7f9bSDimitry Andric switch (Entry.Kind) { 1352139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1353139f7f9bSDimitry Andric case BitstreamEntry::Error: 13548f0fd8f6SDimitry Andric return error("Malformed block"); 1355139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 135691bc56edSDimitry Andric return std::error_code(); 1357139f7f9bSDimitry Andric case BitstreamEntry::Record: 1358139f7f9bSDimitry Andric // The interesting case. 1359139f7f9bSDimitry Andric break; 1360139f7f9bSDimitry Andric } 1361139f7f9bSDimitry Andric 1362139f7f9bSDimitry Andric // Read a record. 1363139f7f9bSDimitry Andric Record.clear(); 1364139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1365139f7f9bSDimitry Andric default: // Default behavior: ignore. 1366139f7f9bSDimitry Andric break; 1367139f7f9bSDimitry Andric case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 1368139f7f9bSDimitry Andric if (Record.size() < 3) 13698f0fd8f6SDimitry Andric return error("Invalid record"); 1370139f7f9bSDimitry Andric 1371139f7f9bSDimitry Andric uint64_t GrpID = Record[0]; 1372139f7f9bSDimitry Andric uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 1373139f7f9bSDimitry Andric 1374139f7f9bSDimitry Andric AttrBuilder B; 1375139f7f9bSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1376139f7f9bSDimitry Andric if (Record[i] == 0) { // Enum attribute 1377f785676fSDimitry Andric Attribute::AttrKind Kind; 13788f0fd8f6SDimitry Andric if (std::error_code EC = parseAttrKind(Record[++i], &Kind)) 1379f785676fSDimitry Andric return EC; 1380f785676fSDimitry Andric 1381f785676fSDimitry Andric B.addAttribute(Kind); 138291bc56edSDimitry Andric } else if (Record[i] == 1) { // Integer attribute 1383f785676fSDimitry Andric Attribute::AttrKind Kind; 13848f0fd8f6SDimitry Andric if (std::error_code EC = parseAttrKind(Record[++i], &Kind)) 1385f785676fSDimitry Andric return EC; 1386f785676fSDimitry Andric if (Kind == Attribute::Alignment) 1387139f7f9bSDimitry Andric B.addAlignmentAttr(Record[++i]); 138891bc56edSDimitry Andric else if (Kind == Attribute::StackAlignment) 1389139f7f9bSDimitry Andric B.addStackAlignmentAttr(Record[++i]); 139091bc56edSDimitry Andric else if (Kind == Attribute::Dereferenceable) 139191bc56edSDimitry Andric B.addDereferenceableAttr(Record[++i]); 1392ff0cc061SDimitry Andric else if (Kind == Attribute::DereferenceableOrNull) 1393ff0cc061SDimitry Andric B.addDereferenceableOrNullAttr(Record[++i]); 1394139f7f9bSDimitry Andric } else { // String attribute 1395139f7f9bSDimitry Andric assert((Record[i] == 3 || Record[i] == 4) && 1396139f7f9bSDimitry Andric "Invalid attribute group entry"); 1397139f7f9bSDimitry Andric bool HasValue = (Record[i++] == 4); 1398139f7f9bSDimitry Andric SmallString<64> KindStr; 1399139f7f9bSDimitry Andric SmallString<64> ValStr; 1400139f7f9bSDimitry Andric 1401139f7f9bSDimitry Andric while (Record[i] != 0 && i != e) 1402139f7f9bSDimitry Andric KindStr += Record[i++]; 1403139f7f9bSDimitry Andric assert(Record[i] == 0 && "Kind string not null terminated"); 1404139f7f9bSDimitry Andric 1405139f7f9bSDimitry Andric if (HasValue) { 1406139f7f9bSDimitry Andric // Has a value associated with it. 1407139f7f9bSDimitry Andric ++i; // Skip the '0' that terminates the "kind" string. 1408139f7f9bSDimitry Andric while (Record[i] != 0 && i != e) 1409139f7f9bSDimitry Andric ValStr += Record[i++]; 1410139f7f9bSDimitry Andric assert(Record[i] == 0 && "Value string not null terminated"); 1411139f7f9bSDimitry Andric } 1412139f7f9bSDimitry Andric 1413139f7f9bSDimitry Andric B.addAttribute(KindStr.str(), ValStr.str()); 1414139f7f9bSDimitry Andric } 1415139f7f9bSDimitry Andric } 1416139f7f9bSDimitry Andric 1417139f7f9bSDimitry Andric MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B); 1418139f7f9bSDimitry Andric break; 1419139f7f9bSDimitry Andric } 1420f22ef01cSRoman Divacky } 1421f22ef01cSRoman Divacky } 1422f22ef01cSRoman Divacky } 1423f22ef01cSRoman Divacky 14248f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseTypeTable() { 142517a519f9SDimitry Andric if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 14268f0fd8f6SDimitry Andric return error("Invalid record"); 1427f22ef01cSRoman Divacky 14288f0fd8f6SDimitry Andric return parseTypeTableBody(); 142917a519f9SDimitry Andric } 143017a519f9SDimitry Andric 14318f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseTypeTableBody() { 1432f22ef01cSRoman Divacky if (!TypeList.empty()) 14338f0fd8f6SDimitry Andric return error("Invalid multiple blocks"); 1434f22ef01cSRoman Divacky 1435f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1436f22ef01cSRoman Divacky unsigned NumRecords = 0; 1437f22ef01cSRoman Divacky 143817a519f9SDimitry Andric SmallString<64> TypeName; 143917a519f9SDimitry Andric 1440f22ef01cSRoman Divacky // Read all the records for this type table. 1441f22ef01cSRoman Divacky while (1) { 1442139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1443139f7f9bSDimitry Andric 1444139f7f9bSDimitry Andric switch (Entry.Kind) { 1445139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1446139f7f9bSDimitry Andric case BitstreamEntry::Error: 14478f0fd8f6SDimitry Andric return error("Malformed block"); 1448139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 1449f22ef01cSRoman Divacky if (NumRecords != TypeList.size()) 14508f0fd8f6SDimitry Andric return error("Malformed block"); 145191bc56edSDimitry Andric return std::error_code(); 1452139f7f9bSDimitry Andric case BitstreamEntry::Record: 1453139f7f9bSDimitry Andric // The interesting case. 1454139f7f9bSDimitry Andric break; 1455f22ef01cSRoman Divacky } 1456f22ef01cSRoman Divacky 1457f22ef01cSRoman Divacky // Read a record. 1458f22ef01cSRoman Divacky Record.clear(); 145991bc56edSDimitry Andric Type *ResultTy = nullptr; 1460139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1461f785676fSDimitry Andric default: 14628f0fd8f6SDimitry Andric return error("Invalid value"); 1463f22ef01cSRoman Divacky case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 1464f22ef01cSRoman Divacky // TYPE_CODE_NUMENTRY contains a count of the number of types in the 1465f22ef01cSRoman Divacky // type list. This allows us to reserve space. 1466f22ef01cSRoman Divacky if (Record.size() < 1) 14678f0fd8f6SDimitry Andric return error("Invalid record"); 146817a519f9SDimitry Andric TypeList.resize(Record[0]); 1469f22ef01cSRoman Divacky continue; 1470f22ef01cSRoman Divacky case bitc::TYPE_CODE_VOID: // VOID 1471f22ef01cSRoman Divacky ResultTy = Type::getVoidTy(Context); 1472f22ef01cSRoman Divacky break; 1473dff0c46cSDimitry Andric case bitc::TYPE_CODE_HALF: // HALF 1474dff0c46cSDimitry Andric ResultTy = Type::getHalfTy(Context); 1475dff0c46cSDimitry Andric break; 1476f22ef01cSRoman Divacky case bitc::TYPE_CODE_FLOAT: // FLOAT 1477f22ef01cSRoman Divacky ResultTy = Type::getFloatTy(Context); 1478f22ef01cSRoman Divacky break; 1479f22ef01cSRoman Divacky case bitc::TYPE_CODE_DOUBLE: // DOUBLE 1480f22ef01cSRoman Divacky ResultTy = Type::getDoubleTy(Context); 1481f22ef01cSRoman Divacky break; 1482f22ef01cSRoman Divacky case bitc::TYPE_CODE_X86_FP80: // X86_FP80 1483f22ef01cSRoman Divacky ResultTy = Type::getX86_FP80Ty(Context); 1484f22ef01cSRoman Divacky break; 1485f22ef01cSRoman Divacky case bitc::TYPE_CODE_FP128: // FP128 1486f22ef01cSRoman Divacky ResultTy = Type::getFP128Ty(Context); 1487f22ef01cSRoman Divacky break; 1488f22ef01cSRoman Divacky case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 1489f22ef01cSRoman Divacky ResultTy = Type::getPPC_FP128Ty(Context); 1490f22ef01cSRoman Divacky break; 1491f22ef01cSRoman Divacky case bitc::TYPE_CODE_LABEL: // LABEL 1492f22ef01cSRoman Divacky ResultTy = Type::getLabelTy(Context); 1493f22ef01cSRoman Divacky break; 1494f22ef01cSRoman Divacky case bitc::TYPE_CODE_METADATA: // METADATA 1495f22ef01cSRoman Divacky ResultTy = Type::getMetadataTy(Context); 1496f22ef01cSRoman Divacky break; 14972754fe60SDimitry Andric case bitc::TYPE_CODE_X86_MMX: // X86_MMX 14982754fe60SDimitry Andric ResultTy = Type::getX86_MMXTy(Context); 14992754fe60SDimitry Andric break; 15007d523365SDimitry Andric case bitc::TYPE_CODE_TOKEN: // TOKEN 15017d523365SDimitry Andric ResultTy = Type::getTokenTy(Context); 15027d523365SDimitry Andric break; 1503ff0cc061SDimitry Andric case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 1504f22ef01cSRoman Divacky if (Record.size() < 1) 15058f0fd8f6SDimitry Andric return error("Invalid record"); 1506f22ef01cSRoman Divacky 1507ff0cc061SDimitry Andric uint64_t NumBits = Record[0]; 1508ff0cc061SDimitry Andric if (NumBits < IntegerType::MIN_INT_BITS || 1509ff0cc061SDimitry Andric NumBits > IntegerType::MAX_INT_BITS) 15108f0fd8f6SDimitry Andric return error("Bitwidth for integer type out of range"); 1511ff0cc061SDimitry Andric ResultTy = IntegerType::get(Context, NumBits); 1512f22ef01cSRoman Divacky break; 1513ff0cc061SDimitry Andric } 1514f22ef01cSRoman Divacky case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 1515f22ef01cSRoman Divacky // [pointee type, address space] 1516f22ef01cSRoman Divacky if (Record.size() < 1) 15178f0fd8f6SDimitry Andric return error("Invalid record"); 1518f22ef01cSRoman Divacky unsigned AddressSpace = 0; 1519f22ef01cSRoman Divacky if (Record.size() == 2) 1520f22ef01cSRoman Divacky AddressSpace = Record[1]; 152117a519f9SDimitry Andric ResultTy = getTypeByID(Record[0]); 1522ff0cc061SDimitry Andric if (!ResultTy || 1523ff0cc061SDimitry Andric !PointerType::isValidElementType(ResultTy)) 15248f0fd8f6SDimitry Andric return error("Invalid type"); 152517a519f9SDimitry Andric ResultTy = PointerType::get(ResultTy, AddressSpace); 1526f22ef01cSRoman Divacky break; 1527f22ef01cSRoman Divacky } 1528dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION_OLD: { 15297ae0e2c9SDimitry Andric // FIXME: attrid is dead, remove it in LLVM 4.0 1530f22ef01cSRoman Divacky // FUNCTION: [vararg, attrid, retty, paramty x N] 1531f22ef01cSRoman Divacky if (Record.size() < 3) 15328f0fd8f6SDimitry Andric return error("Invalid record"); 1533dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys; 153417a519f9SDimitry Andric for (unsigned i = 3, e = Record.size(); i != e; ++i) { 153517a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 153617a519f9SDimitry Andric ArgTys.push_back(T); 153717a519f9SDimitry Andric else 1538f22ef01cSRoman Divacky break; 1539f22ef01cSRoman Divacky } 154017a519f9SDimitry Andric 154117a519f9SDimitry Andric ResultTy = getTypeByID(Record[2]); 154291bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-3) 15438f0fd8f6SDimitry Andric return error("Invalid type"); 154417a519f9SDimitry Andric 154517a519f9SDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 154617a519f9SDimitry Andric break; 154717a519f9SDimitry Andric } 1548dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION: { 1549dff0c46cSDimitry Andric // FUNCTION: [vararg, retty, paramty x N] 1550dff0c46cSDimitry Andric if (Record.size() < 2) 15518f0fd8f6SDimitry Andric return error("Invalid record"); 1552dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys; 1553dff0c46cSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1554ff0cc061SDimitry Andric if (Type *T = getTypeByID(Record[i])) { 1555ff0cc061SDimitry Andric if (!FunctionType::isValidArgumentType(T)) 15568f0fd8f6SDimitry Andric return error("Invalid function argument type"); 1557dff0c46cSDimitry Andric ArgTys.push_back(T); 1558ff0cc061SDimitry Andric } 1559dff0c46cSDimitry Andric else 1560dff0c46cSDimitry Andric break; 1561dff0c46cSDimitry Andric } 1562dff0c46cSDimitry Andric 1563dff0c46cSDimitry Andric ResultTy = getTypeByID(Record[1]); 156491bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-2) 15658f0fd8f6SDimitry Andric return error("Invalid type"); 1566dff0c46cSDimitry Andric 1567dff0c46cSDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 1568dff0c46cSDimitry Andric break; 1569dff0c46cSDimitry Andric } 157017a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 1571f22ef01cSRoman Divacky if (Record.size() < 1) 15728f0fd8f6SDimitry Andric return error("Invalid record"); 1573dff0c46cSDimitry Andric SmallVector<Type*, 8> EltTys; 157417a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 157517a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 157617a519f9SDimitry Andric EltTys.push_back(T); 157717a519f9SDimitry Andric else 157817a519f9SDimitry Andric break; 157917a519f9SDimitry Andric } 158017a519f9SDimitry Andric if (EltTys.size() != Record.size()-1) 15818f0fd8f6SDimitry Andric return error("Invalid type"); 1582f22ef01cSRoman Divacky ResultTy = StructType::get(Context, EltTys, Record[0]); 1583f22ef01cSRoman Divacky break; 1584f22ef01cSRoman Divacky } 158517a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 15868f0fd8f6SDimitry Andric if (convertToString(Record, 0, TypeName)) 15878f0fd8f6SDimitry Andric return error("Invalid record"); 158817a519f9SDimitry Andric continue; 158917a519f9SDimitry Andric 159017a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 159117a519f9SDimitry Andric if (Record.size() < 1) 15928f0fd8f6SDimitry Andric return error("Invalid record"); 159317a519f9SDimitry Andric 159417a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 15958f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 159617a519f9SDimitry Andric 159717a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 159817a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 159917a519f9SDimitry Andric if (Res) { 160017a519f9SDimitry Andric Res->setName(TypeName); 160191bc56edSDimitry Andric TypeList[NumRecords] = nullptr; 160217a519f9SDimitry Andric } else // Otherwise, create a new struct. 160339d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 160417a519f9SDimitry Andric TypeName.clear(); 160517a519f9SDimitry Andric 160617a519f9SDimitry Andric SmallVector<Type*, 8> EltTys; 160717a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) { 160817a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i])) 160917a519f9SDimitry Andric EltTys.push_back(T); 161017a519f9SDimitry Andric else 161117a519f9SDimitry Andric break; 161217a519f9SDimitry Andric } 161317a519f9SDimitry Andric if (EltTys.size() != Record.size()-1) 16148f0fd8f6SDimitry Andric return error("Invalid record"); 161517a519f9SDimitry Andric Res->setBody(EltTys, Record[0]); 161617a519f9SDimitry Andric ResultTy = Res; 161717a519f9SDimitry Andric break; 161817a519f9SDimitry Andric } 161917a519f9SDimitry Andric case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 162017a519f9SDimitry Andric if (Record.size() != 1) 16218f0fd8f6SDimitry Andric return error("Invalid record"); 162217a519f9SDimitry Andric 162317a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16248f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 162517a519f9SDimitry Andric 162617a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp. 162717a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 162817a519f9SDimitry Andric if (Res) { 162917a519f9SDimitry Andric Res->setName(TypeName); 163091bc56edSDimitry Andric TypeList[NumRecords] = nullptr; 163117a519f9SDimitry Andric } else // Otherwise, create a new struct with no body. 163239d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName); 163317a519f9SDimitry Andric TypeName.clear(); 163417a519f9SDimitry Andric ResultTy = Res; 163517a519f9SDimitry Andric break; 163617a519f9SDimitry Andric } 1637f22ef01cSRoman Divacky case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 1638f22ef01cSRoman Divacky if (Record.size() < 2) 16398f0fd8f6SDimitry Andric return error("Invalid record"); 1640ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]); 1641ff0cc061SDimitry Andric if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) 16428f0fd8f6SDimitry Andric return error("Invalid type"); 1643ff0cc061SDimitry Andric ResultTy = ArrayType::get(ResultTy, Record[0]); 1644f22ef01cSRoman Divacky break; 1645f22ef01cSRoman Divacky case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 1646f22ef01cSRoman Divacky if (Record.size() < 2) 16478f0fd8f6SDimitry Andric return error("Invalid record"); 164897bc6c73SDimitry Andric if (Record[0] == 0) 16498f0fd8f6SDimitry Andric return error("Invalid vector length"); 1650ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]); 1651ff0cc061SDimitry Andric if (!ResultTy || !StructType::isValidElementType(ResultTy)) 16528f0fd8f6SDimitry Andric return error("Invalid type"); 1653ff0cc061SDimitry Andric ResultTy = VectorType::get(ResultTy, Record[0]); 1654f22ef01cSRoman Divacky break; 1655f22ef01cSRoman Divacky } 1656f22ef01cSRoman Divacky 165717a519f9SDimitry Andric if (NumRecords >= TypeList.size()) 16588f0fd8f6SDimitry Andric return error("Invalid TYPE table"); 1659ff0cc061SDimitry Andric if (TypeList[NumRecords]) 16608f0fd8f6SDimitry Andric return error( 1661ff0cc061SDimitry Andric "Invalid TYPE table: Only named structs can be forward referenced"); 166217a519f9SDimitry Andric assert(ResultTy && "Didn't read a type?"); 166317a519f9SDimitry Andric TypeList[NumRecords++] = ResultTy; 1664f22ef01cSRoman Divacky } 1665f22ef01cSRoman Divacky } 166617a519f9SDimitry Andric 16677d523365SDimitry Andric std::error_code BitcodeReader::parseOperandBundleTags() { 16687d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) 16697d523365SDimitry Andric return error("Invalid record"); 16707d523365SDimitry Andric 16717d523365SDimitry Andric if (!BundleTags.empty()) 16727d523365SDimitry Andric return error("Invalid multiple blocks"); 16737d523365SDimitry Andric 16747d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 16757d523365SDimitry Andric 16767d523365SDimitry Andric while (1) { 16777d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 16787d523365SDimitry Andric 16797d523365SDimitry Andric switch (Entry.Kind) { 16807d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 16817d523365SDimitry Andric case BitstreamEntry::Error: 16827d523365SDimitry Andric return error("Malformed block"); 16837d523365SDimitry Andric case BitstreamEntry::EndBlock: 16847d523365SDimitry Andric return std::error_code(); 16857d523365SDimitry Andric case BitstreamEntry::Record: 16867d523365SDimitry Andric // The interesting case. 16877d523365SDimitry Andric break; 16887d523365SDimitry Andric } 16897d523365SDimitry Andric 16907d523365SDimitry Andric // Tags are implicitly mapped to integers by their order. 16917d523365SDimitry Andric 16927d523365SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG) 16937d523365SDimitry Andric return error("Invalid record"); 16947d523365SDimitry Andric 16957d523365SDimitry Andric // OPERAND_BUNDLE_TAG: [strchr x N] 16967d523365SDimitry Andric BundleTags.emplace_back(); 16977d523365SDimitry Andric if (convertToString(Record, 0, BundleTags.back())) 16987d523365SDimitry Andric return error("Invalid record"); 16997d523365SDimitry Andric Record.clear(); 17007d523365SDimitry Andric } 17017d523365SDimitry Andric } 17027d523365SDimitry Andric 17037d523365SDimitry Andric /// Associate a value with its name from the given index in the provided record. 17047d523365SDimitry Andric ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, 17057d523365SDimitry Andric unsigned NameIndex, Triple &TT) { 17067d523365SDimitry Andric SmallString<128> ValueName; 17077d523365SDimitry Andric if (convertToString(Record, NameIndex, ValueName)) 17087d523365SDimitry Andric return error("Invalid record"); 17097d523365SDimitry Andric unsigned ValueID = Record[0]; 17107d523365SDimitry Andric if (ValueID >= ValueList.size() || !ValueList[ValueID]) 17117d523365SDimitry Andric return error("Invalid record"); 17127d523365SDimitry Andric Value *V = ValueList[ValueID]; 17137d523365SDimitry Andric 17147d523365SDimitry Andric StringRef NameStr(ValueName.data(), ValueName.size()); 17157d523365SDimitry Andric if (NameStr.find_first_of(0) != StringRef::npos) 17167d523365SDimitry Andric return error("Invalid value name"); 17177d523365SDimitry Andric V->setName(NameStr); 17187d523365SDimitry Andric auto *GO = dyn_cast<GlobalObject>(V); 17197d523365SDimitry Andric if (GO) { 17207d523365SDimitry Andric if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) { 17217d523365SDimitry Andric if (TT.isOSBinFormatMachO()) 17227d523365SDimitry Andric GO->setComdat(nullptr); 17237d523365SDimitry Andric else 17247d523365SDimitry Andric GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 17257d523365SDimitry Andric } 17267d523365SDimitry Andric } 17277d523365SDimitry Andric return V; 17287d523365SDimitry Andric } 17297d523365SDimitry Andric 17307d523365SDimitry Andric /// Parse the value symbol table at either the current parsing location or 17317d523365SDimitry Andric /// at the given bit offset if provided. 17327d523365SDimitry Andric std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) { 17337d523365SDimitry Andric uint64_t CurrentBit; 17347d523365SDimitry Andric // Pass in the Offset to distinguish between calling for the module-level 17357d523365SDimitry Andric // VST (where we want to jump to the VST offset) and the function-level 17367d523365SDimitry Andric // VST (where we don't). 17377d523365SDimitry Andric if (Offset > 0) { 17387d523365SDimitry Andric // Save the current parsing location so we can jump back at the end 17397d523365SDimitry Andric // of the VST read. 17407d523365SDimitry Andric CurrentBit = Stream.GetCurrentBitNo(); 17417d523365SDimitry Andric Stream.JumpToBit(Offset * 32); 17427d523365SDimitry Andric #ifndef NDEBUG 17437d523365SDimitry Andric // Do some checking if we are in debug mode. 17447d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 17457d523365SDimitry Andric assert(Entry.Kind == BitstreamEntry::SubBlock); 17467d523365SDimitry Andric assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID); 17477d523365SDimitry Andric #else 17487d523365SDimitry Andric // In NDEBUG mode ignore the output so we don't get an unused variable 17497d523365SDimitry Andric // warning. 17507d523365SDimitry Andric Stream.advance(); 17517d523365SDimitry Andric #endif 17527d523365SDimitry Andric } 17537d523365SDimitry Andric 17547d523365SDimitry Andric // Compute the delta between the bitcode indices in the VST (the word offset 17557d523365SDimitry Andric // to the word-aligned ENTER_SUBBLOCK for the function block, and that 17567d523365SDimitry Andric // expected by the lazy reader. The reader's EnterSubBlock expects to have 17577d523365SDimitry Andric // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID 17587d523365SDimitry Andric // (size BlockIDWidth). Note that we access the stream's AbbrevID width here 17597d523365SDimitry Andric // just before entering the VST subblock because: 1) the EnterSubBlock 17607d523365SDimitry Andric // changes the AbbrevID width; 2) the VST block is nested within the same 17617d523365SDimitry Andric // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same 17627d523365SDimitry Andric // AbbrevID width before calling EnterSubBlock; and 3) when we want to 17637d523365SDimitry Andric // jump to the FUNCTION_BLOCK using this offset later, we don't want 17647d523365SDimitry Andric // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. 17657d523365SDimitry Andric unsigned FuncBitcodeOffsetDelta = 17667d523365SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 17677d523365SDimitry Andric 1768f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 17698f0fd8f6SDimitry Andric return error("Invalid record"); 1770f22ef01cSRoman Divacky 1771f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1772f22ef01cSRoman Divacky 1773ff0cc061SDimitry Andric Triple TT(TheModule->getTargetTriple()); 1774ff0cc061SDimitry Andric 1775f22ef01cSRoman Divacky // Read all the records for this value table. 1776f22ef01cSRoman Divacky SmallString<128> ValueName; 1777f22ef01cSRoman Divacky while (1) { 1778139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1779f22ef01cSRoman Divacky 1780139f7f9bSDimitry Andric switch (Entry.Kind) { 1781139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1782139f7f9bSDimitry Andric case BitstreamEntry::Error: 17838f0fd8f6SDimitry Andric return error("Malformed block"); 1784139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 17857d523365SDimitry Andric if (Offset > 0) 17867d523365SDimitry Andric Stream.JumpToBit(CurrentBit); 178791bc56edSDimitry Andric return std::error_code(); 1788139f7f9bSDimitry Andric case BitstreamEntry::Record: 1789139f7f9bSDimitry Andric // The interesting case. 1790139f7f9bSDimitry Andric break; 1791f22ef01cSRoman Divacky } 1792f22ef01cSRoman Divacky 1793f22ef01cSRoman Divacky // Read a record. 1794f22ef01cSRoman Divacky Record.clear(); 1795139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 1796f22ef01cSRoman Divacky default: // Default behavior: unknown type. 1797f22ef01cSRoman Divacky break; 1798f22ef01cSRoman Divacky case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 17997d523365SDimitry Andric ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT); 18007d523365SDimitry Andric if (std::error_code EC = ValOrErr.getError()) 18017d523365SDimitry Andric return EC; 18027d523365SDimitry Andric ValOrErr.get(); 18037d523365SDimitry Andric break; 18047d523365SDimitry Andric } 18057d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 18067d523365SDimitry Andric // VST_FNENTRY: [valueid, offset, namechar x N] 18077d523365SDimitry Andric ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT); 18087d523365SDimitry Andric if (std::error_code EC = ValOrErr.getError()) 18097d523365SDimitry Andric return EC; 18107d523365SDimitry Andric Value *V = ValOrErr.get(); 1811f22ef01cSRoman Divacky 18127d523365SDimitry Andric auto *GO = dyn_cast<GlobalObject>(V); 18137d523365SDimitry Andric if (!GO) { 18147d523365SDimitry Andric // If this is an alias, need to get the actual Function object 18157d523365SDimitry Andric // it aliases, in order to set up the DeferredFunctionInfo entry below. 18167d523365SDimitry Andric auto *GA = dyn_cast<GlobalAlias>(V); 18177d523365SDimitry Andric if (GA) 18187d523365SDimitry Andric GO = GA->getBaseObject(); 18197d523365SDimitry Andric assert(GO); 1820ff0cc061SDimitry Andric } 18217d523365SDimitry Andric 18227d523365SDimitry Andric uint64_t FuncWordOffset = Record[1]; 18237d523365SDimitry Andric Function *F = dyn_cast<Function>(GO); 18247d523365SDimitry Andric assert(F); 18257d523365SDimitry Andric uint64_t FuncBitOffset = FuncWordOffset * 32; 18267d523365SDimitry Andric DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; 18277d523365SDimitry Andric // Set the LastFunctionBlockBit to point to the last function block. 18287d523365SDimitry Andric // Later when parsing is resumed after function materialization, 18297d523365SDimitry Andric // we can simply skip that last function block. 18307d523365SDimitry Andric if (FuncBitOffset > LastFunctionBlockBit) 18317d523365SDimitry Andric LastFunctionBlockBit = FuncBitOffset; 1832f22ef01cSRoman Divacky break; 1833f22ef01cSRoman Divacky } 1834f22ef01cSRoman Divacky case bitc::VST_CODE_BBENTRY: { 18358f0fd8f6SDimitry Andric if (convertToString(Record, 1, ValueName)) 18368f0fd8f6SDimitry Andric return error("Invalid record"); 1837f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[0]); 183891bc56edSDimitry Andric if (!BB) 18398f0fd8f6SDimitry Andric return error("Invalid record"); 1840f22ef01cSRoman Divacky 1841f22ef01cSRoman Divacky BB->setName(StringRef(ValueName.data(), ValueName.size())); 1842f22ef01cSRoman Divacky ValueName.clear(); 1843f22ef01cSRoman Divacky break; 1844f22ef01cSRoman Divacky } 1845f22ef01cSRoman Divacky } 1846f22ef01cSRoman Divacky } 1847f22ef01cSRoman Divacky } 1848f22ef01cSRoman Divacky 18497d523365SDimitry Andric /// Parse a single METADATA_KIND record, inserting result in MDKindMap. 18507d523365SDimitry Andric std::error_code 18517d523365SDimitry Andric BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) { 18527d523365SDimitry Andric if (Record.size() < 2) 18537d523365SDimitry Andric return error("Invalid record"); 18547d523365SDimitry Andric 18557d523365SDimitry Andric unsigned Kind = Record[0]; 18567d523365SDimitry Andric SmallString<8> Name(Record.begin() + 1, Record.end()); 18577d523365SDimitry Andric 18587d523365SDimitry Andric unsigned NewKind = TheModule->getMDKindID(Name.str()); 18597d523365SDimitry Andric if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 18607d523365SDimitry Andric return error("Conflicting METADATA_KIND records"); 18617d523365SDimitry Andric return std::error_code(); 18627d523365SDimitry Andric } 18637d523365SDimitry Andric 1864ff0cc061SDimitry Andric static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; } 1865ff0cc061SDimitry Andric 18667d523365SDimitry Andric /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing 18677d523365SDimitry Andric /// module level metadata. 18687d523365SDimitry Andric std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) { 1869ff0cc061SDimitry Andric IsMetadataMaterialized = true; 18707d523365SDimitry Andric unsigned NextMetadataNo = MetadataList.size(); 18717d523365SDimitry Andric if (ModuleLevel && SeenModuleValuesRecord) { 18727d523365SDimitry Andric // Now that we are parsing the module level metadata, we want to restart 18737d523365SDimitry Andric // the numbering of the MD values, and replace temp MD created earlier 18747d523365SDimitry Andric // with their real values. If we saw a METADATA_VALUE record then we 18757d523365SDimitry Andric // would have set the MetadataList size to the number specified in that 18767d523365SDimitry Andric // record, to support parsing function-level metadata first, and we need 18777d523365SDimitry Andric // to reset back to 0 to fill the MetadataList in with the parsed module 18787d523365SDimitry Andric // The function-level metadata parsing should have reset the MetadataList 18797d523365SDimitry Andric // size back to the value reported by the METADATA_VALUE record, saved in 18807d523365SDimitry Andric // NumModuleMDs. 18817d523365SDimitry Andric assert(NumModuleMDs == MetadataList.size() && 18827d523365SDimitry Andric "Expected MetadataList to only contain module level values"); 18837d523365SDimitry Andric NextMetadataNo = 0; 18847d523365SDimitry Andric } 1885f22ef01cSRoman Divacky 1886f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 18878f0fd8f6SDimitry Andric return error("Invalid record"); 1888f22ef01cSRoman Divacky 1889f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 1890f22ef01cSRoman Divacky 18917d523365SDimitry Andric auto getMD = [&](unsigned ID) -> Metadata * { 18927d523365SDimitry Andric return MetadataList.getValueFwdRef(ID); 18937d523365SDimitry Andric }; 1894ff0cc061SDimitry Andric auto getMDOrNull = [&](unsigned ID) -> Metadata *{ 1895ff0cc061SDimitry Andric if (ID) 1896ff0cc061SDimitry Andric return getMD(ID - 1); 1897ff0cc061SDimitry Andric return nullptr; 1898ff0cc061SDimitry Andric }; 1899ff0cc061SDimitry Andric auto getMDString = [&](unsigned ID) -> MDString *{ 1900ff0cc061SDimitry Andric // This requires that the ID is not really a forward reference. In 1901ff0cc061SDimitry Andric // particular, the MDString must already have been resolved. 1902ff0cc061SDimitry Andric return cast_or_null<MDString>(getMDOrNull(ID)); 1903ff0cc061SDimitry Andric }; 1904ff0cc061SDimitry Andric 1905ff0cc061SDimitry Andric #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \ 1906ff0cc061SDimitry Andric (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS) 1907ff0cc061SDimitry Andric 1908f22ef01cSRoman Divacky // Read all the records. 1909f22ef01cSRoman Divacky while (1) { 1910139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1911139f7f9bSDimitry Andric 1912139f7f9bSDimitry Andric switch (Entry.Kind) { 1913139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 1914139f7f9bSDimitry Andric case BitstreamEntry::Error: 19158f0fd8f6SDimitry Andric return error("Malformed block"); 1916139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 19177d523365SDimitry Andric MetadataList.tryToResolveCycles(); 19187d523365SDimitry Andric assert((!(ModuleLevel && SeenModuleValuesRecord) || 19197d523365SDimitry Andric NumModuleMDs == MetadataList.size()) && 19207d523365SDimitry Andric "Inconsistent bitcode: METADATA_VALUES mismatch"); 192191bc56edSDimitry Andric return std::error_code(); 1922139f7f9bSDimitry Andric case BitstreamEntry::Record: 1923139f7f9bSDimitry Andric // The interesting case. 1924139f7f9bSDimitry Andric break; 1925f22ef01cSRoman Divacky } 1926f22ef01cSRoman Divacky 1927f22ef01cSRoman Divacky // Read a record. 1928f22ef01cSRoman Divacky Record.clear(); 1929139f7f9bSDimitry Andric unsigned Code = Stream.readRecord(Entry.ID, Record); 193039d628a0SDimitry Andric bool IsDistinct = false; 1931e580952dSDimitry Andric switch (Code) { 1932f22ef01cSRoman Divacky default: // Default behavior: ignore. 1933f22ef01cSRoman Divacky break; 1934f22ef01cSRoman Divacky case bitc::METADATA_NAME: { 1935139f7f9bSDimitry Andric // Read name of the named metadata. 19367ae0e2c9SDimitry Andric SmallString<8> Name(Record.begin(), Record.end()); 1937f22ef01cSRoman Divacky Record.clear(); 1938f22ef01cSRoman Divacky Code = Stream.ReadCode(); 1939f22ef01cSRoman Divacky 1940139f7f9bSDimitry Andric unsigned NextBitCode = Stream.readRecord(Code, Record); 194197bc6c73SDimitry Andric if (NextBitCode != bitc::METADATA_NAMED_NODE) 19428f0fd8f6SDimitry Andric return error("METADATA_NAME not followed by METADATA_NAMED_NODE"); 1943f22ef01cSRoman Divacky 1944f22ef01cSRoman Divacky // Read named metadata elements. 1945f22ef01cSRoman Divacky unsigned Size = Record.size(); 1946e580952dSDimitry Andric NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 1947f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) { 19487d523365SDimitry Andric MDNode *MD = 19497d523365SDimitry Andric dyn_cast_or_null<MDNode>(MetadataList.getValueFwdRef(Record[i])); 195091bc56edSDimitry Andric if (!MD) 19518f0fd8f6SDimitry Andric return error("Invalid record"); 1952e580952dSDimitry Andric NMD->addOperand(MD); 1953f22ef01cSRoman Divacky } 1954f22ef01cSRoman Divacky break; 1955f22ef01cSRoman Divacky } 195639d628a0SDimitry Andric case bitc::METADATA_OLD_FN_NODE: { 195739d628a0SDimitry Andric // FIXME: Remove in 4.0. 195839d628a0SDimitry Andric // This is a LocalAsMetadata record, the only type of function-local 195939d628a0SDimitry Andric // metadata. 1960ffd1746dSEd Schouten if (Record.size() % 2 == 1) 19618f0fd8f6SDimitry Andric return error("Invalid record"); 196239d628a0SDimitry Andric 196339d628a0SDimitry Andric // If this isn't a LocalAsMetadata record, we're dropping it. This used 196439d628a0SDimitry Andric // to be legal, but there's no upgrade path. 196539d628a0SDimitry Andric auto dropRecord = [&] { 19667d523365SDimitry Andric MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++); 196739d628a0SDimitry Andric }; 196839d628a0SDimitry Andric if (Record.size() != 2) { 196939d628a0SDimitry Andric dropRecord(); 197039d628a0SDimitry Andric break; 197139d628a0SDimitry Andric } 197239d628a0SDimitry Andric 197339d628a0SDimitry Andric Type *Ty = getTypeByID(Record[0]); 197439d628a0SDimitry Andric if (Ty->isMetadataTy() || Ty->isVoidTy()) { 197539d628a0SDimitry Andric dropRecord(); 197639d628a0SDimitry Andric break; 197739d628a0SDimitry Andric } 197839d628a0SDimitry Andric 19797d523365SDimitry Andric MetadataList.assignValue( 198039d628a0SDimitry Andric LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 19817d523365SDimitry Andric NextMetadataNo++); 198239d628a0SDimitry Andric break; 198339d628a0SDimitry Andric } 198439d628a0SDimitry Andric case bitc::METADATA_OLD_NODE: { 198539d628a0SDimitry Andric // FIXME: Remove in 4.0. 198639d628a0SDimitry Andric if (Record.size() % 2 == 1) 19878f0fd8f6SDimitry Andric return error("Invalid record"); 1988f22ef01cSRoman Divacky 1989f22ef01cSRoman Divacky unsigned Size = Record.size(); 199039d628a0SDimitry Andric SmallVector<Metadata *, 8> Elts; 1991f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; i += 2) { 19926122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[i]); 1993f785676fSDimitry Andric if (!Ty) 19948f0fd8f6SDimitry Andric return error("Invalid record"); 1995f22ef01cSRoman Divacky if (Ty->isMetadataTy()) 19967d523365SDimitry Andric Elts.push_back(MetadataList.getValueFwdRef(Record[i + 1])); 199739d628a0SDimitry Andric else if (!Ty->isVoidTy()) { 199839d628a0SDimitry Andric auto *MD = 199939d628a0SDimitry Andric ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty)); 200039d628a0SDimitry Andric assert(isa<ConstantAsMetadata>(MD) && 200139d628a0SDimitry Andric "Expected non-function-local metadata"); 200239d628a0SDimitry Andric Elts.push_back(MD); 200339d628a0SDimitry Andric } else 200491bc56edSDimitry Andric Elts.push_back(nullptr); 2005f22ef01cSRoman Divacky } 20067d523365SDimitry Andric MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++); 200739d628a0SDimitry Andric break; 200839d628a0SDimitry Andric } 200939d628a0SDimitry Andric case bitc::METADATA_VALUE: { 201039d628a0SDimitry Andric if (Record.size() != 2) 20118f0fd8f6SDimitry Andric return error("Invalid record"); 201239d628a0SDimitry Andric 201339d628a0SDimitry Andric Type *Ty = getTypeByID(Record[0]); 201439d628a0SDimitry Andric if (Ty->isMetadataTy() || Ty->isVoidTy()) 20158f0fd8f6SDimitry Andric return error("Invalid record"); 201639d628a0SDimitry Andric 20177d523365SDimitry Andric MetadataList.assignValue( 201839d628a0SDimitry Andric ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 20197d523365SDimitry Andric NextMetadataNo++); 202039d628a0SDimitry Andric break; 202139d628a0SDimitry Andric } 202239d628a0SDimitry Andric case bitc::METADATA_DISTINCT_NODE: 202339d628a0SDimitry Andric IsDistinct = true; 202439d628a0SDimitry Andric // fallthrough... 202539d628a0SDimitry Andric case bitc::METADATA_NODE: { 202639d628a0SDimitry Andric SmallVector<Metadata *, 8> Elts; 202739d628a0SDimitry Andric Elts.reserve(Record.size()); 202839d628a0SDimitry Andric for (unsigned ID : Record) 20297d523365SDimitry Andric Elts.push_back(ID ? MetadataList.getValueFwdRef(ID - 1) : nullptr); 20307d523365SDimitry Andric MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts) 203139d628a0SDimitry Andric : MDNode::get(Context, Elts), 20327d523365SDimitry Andric NextMetadataNo++); 203339d628a0SDimitry Andric break; 203439d628a0SDimitry Andric } 203539d628a0SDimitry Andric case bitc::METADATA_LOCATION: { 203639d628a0SDimitry Andric if (Record.size() != 5) 20378f0fd8f6SDimitry Andric return error("Invalid record"); 203839d628a0SDimitry Andric 203939d628a0SDimitry Andric unsigned Line = Record[1]; 204039d628a0SDimitry Andric unsigned Column = Record[2]; 20417d523365SDimitry Andric MDNode *Scope = cast<MDNode>(MetadataList.getValueFwdRef(Record[3])); 204239d628a0SDimitry Andric Metadata *InlinedAt = 20437d523365SDimitry Andric Record[4] ? MetadataList.getValueFwdRef(Record[4] - 1) : nullptr; 20447d523365SDimitry Andric MetadataList.assignValue( 2045ff0cc061SDimitry Andric GET_OR_DISTINCT(DILocation, Record[0], 2046ff0cc061SDimitry Andric (Context, Line, Column, Scope, InlinedAt)), 20477d523365SDimitry Andric NextMetadataNo++); 2048ff0cc061SDimitry Andric break; 2049ff0cc061SDimitry Andric } 2050ff0cc061SDimitry Andric case bitc::METADATA_GENERIC_DEBUG: { 2051ff0cc061SDimitry Andric if (Record.size() < 4) 20528f0fd8f6SDimitry Andric return error("Invalid record"); 2053ff0cc061SDimitry Andric 2054ff0cc061SDimitry Andric unsigned Tag = Record[1]; 2055ff0cc061SDimitry Andric unsigned Version = Record[2]; 2056ff0cc061SDimitry Andric 2057ff0cc061SDimitry Andric if (Tag >= 1u << 16 || Version != 0) 20588f0fd8f6SDimitry Andric return error("Invalid record"); 2059ff0cc061SDimitry Andric 2060ff0cc061SDimitry Andric auto *Header = getMDString(Record[3]); 2061ff0cc061SDimitry Andric SmallVector<Metadata *, 8> DwarfOps; 2062ff0cc061SDimitry Andric for (unsigned I = 4, E = Record.size(); I != E; ++I) 20637d523365SDimitry Andric DwarfOps.push_back( 20647d523365SDimitry Andric Record[I] ? MetadataList.getValueFwdRef(Record[I] - 1) : nullptr); 20657d523365SDimitry Andric MetadataList.assignValue( 20667d523365SDimitry Andric GET_OR_DISTINCT(GenericDINode, Record[0], 2067ff0cc061SDimitry Andric (Context, Tag, Header, DwarfOps)), 20687d523365SDimitry Andric NextMetadataNo++); 2069ff0cc061SDimitry Andric break; 2070ff0cc061SDimitry Andric } 2071ff0cc061SDimitry Andric case bitc::METADATA_SUBRANGE: { 2072ff0cc061SDimitry Andric if (Record.size() != 3) 20738f0fd8f6SDimitry Andric return error("Invalid record"); 2074ff0cc061SDimitry Andric 20757d523365SDimitry Andric MetadataList.assignValue( 2076ff0cc061SDimitry Andric GET_OR_DISTINCT(DISubrange, Record[0], 2077ff0cc061SDimitry Andric (Context, Record[1], unrotateSign(Record[2]))), 20787d523365SDimitry Andric NextMetadataNo++); 2079ff0cc061SDimitry Andric break; 2080ff0cc061SDimitry Andric } 2081ff0cc061SDimitry Andric case bitc::METADATA_ENUMERATOR: { 2082ff0cc061SDimitry Andric if (Record.size() != 3) 20838f0fd8f6SDimitry Andric return error("Invalid record"); 2084ff0cc061SDimitry Andric 20857d523365SDimitry Andric MetadataList.assignValue( 20867d523365SDimitry Andric GET_OR_DISTINCT( 20877d523365SDimitry Andric DIEnumerator, Record[0], 20887d523365SDimitry Andric (Context, unrotateSign(Record[1]), getMDString(Record[2]))), 20897d523365SDimitry Andric NextMetadataNo++); 2090ff0cc061SDimitry Andric break; 2091ff0cc061SDimitry Andric } 2092ff0cc061SDimitry Andric case bitc::METADATA_BASIC_TYPE: { 2093ff0cc061SDimitry Andric if (Record.size() != 6) 20948f0fd8f6SDimitry Andric return error("Invalid record"); 2095ff0cc061SDimitry Andric 20967d523365SDimitry Andric MetadataList.assignValue( 2097ff0cc061SDimitry Andric GET_OR_DISTINCT(DIBasicType, Record[0], 2098ff0cc061SDimitry Andric (Context, Record[1], getMDString(Record[2]), 2099ff0cc061SDimitry Andric Record[3], Record[4], Record[5])), 21007d523365SDimitry Andric NextMetadataNo++); 2101ff0cc061SDimitry Andric break; 2102ff0cc061SDimitry Andric } 2103ff0cc061SDimitry Andric case bitc::METADATA_DERIVED_TYPE: { 2104ff0cc061SDimitry Andric if (Record.size() != 12) 21058f0fd8f6SDimitry Andric return error("Invalid record"); 2106ff0cc061SDimitry Andric 21077d523365SDimitry Andric MetadataList.assignValue( 2108ff0cc061SDimitry Andric GET_OR_DISTINCT(DIDerivedType, Record[0], 2109ff0cc061SDimitry Andric (Context, Record[1], getMDString(Record[2]), 2110ff0cc061SDimitry Andric getMDOrNull(Record[3]), Record[4], 2111ff0cc061SDimitry Andric getMDOrNull(Record[5]), getMDOrNull(Record[6]), 2112ff0cc061SDimitry Andric Record[7], Record[8], Record[9], Record[10], 2113ff0cc061SDimitry Andric getMDOrNull(Record[11]))), 21147d523365SDimitry Andric NextMetadataNo++); 2115ff0cc061SDimitry Andric break; 2116ff0cc061SDimitry Andric } 2117ff0cc061SDimitry Andric case bitc::METADATA_COMPOSITE_TYPE: { 2118ff0cc061SDimitry Andric if (Record.size() != 16) 21198f0fd8f6SDimitry Andric return error("Invalid record"); 2120ff0cc061SDimitry Andric 21217d523365SDimitry Andric MetadataList.assignValue( 2122ff0cc061SDimitry Andric GET_OR_DISTINCT(DICompositeType, Record[0], 2123ff0cc061SDimitry Andric (Context, Record[1], getMDString(Record[2]), 2124ff0cc061SDimitry Andric getMDOrNull(Record[3]), Record[4], 2125ff0cc061SDimitry Andric getMDOrNull(Record[5]), getMDOrNull(Record[6]), 2126ff0cc061SDimitry Andric Record[7], Record[8], Record[9], Record[10], 2127ff0cc061SDimitry Andric getMDOrNull(Record[11]), Record[12], 2128ff0cc061SDimitry Andric getMDOrNull(Record[13]), getMDOrNull(Record[14]), 2129ff0cc061SDimitry Andric getMDString(Record[15]))), 21307d523365SDimitry Andric NextMetadataNo++); 2131ff0cc061SDimitry Andric break; 2132ff0cc061SDimitry Andric } 2133ff0cc061SDimitry Andric case bitc::METADATA_SUBROUTINE_TYPE: { 2134ff0cc061SDimitry Andric if (Record.size() != 3) 21358f0fd8f6SDimitry Andric return error("Invalid record"); 2136ff0cc061SDimitry Andric 21377d523365SDimitry Andric MetadataList.assignValue( 2138ff0cc061SDimitry Andric GET_OR_DISTINCT(DISubroutineType, Record[0], 2139ff0cc061SDimitry Andric (Context, Record[1], getMDOrNull(Record[2]))), 21407d523365SDimitry Andric NextMetadataNo++); 2141ff0cc061SDimitry Andric break; 2142ff0cc061SDimitry Andric } 21433dac3a9bSDimitry Andric 21443dac3a9bSDimitry Andric case bitc::METADATA_MODULE: { 21453dac3a9bSDimitry Andric if (Record.size() != 6) 21463dac3a9bSDimitry Andric return error("Invalid record"); 21473dac3a9bSDimitry Andric 21487d523365SDimitry Andric MetadataList.assignValue( 21493dac3a9bSDimitry Andric GET_OR_DISTINCT(DIModule, Record[0], 21503dac3a9bSDimitry Andric (Context, getMDOrNull(Record[1]), 21513dac3a9bSDimitry Andric getMDString(Record[2]), getMDString(Record[3]), 21523dac3a9bSDimitry Andric getMDString(Record[4]), getMDString(Record[5]))), 21537d523365SDimitry Andric NextMetadataNo++); 21543dac3a9bSDimitry Andric break; 21553dac3a9bSDimitry Andric } 21563dac3a9bSDimitry Andric 2157ff0cc061SDimitry Andric case bitc::METADATA_FILE: { 2158ff0cc061SDimitry Andric if (Record.size() != 3) 21598f0fd8f6SDimitry Andric return error("Invalid record"); 2160ff0cc061SDimitry Andric 21617d523365SDimitry Andric MetadataList.assignValue( 2162ff0cc061SDimitry Andric GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]), 2163ff0cc061SDimitry Andric getMDString(Record[2]))), 21647d523365SDimitry Andric NextMetadataNo++); 2165ff0cc061SDimitry Andric break; 2166ff0cc061SDimitry Andric } 2167ff0cc061SDimitry Andric case bitc::METADATA_COMPILE_UNIT: { 21687d523365SDimitry Andric if (Record.size() < 14 || Record.size() > 16) 21698f0fd8f6SDimitry Andric return error("Invalid record"); 2170ff0cc061SDimitry Andric 21717d523365SDimitry Andric // Ignore Record[0], which indicates whether this compile unit is 21727d523365SDimitry Andric // distinct. It's always distinct. 21737d523365SDimitry Andric MetadataList.assignValue( 21747d523365SDimitry Andric DICompileUnit::getDistinct( 21757d523365SDimitry Andric Context, Record[1], getMDOrNull(Record[2]), 21768f0fd8f6SDimitry Andric getMDString(Record[3]), Record[4], getMDString(Record[5]), 21778f0fd8f6SDimitry Andric Record[6], getMDString(Record[7]), Record[8], 2178ff0cc061SDimitry Andric getMDOrNull(Record[9]), getMDOrNull(Record[10]), 2179ff0cc061SDimitry Andric getMDOrNull(Record[11]), getMDOrNull(Record[12]), 21807d523365SDimitry Andric getMDOrNull(Record[13]), 21817d523365SDimitry Andric Record.size() <= 15 ? 0 : getMDOrNull(Record[15]), 21827d523365SDimitry Andric Record.size() <= 14 ? 0 : Record[14]), 21837d523365SDimitry Andric NextMetadataNo++); 2184ff0cc061SDimitry Andric break; 2185ff0cc061SDimitry Andric } 2186ff0cc061SDimitry Andric case bitc::METADATA_SUBPROGRAM: { 21877d523365SDimitry Andric if (Record.size() != 18 && Record.size() != 19) 21888f0fd8f6SDimitry Andric return error("Invalid record"); 2189ff0cc061SDimitry Andric 21907d523365SDimitry Andric bool HasFn = Record.size() == 19; 21917d523365SDimitry Andric DISubprogram *SP = GET_OR_DISTINCT( 21927d523365SDimitry Andric DISubprogram, 21937d523365SDimitry Andric Record[0] || Record[8], // All definitions should be distinct. 2194ff0cc061SDimitry Andric (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 2195ff0cc061SDimitry Andric getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 2196ff0cc061SDimitry Andric getMDOrNull(Record[6]), Record[7], Record[8], Record[9], 2197ff0cc061SDimitry Andric getMDOrNull(Record[10]), Record[11], Record[12], Record[13], 21987d523365SDimitry Andric Record[14], getMDOrNull(Record[15 + HasFn]), 21997d523365SDimitry Andric getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn]))); 22007d523365SDimitry Andric MetadataList.assignValue(SP, NextMetadataNo++); 22017d523365SDimitry Andric 22027d523365SDimitry Andric // Upgrade sp->function mapping to function->sp mapping. 22037d523365SDimitry Andric if (HasFn && Record[15]) { 22047d523365SDimitry Andric if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15]))) 22057d523365SDimitry Andric if (auto *F = dyn_cast<Function>(CMD->getValue())) { 22067d523365SDimitry Andric if (F->isMaterializable()) 22077d523365SDimitry Andric // Defer until materialized; unmaterialized functions may not have 22087d523365SDimitry Andric // metadata. 22097d523365SDimitry Andric FunctionsWithSPs[F] = SP; 22107d523365SDimitry Andric else if (!F->empty()) 22117d523365SDimitry Andric F->setSubprogram(SP); 22127d523365SDimitry Andric } 22137d523365SDimitry Andric } 2214ff0cc061SDimitry Andric break; 2215ff0cc061SDimitry Andric } 2216ff0cc061SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK: { 2217ff0cc061SDimitry Andric if (Record.size() != 5) 22188f0fd8f6SDimitry Andric return error("Invalid record"); 2219ff0cc061SDimitry Andric 22207d523365SDimitry Andric MetadataList.assignValue( 2221ff0cc061SDimitry Andric GET_OR_DISTINCT(DILexicalBlock, Record[0], 2222ff0cc061SDimitry Andric (Context, getMDOrNull(Record[1]), 2223ff0cc061SDimitry Andric getMDOrNull(Record[2]), Record[3], Record[4])), 22247d523365SDimitry Andric NextMetadataNo++); 2225ff0cc061SDimitry Andric break; 2226ff0cc061SDimitry Andric } 2227ff0cc061SDimitry Andric case bitc::METADATA_LEXICAL_BLOCK_FILE: { 2228ff0cc061SDimitry Andric if (Record.size() != 4) 22298f0fd8f6SDimitry Andric return error("Invalid record"); 2230ff0cc061SDimitry Andric 22317d523365SDimitry Andric MetadataList.assignValue( 2232ff0cc061SDimitry Andric GET_OR_DISTINCT(DILexicalBlockFile, Record[0], 2233ff0cc061SDimitry Andric (Context, getMDOrNull(Record[1]), 2234ff0cc061SDimitry Andric getMDOrNull(Record[2]), Record[3])), 22357d523365SDimitry Andric NextMetadataNo++); 2236ff0cc061SDimitry Andric break; 2237ff0cc061SDimitry Andric } 2238ff0cc061SDimitry Andric case bitc::METADATA_NAMESPACE: { 2239ff0cc061SDimitry Andric if (Record.size() != 5) 22408f0fd8f6SDimitry Andric return error("Invalid record"); 2241ff0cc061SDimitry Andric 22427d523365SDimitry Andric MetadataList.assignValue( 2243ff0cc061SDimitry Andric GET_OR_DISTINCT(DINamespace, Record[0], 2244ff0cc061SDimitry Andric (Context, getMDOrNull(Record[1]), 2245ff0cc061SDimitry Andric getMDOrNull(Record[2]), getMDString(Record[3]), 2246ff0cc061SDimitry Andric Record[4])), 22477d523365SDimitry Andric NextMetadataNo++); 22487d523365SDimitry Andric break; 22497d523365SDimitry Andric } 22507d523365SDimitry Andric case bitc::METADATA_MACRO: { 22517d523365SDimitry Andric if (Record.size() != 5) 22527d523365SDimitry Andric return error("Invalid record"); 22537d523365SDimitry Andric 22547d523365SDimitry Andric MetadataList.assignValue( 22557d523365SDimitry Andric GET_OR_DISTINCT(DIMacro, Record[0], 22567d523365SDimitry Andric (Context, Record[1], Record[2], 22577d523365SDimitry Andric getMDString(Record[3]), getMDString(Record[4]))), 22587d523365SDimitry Andric NextMetadataNo++); 22597d523365SDimitry Andric break; 22607d523365SDimitry Andric } 22617d523365SDimitry Andric case bitc::METADATA_MACRO_FILE: { 22627d523365SDimitry Andric if (Record.size() != 5) 22637d523365SDimitry Andric return error("Invalid record"); 22647d523365SDimitry Andric 22657d523365SDimitry Andric MetadataList.assignValue( 22667d523365SDimitry Andric GET_OR_DISTINCT(DIMacroFile, Record[0], 22677d523365SDimitry Andric (Context, Record[1], Record[2], 22687d523365SDimitry Andric getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 22697d523365SDimitry Andric NextMetadataNo++); 2270ff0cc061SDimitry Andric break; 2271ff0cc061SDimitry Andric } 2272ff0cc061SDimitry Andric case bitc::METADATA_TEMPLATE_TYPE: { 2273ff0cc061SDimitry Andric if (Record.size() != 3) 22748f0fd8f6SDimitry Andric return error("Invalid record"); 2275ff0cc061SDimitry Andric 22767d523365SDimitry Andric MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter, 2277ff0cc061SDimitry Andric Record[0], 2278ff0cc061SDimitry Andric (Context, getMDString(Record[1]), 2279ff0cc061SDimitry Andric getMDOrNull(Record[2]))), 22807d523365SDimitry Andric NextMetadataNo++); 2281ff0cc061SDimitry Andric break; 2282ff0cc061SDimitry Andric } 2283ff0cc061SDimitry Andric case bitc::METADATA_TEMPLATE_VALUE: { 2284ff0cc061SDimitry Andric if (Record.size() != 5) 22858f0fd8f6SDimitry Andric return error("Invalid record"); 2286ff0cc061SDimitry Andric 22877d523365SDimitry Andric MetadataList.assignValue( 2288ff0cc061SDimitry Andric GET_OR_DISTINCT(DITemplateValueParameter, Record[0], 2289ff0cc061SDimitry Andric (Context, Record[1], getMDString(Record[2]), 2290ff0cc061SDimitry Andric getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 22917d523365SDimitry Andric NextMetadataNo++); 2292ff0cc061SDimitry Andric break; 2293ff0cc061SDimitry Andric } 2294ff0cc061SDimitry Andric case bitc::METADATA_GLOBAL_VAR: { 2295ff0cc061SDimitry Andric if (Record.size() != 11) 22968f0fd8f6SDimitry Andric return error("Invalid record"); 2297ff0cc061SDimitry Andric 22987d523365SDimitry Andric MetadataList.assignValue( 2299ff0cc061SDimitry Andric GET_OR_DISTINCT(DIGlobalVariable, Record[0], 2300ff0cc061SDimitry Andric (Context, getMDOrNull(Record[1]), 2301ff0cc061SDimitry Andric getMDString(Record[2]), getMDString(Record[3]), 2302ff0cc061SDimitry Andric getMDOrNull(Record[4]), Record[5], 2303ff0cc061SDimitry Andric getMDOrNull(Record[6]), Record[7], Record[8], 2304ff0cc061SDimitry Andric getMDOrNull(Record[9]), getMDOrNull(Record[10]))), 23057d523365SDimitry Andric NextMetadataNo++); 2306ff0cc061SDimitry Andric break; 2307ff0cc061SDimitry Andric } 2308ff0cc061SDimitry Andric case bitc::METADATA_LOCAL_VAR: { 2309ff0cc061SDimitry Andric // 10th field is for the obseleted 'inlinedAt:' field. 23107d523365SDimitry Andric if (Record.size() < 8 || Record.size() > 10) 23118f0fd8f6SDimitry Andric return error("Invalid record"); 2312ff0cc061SDimitry Andric 23137d523365SDimitry Andric // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or 23147d523365SDimitry Andric // DW_TAG_arg_variable. 23157d523365SDimitry Andric bool HasTag = Record.size() > 8; 23167d523365SDimitry Andric MetadataList.assignValue( 2317ff0cc061SDimitry Andric GET_OR_DISTINCT(DILocalVariable, Record[0], 23187d523365SDimitry Andric (Context, getMDOrNull(Record[1 + HasTag]), 23197d523365SDimitry Andric getMDString(Record[2 + HasTag]), 23207d523365SDimitry Andric getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag], 23217d523365SDimitry Andric getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag], 23227d523365SDimitry Andric Record[7 + HasTag])), 23237d523365SDimitry Andric NextMetadataNo++); 2324ff0cc061SDimitry Andric break; 2325ff0cc061SDimitry Andric } 2326ff0cc061SDimitry Andric case bitc::METADATA_EXPRESSION: { 2327ff0cc061SDimitry Andric if (Record.size() < 1) 23288f0fd8f6SDimitry Andric return error("Invalid record"); 2329ff0cc061SDimitry Andric 23307d523365SDimitry Andric MetadataList.assignValue( 2331ff0cc061SDimitry Andric GET_OR_DISTINCT(DIExpression, Record[0], 2332ff0cc061SDimitry Andric (Context, makeArrayRef(Record).slice(1))), 23337d523365SDimitry Andric NextMetadataNo++); 2334ff0cc061SDimitry Andric break; 2335ff0cc061SDimitry Andric } 2336ff0cc061SDimitry Andric case bitc::METADATA_OBJC_PROPERTY: { 2337ff0cc061SDimitry Andric if (Record.size() != 8) 23388f0fd8f6SDimitry Andric return error("Invalid record"); 2339ff0cc061SDimitry Andric 23407d523365SDimitry Andric MetadataList.assignValue( 2341ff0cc061SDimitry Andric GET_OR_DISTINCT(DIObjCProperty, Record[0], 2342ff0cc061SDimitry Andric (Context, getMDString(Record[1]), 2343ff0cc061SDimitry Andric getMDOrNull(Record[2]), Record[3], 2344ff0cc061SDimitry Andric getMDString(Record[4]), getMDString(Record[5]), 2345ff0cc061SDimitry Andric Record[6], getMDOrNull(Record[7]))), 23467d523365SDimitry Andric NextMetadataNo++); 2347ff0cc061SDimitry Andric break; 2348ff0cc061SDimitry Andric } 2349ff0cc061SDimitry Andric case bitc::METADATA_IMPORTED_ENTITY: { 2350ff0cc061SDimitry Andric if (Record.size() != 6) 23518f0fd8f6SDimitry Andric return error("Invalid record"); 2352ff0cc061SDimitry Andric 23537d523365SDimitry Andric MetadataList.assignValue( 2354ff0cc061SDimitry Andric GET_OR_DISTINCT(DIImportedEntity, Record[0], 2355ff0cc061SDimitry Andric (Context, Record[1], getMDOrNull(Record[2]), 2356ff0cc061SDimitry Andric getMDOrNull(Record[3]), Record[4], 2357ff0cc061SDimitry Andric getMDString(Record[5]))), 23587d523365SDimitry Andric NextMetadataNo++); 2359f22ef01cSRoman Divacky break; 2360f22ef01cSRoman Divacky } 2361f22ef01cSRoman Divacky case bitc::METADATA_STRING: { 236291bc56edSDimitry Andric std::string String(Record.begin(), Record.end()); 236391bc56edSDimitry Andric llvm::UpgradeMDStringConstant(String); 236439d628a0SDimitry Andric Metadata *MD = MDString::get(Context, String); 23657d523365SDimitry Andric MetadataList.assignValue(MD, NextMetadataNo++); 2366f22ef01cSRoman Divacky break; 2367f22ef01cSRoman Divacky } 2368f22ef01cSRoman Divacky case bitc::METADATA_KIND: { 23697d523365SDimitry Andric // Support older bitcode files that had METADATA_KIND records in a 23707d523365SDimitry Andric // block with METADATA_BLOCK_ID. 23717d523365SDimitry Andric if (std::error_code EC = parseMetadataKindRecord(Record)) 23727d523365SDimitry Andric return EC; 2373f22ef01cSRoman Divacky break; 2374f22ef01cSRoman Divacky } 2375f22ef01cSRoman Divacky } 2376f22ef01cSRoman Divacky } 2377ff0cc061SDimitry Andric #undef GET_OR_DISTINCT 2378f22ef01cSRoman Divacky } 2379f22ef01cSRoman Divacky 23807d523365SDimitry Andric /// Parse the metadata kinds out of the METADATA_KIND_BLOCK. 23817d523365SDimitry Andric std::error_code BitcodeReader::parseMetadataKinds() { 23827d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID)) 23837d523365SDimitry Andric return error("Invalid record"); 23847d523365SDimitry Andric 23857d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 23867d523365SDimitry Andric 23877d523365SDimitry Andric // Read all the records. 23887d523365SDimitry Andric while (1) { 23897d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 23907d523365SDimitry Andric 23917d523365SDimitry Andric switch (Entry.Kind) { 23927d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 23937d523365SDimitry Andric case BitstreamEntry::Error: 23947d523365SDimitry Andric return error("Malformed block"); 23957d523365SDimitry Andric case BitstreamEntry::EndBlock: 23967d523365SDimitry Andric return std::error_code(); 23977d523365SDimitry Andric case BitstreamEntry::Record: 23987d523365SDimitry Andric // The interesting case. 23997d523365SDimitry Andric break; 24007d523365SDimitry Andric } 24017d523365SDimitry Andric 24027d523365SDimitry Andric // Read a record. 24037d523365SDimitry Andric Record.clear(); 24047d523365SDimitry Andric unsigned Code = Stream.readRecord(Entry.ID, Record); 24057d523365SDimitry Andric switch (Code) { 24067d523365SDimitry Andric default: // Default behavior: ignore. 24077d523365SDimitry Andric break; 24087d523365SDimitry Andric case bitc::METADATA_KIND: { 24097d523365SDimitry Andric if (std::error_code EC = parseMetadataKindRecord(Record)) 24107d523365SDimitry Andric return EC; 24117d523365SDimitry Andric break; 24127d523365SDimitry Andric } 24137d523365SDimitry Andric } 24147d523365SDimitry Andric } 24157d523365SDimitry Andric } 24167d523365SDimitry Andric 24178f0fd8f6SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR 24188f0fd8f6SDimitry Andric /// encoding. 24193861d79fSDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 2420f22ef01cSRoman Divacky if ((V & 1) == 0) 2421f22ef01cSRoman Divacky return V >> 1; 2422f22ef01cSRoman Divacky if (V != 1) 2423f22ef01cSRoman Divacky return -(V >> 1); 2424f22ef01cSRoman Divacky // There is no such thing as -0 with integers. "-0" really means MININT. 2425f22ef01cSRoman Divacky return 1ULL << 63; 2426f22ef01cSRoman Divacky } 2427f22ef01cSRoman Divacky 24288f0fd8f6SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can. 24298f0fd8f6SDimitry Andric std::error_code BitcodeReader::resolveGlobalAndAliasInits() { 2430f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 2431f22ef01cSRoman Divacky std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 2432f785676fSDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 243339d628a0SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist; 24348f0fd8f6SDimitry Andric std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist; 2435f22ef01cSRoman Divacky 2436f22ef01cSRoman Divacky GlobalInitWorklist.swap(GlobalInits); 2437f22ef01cSRoman Divacky AliasInitWorklist.swap(AliasInits); 2438f785676fSDimitry Andric FunctionPrefixWorklist.swap(FunctionPrefixes); 243939d628a0SDimitry Andric FunctionPrologueWorklist.swap(FunctionPrologues); 24408f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns); 2441f22ef01cSRoman Divacky 2442f22ef01cSRoman Divacky while (!GlobalInitWorklist.empty()) { 2443f22ef01cSRoman Divacky unsigned ValID = GlobalInitWorklist.back().second; 2444f22ef01cSRoman Divacky if (ValID >= ValueList.size()) { 2445f22ef01cSRoman Divacky // Not ready to resolve this yet, it requires something later in the file. 2446f22ef01cSRoman Divacky GlobalInits.push_back(GlobalInitWorklist.back()); 2447f22ef01cSRoman Divacky } else { 244891bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2449f22ef01cSRoman Divacky GlobalInitWorklist.back().first->setInitializer(C); 2450f22ef01cSRoman Divacky else 24518f0fd8f6SDimitry Andric return error("Expected a constant"); 2452f22ef01cSRoman Divacky } 2453f22ef01cSRoman Divacky GlobalInitWorklist.pop_back(); 2454f22ef01cSRoman Divacky } 2455f22ef01cSRoman Divacky 2456f22ef01cSRoman Divacky while (!AliasInitWorklist.empty()) { 2457f22ef01cSRoman Divacky unsigned ValID = AliasInitWorklist.back().second; 2458f22ef01cSRoman Divacky if (ValID >= ValueList.size()) { 2459f22ef01cSRoman Divacky AliasInits.push_back(AliasInitWorklist.back()); 2460f22ef01cSRoman Divacky } else { 246197bc6c73SDimitry Andric Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); 246297bc6c73SDimitry Andric if (!C) 24638f0fd8f6SDimitry Andric return error("Expected a constant"); 246497bc6c73SDimitry Andric GlobalAlias *Alias = AliasInitWorklist.back().first; 246597bc6c73SDimitry Andric if (C->getType() != Alias->getType()) 24668f0fd8f6SDimitry Andric return error("Alias and aliasee types don't match"); 246797bc6c73SDimitry Andric Alias->setAliasee(C); 2468f22ef01cSRoman Divacky } 2469f22ef01cSRoman Divacky AliasInitWorklist.pop_back(); 2470f22ef01cSRoman Divacky } 2471f785676fSDimitry Andric 2472f785676fSDimitry Andric while (!FunctionPrefixWorklist.empty()) { 2473f785676fSDimitry Andric unsigned ValID = FunctionPrefixWorklist.back().second; 2474f785676fSDimitry Andric if (ValID >= ValueList.size()) { 2475f785676fSDimitry Andric FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 2476f785676fSDimitry Andric } else { 247791bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2478f785676fSDimitry Andric FunctionPrefixWorklist.back().first->setPrefixData(C); 2479f785676fSDimitry Andric else 24808f0fd8f6SDimitry Andric return error("Expected a constant"); 2481f785676fSDimitry Andric } 2482f785676fSDimitry Andric FunctionPrefixWorklist.pop_back(); 2483f785676fSDimitry Andric } 2484f785676fSDimitry Andric 248539d628a0SDimitry Andric while (!FunctionPrologueWorklist.empty()) { 248639d628a0SDimitry Andric unsigned ValID = FunctionPrologueWorklist.back().second; 248739d628a0SDimitry Andric if (ValID >= ValueList.size()) { 248839d628a0SDimitry Andric FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 248939d628a0SDimitry Andric } else { 249039d628a0SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 249139d628a0SDimitry Andric FunctionPrologueWorklist.back().first->setPrologueData(C); 249239d628a0SDimitry Andric else 24938f0fd8f6SDimitry Andric return error("Expected a constant"); 249439d628a0SDimitry Andric } 249539d628a0SDimitry Andric FunctionPrologueWorklist.pop_back(); 249639d628a0SDimitry Andric } 249739d628a0SDimitry Andric 24988f0fd8f6SDimitry Andric while (!FunctionPersonalityFnWorklist.empty()) { 24998f0fd8f6SDimitry Andric unsigned ValID = FunctionPersonalityFnWorklist.back().second; 25008f0fd8f6SDimitry Andric if (ValID >= ValueList.size()) { 25018f0fd8f6SDimitry Andric FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back()); 25028f0fd8f6SDimitry Andric } else { 25038f0fd8f6SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 25048f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C); 25058f0fd8f6SDimitry Andric else 25068f0fd8f6SDimitry Andric return error("Expected a constant"); 25078f0fd8f6SDimitry Andric } 25088f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.pop_back(); 25098f0fd8f6SDimitry Andric } 25108f0fd8f6SDimitry Andric 251191bc56edSDimitry Andric return std::error_code(); 2512f22ef01cSRoman Divacky } 2513f22ef01cSRoman Divacky 25148f0fd8f6SDimitry Andric static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 25157ae0e2c9SDimitry Andric SmallVector<uint64_t, 8> Words(Vals.size()); 25167ae0e2c9SDimitry Andric std::transform(Vals.begin(), Vals.end(), Words.begin(), 25173861d79fSDimitry Andric BitcodeReader::decodeSignRotatedValue); 25187ae0e2c9SDimitry Andric 25197ae0e2c9SDimitry Andric return APInt(TypeBits, Words); 25207ae0e2c9SDimitry Andric } 25217ae0e2c9SDimitry Andric 25228f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseConstants() { 2523f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 25248f0fd8f6SDimitry Andric return error("Invalid record"); 2525f22ef01cSRoman Divacky 2526f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 2527f22ef01cSRoman Divacky 2528f22ef01cSRoman Divacky // Read all the records for this value table. 25296122f3e6SDimitry Andric Type *CurTy = Type::getInt32Ty(Context); 2530f22ef01cSRoman Divacky unsigned NextCstNo = ValueList.size(); 2531f22ef01cSRoman Divacky while (1) { 2532139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2533139f7f9bSDimitry Andric 2534139f7f9bSDimitry Andric switch (Entry.Kind) { 2535139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2536139f7f9bSDimitry Andric case BitstreamEntry::Error: 25378f0fd8f6SDimitry Andric return error("Malformed block"); 2538139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 2539139f7f9bSDimitry Andric if (NextCstNo != ValueList.size()) 25408f0fd8f6SDimitry Andric return error("Invalid ronstant reference"); 2541139f7f9bSDimitry Andric 2542139f7f9bSDimitry Andric // Once all the constants have been read, go through and resolve forward 2543139f7f9bSDimitry Andric // references. 25448f0fd8f6SDimitry Andric ValueList.resolveConstantForwardRefs(); 254591bc56edSDimitry Andric return std::error_code(); 2546139f7f9bSDimitry Andric case BitstreamEntry::Record: 2547139f7f9bSDimitry Andric // The interesting case. 2548f22ef01cSRoman Divacky break; 2549f22ef01cSRoman Divacky } 2550f22ef01cSRoman Divacky 2551f22ef01cSRoman Divacky // Read a record. 2552f22ef01cSRoman Divacky Record.clear(); 255391bc56edSDimitry Andric Value *V = nullptr; 2554139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2555f22ef01cSRoman Divacky switch (BitCode) { 2556f22ef01cSRoman Divacky default: // Default behavior: unknown constant 2557f22ef01cSRoman Divacky case bitc::CST_CODE_UNDEF: // UNDEF 2558f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2559f22ef01cSRoman Divacky break; 2560f22ef01cSRoman Divacky case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 2561f22ef01cSRoman Divacky if (Record.empty()) 25628f0fd8f6SDimitry Andric return error("Invalid record"); 256391bc56edSDimitry Andric if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 25648f0fd8f6SDimitry Andric return error("Invalid record"); 2565f22ef01cSRoman Divacky CurTy = TypeList[Record[0]]; 2566f22ef01cSRoman Divacky continue; // Skip the ValueList manipulation. 2567f22ef01cSRoman Divacky case bitc::CST_CODE_NULL: // NULL 2568f22ef01cSRoman Divacky V = Constant::getNullValue(CurTy); 2569f22ef01cSRoman Divacky break; 2570f22ef01cSRoman Divacky case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 2571f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty()) 25728f0fd8f6SDimitry Andric return error("Invalid record"); 25733861d79fSDimitry Andric V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 2574f22ef01cSRoman Divacky break; 2575f22ef01cSRoman Divacky case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 2576f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty()) 25778f0fd8f6SDimitry Andric return error("Invalid record"); 2578f22ef01cSRoman Divacky 25798f0fd8f6SDimitry Andric APInt VInt = 25808f0fd8f6SDimitry Andric readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 25817ae0e2c9SDimitry Andric V = ConstantInt::get(Context, VInt); 25827ae0e2c9SDimitry Andric 2583f22ef01cSRoman Divacky break; 2584f22ef01cSRoman Divacky } 2585f22ef01cSRoman Divacky case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 2586f22ef01cSRoman Divacky if (Record.empty()) 25878f0fd8f6SDimitry Andric return error("Invalid record"); 2588dff0c46cSDimitry Andric if (CurTy->isHalfTy()) 2589139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 2590139f7f9bSDimitry Andric APInt(16, (uint16_t)Record[0]))); 2591dff0c46cSDimitry Andric else if (CurTy->isFloatTy()) 2592139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 2593139f7f9bSDimitry Andric APInt(32, (uint32_t)Record[0]))); 2594f22ef01cSRoman Divacky else if (CurTy->isDoubleTy()) 2595139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 2596139f7f9bSDimitry Andric APInt(64, Record[0]))); 2597f22ef01cSRoman Divacky else if (CurTy->isX86_FP80Ty()) { 2598f22ef01cSRoman Divacky // Bits are not stored the same way as a normal i80 APInt, compensate. 2599f22ef01cSRoman Divacky uint64_t Rearrange[2]; 2600f22ef01cSRoman Divacky Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 2601f22ef01cSRoman Divacky Rearrange[1] = Record[0] >> 48; 2602139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 2603139f7f9bSDimitry Andric APInt(80, Rearrange))); 2604f22ef01cSRoman Divacky } else if (CurTy->isFP128Ty()) 2605139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 2606139f7f9bSDimitry Andric APInt(128, Record))); 2607f22ef01cSRoman Divacky else if (CurTy->isPPC_FP128Ty()) 2608139f7f9bSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 2609139f7f9bSDimitry Andric APInt(128, Record))); 2610f22ef01cSRoman Divacky else 2611f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2612f22ef01cSRoman Divacky break; 2613f22ef01cSRoman Divacky } 2614f22ef01cSRoman Divacky 2615f22ef01cSRoman Divacky case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 2616f22ef01cSRoman Divacky if (Record.empty()) 26178f0fd8f6SDimitry Andric return error("Invalid record"); 2618f22ef01cSRoman Divacky 2619f22ef01cSRoman Divacky unsigned Size = Record.size(); 2620dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts; 2621f22ef01cSRoman Divacky 26226122f3e6SDimitry Andric if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2623f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2624f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], 2625f22ef01cSRoman Divacky STy->getElementType(i))); 2626f22ef01cSRoman Divacky V = ConstantStruct::get(STy, Elts); 26276122f3e6SDimitry Andric } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 26286122f3e6SDimitry Andric Type *EltTy = ATy->getElementType(); 2629f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2630f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2631f22ef01cSRoman Divacky V = ConstantArray::get(ATy, Elts); 26326122f3e6SDimitry Andric } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 26336122f3e6SDimitry Andric Type *EltTy = VTy->getElementType(); 2634f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i) 2635f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2636f22ef01cSRoman Divacky V = ConstantVector::get(Elts); 2637f22ef01cSRoman Divacky } else { 2638f22ef01cSRoman Divacky V = UndefValue::get(CurTy); 2639f22ef01cSRoman Divacky } 2640f22ef01cSRoman Divacky break; 2641f22ef01cSRoman Divacky } 2642dff0c46cSDimitry Andric case bitc::CST_CODE_STRING: // STRING: [values] 2643f22ef01cSRoman Divacky case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 2644f22ef01cSRoman Divacky if (Record.empty()) 26458f0fd8f6SDimitry Andric return error("Invalid record"); 2646f22ef01cSRoman Divacky 26477ae0e2c9SDimitry Andric SmallString<16> Elts(Record.begin(), Record.end()); 2648dff0c46cSDimitry Andric V = ConstantDataArray::getString(Context, Elts, 2649dff0c46cSDimitry Andric BitCode == bitc::CST_CODE_CSTRING); 2650f22ef01cSRoman Divacky break; 2651f22ef01cSRoman Divacky } 2652dff0c46cSDimitry Andric case bitc::CST_CODE_DATA: {// DATA: [n x value] 2653dff0c46cSDimitry Andric if (Record.empty()) 26548f0fd8f6SDimitry Andric return error("Invalid record"); 2655dff0c46cSDimitry Andric 2656dff0c46cSDimitry Andric Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 2657dff0c46cSDimitry Andric unsigned Size = Record.size(); 2658dff0c46cSDimitry Andric 2659dff0c46cSDimitry Andric if (EltTy->isIntegerTy(8)) { 2660dff0c46cSDimitry Andric SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 2661dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2662dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2663dff0c46cSDimitry Andric else 2664dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2665dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(16)) { 2666dff0c46cSDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2667dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2668dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2669dff0c46cSDimitry Andric else 2670dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2671dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(32)) { 2672dff0c46cSDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2673dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2674dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2675dff0c46cSDimitry Andric else 2676dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2677dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(64)) { 2678dff0c46cSDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2679dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2680dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2681dff0c46cSDimitry Andric else 2682dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2683dff0c46cSDimitry Andric } else if (EltTy->isFloatTy()) { 26847ae0e2c9SDimitry Andric SmallVector<float, 16> Elts(Size); 26857ae0e2c9SDimitry Andric std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); 2686dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2687dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2688dff0c46cSDimitry Andric else 2689dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2690dff0c46cSDimitry Andric } else if (EltTy->isDoubleTy()) { 26917ae0e2c9SDimitry Andric SmallVector<double, 16> Elts(Size); 26927ae0e2c9SDimitry Andric std::transform(Record.begin(), Record.end(), Elts.begin(), 26937ae0e2c9SDimitry Andric BitsToDouble); 2694dff0c46cSDimitry Andric if (isa<VectorType>(CurTy)) 2695dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts); 2696dff0c46cSDimitry Andric else 2697dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts); 2698dff0c46cSDimitry Andric } else { 26998f0fd8f6SDimitry Andric return error("Invalid type for value"); 2700dff0c46cSDimitry Andric } 2701dff0c46cSDimitry Andric break; 2702dff0c46cSDimitry Andric } 2703dff0c46cSDimitry Andric 2704f22ef01cSRoman Divacky case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 2705f785676fSDimitry Andric if (Record.size() < 3) 27068f0fd8f6SDimitry Andric return error("Invalid record"); 27078f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 2708f22ef01cSRoman Divacky if (Opc < 0) { 2709f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown binop. 2710f22ef01cSRoman Divacky } else { 2711f22ef01cSRoman Divacky Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 2712f22ef01cSRoman Divacky Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 2713f22ef01cSRoman Divacky unsigned Flags = 0; 2714f22ef01cSRoman Divacky if (Record.size() >= 4) { 2715f22ef01cSRoman Divacky if (Opc == Instruction::Add || 2716f22ef01cSRoman Divacky Opc == Instruction::Sub || 27172754fe60SDimitry Andric Opc == Instruction::Mul || 27182754fe60SDimitry Andric Opc == Instruction::Shl) { 2719f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2720f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoSignedWrap; 2721f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2722f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 27232754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 27242754fe60SDimitry Andric Opc == Instruction::UDiv || 27252754fe60SDimitry Andric Opc == Instruction::LShr || 27262754fe60SDimitry Andric Opc == Instruction::AShr) { 27272754fe60SDimitry Andric if (Record[3] & (1 << bitc::PEO_EXACT)) 2728f22ef01cSRoman Divacky Flags |= SDivOperator::IsExact; 2729f22ef01cSRoman Divacky } 2730f22ef01cSRoman Divacky } 2731f22ef01cSRoman Divacky V = ConstantExpr::get(Opc, LHS, RHS, Flags); 2732f22ef01cSRoman Divacky } 2733f22ef01cSRoman Divacky break; 2734f22ef01cSRoman Divacky } 2735f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 2736f785676fSDimitry Andric if (Record.size() < 3) 27378f0fd8f6SDimitry Andric return error("Invalid record"); 27388f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[0]); 2739f22ef01cSRoman Divacky if (Opc < 0) { 2740f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown cast. 2741f22ef01cSRoman Divacky } else { 27426122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 2743f785676fSDimitry Andric if (!OpTy) 27448f0fd8f6SDimitry Andric return error("Invalid record"); 2745f22ef01cSRoman Divacky Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 2746f785676fSDimitry Andric V = UpgradeBitCastExpr(Opc, Op, CurTy); 2747f785676fSDimitry Andric if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 2748f22ef01cSRoman Divacky } 2749f22ef01cSRoman Divacky break; 2750f22ef01cSRoman Divacky } 2751f22ef01cSRoman Divacky case bitc::CST_CODE_CE_INBOUNDS_GEP: 2752f22ef01cSRoman Divacky case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 2753ff0cc061SDimitry Andric unsigned OpNum = 0; 2754ff0cc061SDimitry Andric Type *PointeeType = nullptr; 2755ff0cc061SDimitry Andric if (Record.size() % 2) 2756ff0cc061SDimitry Andric PointeeType = getTypeByID(Record[OpNum++]); 2757f22ef01cSRoman Divacky SmallVector<Constant*, 16> Elts; 2758ff0cc061SDimitry Andric while (OpNum != Record.size()) { 2759ff0cc061SDimitry Andric Type *ElTy = getTypeByID(Record[OpNum++]); 2760f785676fSDimitry Andric if (!ElTy) 27618f0fd8f6SDimitry Andric return error("Invalid record"); 2762ff0cc061SDimitry Andric Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); 2763f22ef01cSRoman Divacky } 2764ff0cc061SDimitry Andric 2765ff0cc061SDimitry Andric if (PointeeType && 2766ff0cc061SDimitry Andric PointeeType != 2767ff0cc061SDimitry Andric cast<SequentialType>(Elts[0]->getType()->getScalarType()) 2768ff0cc061SDimitry Andric ->getElementType()) 27698f0fd8f6SDimitry Andric return error("Explicit gep operator type does not match pointee type " 2770ff0cc061SDimitry Andric "of pointer operand"); 2771ff0cc061SDimitry Andric 27726122f3e6SDimitry Andric ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 2773ff0cc061SDimitry Andric V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 27746122f3e6SDimitry Andric BitCode == 27756122f3e6SDimitry Andric bitc::CST_CODE_CE_INBOUNDS_GEP); 2776f22ef01cSRoman Divacky break; 2777f22ef01cSRoman Divacky } 2778f785676fSDimitry Andric case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 2779f785676fSDimitry Andric if (Record.size() < 3) 27808f0fd8f6SDimitry Andric return error("Invalid record"); 2781f785676fSDimitry Andric 2782f785676fSDimitry Andric Type *SelectorTy = Type::getInt1Ty(Context); 2783f785676fSDimitry Andric 27847d523365SDimitry Andric // The selector might be an i1 or an <n x i1> 27857d523365SDimitry Andric // Get the type from the ValueList before getting a forward ref. 2786f785676fSDimitry Andric if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 27877d523365SDimitry Andric if (Value *V = ValueList[Record[0]]) 27887d523365SDimitry Andric if (SelectorTy != V->getType()) 27897d523365SDimitry Andric SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements()); 2790f785676fSDimitry Andric 2791f785676fSDimitry Andric V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 2792f785676fSDimitry Andric SelectorTy), 2793f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[1],CurTy), 2794f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[2],CurTy)); 2795f22ef01cSRoman Divacky break; 2796f785676fSDimitry Andric } 279791bc56edSDimitry Andric case bitc::CST_CODE_CE_EXTRACTELT 279891bc56edSDimitry Andric : { // CE_EXTRACTELT: [opty, opval, opty, opval] 2799f785676fSDimitry Andric if (Record.size() < 3) 28008f0fd8f6SDimitry Andric return error("Invalid record"); 28016122f3e6SDimitry Andric VectorType *OpTy = 2802f22ef01cSRoman Divacky dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 280391bc56edSDimitry Andric if (!OpTy) 28048f0fd8f6SDimitry Andric return error("Invalid record"); 2805f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 280691bc56edSDimitry Andric Constant *Op1 = nullptr; 280791bc56edSDimitry Andric if (Record.size() == 4) { 280891bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]); 280991bc56edSDimitry Andric if (!IdxTy) 28108f0fd8f6SDimitry Andric return error("Invalid record"); 281191bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 281291bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0 281391bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 281491bc56edSDimitry Andric if (!Op1) 28158f0fd8f6SDimitry Andric return error("Invalid record"); 2816f22ef01cSRoman Divacky V = ConstantExpr::getExtractElement(Op0, Op1); 2817f22ef01cSRoman Divacky break; 2818f22ef01cSRoman Divacky } 281991bc56edSDimitry Andric case bitc::CST_CODE_CE_INSERTELT 282091bc56edSDimitry Andric : { // CE_INSERTELT: [opval, opval, opty, opval] 28216122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 282291bc56edSDimitry Andric if (Record.size() < 3 || !OpTy) 28238f0fd8f6SDimitry Andric return error("Invalid record"); 2824f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2825f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 2826f22ef01cSRoman Divacky OpTy->getElementType()); 282791bc56edSDimitry Andric Constant *Op2 = nullptr; 282891bc56edSDimitry Andric if (Record.size() == 4) { 282991bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]); 283091bc56edSDimitry Andric if (!IdxTy) 28318f0fd8f6SDimitry Andric return error("Invalid record"); 283291bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 283391bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0 283491bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 283591bc56edSDimitry Andric if (!Op2) 28368f0fd8f6SDimitry Andric return error("Invalid record"); 2837f22ef01cSRoman Divacky V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 2838f22ef01cSRoman Divacky break; 2839f22ef01cSRoman Divacky } 2840f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 28416122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy); 284291bc56edSDimitry Andric if (Record.size() < 3 || !OpTy) 28438f0fd8f6SDimitry Andric return error("Invalid record"); 2844f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2845f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 28466122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2847f22ef01cSRoman Divacky OpTy->getNumElements()); 2848f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 2849f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2850f22ef01cSRoman Divacky break; 2851f22ef01cSRoman Divacky } 2852f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 28536122f3e6SDimitry Andric VectorType *RTy = dyn_cast<VectorType>(CurTy); 28546122f3e6SDimitry Andric VectorType *OpTy = 28552754fe60SDimitry Andric dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 285691bc56edSDimitry Andric if (Record.size() < 4 || !RTy || !OpTy) 28578f0fd8f6SDimitry Andric return error("Invalid record"); 2858f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2859f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 28606122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2861f22ef01cSRoman Divacky RTy->getNumElements()); 2862f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 2863f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2864f22ef01cSRoman Divacky break; 2865f22ef01cSRoman Divacky } 2866f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 2867f785676fSDimitry Andric if (Record.size() < 4) 28688f0fd8f6SDimitry Andric return error("Invalid record"); 28696122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 287091bc56edSDimitry Andric if (!OpTy) 28718f0fd8f6SDimitry Andric return error("Invalid record"); 2872f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2873f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2874f22ef01cSRoman Divacky 2875f22ef01cSRoman Divacky if (OpTy->isFPOrFPVectorTy()) 2876f22ef01cSRoman Divacky V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 2877f22ef01cSRoman Divacky else 2878f22ef01cSRoman Divacky V = ConstantExpr::getICmp(Record[3], Op0, Op1); 2879f22ef01cSRoman Divacky break; 2880f22ef01cSRoman Divacky } 28813861d79fSDimitry Andric // This maintains backward compatibility, pre-asm dialect keywords. 28823861d79fSDimitry Andric // FIXME: Remove with the 4.0 release. 28833861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM_OLD: { 2884f785676fSDimitry Andric if (Record.size() < 2) 28858f0fd8f6SDimitry Andric return error("Invalid record"); 2886f22ef01cSRoman Divacky std::string AsmStr, ConstrStr; 2887f22ef01cSRoman Divacky bool HasSideEffects = Record[0] & 1; 2888f22ef01cSRoman Divacky bool IsAlignStack = Record[0] >> 1; 2889f22ef01cSRoman Divacky unsigned AsmStrSize = Record[1]; 2890f22ef01cSRoman Divacky if (2+AsmStrSize >= Record.size()) 28918f0fd8f6SDimitry Andric return error("Invalid record"); 2892f22ef01cSRoman Divacky unsigned ConstStrSize = Record[2+AsmStrSize]; 2893f22ef01cSRoman Divacky if (3+AsmStrSize+ConstStrSize > Record.size()) 28948f0fd8f6SDimitry Andric return error("Invalid record"); 2895f22ef01cSRoman Divacky 2896f22ef01cSRoman Divacky for (unsigned i = 0; i != AsmStrSize; ++i) 2897f22ef01cSRoman Divacky AsmStr += (char)Record[2+i]; 2898f22ef01cSRoman Divacky for (unsigned i = 0; i != ConstStrSize; ++i) 2899f22ef01cSRoman Divacky ConstrStr += (char)Record[3+AsmStrSize+i]; 29006122f3e6SDimitry Andric PointerType *PTy = cast<PointerType>(CurTy); 2901f22ef01cSRoman Divacky V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2902f22ef01cSRoman Divacky AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 2903f22ef01cSRoman Divacky break; 2904f22ef01cSRoman Divacky } 29053861d79fSDimitry Andric // This version adds support for the asm dialect keywords (e.g., 29063861d79fSDimitry Andric // inteldialect). 29073861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM: { 2908f785676fSDimitry Andric if (Record.size() < 2) 29098f0fd8f6SDimitry Andric return error("Invalid record"); 29103861d79fSDimitry Andric std::string AsmStr, ConstrStr; 29113861d79fSDimitry Andric bool HasSideEffects = Record[0] & 1; 29123861d79fSDimitry Andric bool IsAlignStack = (Record[0] >> 1) & 1; 29133861d79fSDimitry Andric unsigned AsmDialect = Record[0] >> 2; 29143861d79fSDimitry Andric unsigned AsmStrSize = Record[1]; 29153861d79fSDimitry Andric if (2+AsmStrSize >= Record.size()) 29168f0fd8f6SDimitry Andric return error("Invalid record"); 29173861d79fSDimitry Andric unsigned ConstStrSize = Record[2+AsmStrSize]; 29183861d79fSDimitry Andric if (3+AsmStrSize+ConstStrSize > Record.size()) 29198f0fd8f6SDimitry Andric return error("Invalid record"); 29203861d79fSDimitry Andric 29213861d79fSDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i) 29223861d79fSDimitry Andric AsmStr += (char)Record[2+i]; 29233861d79fSDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i) 29243861d79fSDimitry Andric ConstrStr += (char)Record[3+AsmStrSize+i]; 29253861d79fSDimitry Andric PointerType *PTy = cast<PointerType>(CurTy); 29263861d79fSDimitry Andric V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 29273861d79fSDimitry Andric AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 29283861d79fSDimitry Andric InlineAsm::AsmDialect(AsmDialect)); 29293861d79fSDimitry Andric break; 29303861d79fSDimitry Andric } 2931f22ef01cSRoman Divacky case bitc::CST_CODE_BLOCKADDRESS:{ 2932f785676fSDimitry Andric if (Record.size() < 3) 29338f0fd8f6SDimitry Andric return error("Invalid record"); 29346122f3e6SDimitry Andric Type *FnTy = getTypeByID(Record[0]); 293591bc56edSDimitry Andric if (!FnTy) 29368f0fd8f6SDimitry Andric return error("Invalid record"); 2937f22ef01cSRoman Divacky Function *Fn = 2938f22ef01cSRoman Divacky dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 293991bc56edSDimitry Andric if (!Fn) 29408f0fd8f6SDimitry Andric return error("Invalid record"); 294139d628a0SDimitry Andric 29423861d79fSDimitry Andric // If the function is already parsed we can insert the block address right 29433861d79fSDimitry Andric // away. 294439d628a0SDimitry Andric BasicBlock *BB; 294539d628a0SDimitry Andric unsigned BBID = Record[2]; 294639d628a0SDimitry Andric if (!BBID) 294739d628a0SDimitry Andric // Invalid reference to entry block. 29488f0fd8f6SDimitry Andric return error("Invalid ID"); 29493861d79fSDimitry Andric if (!Fn->empty()) { 29503861d79fSDimitry Andric Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 295139d628a0SDimitry Andric for (size_t I = 0, E = BBID; I != E; ++I) { 29523861d79fSDimitry Andric if (BBI == BBE) 29538f0fd8f6SDimitry Andric return error("Invalid ID"); 29543861d79fSDimitry Andric ++BBI; 29553861d79fSDimitry Andric } 29567d523365SDimitry Andric BB = &*BBI; 29573861d79fSDimitry Andric } else { 29583861d79fSDimitry Andric // Otherwise insert a placeholder and remember it so it can be inserted 29593861d79fSDimitry Andric // when the function is parsed. 296039d628a0SDimitry Andric auto &FwdBBs = BasicBlockFwdRefs[Fn]; 296139d628a0SDimitry Andric if (FwdBBs.empty()) 296239d628a0SDimitry Andric BasicBlockFwdRefQueue.push_back(Fn); 296339d628a0SDimitry Andric if (FwdBBs.size() < BBID + 1) 296439d628a0SDimitry Andric FwdBBs.resize(BBID + 1); 296539d628a0SDimitry Andric if (!FwdBBs[BBID]) 296639d628a0SDimitry Andric FwdBBs[BBID] = BasicBlock::Create(Context); 296739d628a0SDimitry Andric BB = FwdBBs[BBID]; 29683861d79fSDimitry Andric } 296939d628a0SDimitry Andric V = BlockAddress::get(Fn, BB); 2970f22ef01cSRoman Divacky break; 2971f22ef01cSRoman Divacky } 2972f22ef01cSRoman Divacky } 2973f22ef01cSRoman Divacky 29748f0fd8f6SDimitry Andric ValueList.assignValue(V, NextCstNo); 2975f22ef01cSRoman Divacky ++NextCstNo; 2976f22ef01cSRoman Divacky } 2977f22ef01cSRoman Divacky } 2978f22ef01cSRoman Divacky 29798f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseUseLists() { 2980dff0c46cSDimitry Andric if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 29818f0fd8f6SDimitry Andric return error("Invalid record"); 2982dff0c46cSDimitry Andric 2983dff0c46cSDimitry Andric // Read all the records. 298439d628a0SDimitry Andric SmallVector<uint64_t, 64> Record; 2985dff0c46cSDimitry Andric while (1) { 2986139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2987139f7f9bSDimitry Andric 2988139f7f9bSDimitry Andric switch (Entry.Kind) { 2989139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 2990139f7f9bSDimitry Andric case BitstreamEntry::Error: 29918f0fd8f6SDimitry Andric return error("Malformed block"); 2992139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 299391bc56edSDimitry Andric return std::error_code(); 2994139f7f9bSDimitry Andric case BitstreamEntry::Record: 2995139f7f9bSDimitry Andric // The interesting case. 2996139f7f9bSDimitry Andric break; 2997dff0c46cSDimitry Andric } 2998dff0c46cSDimitry Andric 2999dff0c46cSDimitry Andric // Read a use list record. 3000dff0c46cSDimitry Andric Record.clear(); 300139d628a0SDimitry Andric bool IsBB = false; 3002139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 3003dff0c46cSDimitry Andric default: // Default behavior: unknown type. 3004dff0c46cSDimitry Andric break; 300539d628a0SDimitry Andric case bitc::USELIST_CODE_BB: 300639d628a0SDimitry Andric IsBB = true; 300739d628a0SDimitry Andric // fallthrough 300839d628a0SDimitry Andric case bitc::USELIST_CODE_DEFAULT: { 3009dff0c46cSDimitry Andric unsigned RecordLength = Record.size(); 301039d628a0SDimitry Andric if (RecordLength < 3) 301139d628a0SDimitry Andric // Records should have at least an ID and two indexes. 30128f0fd8f6SDimitry Andric return error("Invalid record"); 301339d628a0SDimitry Andric unsigned ID = Record.back(); 301439d628a0SDimitry Andric Record.pop_back(); 301539d628a0SDimitry Andric 301639d628a0SDimitry Andric Value *V; 301739d628a0SDimitry Andric if (IsBB) { 301839d628a0SDimitry Andric assert(ID < FunctionBBs.size() && "Basic block not found"); 301939d628a0SDimitry Andric V = FunctionBBs[ID]; 302039d628a0SDimitry Andric } else 302139d628a0SDimitry Andric V = ValueList[ID]; 302239d628a0SDimitry Andric unsigned NumUses = 0; 302339d628a0SDimitry Andric SmallDenseMap<const Use *, unsigned, 16> Order; 30247d523365SDimitry Andric for (const Use &U : V->materialized_uses()) { 302539d628a0SDimitry Andric if (++NumUses > Record.size()) 302639d628a0SDimitry Andric break; 302739d628a0SDimitry Andric Order[&U] = Record[NumUses - 1]; 302839d628a0SDimitry Andric } 302939d628a0SDimitry Andric if (Order.size() != Record.size() || NumUses > Record.size()) 303039d628a0SDimitry Andric // Mismatches can happen if the functions are being materialized lazily 303139d628a0SDimitry Andric // (out-of-order), or a value has been upgraded. 303239d628a0SDimitry Andric break; 303339d628a0SDimitry Andric 303439d628a0SDimitry Andric V->sortUseList([&](const Use &L, const Use &R) { 303539d628a0SDimitry Andric return Order.lookup(&L) < Order.lookup(&R); 303639d628a0SDimitry Andric }); 3037dff0c46cSDimitry Andric break; 3038dff0c46cSDimitry Andric } 3039dff0c46cSDimitry Andric } 3040dff0c46cSDimitry Andric } 3041dff0c46cSDimitry Andric } 3042dff0c46cSDimitry Andric 3043ff0cc061SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it. 3044ff0cc061SDimitry Andric /// This lets us lazily deserialize the metadata. 3045ff0cc061SDimitry Andric std::error_code BitcodeReader::rememberAndSkipMetadata() { 3046ff0cc061SDimitry Andric // Save the current stream state. 3047ff0cc061SDimitry Andric uint64_t CurBit = Stream.GetCurrentBitNo(); 3048ff0cc061SDimitry Andric DeferredMetadataInfo.push_back(CurBit); 3049ff0cc061SDimitry Andric 3050ff0cc061SDimitry Andric // Skip over the block for now. 3051ff0cc061SDimitry Andric if (Stream.SkipBlock()) 30528f0fd8f6SDimitry Andric return error("Invalid record"); 3053ff0cc061SDimitry Andric return std::error_code(); 3054ff0cc061SDimitry Andric } 3055ff0cc061SDimitry Andric 3056ff0cc061SDimitry Andric std::error_code BitcodeReader::materializeMetadata() { 3057ff0cc061SDimitry Andric for (uint64_t BitPos : DeferredMetadataInfo) { 3058ff0cc061SDimitry Andric // Move the bit stream to the saved position. 3059ff0cc061SDimitry Andric Stream.JumpToBit(BitPos); 30607d523365SDimitry Andric if (std::error_code EC = parseMetadata(true)) 3061ff0cc061SDimitry Andric return EC; 3062ff0cc061SDimitry Andric } 3063ff0cc061SDimitry Andric DeferredMetadataInfo.clear(); 3064ff0cc061SDimitry Andric return std::error_code(); 3065ff0cc061SDimitry Andric } 3066ff0cc061SDimitry Andric 3067ff0cc061SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 3068ff0cc061SDimitry Andric 30697d523365SDimitry Andric void BitcodeReader::saveMetadataList( 30707d523365SDimitry Andric DenseMap<const Metadata *, unsigned> &MetadataToIDs, bool OnlyTempMD) { 30717d523365SDimitry Andric for (unsigned ID = 0; ID < MetadataList.size(); ++ID) { 30727d523365SDimitry Andric Metadata *MD = MetadataList[ID]; 30737d523365SDimitry Andric auto *N = dyn_cast_or_null<MDNode>(MD); 30744d0b32cdSDimitry Andric assert((!N || (N->isResolved() || N->isTemporary())) && 30754d0b32cdSDimitry Andric "Found non-resolved non-temp MDNode while saving metadata"); 30767d523365SDimitry Andric // Save all values if !OnlyTempMD, otherwise just the temporary metadata. 30774d0b32cdSDimitry Andric // Note that in the !OnlyTempMD case we need to save all Metadata, not 30784d0b32cdSDimitry Andric // just MDNode, as we may have references to other types of module-level 30794d0b32cdSDimitry Andric // metadata (e.g. ValueAsMetadata) from instructions. 30807d523365SDimitry Andric if (!OnlyTempMD || (N && N->isTemporary())) { 30817d523365SDimitry Andric // Will call this after materializing each function, in order to 30827d523365SDimitry Andric // handle remapping of the function's instructions/metadata. 30837d523365SDimitry Andric // See if we already have an entry in that case. 30847d523365SDimitry Andric if (OnlyTempMD && MetadataToIDs.count(MD)) { 30857d523365SDimitry Andric assert(MetadataToIDs[MD] == ID && "Inconsistent metadata value id"); 30867d523365SDimitry Andric continue; 30877d523365SDimitry Andric } 30884d0b32cdSDimitry Andric if (N && N->isTemporary()) 30894d0b32cdSDimitry Andric // Ensure that we assert if someone tries to RAUW this temporary 30904d0b32cdSDimitry Andric // metadata while it is the key of a map. The flag will be set back 30914d0b32cdSDimitry Andric // to true when the saved metadata list is destroyed. 30924d0b32cdSDimitry Andric N->setCanReplace(false); 30937d523365SDimitry Andric MetadataToIDs[MD] = ID; 30947d523365SDimitry Andric } 30957d523365SDimitry Andric } 30967d523365SDimitry Andric } 30977d523365SDimitry Andric 30988f0fd8f6SDimitry Andric /// When we see the block for a function body, remember where it is and then 30998f0fd8f6SDimitry Andric /// skip it. This lets us lazily deserialize the functions. 31008f0fd8f6SDimitry Andric std::error_code BitcodeReader::rememberAndSkipFunctionBody() { 3101f22ef01cSRoman Divacky // Get the function we are talking about. 3102f22ef01cSRoman Divacky if (FunctionsWithBodies.empty()) 31038f0fd8f6SDimitry Andric return error("Insufficient function protos"); 3104f22ef01cSRoman Divacky 3105f22ef01cSRoman Divacky Function *Fn = FunctionsWithBodies.back(); 3106f22ef01cSRoman Divacky FunctionsWithBodies.pop_back(); 3107f22ef01cSRoman Divacky 3108f22ef01cSRoman Divacky // Save the current stream state. 3109f22ef01cSRoman Divacky uint64_t CurBit = Stream.GetCurrentBitNo(); 31107d523365SDimitry Andric assert( 31117d523365SDimitry Andric (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 31127d523365SDimitry Andric "Mismatch between VST and scanned function offsets"); 3113f22ef01cSRoman Divacky DeferredFunctionInfo[Fn] = CurBit; 3114f22ef01cSRoman Divacky 3115f22ef01cSRoman Divacky // Skip over the function block for now. 3116f22ef01cSRoman Divacky if (Stream.SkipBlock()) 31178f0fd8f6SDimitry Andric return error("Invalid record"); 311891bc56edSDimitry Andric return std::error_code(); 3119f22ef01cSRoman Divacky } 3120f22ef01cSRoman Divacky 31218f0fd8f6SDimitry Andric std::error_code BitcodeReader::globalCleanup() { 3122f22ef01cSRoman Divacky // Patch the initializers for globals and aliases up. 31238f0fd8f6SDimitry Andric resolveGlobalAndAliasInits(); 3124f22ef01cSRoman Divacky if (!GlobalInits.empty() || !AliasInits.empty()) 31258f0fd8f6SDimitry Andric return error("Malformed global initializer set"); 3126f22ef01cSRoman Divacky 3127f22ef01cSRoman Divacky // Look for intrinsic functions which need to be upgraded at some point 31288f0fd8f6SDimitry Andric for (Function &F : *TheModule) { 3129f22ef01cSRoman Divacky Function *NewFn; 31308f0fd8f6SDimitry Andric if (UpgradeIntrinsicFunction(&F, NewFn)) 31313dac3a9bSDimitry Andric UpgradedIntrinsics[&F] = NewFn; 3132f22ef01cSRoman Divacky } 3133f22ef01cSRoman Divacky 3134e580952dSDimitry Andric // Look for global variables which need to be renamed. 31358f0fd8f6SDimitry Andric for (GlobalVariable &GV : TheModule->globals()) 31368f0fd8f6SDimitry Andric UpgradeGlobalVariable(&GV); 313791bc56edSDimitry Andric 3138f22ef01cSRoman Divacky // Force deallocation of memory for these vectors to favor the client that 3139f22ef01cSRoman Divacky // want lazy deserialization. 3140f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 3141f22ef01cSRoman Divacky std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 314291bc56edSDimitry Andric return std::error_code(); 3143f22ef01cSRoman Divacky } 3144f22ef01cSRoman Divacky 31457d523365SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we 31467d523365SDimitry Andric /// either have an old bitcode file without a VST forward declaration record, 31477d523365SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous 31487d523365SDimitry Andric /// functions do not have a name and are therefore not in the VST. 31497d523365SDimitry Andric std::error_code BitcodeReader::rememberAndSkipFunctionBodies() { 3150dff0c46cSDimitry Andric Stream.JumpToBit(NextUnreadBit); 31517d523365SDimitry Andric 31527d523365SDimitry Andric if (Stream.AtEndOfStream()) 31537d523365SDimitry Andric return error("Could not find function in stream"); 31547d523365SDimitry Andric 31557d523365SDimitry Andric if (!SeenFirstFunctionBody) 31567d523365SDimitry Andric return error("Trying to materialize functions before seeing function blocks"); 31577d523365SDimitry Andric 31587d523365SDimitry Andric // An old bitcode file with the symbol table at the end would have 31597d523365SDimitry Andric // finished the parse greedily. 31607d523365SDimitry Andric assert(SeenValueSymbolTable); 31617d523365SDimitry Andric 31627d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 31637d523365SDimitry Andric 31647d523365SDimitry Andric while (1) { 31657d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 31667d523365SDimitry Andric switch (Entry.Kind) { 31677d523365SDimitry Andric default: 31687d523365SDimitry Andric return error("Expect SubBlock"); 31697d523365SDimitry Andric case BitstreamEntry::SubBlock: 31707d523365SDimitry Andric switch (Entry.ID) { 31717d523365SDimitry Andric default: 31727d523365SDimitry Andric return error("Expect function block"); 31737d523365SDimitry Andric case bitc::FUNCTION_BLOCK_ID: 31747d523365SDimitry Andric if (std::error_code EC = rememberAndSkipFunctionBody()) 31757d523365SDimitry Andric return EC; 31767d523365SDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 31777d523365SDimitry Andric return std::error_code(); 31787d523365SDimitry Andric } 31797d523365SDimitry Andric } 31807d523365SDimitry Andric } 31817d523365SDimitry Andric } 31827d523365SDimitry Andric 31837d523365SDimitry Andric std::error_code BitcodeReader::parseBitcodeVersion() { 31847d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 31857d523365SDimitry Andric return error("Invalid record"); 31867d523365SDimitry Andric 31877d523365SDimitry Andric // Read all the records. 31887d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 31897d523365SDimitry Andric while (1) { 31907d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 31917d523365SDimitry Andric 31927d523365SDimitry Andric switch (Entry.Kind) { 31937d523365SDimitry Andric default: 31947d523365SDimitry Andric case BitstreamEntry::Error: 31957d523365SDimitry Andric return error("Malformed block"); 31967d523365SDimitry Andric case BitstreamEntry::EndBlock: 31977d523365SDimitry Andric return std::error_code(); 31987d523365SDimitry Andric case BitstreamEntry::Record: 31997d523365SDimitry Andric // The interesting case. 32007d523365SDimitry Andric break; 32017d523365SDimitry Andric } 32027d523365SDimitry Andric 32037d523365SDimitry Andric // Read a record. 32047d523365SDimitry Andric Record.clear(); 32057d523365SDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 32067d523365SDimitry Andric switch (BitCode) { 32077d523365SDimitry Andric default: // Default behavior: reject 32087d523365SDimitry Andric return error("Invalid value"); 32097d523365SDimitry Andric case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x 32107d523365SDimitry Andric // N] 32117d523365SDimitry Andric convertToString(Record, 0, ProducerIdentification); 32127d523365SDimitry Andric break; 32137d523365SDimitry Andric } 32147d523365SDimitry Andric case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 32157d523365SDimitry Andric unsigned epoch = (unsigned)Record[0]; 32167d523365SDimitry Andric if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 32177d523365SDimitry Andric return error( 32187d523365SDimitry Andric Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 32197d523365SDimitry Andric "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 32207d523365SDimitry Andric } 32217d523365SDimitry Andric } 32227d523365SDimitry Andric } 32237d523365SDimitry Andric } 32247d523365SDimitry Andric } 32257d523365SDimitry Andric 32267d523365SDimitry Andric std::error_code BitcodeReader::parseModule(uint64_t ResumeBit, 32277d523365SDimitry Andric bool ShouldLazyLoadMetadata) { 32287d523365SDimitry Andric if (ResumeBit) 32297d523365SDimitry Andric Stream.JumpToBit(ResumeBit); 3230dff0c46cSDimitry Andric else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 32318f0fd8f6SDimitry Andric return error("Invalid record"); 3232dff0c46cSDimitry Andric 3233dff0c46cSDimitry Andric SmallVector<uint64_t, 64> Record; 3234dff0c46cSDimitry Andric std::vector<std::string> SectionTable; 3235dff0c46cSDimitry Andric std::vector<std::string> GCTable; 3236dff0c46cSDimitry Andric 3237dff0c46cSDimitry Andric // Read all the records for this module. 3238139f7f9bSDimitry Andric while (1) { 3239139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3240dff0c46cSDimitry Andric 3241139f7f9bSDimitry Andric switch (Entry.Kind) { 3242139f7f9bSDimitry Andric case BitstreamEntry::Error: 32438f0fd8f6SDimitry Andric return error("Malformed block"); 3244139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 32458f0fd8f6SDimitry Andric return globalCleanup(); 3246dff0c46cSDimitry Andric 3247139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3248139f7f9bSDimitry Andric switch (Entry.ID) { 3249f22ef01cSRoman Divacky default: // Skip unknown content. 3250f22ef01cSRoman Divacky if (Stream.SkipBlock()) 32518f0fd8f6SDimitry Andric return error("Invalid record"); 3252f22ef01cSRoman Divacky break; 3253f22ef01cSRoman Divacky case bitc::BLOCKINFO_BLOCK_ID: 3254f22ef01cSRoman Divacky if (Stream.ReadBlockInfoBlock()) 32558f0fd8f6SDimitry Andric return error("Malformed block"); 3256f22ef01cSRoman Divacky break; 3257f22ef01cSRoman Divacky case bitc::PARAMATTR_BLOCK_ID: 32588f0fd8f6SDimitry Andric if (std::error_code EC = parseAttributeBlock()) 3259f785676fSDimitry Andric return EC; 3260f22ef01cSRoman Divacky break; 3261139f7f9bSDimitry Andric case bitc::PARAMATTR_GROUP_BLOCK_ID: 32628f0fd8f6SDimitry Andric if (std::error_code EC = parseAttributeGroupBlock()) 3263f785676fSDimitry Andric return EC; 3264139f7f9bSDimitry Andric break; 326517a519f9SDimitry Andric case bitc::TYPE_BLOCK_ID_NEW: 32668f0fd8f6SDimitry Andric if (std::error_code EC = parseTypeTable()) 3267f785676fSDimitry Andric return EC; 3268f22ef01cSRoman Divacky break; 3269f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 32707d523365SDimitry Andric if (!SeenValueSymbolTable) { 32717d523365SDimitry Andric // Either this is an old form VST without function index and an 32727d523365SDimitry Andric // associated VST forward declaration record (which would have caused 32737d523365SDimitry Andric // the VST to be jumped to and parsed before it was encountered 32747d523365SDimitry Andric // normally in the stream), or there were no function blocks to 32757d523365SDimitry Andric // trigger an earlier parsing of the VST. 32767d523365SDimitry Andric assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 32778f0fd8f6SDimitry Andric if (std::error_code EC = parseValueSymbolTable()) 3278f785676fSDimitry Andric return EC; 3279dff0c46cSDimitry Andric SeenValueSymbolTable = true; 32807d523365SDimitry Andric } else { 32817d523365SDimitry Andric // We must have had a VST forward declaration record, which caused 32827d523365SDimitry Andric // the parser to jump to and parse the VST earlier. 32837d523365SDimitry Andric assert(VSTOffset > 0); 32847d523365SDimitry Andric if (Stream.SkipBlock()) 32857d523365SDimitry Andric return error("Invalid record"); 32867d523365SDimitry Andric } 3287f22ef01cSRoman Divacky break; 3288f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 32898f0fd8f6SDimitry Andric if (std::error_code EC = parseConstants()) 3290f785676fSDimitry Andric return EC; 32918f0fd8f6SDimitry Andric if (std::error_code EC = resolveGlobalAndAliasInits()) 3292f785676fSDimitry Andric return EC; 3293f22ef01cSRoman Divacky break; 3294f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 3295ff0cc061SDimitry Andric if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) { 3296ff0cc061SDimitry Andric if (std::error_code EC = rememberAndSkipMetadata()) 3297ff0cc061SDimitry Andric return EC; 3298ff0cc061SDimitry Andric break; 3299ff0cc061SDimitry Andric } 3300ff0cc061SDimitry Andric assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 33017d523365SDimitry Andric if (std::error_code EC = parseMetadata(true)) 33027d523365SDimitry Andric return EC; 33037d523365SDimitry Andric break; 33047d523365SDimitry Andric case bitc::METADATA_KIND_BLOCK_ID: 33057d523365SDimitry Andric if (std::error_code EC = parseMetadataKinds()) 3306f785676fSDimitry Andric return EC; 3307f22ef01cSRoman Divacky break; 3308f22ef01cSRoman Divacky case bitc::FUNCTION_BLOCK_ID: 3309f22ef01cSRoman Divacky // If this is the first function body we've seen, reverse the 3310f22ef01cSRoman Divacky // FunctionsWithBodies list. 3311dff0c46cSDimitry Andric if (!SeenFirstFunctionBody) { 3312f22ef01cSRoman Divacky std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 33138f0fd8f6SDimitry Andric if (std::error_code EC = globalCleanup()) 3314f785676fSDimitry Andric return EC; 3315dff0c46cSDimitry Andric SeenFirstFunctionBody = true; 3316f22ef01cSRoman Divacky } 3317f22ef01cSRoman Divacky 33187d523365SDimitry Andric if (VSTOffset > 0) { 33197d523365SDimitry Andric // If we have a VST forward declaration record, make sure we 33207d523365SDimitry Andric // parse the VST now if we haven't already. It is needed to 33217d523365SDimitry Andric // set up the DeferredFunctionInfo vector for lazy reading. 33227d523365SDimitry Andric if (!SeenValueSymbolTable) { 33237d523365SDimitry Andric if (std::error_code EC = 33247d523365SDimitry Andric BitcodeReader::parseValueSymbolTable(VSTOffset)) 33257d523365SDimitry Andric return EC; 33267d523365SDimitry Andric SeenValueSymbolTable = true; 33277d523365SDimitry Andric // Fall through so that we record the NextUnreadBit below. 33287d523365SDimitry Andric // This is necessary in case we have an anonymous function that 33297d523365SDimitry Andric // is later materialized. Since it will not have a VST entry we 33307d523365SDimitry Andric // need to fall back to the lazy parse to find its offset. 33317d523365SDimitry Andric } else { 33327d523365SDimitry Andric // If we have a VST forward declaration record, but have already 33337d523365SDimitry Andric // parsed the VST (just above, when the first function body was 33347d523365SDimitry Andric // encountered here), then we are resuming the parse after 33357d523365SDimitry Andric // materializing functions. The ResumeBit points to the 33367d523365SDimitry Andric // start of the last function block recorded in the 33377d523365SDimitry Andric // DeferredFunctionInfo map. Skip it. 33387d523365SDimitry Andric if (Stream.SkipBlock()) 33397d523365SDimitry Andric return error("Invalid record"); 33407d523365SDimitry Andric continue; 33417d523365SDimitry Andric } 33427d523365SDimitry Andric } 33437d523365SDimitry Andric 33447d523365SDimitry Andric // Support older bitcode files that did not have the function 33457d523365SDimitry Andric // index in the VST, nor a VST forward declaration record, as 33467d523365SDimitry Andric // well as anonymous functions that do not have VST entries. 33477d523365SDimitry Andric // Build the DeferredFunctionInfo vector on the fly. 33488f0fd8f6SDimitry Andric if (std::error_code EC = rememberAndSkipFunctionBody()) 3349f785676fSDimitry Andric return EC; 33507d523365SDimitry Andric 33513dac3a9bSDimitry Andric // Suspend parsing when we reach the function bodies. Subsequent 33523dac3a9bSDimitry Andric // materialization calls will resume it when necessary. If the bitcode 33533dac3a9bSDimitry Andric // file is old, the symbol table will be at the end instead and will not 33543dac3a9bSDimitry Andric // have been seen yet. In this case, just finish the parse now. 33553dac3a9bSDimitry Andric if (SeenValueSymbolTable) { 3356dff0c46cSDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 335791bc56edSDimitry Andric return std::error_code(); 3358dff0c46cSDimitry Andric } 3359dff0c46cSDimitry Andric break; 3360dff0c46cSDimitry Andric case bitc::USELIST_BLOCK_ID: 33618f0fd8f6SDimitry Andric if (std::error_code EC = parseUseLists()) 3362f785676fSDimitry Andric return EC; 3363f22ef01cSRoman Divacky break; 33647d523365SDimitry Andric case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 33657d523365SDimitry Andric if (std::error_code EC = parseOperandBundleTags()) 33667d523365SDimitry Andric return EC; 33677d523365SDimitry Andric break; 3368f22ef01cSRoman Divacky } 3369f22ef01cSRoman Divacky continue; 3370139f7f9bSDimitry Andric 3371139f7f9bSDimitry Andric case BitstreamEntry::Record: 3372139f7f9bSDimitry Andric // The interesting case. 3373139f7f9bSDimitry Andric break; 3374f22ef01cSRoman Divacky } 3375f22ef01cSRoman Divacky 3376f22ef01cSRoman Divacky 3377f22ef01cSRoman Divacky // Read a record. 33787d523365SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 33797d523365SDimitry Andric switch (BitCode) { 3380f22ef01cSRoman Divacky default: break; // Default behavior, ignore unknown content. 33813861d79fSDimitry Andric case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 3382f22ef01cSRoman Divacky if (Record.size() < 1) 33838f0fd8f6SDimitry Andric return error("Invalid record"); 33843861d79fSDimitry Andric // Only version #0 and #1 are supported so far. 33853861d79fSDimitry Andric unsigned module_version = Record[0]; 33863861d79fSDimitry Andric switch (module_version) { 3387f785676fSDimitry Andric default: 33888f0fd8f6SDimitry Andric return error("Invalid value"); 33893861d79fSDimitry Andric case 0: 33903861d79fSDimitry Andric UseRelativeIDs = false; 3391f22ef01cSRoman Divacky break; 33923861d79fSDimitry Andric case 1: 33933861d79fSDimitry Andric UseRelativeIDs = true; 33943861d79fSDimitry Andric break; 33953861d79fSDimitry Andric } 33963861d79fSDimitry Andric break; 33973861d79fSDimitry Andric } 3398f22ef01cSRoman Divacky case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3399f22ef01cSRoman Divacky std::string S; 34008f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34018f0fd8f6SDimitry Andric return error("Invalid record"); 3402f22ef01cSRoman Divacky TheModule->setTargetTriple(S); 3403f22ef01cSRoman Divacky break; 3404f22ef01cSRoman Divacky } 3405f22ef01cSRoman Divacky case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 3406f22ef01cSRoman Divacky std::string S; 34078f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34088f0fd8f6SDimitry Andric return error("Invalid record"); 3409f22ef01cSRoman Divacky TheModule->setDataLayout(S); 3410f22ef01cSRoman Divacky break; 3411f22ef01cSRoman Divacky } 3412f22ef01cSRoman Divacky case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 3413f22ef01cSRoman Divacky std::string S; 34148f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34158f0fd8f6SDimitry Andric return error("Invalid record"); 3416f22ef01cSRoman Divacky TheModule->setModuleInlineAsm(S); 3417f22ef01cSRoman Divacky break; 3418f22ef01cSRoman Divacky } 3419f22ef01cSRoman Divacky case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 3420139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 3421f22ef01cSRoman Divacky std::string S; 34228f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34238f0fd8f6SDimitry Andric return error("Invalid record"); 3424139f7f9bSDimitry Andric // Ignore value. 3425f22ef01cSRoman Divacky break; 3426f22ef01cSRoman Divacky } 3427f22ef01cSRoman Divacky case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 3428f22ef01cSRoman Divacky std::string S; 34298f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34308f0fd8f6SDimitry Andric return error("Invalid record"); 3431f22ef01cSRoman Divacky SectionTable.push_back(S); 3432f22ef01cSRoman Divacky break; 3433f22ef01cSRoman Divacky } 3434f22ef01cSRoman Divacky case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 3435f22ef01cSRoman Divacky std::string S; 34368f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34378f0fd8f6SDimitry Andric return error("Invalid record"); 3438f22ef01cSRoman Divacky GCTable.push_back(S); 3439f22ef01cSRoman Divacky break; 3440f22ef01cSRoman Divacky } 344191bc56edSDimitry Andric case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] 344291bc56edSDimitry Andric if (Record.size() < 2) 34438f0fd8f6SDimitry Andric return error("Invalid record"); 344491bc56edSDimitry Andric Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 344591bc56edSDimitry Andric unsigned ComdatNameSize = Record[1]; 344691bc56edSDimitry Andric std::string ComdatName; 344791bc56edSDimitry Andric ComdatName.reserve(ComdatNameSize); 344891bc56edSDimitry Andric for (unsigned i = 0; i != ComdatNameSize; ++i) 344991bc56edSDimitry Andric ComdatName += (char)Record[2 + i]; 345091bc56edSDimitry Andric Comdat *C = TheModule->getOrInsertComdat(ComdatName); 345191bc56edSDimitry Andric C->setSelectionKind(SK); 345291bc56edSDimitry Andric ComdatList.push_back(C); 345391bc56edSDimitry Andric break; 345491bc56edSDimitry Andric } 3455f22ef01cSRoman Divacky // GLOBALVAR: [pointer type, isconst, initid, 34562754fe60SDimitry Andric // linkage, alignment, section, visibility, threadlocal, 3457ff0cc061SDimitry Andric // unnamed_addr, externally_initialized, dllstorageclass, 3458ff0cc061SDimitry Andric // comdat] 3459f22ef01cSRoman Divacky case bitc::MODULE_CODE_GLOBALVAR: { 3460f22ef01cSRoman Divacky if (Record.size() < 6) 34618f0fd8f6SDimitry Andric return error("Invalid record"); 34626122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 3463f785676fSDimitry Andric if (!Ty) 34648f0fd8f6SDimitry Andric return error("Invalid record"); 3465ff0cc061SDimitry Andric bool isConstant = Record[1] & 1; 3466ff0cc061SDimitry Andric bool explicitType = Record[1] & 2; 3467ff0cc061SDimitry Andric unsigned AddressSpace; 3468ff0cc061SDimitry Andric if (explicitType) { 3469ff0cc061SDimitry Andric AddressSpace = Record[1] >> 2; 3470ff0cc061SDimitry Andric } else { 3471f22ef01cSRoman Divacky if (!Ty->isPointerTy()) 34728f0fd8f6SDimitry Andric return error("Invalid type for value"); 3473ff0cc061SDimitry Andric AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 3474f22ef01cSRoman Divacky Ty = cast<PointerType>(Ty)->getElementType(); 3475ff0cc061SDimitry Andric } 3476f22ef01cSRoman Divacky 3477ff0cc061SDimitry Andric uint64_t RawLinkage = Record[3]; 3478ff0cc061SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 3479ff0cc061SDimitry Andric unsigned Alignment; 3480ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[4], Alignment)) 3481ff0cc061SDimitry Andric return EC; 3482f22ef01cSRoman Divacky std::string Section; 3483f22ef01cSRoman Divacky if (Record[5]) { 3484f22ef01cSRoman Divacky if (Record[5]-1 >= SectionTable.size()) 34858f0fd8f6SDimitry Andric return error("Invalid ID"); 3486f22ef01cSRoman Divacky Section = SectionTable[Record[5]-1]; 3487f22ef01cSRoman Divacky } 3488f22ef01cSRoman Divacky GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 348991bc56edSDimitry Andric // Local linkage must have default visibility. 349091bc56edSDimitry Andric if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 349191bc56edSDimitry Andric // FIXME: Change to an error if non-default in 4.0. 34928f0fd8f6SDimitry Andric Visibility = getDecodedVisibility(Record[6]); 34937ae0e2c9SDimitry Andric 34947ae0e2c9SDimitry Andric GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 3495f22ef01cSRoman Divacky if (Record.size() > 7) 34968f0fd8f6SDimitry Andric TLM = getDecodedThreadLocalMode(Record[7]); 3497f22ef01cSRoman Divacky 34982754fe60SDimitry Andric bool UnnamedAddr = false; 34992754fe60SDimitry Andric if (Record.size() > 8) 35002754fe60SDimitry Andric UnnamedAddr = Record[8]; 35012754fe60SDimitry Andric 3502139f7f9bSDimitry Andric bool ExternallyInitialized = false; 3503139f7f9bSDimitry Andric if (Record.size() > 9) 3504139f7f9bSDimitry Andric ExternallyInitialized = Record[9]; 3505139f7f9bSDimitry Andric 3506f22ef01cSRoman Divacky GlobalVariable *NewGV = 350791bc56edSDimitry Andric new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 3508139f7f9bSDimitry Andric TLM, AddressSpace, ExternallyInitialized); 3509f22ef01cSRoman Divacky NewGV->setAlignment(Alignment); 3510f22ef01cSRoman Divacky if (!Section.empty()) 3511f22ef01cSRoman Divacky NewGV->setSection(Section); 3512f22ef01cSRoman Divacky NewGV->setVisibility(Visibility); 35132754fe60SDimitry Andric NewGV->setUnnamedAddr(UnnamedAddr); 3514f22ef01cSRoman Divacky 351591bc56edSDimitry Andric if (Record.size() > 10) 35168f0fd8f6SDimitry Andric NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 351791bc56edSDimitry Andric else 35188f0fd8f6SDimitry Andric upgradeDLLImportExportLinkage(NewGV, RawLinkage); 351991bc56edSDimitry Andric 3520f22ef01cSRoman Divacky ValueList.push_back(NewGV); 3521f22ef01cSRoman Divacky 3522f22ef01cSRoman Divacky // Remember which value to use for the global initializer. 3523f22ef01cSRoman Divacky if (unsigned InitID = Record[2]) 3524f22ef01cSRoman Divacky GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 352591bc56edSDimitry Andric 3526ff0cc061SDimitry Andric if (Record.size() > 11) { 352791bc56edSDimitry Andric if (unsigned ComdatID = Record[11]) { 3528ff0cc061SDimitry Andric if (ComdatID > ComdatList.size()) 35298f0fd8f6SDimitry Andric return error("Invalid global variable comdat ID"); 353091bc56edSDimitry Andric NewGV->setComdat(ComdatList[ComdatID - 1]); 353191bc56edSDimitry Andric } 3532ff0cc061SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 3533ff0cc061SDimitry Andric NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 3534ff0cc061SDimitry Andric } 3535f22ef01cSRoman Divacky break; 3536f22ef01cSRoman Divacky } 3537f22ef01cSRoman Divacky // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 353891bc56edSDimitry Andric // alignment, section, visibility, gc, unnamed_addr, 353939d628a0SDimitry Andric // prologuedata, dllstorageclass, comdat, prefixdata] 3540f22ef01cSRoman Divacky case bitc::MODULE_CODE_FUNCTION: { 3541f22ef01cSRoman Divacky if (Record.size() < 8) 35428f0fd8f6SDimitry Andric return error("Invalid record"); 35436122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 3544f785676fSDimitry Andric if (!Ty) 35458f0fd8f6SDimitry Andric return error("Invalid record"); 3546ff0cc061SDimitry Andric if (auto *PTy = dyn_cast<PointerType>(Ty)) 3547ff0cc061SDimitry Andric Ty = PTy->getElementType(); 3548ff0cc061SDimitry Andric auto *FTy = dyn_cast<FunctionType>(Ty); 3549f22ef01cSRoman Divacky if (!FTy) 35508f0fd8f6SDimitry Andric return error("Invalid type for value"); 35517d523365SDimitry Andric auto CC = static_cast<CallingConv::ID>(Record[1]); 35527d523365SDimitry Andric if (CC & ~CallingConv::MaxID) 35537d523365SDimitry Andric return error("Invalid calling convention ID"); 3554f22ef01cSRoman Divacky 3555f22ef01cSRoman Divacky Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 3556f22ef01cSRoman Divacky "", TheModule); 3557f22ef01cSRoman Divacky 35587d523365SDimitry Andric Func->setCallingConv(CC); 3559f22ef01cSRoman Divacky bool isProto = Record[2]; 3560ff0cc061SDimitry Andric uint64_t RawLinkage = Record[3]; 3561ff0cc061SDimitry Andric Func->setLinkage(getDecodedLinkage(RawLinkage)); 3562f22ef01cSRoman Divacky Func->setAttributes(getAttributes(Record[4])); 3563f22ef01cSRoman Divacky 3564ff0cc061SDimitry Andric unsigned Alignment; 3565ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[5], Alignment)) 3566ff0cc061SDimitry Andric return EC; 3567ff0cc061SDimitry Andric Func->setAlignment(Alignment); 3568f22ef01cSRoman Divacky if (Record[6]) { 3569f22ef01cSRoman Divacky if (Record[6]-1 >= SectionTable.size()) 35708f0fd8f6SDimitry Andric return error("Invalid ID"); 3571f22ef01cSRoman Divacky Func->setSection(SectionTable[Record[6]-1]); 3572f22ef01cSRoman Divacky } 357391bc56edSDimitry Andric // Local linkage must have default visibility. 357491bc56edSDimitry Andric if (!Func->hasLocalLinkage()) 357591bc56edSDimitry Andric // FIXME: Change to an error if non-default in 4.0. 35768f0fd8f6SDimitry Andric Func->setVisibility(getDecodedVisibility(Record[7])); 3577f22ef01cSRoman Divacky if (Record.size() > 8 && Record[8]) { 3578ff0cc061SDimitry Andric if (Record[8]-1 >= GCTable.size()) 35798f0fd8f6SDimitry Andric return error("Invalid ID"); 3580f22ef01cSRoman Divacky Func->setGC(GCTable[Record[8]-1].c_str()); 3581f22ef01cSRoman Divacky } 35822754fe60SDimitry Andric bool UnnamedAddr = false; 35832754fe60SDimitry Andric if (Record.size() > 9) 35842754fe60SDimitry Andric UnnamedAddr = Record[9]; 35852754fe60SDimitry Andric Func->setUnnamedAddr(UnnamedAddr); 3586f785676fSDimitry Andric if (Record.size() > 10 && Record[10] != 0) 358739d628a0SDimitry Andric FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1)); 358891bc56edSDimitry Andric 358991bc56edSDimitry Andric if (Record.size() > 11) 35908f0fd8f6SDimitry Andric Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 359191bc56edSDimitry Andric else 35928f0fd8f6SDimitry Andric upgradeDLLImportExportLinkage(Func, RawLinkage); 359391bc56edSDimitry Andric 3594ff0cc061SDimitry Andric if (Record.size() > 12) { 359591bc56edSDimitry Andric if (unsigned ComdatID = Record[12]) { 3596ff0cc061SDimitry Andric if (ComdatID > ComdatList.size()) 35978f0fd8f6SDimitry Andric return error("Invalid function comdat ID"); 359891bc56edSDimitry Andric Func->setComdat(ComdatList[ComdatID - 1]); 359991bc56edSDimitry Andric } 3600ff0cc061SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 3601ff0cc061SDimitry Andric Func->setComdat(reinterpret_cast<Comdat *>(1)); 3602ff0cc061SDimitry Andric } 360391bc56edSDimitry Andric 360439d628a0SDimitry Andric if (Record.size() > 13 && Record[13] != 0) 360539d628a0SDimitry Andric FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1)); 360639d628a0SDimitry Andric 36078f0fd8f6SDimitry Andric if (Record.size() > 14 && Record[14] != 0) 36088f0fd8f6SDimitry Andric FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); 36098f0fd8f6SDimitry Andric 3610f22ef01cSRoman Divacky ValueList.push_back(Func); 3611f22ef01cSRoman Divacky 3612f22ef01cSRoman Divacky // If this is a function with a body, remember the prototype we are 3613f22ef01cSRoman Divacky // creating now, so that we can match up the body with them later. 3614dff0c46cSDimitry Andric if (!isProto) { 361539d628a0SDimitry Andric Func->setIsMaterializable(true); 3616f22ef01cSRoman Divacky FunctionsWithBodies.push_back(Func); 361739d628a0SDimitry Andric DeferredFunctionInfo[Func] = 0; 3618dff0c46cSDimitry Andric } 3619f22ef01cSRoman Divacky break; 3620f22ef01cSRoman Divacky } 36217d523365SDimitry Andric // ALIAS: [alias type, addrspace, aliasee val#, linkage] 36227d523365SDimitry Andric // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass] 36237d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS: 36247d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS_OLD: { 36257d523365SDimitry Andric bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS; 36267d523365SDimitry Andric if (Record.size() < (3 + (unsigned)NewRecord)) 36278f0fd8f6SDimitry Andric return error("Invalid record"); 36287d523365SDimitry Andric unsigned OpNum = 0; 36297d523365SDimitry Andric Type *Ty = getTypeByID(Record[OpNum++]); 3630f785676fSDimitry Andric if (!Ty) 36318f0fd8f6SDimitry Andric return error("Invalid record"); 36327d523365SDimitry Andric 36337d523365SDimitry Andric unsigned AddrSpace; 36347d523365SDimitry Andric if (!NewRecord) { 363591bc56edSDimitry Andric auto *PTy = dyn_cast<PointerType>(Ty); 363691bc56edSDimitry Andric if (!PTy) 36378f0fd8f6SDimitry Andric return error("Invalid type for value"); 36387d523365SDimitry Andric Ty = PTy->getElementType(); 36397d523365SDimitry Andric AddrSpace = PTy->getAddressSpace(); 36407d523365SDimitry Andric } else { 36417d523365SDimitry Andric AddrSpace = Record[OpNum++]; 36427d523365SDimitry Andric } 3643f22ef01cSRoman Divacky 36447d523365SDimitry Andric auto Val = Record[OpNum++]; 36457d523365SDimitry Andric auto Linkage = Record[OpNum++]; 36467d523365SDimitry Andric auto *NewGA = GlobalAlias::create( 36477d523365SDimitry Andric Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule); 3648f22ef01cSRoman Divacky // Old bitcode files didn't have visibility field. 364991bc56edSDimitry Andric // Local linkage must have default visibility. 36507d523365SDimitry Andric if (OpNum != Record.size()) { 36517d523365SDimitry Andric auto VisInd = OpNum++; 36527d523365SDimitry Andric if (!NewGA->hasLocalLinkage()) 365391bc56edSDimitry Andric // FIXME: Change to an error if non-default in 4.0. 36547d523365SDimitry Andric NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 36557d523365SDimitry Andric } 36567d523365SDimitry Andric if (OpNum != Record.size()) 36577d523365SDimitry Andric NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); 365891bc56edSDimitry Andric else 36597d523365SDimitry Andric upgradeDLLImportExportLinkage(NewGA, Linkage); 36607d523365SDimitry Andric if (OpNum != Record.size()) 36617d523365SDimitry Andric NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 36627d523365SDimitry Andric if (OpNum != Record.size()) 36637d523365SDimitry Andric NewGA->setUnnamedAddr(Record[OpNum++]); 3664f22ef01cSRoman Divacky ValueList.push_back(NewGA); 36657d523365SDimitry Andric AliasInits.push_back(std::make_pair(NewGA, Val)); 3666f22ef01cSRoman Divacky break; 3667f22ef01cSRoman Divacky } 3668f22ef01cSRoman Divacky /// MODULE_CODE_PURGEVALS: [numvals] 3669f22ef01cSRoman Divacky case bitc::MODULE_CODE_PURGEVALS: 3670f22ef01cSRoman Divacky // Trim down the value list to the specified size. 3671f22ef01cSRoman Divacky if (Record.size() < 1 || Record[0] > ValueList.size()) 36728f0fd8f6SDimitry Andric return error("Invalid record"); 3673f22ef01cSRoman Divacky ValueList.shrinkTo(Record[0]); 3674f22ef01cSRoman Divacky break; 36757d523365SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 36767d523365SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 36777d523365SDimitry Andric if (Record.size() < 1) 36787d523365SDimitry Andric return error("Invalid record"); 36797d523365SDimitry Andric VSTOffset = Record[0]; 36807d523365SDimitry Andric break; 36817d523365SDimitry Andric /// MODULE_CODE_METADATA_VALUES: [numvals] 36827d523365SDimitry Andric case bitc::MODULE_CODE_METADATA_VALUES: 36837d523365SDimitry Andric if (Record.size() < 1) 36847d523365SDimitry Andric return error("Invalid record"); 36857d523365SDimitry Andric assert(!IsMetadataMaterialized); 36867d523365SDimitry Andric // This record contains the number of metadata values in the module-level 36877d523365SDimitry Andric // METADATA_BLOCK. It is used to support lazy parsing of metadata as 36887d523365SDimitry Andric // a postpass, where we will parse function-level metadata first. 36897d523365SDimitry Andric // This is needed because the ids of metadata are assigned implicitly 36907d523365SDimitry Andric // based on their ordering in the bitcode, with the function-level 36917d523365SDimitry Andric // metadata ids starting after the module-level metadata ids. Otherwise, 36927d523365SDimitry Andric // we would have to parse the module-level metadata block to prime the 36937d523365SDimitry Andric // MetadataList when we are lazy loading metadata during function 36947d523365SDimitry Andric // importing. Initialize the MetadataList size here based on the 36957d523365SDimitry Andric // record value, regardless of whether we are doing lazy metadata 36967d523365SDimitry Andric // loading, so that we have consistent handling and assertion 36977d523365SDimitry Andric // checking in parseMetadata for module-level metadata. 36987d523365SDimitry Andric NumModuleMDs = Record[0]; 36997d523365SDimitry Andric SeenModuleValuesRecord = true; 37007d523365SDimitry Andric assert(MetadataList.size() == 0); 37017d523365SDimitry Andric MetadataList.resize(NumModuleMDs); 37027d523365SDimitry Andric break; 3703f22ef01cSRoman Divacky } 3704f22ef01cSRoman Divacky Record.clear(); 3705f22ef01cSRoman Divacky } 3706f22ef01cSRoman Divacky } 3707f22ef01cSRoman Divacky 37087d523365SDimitry Andric /// Helper to read the header common to all bitcode files. 37097d523365SDimitry Andric static bool hasValidBitcodeHeader(BitstreamCursor &Stream) { 37107d523365SDimitry Andric // Sniff for the signature. 37117d523365SDimitry Andric if (Stream.Read(8) != 'B' || 37127d523365SDimitry Andric Stream.Read(8) != 'C' || 37137d523365SDimitry Andric Stream.Read(4) != 0x0 || 37147d523365SDimitry Andric Stream.Read(4) != 0xC || 37157d523365SDimitry Andric Stream.Read(4) != 0xE || 37167d523365SDimitry Andric Stream.Read(4) != 0xD) 37177d523365SDimitry Andric return false; 37187d523365SDimitry Andric return true; 37197d523365SDimitry Andric } 37207d523365SDimitry Andric 37218f0fd8f6SDimitry Andric std::error_code 37228f0fd8f6SDimitry Andric BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer, 37238f0fd8f6SDimitry Andric Module *M, bool ShouldLazyLoadMetadata) { 37248f0fd8f6SDimitry Andric TheModule = M; 3725f22ef01cSRoman Divacky 37268f0fd8f6SDimitry Andric if (std::error_code EC = initStream(std::move(Streamer))) 3727f785676fSDimitry Andric return EC; 3728f22ef01cSRoman Divacky 3729f22ef01cSRoman Divacky // Sniff for the signature. 37307d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 37318f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 3732f22ef01cSRoman Divacky 3733f22ef01cSRoman Divacky // We expect a number of well-defined blocks, though we don't necessarily 3734f22ef01cSRoman Divacky // need to understand them all. 3735139f7f9bSDimitry Andric while (1) { 3736ff0cc061SDimitry Andric if (Stream.AtEndOfStream()) { 3737ff0cc061SDimitry Andric // We didn't really read a proper Module. 37388f0fd8f6SDimitry Andric return error("Malformed IR file"); 3739ff0cc061SDimitry Andric } 3740bd5abe19SDimitry Andric 3741139f7f9bSDimitry Andric BitstreamEntry Entry = 3742139f7f9bSDimitry Andric Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 3743f22ef01cSRoman Divacky 37448f0fd8f6SDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock) 37458f0fd8f6SDimitry Andric return error("Malformed block"); 3746f22ef01cSRoman Divacky 37477d523365SDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 37487d523365SDimitry Andric parseBitcodeVersion(); 37497d523365SDimitry Andric continue; 37507d523365SDimitry Andric } 37517d523365SDimitry Andric 37528f0fd8f6SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 37537d523365SDimitry Andric return parseModule(0, ShouldLazyLoadMetadata); 37548f0fd8f6SDimitry Andric 3755f22ef01cSRoman Divacky if (Stream.SkipBlock()) 37568f0fd8f6SDimitry Andric return error("Invalid record"); 3757139f7f9bSDimitry Andric } 3758f22ef01cSRoman Divacky } 3759f22ef01cSRoman Divacky 376091bc56edSDimitry Andric ErrorOr<std::string> BitcodeReader::parseModuleTriple() { 37612754fe60SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 37628f0fd8f6SDimitry Andric return error("Invalid record"); 37632754fe60SDimitry Andric 37642754fe60SDimitry Andric SmallVector<uint64_t, 64> Record; 37652754fe60SDimitry Andric 376691bc56edSDimitry Andric std::string Triple; 37672754fe60SDimitry Andric // Read all the records for this module. 3768139f7f9bSDimitry Andric while (1) { 3769139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 37702754fe60SDimitry Andric 3771139f7f9bSDimitry Andric switch (Entry.Kind) { 3772139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 3773139f7f9bSDimitry Andric case BitstreamEntry::Error: 37748f0fd8f6SDimitry Andric return error("Malformed block"); 3775139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 377691bc56edSDimitry Andric return Triple; 3777139f7f9bSDimitry Andric case BitstreamEntry::Record: 3778139f7f9bSDimitry Andric // The interesting case. 37792754fe60SDimitry Andric break; 37802754fe60SDimitry Andric } 37812754fe60SDimitry Andric 37822754fe60SDimitry Andric // Read a record. 3783139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 37842754fe60SDimitry Andric default: break; // Default behavior, ignore unknown content. 37852754fe60SDimitry Andric case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 37862754fe60SDimitry Andric std::string S; 37878f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 37888f0fd8f6SDimitry Andric return error("Invalid record"); 37892754fe60SDimitry Andric Triple = S; 37902754fe60SDimitry Andric break; 37912754fe60SDimitry Andric } 37922754fe60SDimitry Andric } 37932754fe60SDimitry Andric Record.clear(); 37942754fe60SDimitry Andric } 379591bc56edSDimitry Andric llvm_unreachable("Exit infinite loop"); 37962754fe60SDimitry Andric } 37972754fe60SDimitry Andric 379891bc56edSDimitry Andric ErrorOr<std::string> BitcodeReader::parseTriple() { 37998f0fd8f6SDimitry Andric if (std::error_code EC = initStream(nullptr)) 3800f785676fSDimitry Andric return EC; 38012754fe60SDimitry Andric 38022754fe60SDimitry Andric // Sniff for the signature. 38037d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 38048f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 38052754fe60SDimitry Andric 38062754fe60SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 38072754fe60SDimitry Andric // need to understand them all. 3808139f7f9bSDimitry Andric while (1) { 3809139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 38102754fe60SDimitry Andric 3811139f7f9bSDimitry Andric switch (Entry.Kind) { 3812139f7f9bSDimitry Andric case BitstreamEntry::Error: 38138f0fd8f6SDimitry Andric return error("Malformed block"); 3814139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 381591bc56edSDimitry Andric return std::error_code(); 3816139f7f9bSDimitry Andric 3817139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3818139f7f9bSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 381991bc56edSDimitry Andric return parseModuleTriple(); 3820139f7f9bSDimitry Andric 3821139f7f9bSDimitry Andric // Ignore other sub-blocks. 3822f785676fSDimitry Andric if (Stream.SkipBlock()) 38238f0fd8f6SDimitry Andric return error("Malformed block"); 3824139f7f9bSDimitry Andric continue; 3825139f7f9bSDimitry Andric 3826139f7f9bSDimitry Andric case BitstreamEntry::Record: 3827139f7f9bSDimitry Andric Stream.skipRecord(Entry.ID); 3828139f7f9bSDimitry Andric continue; 3829139f7f9bSDimitry Andric } 3830139f7f9bSDimitry Andric } 38312754fe60SDimitry Andric } 38322754fe60SDimitry Andric 38337d523365SDimitry Andric ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() { 38347d523365SDimitry Andric if (std::error_code EC = initStream(nullptr)) 38357d523365SDimitry Andric return EC; 38367d523365SDimitry Andric 38377d523365SDimitry Andric // Sniff for the signature. 38387d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 38397d523365SDimitry Andric return error("Invalid bitcode signature"); 38407d523365SDimitry Andric 38417d523365SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 38427d523365SDimitry Andric // need to understand them all. 38437d523365SDimitry Andric while (1) { 38447d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 38457d523365SDimitry Andric switch (Entry.Kind) { 38467d523365SDimitry Andric case BitstreamEntry::Error: 38477d523365SDimitry Andric return error("Malformed block"); 38487d523365SDimitry Andric case BitstreamEntry::EndBlock: 38497d523365SDimitry Andric return std::error_code(); 38507d523365SDimitry Andric 38517d523365SDimitry Andric case BitstreamEntry::SubBlock: 38527d523365SDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 38537d523365SDimitry Andric if (std::error_code EC = parseBitcodeVersion()) 38547d523365SDimitry Andric return EC; 38557d523365SDimitry Andric return ProducerIdentification; 38567d523365SDimitry Andric } 38577d523365SDimitry Andric // Ignore other sub-blocks. 38587d523365SDimitry Andric if (Stream.SkipBlock()) 38597d523365SDimitry Andric return error("Malformed block"); 38607d523365SDimitry Andric continue; 38617d523365SDimitry Andric case BitstreamEntry::Record: 38627d523365SDimitry Andric Stream.skipRecord(Entry.ID); 38637d523365SDimitry Andric continue; 38647d523365SDimitry Andric } 38657d523365SDimitry Andric } 38667d523365SDimitry Andric } 38677d523365SDimitry Andric 38688f0fd8f6SDimitry Andric /// Parse metadata attachments. 38698f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseMetadataAttachment(Function &F) { 3870f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 38718f0fd8f6SDimitry Andric return error("Invalid record"); 3872f22ef01cSRoman Divacky 3873f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 3874f22ef01cSRoman Divacky while (1) { 3875139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3876139f7f9bSDimitry Andric 3877139f7f9bSDimitry Andric switch (Entry.Kind) { 3878139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 3879139f7f9bSDimitry Andric case BitstreamEntry::Error: 38808f0fd8f6SDimitry Andric return error("Malformed block"); 3881139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 388291bc56edSDimitry Andric return std::error_code(); 3883139f7f9bSDimitry Andric case BitstreamEntry::Record: 3884139f7f9bSDimitry Andric // The interesting case. 3885f22ef01cSRoman Divacky break; 3886f22ef01cSRoman Divacky } 3887139f7f9bSDimitry Andric 3888f22ef01cSRoman Divacky // Read a metadata attachment record. 3889f22ef01cSRoman Divacky Record.clear(); 3890139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 3891f22ef01cSRoman Divacky default: // Default behavior: ignore. 3892f22ef01cSRoman Divacky break; 389317a519f9SDimitry Andric case bitc::METADATA_ATTACHMENT: { 3894f22ef01cSRoman Divacky unsigned RecordLength = Record.size(); 3895ff0cc061SDimitry Andric if (Record.empty()) 38968f0fd8f6SDimitry Andric return error("Invalid record"); 3897ff0cc061SDimitry Andric if (RecordLength % 2 == 0) { 3898ff0cc061SDimitry Andric // A function attachment. 3899ff0cc061SDimitry Andric for (unsigned I = 0; I != RecordLength; I += 2) { 3900ff0cc061SDimitry Andric auto K = MDKindMap.find(Record[I]); 3901ff0cc061SDimitry Andric if (K == MDKindMap.end()) 39028f0fd8f6SDimitry Andric return error("Invalid ID"); 39037d523365SDimitry Andric Metadata *MD = MetadataList.getValueFwdRef(Record[I + 1]); 3904ff0cc061SDimitry Andric F.setMetadata(K->second, cast<MDNode>(MD)); 3905ff0cc061SDimitry Andric } 3906ff0cc061SDimitry Andric continue; 3907ff0cc061SDimitry Andric } 3908ff0cc061SDimitry Andric 3909ff0cc061SDimitry Andric // An instruction attachment. 3910f22ef01cSRoman Divacky Instruction *Inst = InstructionList[Record[0]]; 3911f22ef01cSRoman Divacky for (unsigned i = 1; i != RecordLength; i = i+2) { 3912f22ef01cSRoman Divacky unsigned Kind = Record[i]; 3913e580952dSDimitry Andric DenseMap<unsigned, unsigned>::iterator I = 3914e580952dSDimitry Andric MDKindMap.find(Kind); 3915e580952dSDimitry Andric if (I == MDKindMap.end()) 39168f0fd8f6SDimitry Andric return error("Invalid ID"); 39177d523365SDimitry Andric Metadata *Node = MetadataList.getValueFwdRef(Record[i + 1]); 391839d628a0SDimitry Andric if (isa<LocalAsMetadata>(Node)) 391939d628a0SDimitry Andric // Drop the attachment. This used to be legal, but there's no 392039d628a0SDimitry Andric // upgrade path. 392139d628a0SDimitry Andric break; 3922e580952dSDimitry Andric Inst->setMetadata(I->second, cast<MDNode>(Node)); 3923f785676fSDimitry Andric if (I->second == LLVMContext::MD_tbaa) 3924f785676fSDimitry Andric InstsWithTBAATag.push_back(Inst); 3925f22ef01cSRoman Divacky } 3926f22ef01cSRoman Divacky break; 3927f22ef01cSRoman Divacky } 3928f22ef01cSRoman Divacky } 3929f22ef01cSRoman Divacky } 3930f22ef01cSRoman Divacky } 3931f22ef01cSRoman Divacky 39327d523365SDimitry Andric static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 39337d523365SDimitry Andric LLVMContext &Context = PtrType->getContext(); 3934ff0cc061SDimitry Andric if (!isa<PointerType>(PtrType)) 39357d523365SDimitry Andric return error(Context, "Load/Store operand is not a pointer type"); 3936ff0cc061SDimitry Andric Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 3937ff0cc061SDimitry Andric 3938ff0cc061SDimitry Andric if (ValType && ValType != ElemType) 39397d523365SDimitry Andric return error(Context, "Explicit load/store type does not match pointee " 39407d523365SDimitry Andric "type of pointer operand"); 3941ff0cc061SDimitry Andric if (!PointerType::isLoadableOrStorableType(ElemType)) 39427d523365SDimitry Andric return error(Context, "Cannot load/store from pointer"); 3943ff0cc061SDimitry Andric return std::error_code(); 3944ff0cc061SDimitry Andric } 3945ff0cc061SDimitry Andric 39468f0fd8f6SDimitry Andric /// Lazily parse the specified function body block. 39478f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseFunctionBody(Function *F) { 3948f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 39498f0fd8f6SDimitry Andric return error("Invalid record"); 3950f22ef01cSRoman Divacky 3951f22ef01cSRoman Divacky InstructionList.clear(); 3952f22ef01cSRoman Divacky unsigned ModuleValueListSize = ValueList.size(); 39537d523365SDimitry Andric unsigned ModuleMetadataListSize = MetadataList.size(); 3954f22ef01cSRoman Divacky 3955f22ef01cSRoman Divacky // Add all the function arguments to the value table. 39567d523365SDimitry Andric for (Argument &I : F->args()) 39577d523365SDimitry Andric ValueList.push_back(&I); 3958f22ef01cSRoman Divacky 3959f22ef01cSRoman Divacky unsigned NextValueNo = ValueList.size(); 396091bc56edSDimitry Andric BasicBlock *CurBB = nullptr; 3961f22ef01cSRoman Divacky unsigned CurBBNo = 0; 3962f22ef01cSRoman Divacky 3963f22ef01cSRoman Divacky DebugLoc LastLoc; 396439d628a0SDimitry Andric auto getLastInstruction = [&]() -> Instruction * { 396539d628a0SDimitry Andric if (CurBB && !CurBB->empty()) 396639d628a0SDimitry Andric return &CurBB->back(); 396739d628a0SDimitry Andric else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 396839d628a0SDimitry Andric !FunctionBBs[CurBBNo - 1]->empty()) 396939d628a0SDimitry Andric return &FunctionBBs[CurBBNo - 1]->back(); 397039d628a0SDimitry Andric return nullptr; 397139d628a0SDimitry Andric }; 3972f22ef01cSRoman Divacky 39737d523365SDimitry Andric std::vector<OperandBundleDef> OperandBundles; 39747d523365SDimitry Andric 3975f22ef01cSRoman Divacky // Read all the records. 3976f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 3977f22ef01cSRoman Divacky while (1) { 3978139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3979f22ef01cSRoman Divacky 3980139f7f9bSDimitry Andric switch (Entry.Kind) { 3981139f7f9bSDimitry Andric case BitstreamEntry::Error: 39828f0fd8f6SDimitry Andric return error("Malformed block"); 3983139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 3984139f7f9bSDimitry Andric goto OutOfRecordLoop; 3985139f7f9bSDimitry Andric 3986139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3987139f7f9bSDimitry Andric switch (Entry.ID) { 3988f22ef01cSRoman Divacky default: // Skip unknown content. 3989f22ef01cSRoman Divacky if (Stream.SkipBlock()) 39908f0fd8f6SDimitry Andric return error("Invalid record"); 3991f22ef01cSRoman Divacky break; 3992f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 39938f0fd8f6SDimitry Andric if (std::error_code EC = parseConstants()) 3994f785676fSDimitry Andric return EC; 3995f22ef01cSRoman Divacky NextValueNo = ValueList.size(); 3996f22ef01cSRoman Divacky break; 3997f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 39988f0fd8f6SDimitry Andric if (std::error_code EC = parseValueSymbolTable()) 3999f785676fSDimitry Andric return EC; 4000f22ef01cSRoman Divacky break; 4001f22ef01cSRoman Divacky case bitc::METADATA_ATTACHMENT_ID: 40028f0fd8f6SDimitry Andric if (std::error_code EC = parseMetadataAttachment(*F)) 4003f785676fSDimitry Andric return EC; 4004f22ef01cSRoman Divacky break; 4005f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 40068f0fd8f6SDimitry Andric if (std::error_code EC = parseMetadata()) 4007f785676fSDimitry Andric return EC; 4008f22ef01cSRoman Divacky break; 400939d628a0SDimitry Andric case bitc::USELIST_BLOCK_ID: 40108f0fd8f6SDimitry Andric if (std::error_code EC = parseUseLists()) 401139d628a0SDimitry Andric return EC; 401239d628a0SDimitry Andric break; 4013f22ef01cSRoman Divacky } 4014f22ef01cSRoman Divacky continue; 4015f22ef01cSRoman Divacky 4016139f7f9bSDimitry Andric case BitstreamEntry::Record: 4017139f7f9bSDimitry Andric // The interesting case. 4018139f7f9bSDimitry Andric break; 4019f22ef01cSRoman Divacky } 4020f22ef01cSRoman Divacky 4021f22ef01cSRoman Divacky // Read a record. 4022f22ef01cSRoman Divacky Record.clear(); 402391bc56edSDimitry Andric Instruction *I = nullptr; 4024139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 4025f22ef01cSRoman Divacky switch (BitCode) { 4026f22ef01cSRoman Divacky default: // Default behavior: reject 40278f0fd8f6SDimitry Andric return error("Invalid value"); 402839d628a0SDimitry Andric case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 4029f22ef01cSRoman Divacky if (Record.size() < 1 || Record[0] == 0) 40308f0fd8f6SDimitry Andric return error("Invalid record"); 4031f22ef01cSRoman Divacky // Create all the basic blocks for the function. 4032f22ef01cSRoman Divacky FunctionBBs.resize(Record[0]); 403339d628a0SDimitry Andric 403439d628a0SDimitry Andric // See if anything took the address of blocks in this function. 403539d628a0SDimitry Andric auto BBFRI = BasicBlockFwdRefs.find(F); 403639d628a0SDimitry Andric if (BBFRI == BasicBlockFwdRefs.end()) { 4037f22ef01cSRoman Divacky for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 4038f22ef01cSRoman Divacky FunctionBBs[i] = BasicBlock::Create(Context, "", F); 403939d628a0SDimitry Andric } else { 404039d628a0SDimitry Andric auto &BBRefs = BBFRI->second; 404139d628a0SDimitry Andric // Check for invalid basic block references. 404239d628a0SDimitry Andric if (BBRefs.size() > FunctionBBs.size()) 40438f0fd8f6SDimitry Andric return error("Invalid ID"); 404439d628a0SDimitry Andric assert(!BBRefs.empty() && "Unexpected empty array"); 404539d628a0SDimitry Andric assert(!BBRefs.front() && "Invalid reference to entry block"); 404639d628a0SDimitry Andric for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 404739d628a0SDimitry Andric ++I) 404839d628a0SDimitry Andric if (I < RE && BBRefs[I]) { 404939d628a0SDimitry Andric BBRefs[I]->insertInto(F); 405039d628a0SDimitry Andric FunctionBBs[I] = BBRefs[I]; 405139d628a0SDimitry Andric } else { 405239d628a0SDimitry Andric FunctionBBs[I] = BasicBlock::Create(Context, "", F); 405339d628a0SDimitry Andric } 405439d628a0SDimitry Andric 405539d628a0SDimitry Andric // Erase from the table. 405639d628a0SDimitry Andric BasicBlockFwdRefs.erase(BBFRI); 405739d628a0SDimitry Andric } 405839d628a0SDimitry Andric 4059f22ef01cSRoman Divacky CurBB = FunctionBBs[0]; 4060f22ef01cSRoman Divacky continue; 406139d628a0SDimitry Andric } 4062f22ef01cSRoman Divacky 4063f22ef01cSRoman Divacky case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 4064f22ef01cSRoman Divacky // This record indicates that the last instruction is at the same 4065f22ef01cSRoman Divacky // location as the previous instruction with a location. 406639d628a0SDimitry Andric I = getLastInstruction(); 4067f22ef01cSRoman Divacky 406891bc56edSDimitry Andric if (!I) 40698f0fd8f6SDimitry Andric return error("Invalid record"); 4070f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 407191bc56edSDimitry Andric I = nullptr; 4072f22ef01cSRoman Divacky continue; 4073f22ef01cSRoman Divacky 407417a519f9SDimitry Andric case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 407539d628a0SDimitry Andric I = getLastInstruction(); 407691bc56edSDimitry Andric if (!I || Record.size() < 4) 40778f0fd8f6SDimitry Andric return error("Invalid record"); 4078f22ef01cSRoman Divacky 4079f22ef01cSRoman Divacky unsigned Line = Record[0], Col = Record[1]; 4080f22ef01cSRoman Divacky unsigned ScopeID = Record[2], IAID = Record[3]; 4081f22ef01cSRoman Divacky 408291bc56edSDimitry Andric MDNode *Scope = nullptr, *IA = nullptr; 40837d523365SDimitry Andric if (ScopeID) 40847d523365SDimitry Andric Scope = cast<MDNode>(MetadataList.getValueFwdRef(ScopeID - 1)); 40857d523365SDimitry Andric if (IAID) 40867d523365SDimitry Andric IA = cast<MDNode>(MetadataList.getValueFwdRef(IAID - 1)); 4087f22ef01cSRoman Divacky LastLoc = DebugLoc::get(Line, Col, Scope, IA); 4088f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 408991bc56edSDimitry Andric I = nullptr; 4090f22ef01cSRoman Divacky continue; 4091f22ef01cSRoman Divacky } 4092f22ef01cSRoman Divacky 4093f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 4094f22ef01cSRoman Divacky unsigned OpNum = 0; 4095f22ef01cSRoman Divacky Value *LHS, *RHS; 4096f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 40973861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 4098f22ef01cSRoman Divacky OpNum+1 > Record.size()) 40998f0fd8f6SDimitry Andric return error("Invalid record"); 4100f22ef01cSRoman Divacky 41018f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 4102f785676fSDimitry Andric if (Opc == -1) 41038f0fd8f6SDimitry Andric return error("Invalid record"); 4104f22ef01cSRoman Divacky I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 4105f22ef01cSRoman Divacky InstructionList.push_back(I); 4106f22ef01cSRoman Divacky if (OpNum < Record.size()) { 4107f22ef01cSRoman Divacky if (Opc == Instruction::Add || 4108f22ef01cSRoman Divacky Opc == Instruction::Sub || 41092754fe60SDimitry Andric Opc == Instruction::Mul || 41102754fe60SDimitry Andric Opc == Instruction::Shl) { 4111f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 4112f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 4113f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 4114f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 41152754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 41162754fe60SDimitry Andric Opc == Instruction::UDiv || 41172754fe60SDimitry Andric Opc == Instruction::LShr || 41182754fe60SDimitry Andric Opc == Instruction::AShr) { 41192754fe60SDimitry Andric if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 4120f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setIsExact(true); 4121139f7f9bSDimitry Andric } else if (isa<FPMathOperator>(I)) { 4122875ed548SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4123139f7f9bSDimitry Andric if (FMF.any()) 4124139f7f9bSDimitry Andric I->setFastMathFlags(FMF); 4125f22ef01cSRoman Divacky } 4126139f7f9bSDimitry Andric 4127f22ef01cSRoman Divacky } 4128f22ef01cSRoman Divacky break; 4129f22ef01cSRoman Divacky } 4130f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 4131f22ef01cSRoman Divacky unsigned OpNum = 0; 4132f22ef01cSRoman Divacky Value *Op; 4133f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4134f22ef01cSRoman Divacky OpNum+2 != Record.size()) 41358f0fd8f6SDimitry Andric return error("Invalid record"); 4136f22ef01cSRoman Divacky 41376122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[OpNum]); 41388f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 413991bc56edSDimitry Andric if (Opc == -1 || !ResTy) 41408f0fd8f6SDimitry Andric return error("Invalid record"); 414191bc56edSDimitry Andric Instruction *Temp = nullptr; 4142f785676fSDimitry Andric if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4143f785676fSDimitry Andric if (Temp) { 4144f785676fSDimitry Andric InstructionList.push_back(Temp); 4145f785676fSDimitry Andric CurBB->getInstList().push_back(Temp); 4146f785676fSDimitry Andric } 4147f785676fSDimitry Andric } else { 41487d523365SDimitry Andric auto CastOp = (Instruction::CastOps)Opc; 41497d523365SDimitry Andric if (!CastInst::castIsValid(CastOp, Op, ResTy)) 41507d523365SDimitry Andric return error("Invalid cast"); 41517d523365SDimitry Andric I = CastInst::Create(CastOp, Op, ResTy); 4152f785676fSDimitry Andric } 4153f22ef01cSRoman Divacky InstructionList.push_back(I); 4154f22ef01cSRoman Divacky break; 4155f22ef01cSRoman Divacky } 4156ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4157ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP_OLD: 4158ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4159f22ef01cSRoman Divacky unsigned OpNum = 0; 4160ff0cc061SDimitry Andric 4161ff0cc061SDimitry Andric Type *Ty; 4162ff0cc061SDimitry Andric bool InBounds; 4163ff0cc061SDimitry Andric 4164ff0cc061SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4165ff0cc061SDimitry Andric InBounds = Record[OpNum++]; 4166ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 4167ff0cc061SDimitry Andric } else { 4168ff0cc061SDimitry Andric InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4169ff0cc061SDimitry Andric Ty = nullptr; 4170ff0cc061SDimitry Andric } 4171ff0cc061SDimitry Andric 4172f22ef01cSRoman Divacky Value *BasePtr; 4173f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 41748f0fd8f6SDimitry Andric return error("Invalid record"); 4175f22ef01cSRoman Divacky 4176ff0cc061SDimitry Andric if (!Ty) 4177ff0cc061SDimitry Andric Ty = cast<SequentialType>(BasePtr->getType()->getScalarType()) 4178ff0cc061SDimitry Andric ->getElementType(); 4179ff0cc061SDimitry Andric else if (Ty != 4180ff0cc061SDimitry Andric cast<SequentialType>(BasePtr->getType()->getScalarType()) 4181ff0cc061SDimitry Andric ->getElementType()) 41828f0fd8f6SDimitry Andric return error( 4183ff0cc061SDimitry Andric "Explicit gep type does not match pointee type of pointer operand"); 4184ff0cc061SDimitry Andric 4185f22ef01cSRoman Divacky SmallVector<Value*, 16> GEPIdx; 4186f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4187f22ef01cSRoman Divacky Value *Op; 4188f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 41898f0fd8f6SDimitry Andric return error("Invalid record"); 4190f22ef01cSRoman Divacky GEPIdx.push_back(Op); 4191f22ef01cSRoman Divacky } 4192f22ef01cSRoman Divacky 4193ff0cc061SDimitry Andric I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4194ff0cc061SDimitry Andric 4195f22ef01cSRoman Divacky InstructionList.push_back(I); 4196ff0cc061SDimitry Andric if (InBounds) 4197f22ef01cSRoman Divacky cast<GetElementPtrInst>(I)->setIsInBounds(true); 4198f22ef01cSRoman Divacky break; 4199f22ef01cSRoman Divacky } 4200f22ef01cSRoman Divacky 4201f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4202f22ef01cSRoman Divacky // EXTRACTVAL: [opty, opval, n x indices] 4203f22ef01cSRoman Divacky unsigned OpNum = 0; 4204f22ef01cSRoman Divacky Value *Agg; 4205f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 42068f0fd8f6SDimitry Andric return error("Invalid record"); 4207f22ef01cSRoman Divacky 4208ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 4209ff0cc061SDimitry Andric if (OpNum == RecSize) 42108f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4211ff0cc061SDimitry Andric 4212f22ef01cSRoman Divacky SmallVector<unsigned, 4> EXTRACTVALIdx; 4213ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 4214ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 4215ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 4216ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 4217f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 4218ff0cc061SDimitry Andric 4219ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 42208f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid type"); 4221f22ef01cSRoman Divacky if ((unsigned)Index != Index) 42228f0fd8f6SDimitry Andric return error("Invalid value"); 4223ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 42248f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid struct index"); 4225ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 42268f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid array index"); 4227f22ef01cSRoman Divacky EXTRACTVALIdx.push_back((unsigned)Index); 4228ff0cc061SDimitry Andric 4229ff0cc061SDimitry Andric if (IsStruct) 4230ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 4231ff0cc061SDimitry Andric else 4232ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 4233f22ef01cSRoman Divacky } 4234f22ef01cSRoman Divacky 423517a519f9SDimitry Andric I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 4236f22ef01cSRoman Divacky InstructionList.push_back(I); 4237f22ef01cSRoman Divacky break; 4238f22ef01cSRoman Divacky } 4239f22ef01cSRoman Divacky 4240f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTVAL: { 4241f22ef01cSRoman Divacky // INSERTVAL: [opty, opval, opty, opval, n x indices] 4242f22ef01cSRoman Divacky unsigned OpNum = 0; 4243f22ef01cSRoman Divacky Value *Agg; 4244f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 42458f0fd8f6SDimitry Andric return error("Invalid record"); 4246f22ef01cSRoman Divacky Value *Val; 4247f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 42488f0fd8f6SDimitry Andric return error("Invalid record"); 4249f22ef01cSRoman Divacky 4250ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 4251ff0cc061SDimitry Andric if (OpNum == RecSize) 42528f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid instruction with 0 indices"); 4253ff0cc061SDimitry Andric 4254f22ef01cSRoman Divacky SmallVector<unsigned, 4> INSERTVALIdx; 4255ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 4256ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 4257ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 4258ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 4259f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 4260ff0cc061SDimitry Andric 4261ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 42628f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid type"); 4263f22ef01cSRoman Divacky if ((unsigned)Index != Index) 42648f0fd8f6SDimitry Andric return error("Invalid value"); 4265ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 42668f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid struct index"); 4267ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 42688f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid array index"); 4269ff0cc061SDimitry Andric 4270f22ef01cSRoman Divacky INSERTVALIdx.push_back((unsigned)Index); 4271ff0cc061SDimitry Andric if (IsStruct) 4272ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 4273ff0cc061SDimitry Andric else 4274ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 4275f22ef01cSRoman Divacky } 4276f22ef01cSRoman Divacky 4277ff0cc061SDimitry Andric if (CurTy != Val->getType()) 42788f0fd8f6SDimitry Andric return error("Inserted value type doesn't match aggregate type"); 4279ff0cc061SDimitry Andric 428017a519f9SDimitry Andric I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 4281f22ef01cSRoman Divacky InstructionList.push_back(I); 4282f22ef01cSRoman Divacky break; 4283f22ef01cSRoman Divacky } 4284f22ef01cSRoman Divacky 4285f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 4286f22ef01cSRoman Divacky // obsolete form of select 4287f22ef01cSRoman Divacky // handles select i1 ... in old bitcode 4288f22ef01cSRoman Divacky unsigned OpNum = 0; 4289f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 4290f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 42913861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 42923861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 42938f0fd8f6SDimitry Andric return error("Invalid record"); 4294f22ef01cSRoman Divacky 4295f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 4296f22ef01cSRoman Divacky InstructionList.push_back(I); 4297f22ef01cSRoman Divacky break; 4298f22ef01cSRoman Divacky } 4299f22ef01cSRoman Divacky 4300f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 4301f22ef01cSRoman Divacky // new form of select 4302f22ef01cSRoman Divacky // handles select i1 or select [N x i1] 4303f22ef01cSRoman Divacky unsigned OpNum = 0; 4304f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 4305f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 43063861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4307f22ef01cSRoman Divacky getValueTypePair(Record, OpNum, NextValueNo, Cond)) 43088f0fd8f6SDimitry Andric return error("Invalid record"); 4309f22ef01cSRoman Divacky 4310f22ef01cSRoman Divacky // select condition can be either i1 or [N x i1] 43116122f3e6SDimitry Andric if (VectorType* vector_type = 43126122f3e6SDimitry Andric dyn_cast<VectorType>(Cond->getType())) { 4313f22ef01cSRoman Divacky // expect <n x i1> 4314f22ef01cSRoman Divacky if (vector_type->getElementType() != Type::getInt1Ty(Context)) 43158f0fd8f6SDimitry Andric return error("Invalid type for value"); 4316f22ef01cSRoman Divacky } else { 4317f22ef01cSRoman Divacky // expect i1 4318f22ef01cSRoman Divacky if (Cond->getType() != Type::getInt1Ty(Context)) 43198f0fd8f6SDimitry Andric return error("Invalid type for value"); 4320f22ef01cSRoman Divacky } 4321f22ef01cSRoman Divacky 4322f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 4323f22ef01cSRoman Divacky InstructionList.push_back(I); 4324f22ef01cSRoman Divacky break; 4325f22ef01cSRoman Divacky } 4326f22ef01cSRoman Divacky 4327f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 4328f22ef01cSRoman Divacky unsigned OpNum = 0; 4329f22ef01cSRoman Divacky Value *Vec, *Idx; 4330f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 433191bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 43328f0fd8f6SDimitry Andric return error("Invalid record"); 4333ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 43348f0fd8f6SDimitry Andric return error("Invalid type for value"); 4335f22ef01cSRoman Divacky I = ExtractElementInst::Create(Vec, Idx); 4336f22ef01cSRoman Divacky InstructionList.push_back(I); 4337f22ef01cSRoman Divacky break; 4338f22ef01cSRoman Divacky } 4339f22ef01cSRoman Divacky 4340f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 4341f22ef01cSRoman Divacky unsigned OpNum = 0; 4342f22ef01cSRoman Divacky Value *Vec, *Elt, *Idx; 4343ff0cc061SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 43448f0fd8f6SDimitry Andric return error("Invalid record"); 4345ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 43468f0fd8f6SDimitry Andric return error("Invalid type for value"); 4347ff0cc061SDimitry Andric if (popValue(Record, OpNum, NextValueNo, 4348f22ef01cSRoman Divacky cast<VectorType>(Vec->getType())->getElementType(), Elt) || 434991bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 43508f0fd8f6SDimitry Andric return error("Invalid record"); 4351f22ef01cSRoman Divacky I = InsertElementInst::Create(Vec, Elt, Idx); 4352f22ef01cSRoman Divacky InstructionList.push_back(I); 4353f22ef01cSRoman Divacky break; 4354f22ef01cSRoman Divacky } 4355f22ef01cSRoman Divacky 4356f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 4357f22ef01cSRoman Divacky unsigned OpNum = 0; 4358f22ef01cSRoman Divacky Value *Vec1, *Vec2, *Mask; 4359f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 43603861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 43618f0fd8f6SDimitry Andric return error("Invalid record"); 4362f22ef01cSRoman Divacky 4363f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 43648f0fd8f6SDimitry Andric return error("Invalid record"); 4365ff0cc061SDimitry Andric if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 43668f0fd8f6SDimitry Andric return error("Invalid type for value"); 4367f22ef01cSRoman Divacky I = new ShuffleVectorInst(Vec1, Vec2, Mask); 4368f22ef01cSRoman Divacky InstructionList.push_back(I); 4369f22ef01cSRoman Divacky break; 4370f22ef01cSRoman Divacky } 4371f22ef01cSRoman Divacky 4372f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 4373f22ef01cSRoman Divacky // Old form of ICmp/FCmp returning bool 4374f22ef01cSRoman Divacky // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 4375f22ef01cSRoman Divacky // both legal on vectors but had different behaviour. 4376f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 4377f22ef01cSRoman Divacky // FCmp/ICmp returning bool or vector of bool 4378f22ef01cSRoman Divacky 4379f22ef01cSRoman Divacky unsigned OpNum = 0; 4380f22ef01cSRoman Divacky Value *LHS, *RHS; 4381f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4382875ed548SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 4383875ed548SDimitry Andric return error("Invalid record"); 4384875ed548SDimitry Andric 4385875ed548SDimitry Andric unsigned PredVal = Record[OpNum]; 4386875ed548SDimitry Andric bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 4387875ed548SDimitry Andric FastMathFlags FMF; 4388875ed548SDimitry Andric if (IsFP && Record.size() > OpNum+1) 4389875ed548SDimitry Andric FMF = getDecodedFastMathFlags(Record[++OpNum]); 4390875ed548SDimitry Andric 4391875ed548SDimitry Andric if (OpNum+1 != Record.size()) 43928f0fd8f6SDimitry Andric return error("Invalid record"); 4393f22ef01cSRoman Divacky 4394f22ef01cSRoman Divacky if (LHS->getType()->isFPOrFPVectorTy()) 4395875ed548SDimitry Andric I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 4396f22ef01cSRoman Divacky else 4397875ed548SDimitry Andric I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 4398875ed548SDimitry Andric 4399875ed548SDimitry Andric if (FMF.any()) 4400875ed548SDimitry Andric I->setFastMathFlags(FMF); 4401f22ef01cSRoman Divacky InstructionList.push_back(I); 4402f22ef01cSRoman Divacky break; 4403f22ef01cSRoman Divacky } 4404f22ef01cSRoman Divacky 4405f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 4406f22ef01cSRoman Divacky { 4407f22ef01cSRoman Divacky unsigned Size = Record.size(); 4408f22ef01cSRoman Divacky if (Size == 0) { 4409f22ef01cSRoman Divacky I = ReturnInst::Create(Context); 4410f22ef01cSRoman Divacky InstructionList.push_back(I); 4411f22ef01cSRoman Divacky break; 4412f22ef01cSRoman Divacky } 4413f22ef01cSRoman Divacky 4414f22ef01cSRoman Divacky unsigned OpNum = 0; 441591bc56edSDimitry Andric Value *Op = nullptr; 4416f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 44178f0fd8f6SDimitry Andric return error("Invalid record"); 441817a519f9SDimitry Andric if (OpNum != Record.size()) 44198f0fd8f6SDimitry Andric return error("Invalid record"); 4420f22ef01cSRoman Divacky 442117a519f9SDimitry Andric I = ReturnInst::Create(Context, Op); 4422f22ef01cSRoman Divacky InstructionList.push_back(I); 4423f22ef01cSRoman Divacky break; 4424f22ef01cSRoman Divacky } 4425f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 4426f22ef01cSRoman Divacky if (Record.size() != 1 && Record.size() != 3) 44278f0fd8f6SDimitry Andric return error("Invalid record"); 4428f22ef01cSRoman Divacky BasicBlock *TrueDest = getBasicBlock(Record[0]); 442991bc56edSDimitry Andric if (!TrueDest) 44308f0fd8f6SDimitry Andric return error("Invalid record"); 4431f22ef01cSRoman Divacky 4432f22ef01cSRoman Divacky if (Record.size() == 1) { 4433f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest); 4434f22ef01cSRoman Divacky InstructionList.push_back(I); 4435f22ef01cSRoman Divacky } 4436f22ef01cSRoman Divacky else { 4437f22ef01cSRoman Divacky BasicBlock *FalseDest = getBasicBlock(Record[1]); 44383861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, 44393861d79fSDimitry Andric Type::getInt1Ty(Context)); 444091bc56edSDimitry Andric if (!FalseDest || !Cond) 44418f0fd8f6SDimitry Andric return error("Invalid record"); 4442f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest, FalseDest, Cond); 4443f22ef01cSRoman Divacky InstructionList.push_back(I); 4444f22ef01cSRoman Divacky } 4445f22ef01cSRoman Divacky break; 4446f22ef01cSRoman Divacky } 44477d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 44487d523365SDimitry Andric if (Record.size() != 1 && Record.size() != 2) 44497d523365SDimitry Andric return error("Invalid record"); 44507d523365SDimitry Andric unsigned Idx = 0; 44517d523365SDimitry Andric Value *CleanupPad = 44527d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 44537d523365SDimitry Andric if (!CleanupPad) 44547d523365SDimitry Andric return error("Invalid record"); 44557d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 44567d523365SDimitry Andric if (Record.size() == 2) { 44577d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 44587d523365SDimitry Andric if (!UnwindDest) 44597d523365SDimitry Andric return error("Invalid record"); 44607d523365SDimitry Andric } 44617d523365SDimitry Andric 44627d523365SDimitry Andric I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 44637d523365SDimitry Andric InstructionList.push_back(I); 44647d523365SDimitry Andric break; 44657d523365SDimitry Andric } 44667d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 44677d523365SDimitry Andric if (Record.size() != 2) 44687d523365SDimitry Andric return error("Invalid record"); 44697d523365SDimitry Andric unsigned Idx = 0; 44707d523365SDimitry Andric Value *CatchPad = 44717d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 44727d523365SDimitry Andric if (!CatchPad) 44737d523365SDimitry Andric return error("Invalid record"); 44747d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 44757d523365SDimitry Andric if (!BB) 44767d523365SDimitry Andric return error("Invalid record"); 44777d523365SDimitry Andric 44787d523365SDimitry Andric I = CatchReturnInst::Create(CatchPad, BB); 44797d523365SDimitry Andric InstructionList.push_back(I); 44807d523365SDimitry Andric break; 44817d523365SDimitry Andric } 44827d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 44837d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 44847d523365SDimitry Andric if (Record.size() < 2) 44857d523365SDimitry Andric return error("Invalid record"); 44867d523365SDimitry Andric 44877d523365SDimitry Andric unsigned Idx = 0; 44887d523365SDimitry Andric 44897d523365SDimitry Andric Value *ParentPad = 44907d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 44917d523365SDimitry Andric 44927d523365SDimitry Andric unsigned NumHandlers = Record[Idx++]; 44937d523365SDimitry Andric 44947d523365SDimitry Andric SmallVector<BasicBlock *, 2> Handlers; 44957d523365SDimitry Andric for (unsigned Op = 0; Op != NumHandlers; ++Op) { 44967d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 44977d523365SDimitry Andric if (!BB) 44987d523365SDimitry Andric return error("Invalid record"); 44997d523365SDimitry Andric Handlers.push_back(BB); 45007d523365SDimitry Andric } 45017d523365SDimitry Andric 45027d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 45037d523365SDimitry Andric if (Idx + 1 == Record.size()) { 45047d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 45057d523365SDimitry Andric if (!UnwindDest) 45067d523365SDimitry Andric return error("Invalid record"); 45077d523365SDimitry Andric } 45087d523365SDimitry Andric 45097d523365SDimitry Andric if (Record.size() != Idx) 45107d523365SDimitry Andric return error("Invalid record"); 45117d523365SDimitry Andric 45127d523365SDimitry Andric auto *CatchSwitch = 45137d523365SDimitry Andric CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 45147d523365SDimitry Andric for (BasicBlock *Handler : Handlers) 45157d523365SDimitry Andric CatchSwitch->addHandler(Handler); 45167d523365SDimitry Andric I = CatchSwitch; 45177d523365SDimitry Andric InstructionList.push_back(I); 45187d523365SDimitry Andric break; 45197d523365SDimitry Andric } 45207d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHPAD: 45217d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 45227d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 45237d523365SDimitry Andric if (Record.size() < 2) 45247d523365SDimitry Andric return error("Invalid record"); 45257d523365SDimitry Andric 45267d523365SDimitry Andric unsigned Idx = 0; 45277d523365SDimitry Andric 45287d523365SDimitry Andric Value *ParentPad = 45297d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 45307d523365SDimitry Andric 45317d523365SDimitry Andric unsigned NumArgOperands = Record[Idx++]; 45327d523365SDimitry Andric 45337d523365SDimitry Andric SmallVector<Value *, 2> Args; 45347d523365SDimitry Andric for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 45357d523365SDimitry Andric Value *Val; 45367d523365SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 45377d523365SDimitry Andric return error("Invalid record"); 45387d523365SDimitry Andric Args.push_back(Val); 45397d523365SDimitry Andric } 45407d523365SDimitry Andric 45417d523365SDimitry Andric if (Record.size() != Idx) 45427d523365SDimitry Andric return error("Invalid record"); 45437d523365SDimitry Andric 45447d523365SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 45457d523365SDimitry Andric I = CleanupPadInst::Create(ParentPad, Args); 45467d523365SDimitry Andric else 45477d523365SDimitry Andric I = CatchPadInst::Create(ParentPad, Args); 45487d523365SDimitry Andric InstructionList.push_back(I); 45497d523365SDimitry Andric break; 45507d523365SDimitry Andric } 4551f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 45527ae0e2c9SDimitry Andric // Check magic 45537ae0e2c9SDimitry Andric if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 4554f785676fSDimitry Andric // "New" SwitchInst format with case ranges. The changes to write this 4555f785676fSDimitry Andric // format were reverted but we still recognize bitcode that uses it. 4556f785676fSDimitry Andric // Hopefully someday we will have support for case ranges and can use 4557f785676fSDimitry Andric // this format again. 45587ae0e2c9SDimitry Andric 45597ae0e2c9SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 45607ae0e2c9SDimitry Andric unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 45617ae0e2c9SDimitry Andric 45623861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 45637ae0e2c9SDimitry Andric BasicBlock *Default = getBasicBlock(Record[3]); 456491bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 45658f0fd8f6SDimitry Andric return error("Invalid record"); 45667ae0e2c9SDimitry Andric 45677ae0e2c9SDimitry Andric unsigned NumCases = Record[4]; 45687ae0e2c9SDimitry Andric 45697ae0e2c9SDimitry Andric SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 45707ae0e2c9SDimitry Andric InstructionList.push_back(SI); 45717ae0e2c9SDimitry Andric 45727ae0e2c9SDimitry Andric unsigned CurIdx = 5; 45737ae0e2c9SDimitry Andric for (unsigned i = 0; i != NumCases; ++i) { 4574f785676fSDimitry Andric SmallVector<ConstantInt*, 1> CaseVals; 45757ae0e2c9SDimitry Andric unsigned NumItems = Record[CurIdx++]; 45767ae0e2c9SDimitry Andric for (unsigned ci = 0; ci != NumItems; ++ci) { 45777ae0e2c9SDimitry Andric bool isSingleNumber = Record[CurIdx++]; 45787ae0e2c9SDimitry Andric 45797ae0e2c9SDimitry Andric APInt Low; 45807ae0e2c9SDimitry Andric unsigned ActiveWords = 1; 45817ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 45827ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 45838f0fd8f6SDimitry Andric Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 45847ae0e2c9SDimitry Andric ValueBitWidth); 45857ae0e2c9SDimitry Andric CurIdx += ActiveWords; 45867ae0e2c9SDimitry Andric 45877ae0e2c9SDimitry Andric if (!isSingleNumber) { 45887ae0e2c9SDimitry Andric ActiveWords = 1; 45897ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 45907ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 45918f0fd8f6SDimitry Andric APInt High = readWideAPInt( 45928f0fd8f6SDimitry Andric makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 45937ae0e2c9SDimitry Andric CurIdx += ActiveWords; 4594f785676fSDimitry Andric 4595f785676fSDimitry Andric // FIXME: It is not clear whether values in the range should be 4596f785676fSDimitry Andric // compared as signed or unsigned values. The partially 4597f785676fSDimitry Andric // implemented changes that used this format in the past used 4598f785676fSDimitry Andric // unsigned comparisons. 4599f785676fSDimitry Andric for ( ; Low.ule(High); ++Low) 4600f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 46017ae0e2c9SDimitry Andric } else 4602f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 46037ae0e2c9SDimitry Andric } 46047ae0e2c9SDimitry Andric BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 4605f785676fSDimitry Andric for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 4606f785676fSDimitry Andric cve = CaseVals.end(); cvi != cve; ++cvi) 4607f785676fSDimitry Andric SI->addCase(*cvi, DestBB); 46087ae0e2c9SDimitry Andric } 46097ae0e2c9SDimitry Andric I = SI; 46107ae0e2c9SDimitry Andric break; 46117ae0e2c9SDimitry Andric } 46127ae0e2c9SDimitry Andric 46137ae0e2c9SDimitry Andric // Old SwitchInst format without case ranges. 46147ae0e2c9SDimitry Andric 4615f22ef01cSRoman Divacky if (Record.size() < 3 || (Record.size() & 1) == 0) 46168f0fd8f6SDimitry Andric return error("Invalid record"); 46176122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 46183861d79fSDimitry Andric Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 4619f22ef01cSRoman Divacky BasicBlock *Default = getBasicBlock(Record[2]); 462091bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 46218f0fd8f6SDimitry Andric return error("Invalid record"); 4622f22ef01cSRoman Divacky unsigned NumCases = (Record.size()-3)/2; 4623f22ef01cSRoman Divacky SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4624f22ef01cSRoman Divacky InstructionList.push_back(SI); 4625f22ef01cSRoman Divacky for (unsigned i = 0, e = NumCases; i != e; ++i) { 4626f22ef01cSRoman Divacky ConstantInt *CaseVal = 4627f22ef01cSRoman Divacky dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 4628f22ef01cSRoman Divacky BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 462991bc56edSDimitry Andric if (!CaseVal || !DestBB) { 4630f22ef01cSRoman Divacky delete SI; 46318f0fd8f6SDimitry Andric return error("Invalid record"); 4632f22ef01cSRoman Divacky } 4633f22ef01cSRoman Divacky SI->addCase(CaseVal, DestBB); 4634f22ef01cSRoman Divacky } 4635f22ef01cSRoman Divacky I = SI; 4636f22ef01cSRoman Divacky break; 4637f22ef01cSRoman Divacky } 4638f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4639f22ef01cSRoman Divacky if (Record.size() < 2) 46408f0fd8f6SDimitry Andric return error("Invalid record"); 46416122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 46423861d79fSDimitry Andric Value *Address = getValue(Record, 1, NextValueNo, OpTy); 464391bc56edSDimitry Andric if (!OpTy || !Address) 46448f0fd8f6SDimitry Andric return error("Invalid record"); 4645f22ef01cSRoman Divacky unsigned NumDests = Record.size()-2; 4646f22ef01cSRoman Divacky IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4647f22ef01cSRoman Divacky InstructionList.push_back(IBI); 4648f22ef01cSRoman Divacky for (unsigned i = 0, e = NumDests; i != e; ++i) { 4649f22ef01cSRoman Divacky if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4650f22ef01cSRoman Divacky IBI->addDestination(DestBB); 4651f22ef01cSRoman Divacky } else { 4652f22ef01cSRoman Divacky delete IBI; 46538f0fd8f6SDimitry Andric return error("Invalid record"); 4654f22ef01cSRoman Divacky } 4655f22ef01cSRoman Divacky } 4656f22ef01cSRoman Divacky I = IBI; 4657f22ef01cSRoman Divacky break; 4658f22ef01cSRoman Divacky } 4659f22ef01cSRoman Divacky 4660f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INVOKE: { 4661f22ef01cSRoman Divacky // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4662f785676fSDimitry Andric if (Record.size() < 4) 46638f0fd8f6SDimitry Andric return error("Invalid record"); 4664ff0cc061SDimitry Andric unsigned OpNum = 0; 4665ff0cc061SDimitry Andric AttributeSet PAL = getAttributes(Record[OpNum++]); 4666ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 4667ff0cc061SDimitry Andric BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4668ff0cc061SDimitry Andric BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4669f22ef01cSRoman Divacky 4670ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 4671ff0cc061SDimitry Andric if (CCInfo >> 13 & 1 && 4672ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 46738f0fd8f6SDimitry Andric return error("Explicit invoke type is not a function type"); 4674ff0cc061SDimitry Andric 4675f22ef01cSRoman Divacky Value *Callee; 4676f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 46778f0fd8f6SDimitry Andric return error("Invalid record"); 4678f22ef01cSRoman Divacky 46796122f3e6SDimitry Andric PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4680ff0cc061SDimitry Andric if (!CalleeTy) 46818f0fd8f6SDimitry Andric return error("Callee is not a pointer"); 4682ff0cc061SDimitry Andric if (!FTy) { 4683ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 4684ff0cc061SDimitry Andric if (!FTy) 46858f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 4686ff0cc061SDimitry Andric } else if (CalleeTy->getElementType() != FTy) 46878f0fd8f6SDimitry Andric return error("Explicit invoke type does not match pointee type of " 4688ff0cc061SDimitry Andric "callee operand"); 4689ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 46908f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 4691f22ef01cSRoman Divacky 4692f22ef01cSRoman Divacky SmallVector<Value*, 16> Ops; 4693f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 46943861d79fSDimitry Andric Ops.push_back(getValue(Record, OpNum, NextValueNo, 46953861d79fSDimitry Andric FTy->getParamType(i))); 469691bc56edSDimitry Andric if (!Ops.back()) 46978f0fd8f6SDimitry Andric return error("Invalid record"); 4698f22ef01cSRoman Divacky } 4699f22ef01cSRoman Divacky 4700f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 4701f22ef01cSRoman Divacky if (Record.size() != OpNum) 47028f0fd8f6SDimitry Andric return error("Invalid record"); 4703f22ef01cSRoman Divacky } else { 4704f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 4705f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4706f22ef01cSRoman Divacky Value *Op; 4707f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 47088f0fd8f6SDimitry Andric return error("Invalid record"); 4709f22ef01cSRoman Divacky Ops.push_back(Op); 4710f22ef01cSRoman Divacky } 4711f22ef01cSRoman Divacky } 4712f22ef01cSRoman Divacky 47137d523365SDimitry Andric I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 47147d523365SDimitry Andric OperandBundles.clear(); 4715f22ef01cSRoman Divacky InstructionList.push_back(I); 47167d523365SDimitry Andric cast<InvokeInst>(I)->setCallingConv( 47177d523365SDimitry Andric static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 4718f22ef01cSRoman Divacky cast<InvokeInst>(I)->setAttributes(PAL); 4719f22ef01cSRoman Divacky break; 4720f22ef01cSRoman Divacky } 47216122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 47226122f3e6SDimitry Andric unsigned Idx = 0; 472391bc56edSDimitry Andric Value *Val = nullptr; 47246122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 47258f0fd8f6SDimitry Andric return error("Invalid record"); 47266122f3e6SDimitry Andric I = ResumeInst::Create(Val); 47276122f3e6SDimitry Andric InstructionList.push_back(I); 47286122f3e6SDimitry Andric break; 47296122f3e6SDimitry Andric } 4730f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4731f22ef01cSRoman Divacky I = new UnreachableInst(Context); 4732f22ef01cSRoman Divacky InstructionList.push_back(I); 4733f22ef01cSRoman Divacky break; 4734f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4735f22ef01cSRoman Divacky if (Record.size() < 1 || ((Record.size()-1)&1)) 47368f0fd8f6SDimitry Andric return error("Invalid record"); 47376122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4738f785676fSDimitry Andric if (!Ty) 47398f0fd8f6SDimitry Andric return error("Invalid record"); 4740f22ef01cSRoman Divacky 47413b0f4066SDimitry Andric PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 4742f22ef01cSRoman Divacky InstructionList.push_back(PN); 4743f22ef01cSRoman Divacky 4744f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 47453861d79fSDimitry Andric Value *V; 47463861d79fSDimitry Andric // With the new function encoding, it is possible that operands have 47473861d79fSDimitry Andric // negative IDs (for forward references). Use a signed VBR 47483861d79fSDimitry Andric // representation to keep the encoding small. 47493861d79fSDimitry Andric if (UseRelativeIDs) 47503861d79fSDimitry Andric V = getValueSigned(Record, 1+i, NextValueNo, Ty); 47513861d79fSDimitry Andric else 47523861d79fSDimitry Andric V = getValue(Record, 1+i, NextValueNo, Ty); 4753f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[2+i]); 4754f785676fSDimitry Andric if (!V || !BB) 47558f0fd8f6SDimitry Andric return error("Invalid record"); 4756f22ef01cSRoman Divacky PN->addIncoming(V, BB); 4757f22ef01cSRoman Divacky } 4758f22ef01cSRoman Divacky I = PN; 4759f22ef01cSRoman Divacky break; 4760f22ef01cSRoman Divacky } 4761f22ef01cSRoman Divacky 47628f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD: 47638f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 47646122f3e6SDimitry Andric // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 47656122f3e6SDimitry Andric unsigned Idx = 0; 47668f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 47678f0fd8f6SDimitry Andric if (Record.size() < 3) 47688f0fd8f6SDimitry Andric return error("Invalid record"); 47698f0fd8f6SDimitry Andric } else { 47708f0fd8f6SDimitry Andric assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 47716122f3e6SDimitry Andric if (Record.size() < 4) 47728f0fd8f6SDimitry Andric return error("Invalid record"); 47738f0fd8f6SDimitry Andric } 47746122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[Idx++]); 4775f785676fSDimitry Andric if (!Ty) 47768f0fd8f6SDimitry Andric return error("Invalid record"); 47778f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 477891bc56edSDimitry Andric Value *PersFn = nullptr; 47796122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 47808f0fd8f6SDimitry Andric return error("Invalid record"); 47818f0fd8f6SDimitry Andric 47828f0fd8f6SDimitry Andric if (!F->hasPersonalityFn()) 47838f0fd8f6SDimitry Andric F->setPersonalityFn(cast<Constant>(PersFn)); 47848f0fd8f6SDimitry Andric else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 47858f0fd8f6SDimitry Andric return error("Personality function mismatch"); 47868f0fd8f6SDimitry Andric } 47876122f3e6SDimitry Andric 47886122f3e6SDimitry Andric bool IsCleanup = !!Record[Idx++]; 47896122f3e6SDimitry Andric unsigned NumClauses = Record[Idx++]; 47908f0fd8f6SDimitry Andric LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 47916122f3e6SDimitry Andric LP->setCleanup(IsCleanup); 47926122f3e6SDimitry Andric for (unsigned J = 0; J != NumClauses; ++J) { 47936122f3e6SDimitry Andric LandingPadInst::ClauseType CT = 47946122f3e6SDimitry Andric LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 47956122f3e6SDimitry Andric Value *Val; 47966122f3e6SDimitry Andric 47976122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 47986122f3e6SDimitry Andric delete LP; 47998f0fd8f6SDimitry Andric return error("Invalid record"); 48006122f3e6SDimitry Andric } 48016122f3e6SDimitry Andric 48026122f3e6SDimitry Andric assert((CT != LandingPadInst::Catch || 48036122f3e6SDimitry Andric !isa<ArrayType>(Val->getType())) && 48046122f3e6SDimitry Andric "Catch clause has a invalid type!"); 48056122f3e6SDimitry Andric assert((CT != LandingPadInst::Filter || 48066122f3e6SDimitry Andric isa<ArrayType>(Val->getType())) && 48076122f3e6SDimitry Andric "Filter clause has invalid type!"); 480891bc56edSDimitry Andric LP->addClause(cast<Constant>(Val)); 48096122f3e6SDimitry Andric } 48106122f3e6SDimitry Andric 48116122f3e6SDimitry Andric I = LP; 48126122f3e6SDimitry Andric InstructionList.push_back(I); 48136122f3e6SDimitry Andric break; 48146122f3e6SDimitry Andric } 48156122f3e6SDimitry Andric 481617a519f9SDimitry Andric case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 481717a519f9SDimitry Andric if (Record.size() != 4) 48188f0fd8f6SDimitry Andric return error("Invalid record"); 4819ff0cc061SDimitry Andric uint64_t AlignRecord = Record[3]; 4820ff0cc061SDimitry Andric const uint64_t InAllocaMask = uint64_t(1) << 5; 4821ff0cc061SDimitry Andric const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 48227d523365SDimitry Andric // Reserve bit 7 for SwiftError flag. 48237d523365SDimitry Andric // const uint64_t SwiftErrorMask = uint64_t(1) << 7; 4824ff0cc061SDimitry Andric const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask; 4825ff0cc061SDimitry Andric bool InAlloca = AlignRecord & InAllocaMask; 4826ff0cc061SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4827ff0cc061SDimitry Andric if ((AlignRecord & ExplicitTypeMask) == 0) { 4828ff0cc061SDimitry Andric auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4829ff0cc061SDimitry Andric if (!PTy) 48308f0fd8f6SDimitry Andric return error("Old-style alloca with a non-pointer type"); 4831ff0cc061SDimitry Andric Ty = PTy->getElementType(); 4832ff0cc061SDimitry Andric } 48336122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 483417a519f9SDimitry Andric Value *Size = getFnValueByID(Record[2], OpTy); 4835ff0cc061SDimitry Andric unsigned Align; 4836ff0cc061SDimitry Andric if (std::error_code EC = 4837ff0cc061SDimitry Andric parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 4838ff0cc061SDimitry Andric return EC; 4839ff0cc061SDimitry Andric } 4840f785676fSDimitry Andric if (!Ty || !Size) 48418f0fd8f6SDimitry Andric return error("Invalid record"); 4842ff0cc061SDimitry Andric AllocaInst *AI = new AllocaInst(Ty, Size, Align); 484391bc56edSDimitry Andric AI->setUsedWithInAlloca(InAlloca); 484491bc56edSDimitry Andric I = AI; 4845f22ef01cSRoman Divacky InstructionList.push_back(I); 4846f22ef01cSRoman Divacky break; 4847f22ef01cSRoman Divacky } 4848f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4849f22ef01cSRoman Divacky unsigned OpNum = 0; 4850f22ef01cSRoman Divacky Value *Op; 4851f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4852ff0cc061SDimitry Andric (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 48538f0fd8f6SDimitry Andric return error("Invalid record"); 4854f22ef01cSRoman Divacky 4855ff0cc061SDimitry Andric Type *Ty = nullptr; 4856ff0cc061SDimitry Andric if (OpNum + 3 == Record.size()) 4857ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 48587d523365SDimitry Andric if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType())) 4859ff0cc061SDimitry Andric return EC; 4860ff0cc061SDimitry Andric if (!Ty) 4861ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4862ff0cc061SDimitry Andric 4863ff0cc061SDimitry Andric unsigned Align; 4864ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4865ff0cc061SDimitry Andric return EC; 4866ff0cc061SDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 4867ff0cc061SDimitry Andric 4868f22ef01cSRoman Divacky InstructionList.push_back(I); 4869f22ef01cSRoman Divacky break; 4870f22ef01cSRoman Divacky } 48716122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_LOADATOMIC: { 48726122f3e6SDimitry Andric // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 48736122f3e6SDimitry Andric unsigned OpNum = 0; 48746122f3e6SDimitry Andric Value *Op; 48756122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4876ff0cc061SDimitry Andric (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 48778f0fd8f6SDimitry Andric return error("Invalid record"); 48786122f3e6SDimitry Andric 4879ff0cc061SDimitry Andric Type *Ty = nullptr; 4880ff0cc061SDimitry Andric if (OpNum + 5 == Record.size()) 4881ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 48827d523365SDimitry Andric if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType())) 4883ff0cc061SDimitry Andric return EC; 4884ff0cc061SDimitry Andric if (!Ty) 4885ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4886ff0cc061SDimitry Andric 48878f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 48886122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Release || 48896122f3e6SDimitry Andric Ordering == AcquireRelease) 48908f0fd8f6SDimitry Andric return error("Invalid record"); 48916122f3e6SDimitry Andric if (Ordering != NotAtomic && Record[OpNum] == 0) 48928f0fd8f6SDimitry Andric return error("Invalid record"); 48938f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 48946122f3e6SDimitry Andric 4895ff0cc061SDimitry Andric unsigned Align; 4896ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4897ff0cc061SDimitry Andric return EC; 4898ff0cc061SDimitry Andric I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope); 4899ff0cc061SDimitry Andric 49006122f3e6SDimitry Andric InstructionList.push_back(I); 49016122f3e6SDimitry Andric break; 49026122f3e6SDimitry Andric } 4903ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE: 4904ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 4905f22ef01cSRoman Divacky unsigned OpNum = 0; 4906f22ef01cSRoman Divacky Value *Val, *Ptr; 4907f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4908ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STORE 4909ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4910ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4911ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4912ff0cc061SDimitry Andric Val)) || 4913f22ef01cSRoman Divacky OpNum + 2 != Record.size()) 49148f0fd8f6SDimitry Andric return error("Invalid record"); 4915f22ef01cSRoman Divacky 49167d523365SDimitry Andric if (std::error_code EC = 49177d523365SDimitry Andric typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4918ff0cc061SDimitry Andric return EC; 4919ff0cc061SDimitry Andric unsigned Align; 4920ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4921ff0cc061SDimitry Andric return EC; 4922ff0cc061SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 4923f22ef01cSRoman Divacky InstructionList.push_back(I); 4924f22ef01cSRoman Divacky break; 4925f22ef01cSRoman Divacky } 4926ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC: 4927ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 49286122f3e6SDimitry Andric // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 49296122f3e6SDimitry Andric unsigned OpNum = 0; 49306122f3e6SDimitry Andric Value *Val, *Ptr; 49316122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4932ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 4933ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4934ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4935ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4936ff0cc061SDimitry Andric Val)) || 49376122f3e6SDimitry Andric OpNum + 4 != Record.size()) 49388f0fd8f6SDimitry Andric return error("Invalid record"); 49396122f3e6SDimitry Andric 49407d523365SDimitry Andric if (std::error_code EC = 49417d523365SDimitry Andric typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4942ff0cc061SDimitry Andric return EC; 49438f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 49446122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Acquire || 49456122f3e6SDimitry Andric Ordering == AcquireRelease) 49468f0fd8f6SDimitry Andric return error("Invalid record"); 49478f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 49486122f3e6SDimitry Andric if (Ordering != NotAtomic && Record[OpNum] == 0) 49498f0fd8f6SDimitry Andric return error("Invalid record"); 49506122f3e6SDimitry Andric 4951ff0cc061SDimitry Andric unsigned Align; 4952ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4953ff0cc061SDimitry Andric return EC; 4954ff0cc061SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope); 49556122f3e6SDimitry Andric InstructionList.push_back(I); 49566122f3e6SDimitry Andric break; 49576122f3e6SDimitry Andric } 4958ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 49596122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG: { 496091bc56edSDimitry Andric // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 496191bc56edSDimitry Andric // failureordering?, isweak?] 49626122f3e6SDimitry Andric unsigned OpNum = 0; 49636122f3e6SDimitry Andric Value *Ptr, *Cmp, *New; 49646122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4965ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 4966ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 4967ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4968ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4969ff0cc061SDimitry Andric Cmp)) || 4970ff0cc061SDimitry Andric popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 4971ff0cc061SDimitry Andric Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 49728f0fd8f6SDimitry Andric return error("Invalid record"); 49738f0fd8f6SDimitry Andric AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 497491bc56edSDimitry Andric if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered) 49758f0fd8f6SDimitry Andric return error("Invalid record"); 49768f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]); 497791bc56edSDimitry Andric 49787d523365SDimitry Andric if (std::error_code EC = 49797d523365SDimitry Andric typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 4980ff0cc061SDimitry Andric return EC; 498191bc56edSDimitry Andric AtomicOrdering FailureOrdering; 498291bc56edSDimitry Andric if (Record.size() < 7) 498391bc56edSDimitry Andric FailureOrdering = 498491bc56edSDimitry Andric AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 498591bc56edSDimitry Andric else 49868f0fd8f6SDimitry Andric FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 498791bc56edSDimitry Andric 498891bc56edSDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 498991bc56edSDimitry Andric SynchScope); 49906122f3e6SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 499191bc56edSDimitry Andric 499291bc56edSDimitry Andric if (Record.size() < 8) { 499391bc56edSDimitry Andric // Before weak cmpxchgs existed, the instruction simply returned the 499491bc56edSDimitry Andric // value loaded from memory, so bitcode files from that era will be 499591bc56edSDimitry Andric // expecting the first component of a modern cmpxchg. 499691bc56edSDimitry Andric CurBB->getInstList().push_back(I); 499791bc56edSDimitry Andric I = ExtractValueInst::Create(I, 0); 499891bc56edSDimitry Andric } else { 499991bc56edSDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 500091bc56edSDimitry Andric } 500191bc56edSDimitry Andric 50026122f3e6SDimitry Andric InstructionList.push_back(I); 50036122f3e6SDimitry Andric break; 50046122f3e6SDimitry Andric } 50056122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW: { 50066122f3e6SDimitry Andric // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 50076122f3e6SDimitry Andric unsigned OpNum = 0; 50086122f3e6SDimitry Andric Value *Ptr, *Val; 50096122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 50103861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, 50116122f3e6SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), Val) || 50126122f3e6SDimitry Andric OpNum+4 != Record.size()) 50138f0fd8f6SDimitry Andric return error("Invalid record"); 50148f0fd8f6SDimitry Andric AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 50156122f3e6SDimitry Andric if (Operation < AtomicRMWInst::FIRST_BINOP || 50166122f3e6SDimitry Andric Operation > AtomicRMWInst::LAST_BINOP) 50178f0fd8f6SDimitry Andric return error("Invalid record"); 50188f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 50196122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Unordered) 50208f0fd8f6SDimitry Andric return error("Invalid record"); 50218f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 50226122f3e6SDimitry Andric I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 50236122f3e6SDimitry Andric cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 50246122f3e6SDimitry Andric InstructionList.push_back(I); 50256122f3e6SDimitry Andric break; 50266122f3e6SDimitry Andric } 50276122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 50286122f3e6SDimitry Andric if (2 != Record.size()) 50298f0fd8f6SDimitry Andric return error("Invalid record"); 50308f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 50316122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Unordered || 50326122f3e6SDimitry Andric Ordering == Monotonic) 50338f0fd8f6SDimitry Andric return error("Invalid record"); 50348f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]); 50356122f3e6SDimitry Andric I = new FenceInst(Context, Ordering, SynchScope); 50366122f3e6SDimitry Andric InstructionList.push_back(I); 50376122f3e6SDimitry Andric break; 50386122f3e6SDimitry Andric } 503917a519f9SDimitry Andric case bitc::FUNC_CODE_INST_CALL: { 50407d523365SDimitry Andric // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 5041f22ef01cSRoman Divacky if (Record.size() < 3) 50428f0fd8f6SDimitry Andric return error("Invalid record"); 5043f22ef01cSRoman Divacky 5044ff0cc061SDimitry Andric unsigned OpNum = 0; 5045ff0cc061SDimitry Andric AttributeSet PAL = getAttributes(Record[OpNum++]); 5046ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 5047f22ef01cSRoman Divacky 50487d523365SDimitry Andric FastMathFlags FMF; 50497d523365SDimitry Andric if ((CCInfo >> bitc::CALL_FMF) & 1) { 50507d523365SDimitry Andric FMF = getDecodedFastMathFlags(Record[OpNum++]); 50517d523365SDimitry Andric if (!FMF.any()) 50527d523365SDimitry Andric return error("Fast math flags indicator set for call with no FMF"); 50537d523365SDimitry Andric } 50547d523365SDimitry Andric 5055ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 50567d523365SDimitry Andric if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 5057ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 50588f0fd8f6SDimitry Andric return error("Explicit call type is not a function type"); 5059ff0cc061SDimitry Andric 5060f22ef01cSRoman Divacky Value *Callee; 5061f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 50628f0fd8f6SDimitry Andric return error("Invalid record"); 5063f22ef01cSRoman Divacky 50646122f3e6SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5065ff0cc061SDimitry Andric if (!OpTy) 50668f0fd8f6SDimitry Andric return error("Callee is not a pointer type"); 5067ff0cc061SDimitry Andric if (!FTy) { 5068ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 5069ff0cc061SDimitry Andric if (!FTy) 50708f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 5071ff0cc061SDimitry Andric } else if (OpTy->getElementType() != FTy) 50728f0fd8f6SDimitry Andric return error("Explicit call type does not match pointee type of " 5073ff0cc061SDimitry Andric "callee operand"); 5074ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 50758f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 5076f22ef01cSRoman Divacky 5077f22ef01cSRoman Divacky SmallVector<Value*, 16> Args; 5078f22ef01cSRoman Divacky // Read the fixed params. 5079f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 508017a519f9SDimitry Andric if (FTy->getParamType(i)->isLabelTy()) 5081f22ef01cSRoman Divacky Args.push_back(getBasicBlock(Record[OpNum])); 5082f22ef01cSRoman Divacky else 50833861d79fSDimitry Andric Args.push_back(getValue(Record, OpNum, NextValueNo, 50843861d79fSDimitry Andric FTy->getParamType(i))); 508591bc56edSDimitry Andric if (!Args.back()) 50868f0fd8f6SDimitry Andric return error("Invalid record"); 5087f22ef01cSRoman Divacky } 5088f22ef01cSRoman Divacky 5089f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 5090f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 5091f22ef01cSRoman Divacky if (OpNum != Record.size()) 50928f0fd8f6SDimitry Andric return error("Invalid record"); 5093f22ef01cSRoman Divacky } else { 5094f22ef01cSRoman Divacky while (OpNum != Record.size()) { 5095f22ef01cSRoman Divacky Value *Op; 5096f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 50978f0fd8f6SDimitry Andric return error("Invalid record"); 5098f22ef01cSRoman Divacky Args.push_back(Op); 5099f22ef01cSRoman Divacky } 5100f22ef01cSRoman Divacky } 5101f22ef01cSRoman Divacky 51027d523365SDimitry Andric I = CallInst::Create(FTy, Callee, Args, OperandBundles); 51037d523365SDimitry Andric OperandBundles.clear(); 5104f22ef01cSRoman Divacky InstructionList.push_back(I); 5105f22ef01cSRoman Divacky cast<CallInst>(I)->setCallingConv( 51067d523365SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 510791bc56edSDimitry Andric CallInst::TailCallKind TCK = CallInst::TCK_None; 51087d523365SDimitry Andric if (CCInfo & 1 << bitc::CALL_TAIL) 510991bc56edSDimitry Andric TCK = CallInst::TCK_Tail; 51107d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 511191bc56edSDimitry Andric TCK = CallInst::TCK_MustTail; 51127d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_NOTAIL)) 51137d523365SDimitry Andric TCK = CallInst::TCK_NoTail; 511491bc56edSDimitry Andric cast<CallInst>(I)->setTailCallKind(TCK); 5115f22ef01cSRoman Divacky cast<CallInst>(I)->setAttributes(PAL); 51167d523365SDimitry Andric if (FMF.any()) { 51177d523365SDimitry Andric if (!isa<FPMathOperator>(I)) 51187d523365SDimitry Andric return error("Fast-math-flags specified for call without " 51197d523365SDimitry Andric "floating-point scalar or vector return type"); 51207d523365SDimitry Andric I->setFastMathFlags(FMF); 51217d523365SDimitry Andric } 5122f22ef01cSRoman Divacky break; 5123f22ef01cSRoman Divacky } 5124f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 5125f22ef01cSRoman Divacky if (Record.size() < 3) 51268f0fd8f6SDimitry Andric return error("Invalid record"); 51276122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 51283861d79fSDimitry Andric Value *Op = getValue(Record, 1, NextValueNo, OpTy); 51296122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[2]); 5130f22ef01cSRoman Divacky if (!OpTy || !Op || !ResTy) 51318f0fd8f6SDimitry Andric return error("Invalid record"); 5132f22ef01cSRoman Divacky I = new VAArgInst(Op, ResTy); 5133f22ef01cSRoman Divacky InstructionList.push_back(I); 5134f22ef01cSRoman Divacky break; 5135f22ef01cSRoman Divacky } 51367d523365SDimitry Andric 51377d523365SDimitry Andric case bitc::FUNC_CODE_OPERAND_BUNDLE: { 51387d523365SDimitry Andric // A call or an invoke can be optionally prefixed with some variable 51397d523365SDimitry Andric // number of operand bundle blocks. These blocks are read into 51407d523365SDimitry Andric // OperandBundles and consumed at the next call or invoke instruction. 51417d523365SDimitry Andric 51427d523365SDimitry Andric if (Record.size() < 1 || Record[0] >= BundleTags.size()) 51437d523365SDimitry Andric return error("Invalid record"); 51447d523365SDimitry Andric 51457d523365SDimitry Andric std::vector<Value *> Inputs; 51467d523365SDimitry Andric 51477d523365SDimitry Andric unsigned OpNum = 1; 51487d523365SDimitry Andric while (OpNum != Record.size()) { 51497d523365SDimitry Andric Value *Op; 51507d523365SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 51517d523365SDimitry Andric return error("Invalid record"); 51527d523365SDimitry Andric Inputs.push_back(Op); 51537d523365SDimitry Andric } 51547d523365SDimitry Andric 51557d523365SDimitry Andric OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 51567d523365SDimitry Andric continue; 51577d523365SDimitry Andric } 5158f22ef01cSRoman Divacky } 5159f22ef01cSRoman Divacky 5160f22ef01cSRoman Divacky // Add instruction to end of current BB. If there is no current BB, reject 5161f22ef01cSRoman Divacky // this file. 516291bc56edSDimitry Andric if (!CurBB) { 5163f22ef01cSRoman Divacky delete I; 51648f0fd8f6SDimitry Andric return error("Invalid instruction with no BB"); 5165f22ef01cSRoman Divacky } 51667d523365SDimitry Andric if (!OperandBundles.empty()) { 51677d523365SDimitry Andric delete I; 51687d523365SDimitry Andric return error("Operand bundles found with no consumer"); 51697d523365SDimitry Andric } 5170f22ef01cSRoman Divacky CurBB->getInstList().push_back(I); 5171f22ef01cSRoman Divacky 5172f22ef01cSRoman Divacky // If this was a terminator instruction, move to the next block. 5173f22ef01cSRoman Divacky if (isa<TerminatorInst>(I)) { 5174f22ef01cSRoman Divacky ++CurBBNo; 517591bc56edSDimitry Andric CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 5176f22ef01cSRoman Divacky } 5177f22ef01cSRoman Divacky 5178f22ef01cSRoman Divacky // Non-void values get registered in the value table for future use. 5179f22ef01cSRoman Divacky if (I && !I->getType()->isVoidTy()) 51808f0fd8f6SDimitry Andric ValueList.assignValue(I, NextValueNo++); 5181f22ef01cSRoman Divacky } 5182f22ef01cSRoman Divacky 5183139f7f9bSDimitry Andric OutOfRecordLoop: 5184139f7f9bSDimitry Andric 51857d523365SDimitry Andric if (!OperandBundles.empty()) 51867d523365SDimitry Andric return error("Operand bundles found with no consumer"); 51877d523365SDimitry Andric 5188f22ef01cSRoman Divacky // Check the function list for unresolved values. 5189f22ef01cSRoman Divacky if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 519091bc56edSDimitry Andric if (!A->getParent()) { 5191f22ef01cSRoman Divacky // We found at least one unresolved value. Nuke them all to avoid leaks. 5192f22ef01cSRoman Divacky for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 519391bc56edSDimitry Andric if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 5194f22ef01cSRoman Divacky A->replaceAllUsesWith(UndefValue::get(A->getType())); 5195f22ef01cSRoman Divacky delete A; 5196f22ef01cSRoman Divacky } 5197f22ef01cSRoman Divacky } 51988f0fd8f6SDimitry Andric return error("Never resolved value found in function"); 5199f22ef01cSRoman Divacky } 5200f22ef01cSRoman Divacky } 5201f22ef01cSRoman Divacky 5202e580952dSDimitry Andric // FIXME: Check for unresolved forward-declared metadata references 5203e580952dSDimitry Andric // and clean up leaks. 5204e580952dSDimitry Andric 5205f22ef01cSRoman Divacky // Trim the value list down to the size it was before we parsed this function. 5206f22ef01cSRoman Divacky ValueList.shrinkTo(ModuleValueListSize); 52077d523365SDimitry Andric MetadataList.shrinkTo(ModuleMetadataListSize); 5208f22ef01cSRoman Divacky std::vector<BasicBlock*>().swap(FunctionBBs); 520991bc56edSDimitry Andric return std::error_code(); 5210f22ef01cSRoman Divacky } 5211f22ef01cSRoman Divacky 5212f785676fSDimitry Andric /// Find the function body in the bitcode stream 52138f0fd8f6SDimitry Andric std::error_code BitcodeReader::findFunctionInStream( 521491bc56edSDimitry Andric Function *F, 5215dff0c46cSDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 5216dff0c46cSDimitry Andric while (DeferredFunctionInfoIterator->second == 0) { 52177d523365SDimitry Andric // This is the fallback handling for the old format bitcode that 52187d523365SDimitry Andric // didn't contain the function index in the VST, or when we have 52197d523365SDimitry Andric // an anonymous function which would not have a VST entry. 52207d523365SDimitry Andric // Assert that we have one of those two cases. 52217d523365SDimitry Andric assert(VSTOffset == 0 || !F->hasName()); 52227d523365SDimitry Andric // Parse the next body in the stream and set its position in the 52237d523365SDimitry Andric // DeferredFunctionInfo map. 52247d523365SDimitry Andric if (std::error_code EC = rememberAndSkipFunctionBodies()) 5225f785676fSDimitry Andric return EC; 5226dff0c46cSDimitry Andric } 522791bc56edSDimitry Andric return std::error_code(); 5228dff0c46cSDimitry Andric } 5229dff0c46cSDimitry Andric 5230f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5231f22ef01cSRoman Divacky // GVMaterializer implementation 5232f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5233f22ef01cSRoman Divacky 523491bc56edSDimitry Andric void BitcodeReader::releaseBuffer() { Buffer.release(); } 5235f22ef01cSRoman Divacky 523639d628a0SDimitry Andric std::error_code BitcodeReader::materialize(GlobalValue *GV) { 52377d523365SDimitry Andric // In older bitcode we must materialize the metadata before parsing 52387d523365SDimitry Andric // any functions, in order to set up the MetadataList properly. 52397d523365SDimitry Andric if (!SeenModuleValuesRecord) { 5240ff0cc061SDimitry Andric if (std::error_code EC = materializeMetadata()) 5241ff0cc061SDimitry Andric return EC; 52427d523365SDimitry Andric } 5243ff0cc061SDimitry Andric 5244f22ef01cSRoman Divacky Function *F = dyn_cast<Function>(GV); 5245f22ef01cSRoman Divacky // If it's not a function or is already material, ignore the request. 5246f785676fSDimitry Andric if (!F || !F->isMaterializable()) 524791bc56edSDimitry Andric return std::error_code(); 5248f22ef01cSRoman Divacky 5249f22ef01cSRoman Divacky DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 5250f22ef01cSRoman Divacky assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 5251dff0c46cSDimitry Andric // If its position is recorded as 0, its body is somewhere in the stream 5252dff0c46cSDimitry Andric // but we haven't seen it yet. 52533dac3a9bSDimitry Andric if (DFII->second == 0) 52548f0fd8f6SDimitry Andric if (std::error_code EC = findFunctionInStream(F, DFII)) 5255f785676fSDimitry Andric return EC; 5256f22ef01cSRoman Divacky 5257f22ef01cSRoman Divacky // Move the bit stream to the saved position of the deferred function body. 5258f22ef01cSRoman Divacky Stream.JumpToBit(DFII->second); 5259f22ef01cSRoman Divacky 52608f0fd8f6SDimitry Andric if (std::error_code EC = parseFunctionBody(F)) 5261f785676fSDimitry Andric return EC; 526239d628a0SDimitry Andric F->setIsMaterializable(false); 5263f22ef01cSRoman Divacky 5264ff0cc061SDimitry Andric if (StripDebugInfo) 5265ff0cc061SDimitry Andric stripDebugInfo(*F); 5266ff0cc061SDimitry Andric 5267f22ef01cSRoman Divacky // Upgrade any old intrinsic calls in the function. 52683dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 52697d523365SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 52707d523365SDimitry Andric UI != UE;) { 52713dac3a9bSDimitry Andric User *U = *UI; 52723dac3a9bSDimitry Andric ++UI; 52733dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 52743dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 5275f22ef01cSRoman Divacky } 5276f22ef01cSRoman Divacky } 5277f22ef01cSRoman Divacky 52787d523365SDimitry Andric // Finish fn->subprogram upgrade for materialized functions. 52797d523365SDimitry Andric if (DISubprogram *SP = FunctionsWithSPs.lookup(F)) 52807d523365SDimitry Andric F->setSubprogram(SP); 52817d523365SDimitry Andric 528239d628a0SDimitry Andric // Bring in any functions that this function forward-referenced via 528339d628a0SDimitry Andric // blockaddresses. 528439d628a0SDimitry Andric return materializeForwardReferencedFunctions(); 5285f22ef01cSRoman Divacky } 5286f22ef01cSRoman Divacky 52877d523365SDimitry Andric std::error_code BitcodeReader::materializeModule() { 5288ff0cc061SDimitry Andric if (std::error_code EC = materializeMetadata()) 5289ff0cc061SDimitry Andric return EC; 5290ff0cc061SDimitry Andric 529139d628a0SDimitry Andric // Promise to materialize all forward references. 529239d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 529339d628a0SDimitry Andric 5294f22ef01cSRoman Divacky // Iterate over the module, deserializing any functions that are still on 5295f22ef01cSRoman Divacky // disk. 52967d523365SDimitry Andric for (Function &F : *TheModule) { 52977d523365SDimitry Andric if (std::error_code EC = materialize(&F)) 5298f785676fSDimitry Andric return EC; 5299f785676fSDimitry Andric } 53007d523365SDimitry Andric // At this point, if there are any function bodies, parse the rest of 53017d523365SDimitry Andric // the bits in the module past the last function block we have recorded 53027d523365SDimitry Andric // through either lazy scanning or the VST. 53037d523365SDimitry Andric if (LastFunctionBlockBit || NextUnreadBit) 53047d523365SDimitry Andric parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit 53057d523365SDimitry Andric : NextUnreadBit); 5306dff0c46cSDimitry Andric 530739d628a0SDimitry Andric // Check that all block address forward references got resolved (as we 530839d628a0SDimitry Andric // promised above). 530939d628a0SDimitry Andric if (!BasicBlockFwdRefs.empty()) 53108f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 531139d628a0SDimitry Andric 5312f22ef01cSRoman Divacky // Upgrade any intrinsic calls that slipped through (should not happen!) and 5313f22ef01cSRoman Divacky // delete the old functions to clean up. We can't do this unless the entire 5314f22ef01cSRoman Divacky // module is materialized because there could always be another function body 5315f22ef01cSRoman Divacky // with calls to the old function. 53163dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 53173dac3a9bSDimitry Andric for (auto *U : I.first->users()) { 53183dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 53193dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 5320f22ef01cSRoman Divacky } 53213dac3a9bSDimitry Andric if (!I.first->use_empty()) 53223dac3a9bSDimitry Andric I.first->replaceAllUsesWith(I.second); 53233dac3a9bSDimitry Andric I.first->eraseFromParent(); 5324f22ef01cSRoman Divacky } 53253dac3a9bSDimitry Andric UpgradedIntrinsics.clear(); 5326f22ef01cSRoman Divacky 5327f785676fSDimitry Andric for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 5328f785676fSDimitry Andric UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 5329f785676fSDimitry Andric 53307d523365SDimitry Andric UpgradeDebugInfo(*TheModule); 533191bc56edSDimitry Andric return std::error_code(); 5332dff0c46cSDimitry Andric } 53336122f3e6SDimitry Andric 533439d628a0SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 533539d628a0SDimitry Andric return IdentifiedStructTypes; 533639d628a0SDimitry Andric } 533739d628a0SDimitry Andric 53388f0fd8f6SDimitry Andric std::error_code 53398f0fd8f6SDimitry Andric BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) { 53408f0fd8f6SDimitry Andric if (Streamer) 53418f0fd8f6SDimitry Andric return initLazyStream(std::move(Streamer)); 53428f0fd8f6SDimitry Andric return initStreamFromBuffer(); 5343dff0c46cSDimitry Andric } 5344dff0c46cSDimitry Andric 53458f0fd8f6SDimitry Andric std::error_code BitcodeReader::initStreamFromBuffer() { 53463861d79fSDimitry Andric const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 5347dff0c46cSDimitry Andric const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 5348dff0c46cSDimitry Andric 534939d628a0SDimitry Andric if (Buffer->getBufferSize() & 3) 53508f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 5351dff0c46cSDimitry Andric 5352dff0c46cSDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents. 5353dff0c46cSDimitry Andric // The magic number is 0x0B17C0DE stored in little endian. 5354dff0c46cSDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd)) 5355dff0c46cSDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 53568f0fd8f6SDimitry Andric return error("Invalid bitcode wrapper header"); 5357dff0c46cSDimitry Andric 5358dff0c46cSDimitry Andric StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 535939d628a0SDimitry Andric Stream.init(&*StreamFile); 5360f22ef01cSRoman Divacky 536191bc56edSDimitry Andric return std::error_code(); 5362f22ef01cSRoman Divacky } 5363f22ef01cSRoman Divacky 53648f0fd8f6SDimitry Andric std::error_code 53658f0fd8f6SDimitry Andric BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) { 5366dff0c46cSDimitry Andric // Check and strip off the bitcode wrapper; BitstreamReader expects never to 5367dff0c46cSDimitry Andric // see it. 53688f0fd8f6SDimitry Andric auto OwnedBytes = 53698f0fd8f6SDimitry Andric llvm::make_unique<StreamingMemoryObject>(std::move(Streamer)); 537039d628a0SDimitry Andric StreamingMemoryObject &Bytes = *OwnedBytes; 537139d628a0SDimitry Andric StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 537239d628a0SDimitry Andric Stream.init(&*StreamFile); 5373dff0c46cSDimitry Andric 5374dff0c46cSDimitry Andric unsigned char buf[16]; 537539d628a0SDimitry Andric if (Bytes.readBytes(buf, 16, 0) != 16) 53768f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 5377dff0c46cSDimitry Andric 5378dff0c46cSDimitry Andric if (!isBitcode(buf, buf + 16)) 53798f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 5380dff0c46cSDimitry Andric 5381dff0c46cSDimitry Andric if (isBitcodeWrapper(buf, buf + 4)) { 5382dff0c46cSDimitry Andric const unsigned char *bitcodeStart = buf; 5383dff0c46cSDimitry Andric const unsigned char *bitcodeEnd = buf + 16; 5384dff0c46cSDimitry Andric SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 538539d628a0SDimitry Andric Bytes.dropLeadingBytes(bitcodeStart - buf); 538639d628a0SDimitry Andric Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 5387dff0c46cSDimitry Andric } 538891bc56edSDimitry Andric return std::error_code(); 5389f785676fSDimitry Andric } 5390f785676fSDimitry Andric 53917d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::error(BitcodeError E, 53927d523365SDimitry Andric const Twine &Message) { 53937d523365SDimitry Andric return ::error(DiagnosticHandler, make_error_code(E), Message); 53947d523365SDimitry Andric } 53957d523365SDimitry Andric 53967d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) { 53977d523365SDimitry Andric return ::error(DiagnosticHandler, 53987d523365SDimitry Andric make_error_code(BitcodeError::CorruptedBitcode), Message); 53997d523365SDimitry Andric } 54007d523365SDimitry Andric 54017d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) { 54027d523365SDimitry Andric return ::error(DiagnosticHandler, make_error_code(E)); 54037d523365SDimitry Andric } 54047d523365SDimitry Andric 54057d523365SDimitry Andric FunctionIndexBitcodeReader::FunctionIndexBitcodeReader( 54067d523365SDimitry Andric MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler, 54077d523365SDimitry Andric bool IsLazy, bool CheckFuncSummaryPresenceOnly) 54087d523365SDimitry Andric : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy), 54097d523365SDimitry Andric CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {} 54107d523365SDimitry Andric 54117d523365SDimitry Andric FunctionIndexBitcodeReader::FunctionIndexBitcodeReader( 54127d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy, 54137d523365SDimitry Andric bool CheckFuncSummaryPresenceOnly) 54147d523365SDimitry Andric : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy), 54157d523365SDimitry Andric CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {} 54167d523365SDimitry Andric 54177d523365SDimitry Andric void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; } 54187d523365SDimitry Andric 54197d523365SDimitry Andric void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); } 54207d523365SDimitry Andric 54217d523365SDimitry Andric // Specialized value symbol table parser used when reading function index 54227d523365SDimitry Andric // blocks where we don't actually create global values. 54237d523365SDimitry Andric // At the end of this routine the function index is populated with a map 54247d523365SDimitry Andric // from function name to FunctionInfo. The function info contains 54257d523365SDimitry Andric // the function block's bitcode offset as well as the offset into the 54267d523365SDimitry Andric // function summary section. 54277d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() { 54287d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 54297d523365SDimitry Andric return error("Invalid record"); 54307d523365SDimitry Andric 54317d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 54327d523365SDimitry Andric 54337d523365SDimitry Andric // Read all the records for this value table. 54347d523365SDimitry Andric SmallString<128> ValueName; 54357d523365SDimitry Andric while (1) { 54367d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 54377d523365SDimitry Andric 54387d523365SDimitry Andric switch (Entry.Kind) { 54397d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 54407d523365SDimitry Andric case BitstreamEntry::Error: 54417d523365SDimitry Andric return error("Malformed block"); 54427d523365SDimitry Andric case BitstreamEntry::EndBlock: 54437d523365SDimitry Andric return std::error_code(); 54447d523365SDimitry Andric case BitstreamEntry::Record: 54457d523365SDimitry Andric // The interesting case. 54467d523365SDimitry Andric break; 54477d523365SDimitry Andric } 54487d523365SDimitry Andric 54497d523365SDimitry Andric // Read a record. 54507d523365SDimitry Andric Record.clear(); 54517d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 54527d523365SDimitry Andric default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 54537d523365SDimitry Andric break; 54547d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 54557d523365SDimitry Andric // VST_FNENTRY: [valueid, offset, namechar x N] 54567d523365SDimitry Andric if (convertToString(Record, 2, ValueName)) 54577d523365SDimitry Andric return error("Invalid record"); 54587d523365SDimitry Andric unsigned ValueID = Record[0]; 54597d523365SDimitry Andric uint64_t FuncOffset = Record[1]; 54607d523365SDimitry Andric std::unique_ptr<FunctionInfo> FuncInfo = 54617d523365SDimitry Andric llvm::make_unique<FunctionInfo>(FuncOffset); 54627d523365SDimitry Andric if (foundFuncSummary() && !IsLazy) { 54637d523365SDimitry Andric DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI = 54647d523365SDimitry Andric SummaryMap.find(ValueID); 54657d523365SDimitry Andric assert(SMI != SummaryMap.end() && "Summary info not found"); 54667d523365SDimitry Andric FuncInfo->setFunctionSummary(std::move(SMI->second)); 54677d523365SDimitry Andric } 54687d523365SDimitry Andric TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo)); 54697d523365SDimitry Andric 54707d523365SDimitry Andric ValueName.clear(); 54717d523365SDimitry Andric break; 54727d523365SDimitry Andric } 54737d523365SDimitry Andric case bitc::VST_CODE_COMBINED_FNENTRY: { 54747d523365SDimitry Andric // VST_FNENTRY: [offset, namechar x N] 54757d523365SDimitry Andric if (convertToString(Record, 1, ValueName)) 54767d523365SDimitry Andric return error("Invalid record"); 54777d523365SDimitry Andric uint64_t FuncSummaryOffset = Record[0]; 54787d523365SDimitry Andric std::unique_ptr<FunctionInfo> FuncInfo = 54797d523365SDimitry Andric llvm::make_unique<FunctionInfo>(FuncSummaryOffset); 54807d523365SDimitry Andric if (foundFuncSummary() && !IsLazy) { 54817d523365SDimitry Andric DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI = 54827d523365SDimitry Andric SummaryMap.find(FuncSummaryOffset); 54837d523365SDimitry Andric assert(SMI != SummaryMap.end() && "Summary info not found"); 54847d523365SDimitry Andric FuncInfo->setFunctionSummary(std::move(SMI->second)); 54857d523365SDimitry Andric } 54867d523365SDimitry Andric TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo)); 54877d523365SDimitry Andric 54887d523365SDimitry Andric ValueName.clear(); 54897d523365SDimitry Andric break; 54907d523365SDimitry Andric } 54917d523365SDimitry Andric } 54927d523365SDimitry Andric } 54937d523365SDimitry Andric } 54947d523365SDimitry Andric 54957d523365SDimitry Andric // Parse just the blocks needed for function index building out of the module. 54967d523365SDimitry Andric // At the end of this routine the function Index is populated with a map 54977d523365SDimitry Andric // from function name to FunctionInfo. The function info contains 54987d523365SDimitry Andric // either the parsed function summary information (when parsing summaries 54997d523365SDimitry Andric // eagerly), or just to the function summary record's offset 55007d523365SDimitry Andric // if parsing lazily (IsLazy). 55017d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseModule() { 55027d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 55037d523365SDimitry Andric return error("Invalid record"); 55047d523365SDimitry Andric 55057d523365SDimitry Andric // Read the function index for this module. 55067d523365SDimitry Andric while (1) { 55077d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 55087d523365SDimitry Andric 55097d523365SDimitry Andric switch (Entry.Kind) { 55107d523365SDimitry Andric case BitstreamEntry::Error: 55117d523365SDimitry Andric return error("Malformed block"); 55127d523365SDimitry Andric case BitstreamEntry::EndBlock: 55137d523365SDimitry Andric return std::error_code(); 55147d523365SDimitry Andric 55157d523365SDimitry Andric case BitstreamEntry::SubBlock: 55167d523365SDimitry Andric if (CheckFuncSummaryPresenceOnly) { 55177d523365SDimitry Andric if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID) { 55187d523365SDimitry Andric SeenFuncSummary = true; 55197d523365SDimitry Andric // No need to parse the rest since we found the summary. 55207d523365SDimitry Andric return std::error_code(); 55217d523365SDimitry Andric } 55227d523365SDimitry Andric if (Stream.SkipBlock()) 55237d523365SDimitry Andric return error("Invalid record"); 55247d523365SDimitry Andric continue; 55257d523365SDimitry Andric } 55267d523365SDimitry Andric switch (Entry.ID) { 55277d523365SDimitry Andric default: // Skip unknown content. 55287d523365SDimitry Andric if (Stream.SkipBlock()) 55297d523365SDimitry Andric return error("Invalid record"); 55307d523365SDimitry Andric break; 55317d523365SDimitry Andric case bitc::BLOCKINFO_BLOCK_ID: 55327d523365SDimitry Andric // Need to parse these to get abbrev ids (e.g. for VST) 55337d523365SDimitry Andric if (Stream.ReadBlockInfoBlock()) 55347d523365SDimitry Andric return error("Malformed block"); 55357d523365SDimitry Andric break; 55367d523365SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID: 55377d523365SDimitry Andric if (std::error_code EC = parseValueSymbolTable()) 55387d523365SDimitry Andric return EC; 55397d523365SDimitry Andric break; 55407d523365SDimitry Andric case bitc::FUNCTION_SUMMARY_BLOCK_ID: 55417d523365SDimitry Andric SeenFuncSummary = true; 55427d523365SDimitry Andric if (IsLazy) { 55437d523365SDimitry Andric // Lazy parsing of summary info, skip it. 55447d523365SDimitry Andric if (Stream.SkipBlock()) 55457d523365SDimitry Andric return error("Invalid record"); 55467d523365SDimitry Andric } else if (std::error_code EC = parseEntireSummary()) 55477d523365SDimitry Andric return EC; 55487d523365SDimitry Andric break; 55497d523365SDimitry Andric case bitc::MODULE_STRTAB_BLOCK_ID: 55507d523365SDimitry Andric if (std::error_code EC = parseModuleStringTable()) 55517d523365SDimitry Andric return EC; 55527d523365SDimitry Andric break; 55537d523365SDimitry Andric } 55547d523365SDimitry Andric continue; 55557d523365SDimitry Andric 55567d523365SDimitry Andric case BitstreamEntry::Record: 55577d523365SDimitry Andric Stream.skipRecord(Entry.ID); 55587d523365SDimitry Andric continue; 55597d523365SDimitry Andric } 55607d523365SDimitry Andric } 55617d523365SDimitry Andric } 55627d523365SDimitry Andric 55637d523365SDimitry Andric // Eagerly parse the entire function summary block (i.e. for all functions 55647d523365SDimitry Andric // in the index). This populates the FunctionSummary objects in 55657d523365SDimitry Andric // the index. 55667d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseEntireSummary() { 55677d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID)) 55687d523365SDimitry Andric return error("Invalid record"); 55697d523365SDimitry Andric 55707d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 55717d523365SDimitry Andric 55727d523365SDimitry Andric while (1) { 55737d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 55747d523365SDimitry Andric 55757d523365SDimitry Andric switch (Entry.Kind) { 55767d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 55777d523365SDimitry Andric case BitstreamEntry::Error: 55787d523365SDimitry Andric return error("Malformed block"); 55797d523365SDimitry Andric case BitstreamEntry::EndBlock: 55807d523365SDimitry Andric return std::error_code(); 55817d523365SDimitry Andric case BitstreamEntry::Record: 55827d523365SDimitry Andric // The interesting case. 55837d523365SDimitry Andric break; 55847d523365SDimitry Andric } 55857d523365SDimitry Andric 55867d523365SDimitry Andric // Read a record. The record format depends on whether this 55877d523365SDimitry Andric // is a per-module index or a combined index file. In the per-module 55887d523365SDimitry Andric // case the records contain the associated value's ID for correlation 55897d523365SDimitry Andric // with VST entries. In the combined index the correlation is done 55907d523365SDimitry Andric // via the bitcode offset of the summary records (which were saved 55917d523365SDimitry Andric // in the combined index VST entries). The records also contain 55927d523365SDimitry Andric // information used for ThinLTO renaming and importing. 55937d523365SDimitry Andric Record.clear(); 55947d523365SDimitry Andric uint64_t CurRecordBit = Stream.GetCurrentBitNo(); 55957d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 55967d523365SDimitry Andric default: // Default behavior: ignore. 55977d523365SDimitry Andric break; 55987d523365SDimitry Andric // FS_PERMODULE_ENTRY: [valueid, islocal, instcount] 55997d523365SDimitry Andric case bitc::FS_CODE_PERMODULE_ENTRY: { 56007d523365SDimitry Andric unsigned ValueID = Record[0]; 56017d523365SDimitry Andric bool IsLocal = Record[1]; 56027d523365SDimitry Andric unsigned InstCount = Record[2]; 56037d523365SDimitry Andric std::unique_ptr<FunctionSummary> FS = 56047d523365SDimitry Andric llvm::make_unique<FunctionSummary>(InstCount); 56057d523365SDimitry Andric FS->setLocalFunction(IsLocal); 56067d523365SDimitry Andric // The module path string ref set in the summary must be owned by the 56077d523365SDimitry Andric // index's module string table. Since we don't have a module path 56087d523365SDimitry Andric // string table section in the per-module index, we create a single 56097d523365SDimitry Andric // module path string table entry with an empty (0) ID to take 56107d523365SDimitry Andric // ownership. 56117d523365SDimitry Andric FS->setModulePath( 56127d523365SDimitry Andric TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)); 56137d523365SDimitry Andric SummaryMap[ValueID] = std::move(FS); 56147d523365SDimitry Andric } 56157d523365SDimitry Andric // FS_COMBINED_ENTRY: [modid, instcount] 56167d523365SDimitry Andric case bitc::FS_CODE_COMBINED_ENTRY: { 56177d523365SDimitry Andric uint64_t ModuleId = Record[0]; 56187d523365SDimitry Andric unsigned InstCount = Record[1]; 56197d523365SDimitry Andric std::unique_ptr<FunctionSummary> FS = 56207d523365SDimitry Andric llvm::make_unique<FunctionSummary>(InstCount); 56217d523365SDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 56227d523365SDimitry Andric SummaryMap[CurRecordBit] = std::move(FS); 56237d523365SDimitry Andric } 56247d523365SDimitry Andric } 56257d523365SDimitry Andric } 56267d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 56277d523365SDimitry Andric } 56287d523365SDimitry Andric 56297d523365SDimitry Andric // Parse the module string table block into the Index. 56307d523365SDimitry Andric // This populates the ModulePathStringTable map in the index. 56317d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() { 56327d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 56337d523365SDimitry Andric return error("Invalid record"); 56347d523365SDimitry Andric 56357d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 56367d523365SDimitry Andric 56377d523365SDimitry Andric SmallString<128> ModulePath; 56387d523365SDimitry Andric while (1) { 56397d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 56407d523365SDimitry Andric 56417d523365SDimitry Andric switch (Entry.Kind) { 56427d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 56437d523365SDimitry Andric case BitstreamEntry::Error: 56447d523365SDimitry Andric return error("Malformed block"); 56457d523365SDimitry Andric case BitstreamEntry::EndBlock: 56467d523365SDimitry Andric return std::error_code(); 56477d523365SDimitry Andric case BitstreamEntry::Record: 56487d523365SDimitry Andric // The interesting case. 56497d523365SDimitry Andric break; 56507d523365SDimitry Andric } 56517d523365SDimitry Andric 56527d523365SDimitry Andric Record.clear(); 56537d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 56547d523365SDimitry Andric default: // Default behavior: ignore. 56557d523365SDimitry Andric break; 56567d523365SDimitry Andric case bitc::MST_CODE_ENTRY: { 56577d523365SDimitry Andric // MST_ENTRY: [modid, namechar x N] 56587d523365SDimitry Andric if (convertToString(Record, 1, ModulePath)) 56597d523365SDimitry Andric return error("Invalid record"); 56607d523365SDimitry Andric uint64_t ModuleId = Record[0]; 56617d523365SDimitry Andric StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId); 56627d523365SDimitry Andric ModuleIdMap[ModuleId] = ModulePathInMap; 56637d523365SDimitry Andric ModulePath.clear(); 56647d523365SDimitry Andric break; 56657d523365SDimitry Andric } 56667d523365SDimitry Andric } 56677d523365SDimitry Andric } 56687d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 56697d523365SDimitry Andric } 56707d523365SDimitry Andric 56717d523365SDimitry Andric // Parse the function info index from the bitcode streamer into the given index. 56727d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto( 56737d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) { 56747d523365SDimitry Andric TheIndex = I; 56757d523365SDimitry Andric 56767d523365SDimitry Andric if (std::error_code EC = initStream(std::move(Streamer))) 56777d523365SDimitry Andric return EC; 56787d523365SDimitry Andric 56797d523365SDimitry Andric // Sniff for the signature. 56807d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 56817d523365SDimitry Andric return error("Invalid bitcode signature"); 56827d523365SDimitry Andric 56837d523365SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 56847d523365SDimitry Andric // need to understand them all. 56857d523365SDimitry Andric while (1) { 56867d523365SDimitry Andric if (Stream.AtEndOfStream()) { 56877d523365SDimitry Andric // We didn't really read a proper Module block. 56887d523365SDimitry Andric return error("Malformed block"); 56897d523365SDimitry Andric } 56907d523365SDimitry Andric 56917d523365SDimitry Andric BitstreamEntry Entry = 56927d523365SDimitry Andric Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 56937d523365SDimitry Andric 56947d523365SDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock) 56957d523365SDimitry Andric return error("Malformed block"); 56967d523365SDimitry Andric 56977d523365SDimitry Andric // If we see a MODULE_BLOCK, parse it to find the blocks needed for 56987d523365SDimitry Andric // building the function summary index. 56997d523365SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 57007d523365SDimitry Andric return parseModule(); 57017d523365SDimitry Andric 57027d523365SDimitry Andric if (Stream.SkipBlock()) 57037d523365SDimitry Andric return error("Invalid record"); 57047d523365SDimitry Andric } 57057d523365SDimitry Andric } 57067d523365SDimitry Andric 57077d523365SDimitry Andric // Parse the function information at the given offset in the buffer into 57087d523365SDimitry Andric // the index. Used to support lazy parsing of function summaries from the 57097d523365SDimitry Andric // combined index during importing. 57107d523365SDimitry Andric // TODO: This function is not yet complete as it won't have a consumer 57117d523365SDimitry Andric // until ThinLTO function importing is added. 57127d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseFunctionSummary( 57137d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I, 57147d523365SDimitry Andric size_t FunctionSummaryOffset) { 57157d523365SDimitry Andric TheIndex = I; 57167d523365SDimitry Andric 57177d523365SDimitry Andric if (std::error_code EC = initStream(std::move(Streamer))) 57187d523365SDimitry Andric return EC; 57197d523365SDimitry Andric 57207d523365SDimitry Andric // Sniff for the signature. 57217d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 57227d523365SDimitry Andric return error("Invalid bitcode signature"); 57237d523365SDimitry Andric 57247d523365SDimitry Andric Stream.JumpToBit(FunctionSummaryOffset); 57257d523365SDimitry Andric 57267d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 57277d523365SDimitry Andric 57287d523365SDimitry Andric switch (Entry.Kind) { 57297d523365SDimitry Andric default: 57307d523365SDimitry Andric return error("Malformed block"); 57317d523365SDimitry Andric case BitstreamEntry::Record: 57327d523365SDimitry Andric // The expected case. 57337d523365SDimitry Andric break; 57347d523365SDimitry Andric } 57357d523365SDimitry Andric 57367d523365SDimitry Andric // TODO: Read a record. This interface will be completed when ThinLTO 57377d523365SDimitry Andric // importing is added so that it can be tested. 57387d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 57397d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 57407d523365SDimitry Andric case bitc::FS_CODE_COMBINED_ENTRY: 57417d523365SDimitry Andric default: 57427d523365SDimitry Andric return error("Invalid record"); 57437d523365SDimitry Andric } 57447d523365SDimitry Andric 57457d523365SDimitry Andric return std::error_code(); 57467d523365SDimitry Andric } 57477d523365SDimitry Andric 57487d523365SDimitry Andric std::error_code 57497d523365SDimitry Andric FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) { 57507d523365SDimitry Andric if (Streamer) 57517d523365SDimitry Andric return initLazyStream(std::move(Streamer)); 57527d523365SDimitry Andric return initStreamFromBuffer(); 57537d523365SDimitry Andric } 57547d523365SDimitry Andric 57557d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() { 57567d523365SDimitry Andric const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart(); 57577d523365SDimitry Andric const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize(); 57587d523365SDimitry Andric 57597d523365SDimitry Andric if (Buffer->getBufferSize() & 3) 57607d523365SDimitry Andric return error("Invalid bitcode signature"); 57617d523365SDimitry Andric 57627d523365SDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents. 57637d523365SDimitry Andric // The magic number is 0x0B17C0DE stored in little endian. 57647d523365SDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd)) 57657d523365SDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 57667d523365SDimitry Andric return error("Invalid bitcode wrapper header"); 57677d523365SDimitry Andric 57687d523365SDimitry Andric StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 57697d523365SDimitry Andric Stream.init(&*StreamFile); 57707d523365SDimitry Andric 57717d523365SDimitry Andric return std::error_code(); 57727d523365SDimitry Andric } 57737d523365SDimitry Andric 57747d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::initLazyStream( 57757d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer) { 57767d523365SDimitry Andric // Check and strip off the bitcode wrapper; BitstreamReader expects never to 57777d523365SDimitry Andric // see it. 57787d523365SDimitry Andric auto OwnedBytes = 57797d523365SDimitry Andric llvm::make_unique<StreamingMemoryObject>(std::move(Streamer)); 57807d523365SDimitry Andric StreamingMemoryObject &Bytes = *OwnedBytes; 57817d523365SDimitry Andric StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 57827d523365SDimitry Andric Stream.init(&*StreamFile); 57837d523365SDimitry Andric 57847d523365SDimitry Andric unsigned char buf[16]; 57857d523365SDimitry Andric if (Bytes.readBytes(buf, 16, 0) != 16) 57867d523365SDimitry Andric return error("Invalid bitcode signature"); 57877d523365SDimitry Andric 57887d523365SDimitry Andric if (!isBitcode(buf, buf + 16)) 57897d523365SDimitry Andric return error("Invalid bitcode signature"); 57907d523365SDimitry Andric 57917d523365SDimitry Andric if (isBitcodeWrapper(buf, buf + 4)) { 57927d523365SDimitry Andric const unsigned char *bitcodeStart = buf; 57937d523365SDimitry Andric const unsigned char *bitcodeEnd = buf + 16; 57947d523365SDimitry Andric SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 57957d523365SDimitry Andric Bytes.dropLeadingBytes(bitcodeStart - buf); 57967d523365SDimitry Andric Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 57977d523365SDimitry Andric } 57987d523365SDimitry Andric return std::error_code(); 57997d523365SDimitry Andric } 58007d523365SDimitry Andric 5801f785676fSDimitry Andric namespace { 580291bc56edSDimitry Andric class BitcodeErrorCategoryType : public std::error_category { 580391bc56edSDimitry Andric const char *name() const LLVM_NOEXCEPT override { 5804f785676fSDimitry Andric return "llvm.bitcode"; 5805f785676fSDimitry Andric } 580691bc56edSDimitry Andric std::string message(int IE) const override { 580739d628a0SDimitry Andric BitcodeError E = static_cast<BitcodeError>(IE); 5808f785676fSDimitry Andric switch (E) { 580939d628a0SDimitry Andric case BitcodeError::InvalidBitcodeSignature: 5810f785676fSDimitry Andric return "Invalid bitcode signature"; 581139d628a0SDimitry Andric case BitcodeError::CorruptedBitcode: 581239d628a0SDimitry Andric return "Corrupted bitcode"; 5813f785676fSDimitry Andric } 5814f785676fSDimitry Andric llvm_unreachable("Unknown error type!"); 5815f785676fSDimitry Andric } 5816f785676fSDimitry Andric }; 58173dac3a9bSDimitry Andric } 5818f785676fSDimitry Andric 581939d628a0SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 582039d628a0SDimitry Andric 582139d628a0SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() { 582239d628a0SDimitry Andric return *ErrorCategory; 5823dff0c46cSDimitry Andric } 5824f22ef01cSRoman Divacky 5825f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5826f22ef01cSRoman Divacky // External interface 5827f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5828f22ef01cSRoman Divacky 58298f0fd8f6SDimitry Andric static ErrorOr<std::unique_ptr<Module>> 58308f0fd8f6SDimitry Andric getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name, 58318f0fd8f6SDimitry Andric BitcodeReader *R, LLVMContext &Context, 58328f0fd8f6SDimitry Andric bool MaterializeAll, bool ShouldLazyLoadMetadata) { 58338f0fd8f6SDimitry Andric std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 58348f0fd8f6SDimitry Andric M->setMaterializer(R); 58358f0fd8f6SDimitry Andric 58368f0fd8f6SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 58378f0fd8f6SDimitry Andric R->releaseBuffer(); // Never take ownership on error. 58388f0fd8f6SDimitry Andric return EC; 58398f0fd8f6SDimitry Andric }; 58408f0fd8f6SDimitry Andric 58418f0fd8f6SDimitry Andric // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 58428f0fd8f6SDimitry Andric if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(), 58438f0fd8f6SDimitry Andric ShouldLazyLoadMetadata)) 58448f0fd8f6SDimitry Andric return cleanupOnError(EC); 58458f0fd8f6SDimitry Andric 58468f0fd8f6SDimitry Andric if (MaterializeAll) { 58478f0fd8f6SDimitry Andric // Read in the entire module, and destroy the BitcodeReader. 58487d523365SDimitry Andric if (std::error_code EC = M->materializeAll()) 58498f0fd8f6SDimitry Andric return cleanupOnError(EC); 58508f0fd8f6SDimitry Andric } else { 58518f0fd8f6SDimitry Andric // Resolve forward references from blockaddresses. 58528f0fd8f6SDimitry Andric if (std::error_code EC = R->materializeForwardReferencedFunctions()) 58538f0fd8f6SDimitry Andric return cleanupOnError(EC); 58548f0fd8f6SDimitry Andric } 58558f0fd8f6SDimitry Andric return std::move(M); 58568f0fd8f6SDimitry Andric } 58578f0fd8f6SDimitry Andric 585839d628a0SDimitry Andric /// \brief Get a lazy one-at-time loading module from bitcode. 5859f22ef01cSRoman Divacky /// 586039d628a0SDimitry Andric /// This isn't always used in a lazy context. In particular, it's also used by 586139d628a0SDimitry Andric /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull 586239d628a0SDimitry Andric /// in forward-referenced functions from block address references. 586339d628a0SDimitry Andric /// 58648f0fd8f6SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize 58658f0fd8f6SDimitry Andric /// everything. 58668f0fd8f6SDimitry Andric static ErrorOr<std::unique_ptr<Module>> 586739d628a0SDimitry Andric getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer, 58688f0fd8f6SDimitry Andric LLVMContext &Context, bool MaterializeAll, 5869ff0cc061SDimitry Andric bool ShouldLazyLoadMetadata = false) { 58707d523365SDimitry Andric BitcodeReader *R = new BitcodeReader(Buffer.get(), Context); 587139d628a0SDimitry Andric 58728f0fd8f6SDimitry Andric ErrorOr<std::unique_ptr<Module>> Ret = 58738f0fd8f6SDimitry Andric getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context, 58748f0fd8f6SDimitry Andric MaterializeAll, ShouldLazyLoadMetadata); 58758f0fd8f6SDimitry Andric if (!Ret) 58768f0fd8f6SDimitry Andric return Ret; 587739d628a0SDimitry Andric 587839d628a0SDimitry Andric Buffer.release(); // The BitcodeReader owns it now. 58798f0fd8f6SDimitry Andric return Ret; 5880dff0c46cSDimitry Andric } 5881dff0c46cSDimitry Andric 58827d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>> 58837d523365SDimitry Andric llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 58847d523365SDimitry Andric LLVMContext &Context, bool ShouldLazyLoadMetadata) { 588539d628a0SDimitry Andric return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false, 58867d523365SDimitry Andric ShouldLazyLoadMetadata); 5887f22ef01cSRoman Divacky } 5888f22ef01cSRoman Divacky 58897d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>> 58907d523365SDimitry Andric llvm::getStreamedBitcodeModule(StringRef Name, 58917d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer, 58927d523365SDimitry Andric LLVMContext &Context) { 589339d628a0SDimitry Andric std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 58947d523365SDimitry Andric BitcodeReader *R = new BitcodeReader(Context); 58958f0fd8f6SDimitry Andric 58968f0fd8f6SDimitry Andric return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false, 58978f0fd8f6SDimitry Andric false); 589839d628a0SDimitry Andric } 589939d628a0SDimitry Andric 59007d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 59017d523365SDimitry Andric LLVMContext &Context) { 590239d628a0SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59037d523365SDimitry Andric return getLazyBitcodeModuleImpl(std::move(Buf), Context, true); 5904dff0c46cSDimitry Andric // TODO: Restore the use-lists to the in-memory state when the bitcode was 5905dff0c46cSDimitry Andric // written. We must defer until the Module has been fully materialized. 5906f22ef01cSRoman Divacky } 59072754fe60SDimitry Andric 59087d523365SDimitry Andric std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, 59097d523365SDimitry Andric LLVMContext &Context) { 591039d628a0SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59117d523365SDimitry Andric auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context); 591291bc56edSDimitry Andric ErrorOr<std::string> Triple = R->parseTriple(); 591391bc56edSDimitry Andric if (Triple.getError()) 591491bc56edSDimitry Andric return ""; 591591bc56edSDimitry Andric return Triple.get(); 59162754fe60SDimitry Andric } 59177d523365SDimitry Andric 59187d523365SDimitry Andric std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer, 59197d523365SDimitry Andric LLVMContext &Context) { 59207d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59217d523365SDimitry Andric BitcodeReader R(Buf.release(), Context); 59227d523365SDimitry Andric ErrorOr<std::string> ProducerString = R.parseIdentificationBlock(); 59237d523365SDimitry Andric if (ProducerString.getError()) 59247d523365SDimitry Andric return ""; 59257d523365SDimitry Andric return ProducerString.get(); 59267d523365SDimitry Andric } 59277d523365SDimitry Andric 59287d523365SDimitry Andric // Parse the specified bitcode buffer, returning the function info index. 59297d523365SDimitry Andric // If IsLazy is false, parse the entire function summary into 59307d523365SDimitry Andric // the index. Otherwise skip the function summary section, and only create 59317d523365SDimitry Andric // an index object with a map from function name to function summary offset. 59327d523365SDimitry Andric // The index is used to perform lazy function summary reading later. 59337d523365SDimitry Andric ErrorOr<std::unique_ptr<FunctionInfoIndex>> 59347d523365SDimitry Andric llvm::getFunctionInfoIndex(MemoryBufferRef Buffer, 59357d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler, 59367d523365SDimitry Andric bool IsLazy) { 59377d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59387d523365SDimitry Andric FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy); 59397d523365SDimitry Andric 59407d523365SDimitry Andric auto Index = llvm::make_unique<FunctionInfoIndex>(); 59417d523365SDimitry Andric 59427d523365SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 59437d523365SDimitry Andric R.releaseBuffer(); // Never take ownership on error. 59447d523365SDimitry Andric return EC; 59457d523365SDimitry Andric }; 59467d523365SDimitry Andric 59477d523365SDimitry Andric if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get())) 59487d523365SDimitry Andric return cleanupOnError(EC); 59497d523365SDimitry Andric 59507d523365SDimitry Andric Buf.release(); // The FunctionIndexBitcodeReader owns it now. 59517d523365SDimitry Andric return std::move(Index); 59527d523365SDimitry Andric } 59537d523365SDimitry Andric 59547d523365SDimitry Andric // Check if the given bitcode buffer contains a function summary block. 59557d523365SDimitry Andric bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, 59567d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler) { 59577d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59587d523365SDimitry Andric FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true); 59597d523365SDimitry Andric 59607d523365SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 59617d523365SDimitry Andric R.releaseBuffer(); // Never take ownership on error. 59627d523365SDimitry Andric return false; 59637d523365SDimitry Andric }; 59647d523365SDimitry Andric 59657d523365SDimitry Andric if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr)) 59667d523365SDimitry Andric return cleanupOnError(EC); 59677d523365SDimitry Andric 59687d523365SDimitry Andric Buf.release(); // The FunctionIndexBitcodeReader owns it now. 59697d523365SDimitry Andric return R.foundFuncSummary(); 59707d523365SDimitry Andric } 59717d523365SDimitry Andric 59727d523365SDimitry Andric // This method supports lazy reading of function summary data from the combined 59737d523365SDimitry Andric // index during ThinLTO function importing. When reading the combined index 59747d523365SDimitry Andric // file, getFunctionInfoIndex is first invoked with IsLazy=true. 59757d523365SDimitry Andric // Then this method is called for each function considered for importing, 59767d523365SDimitry Andric // to parse the summary information for the given function name into 59777d523365SDimitry Andric // the index. 59787d523365SDimitry Andric std::error_code llvm::readFunctionSummary( 59797d523365SDimitry Andric MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler, 59807d523365SDimitry Andric StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) { 59817d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59827d523365SDimitry Andric FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler); 59837d523365SDimitry Andric 59847d523365SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 59857d523365SDimitry Andric R.releaseBuffer(); // Never take ownership on error. 59867d523365SDimitry Andric return EC; 59877d523365SDimitry Andric }; 59887d523365SDimitry Andric 59897d523365SDimitry Andric // Lookup the given function name in the FunctionMap, which may 59907d523365SDimitry Andric // contain a list of function infos in the case of a COMDAT. Walk through 59917d523365SDimitry Andric // and parse each function summary info at the function summary offset 59927d523365SDimitry Andric // recorded when parsing the value symbol table. 59937d523365SDimitry Andric for (const auto &FI : Index->getFunctionInfoList(FunctionName)) { 59947d523365SDimitry Andric size_t FunctionSummaryOffset = FI->bitcodeIndex(); 59957d523365SDimitry Andric if (std::error_code EC = 59967d523365SDimitry Andric R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset)) 59977d523365SDimitry Andric return cleanupOnError(EC); 59987d523365SDimitry Andric } 59997d523365SDimitry Andric 60007d523365SDimitry Andric Buf.release(); // The FunctionIndexBitcodeReader owns it now. 60017d523365SDimitry Andric return std::error_code(); 60027d523365SDimitry Andric } 6003