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); 30747d523365SDimitry Andric // Save all values if !OnlyTempMD, otherwise just the temporary metadata. 30757d523365SDimitry Andric if (!OnlyTempMD || (N && N->isTemporary())) { 30767d523365SDimitry Andric // Will call this after materializing each function, in order to 30777d523365SDimitry Andric // handle remapping of the function's instructions/metadata. 30787d523365SDimitry Andric // See if we already have an entry in that case. 30797d523365SDimitry Andric if (OnlyTempMD && MetadataToIDs.count(MD)) { 30807d523365SDimitry Andric assert(MetadataToIDs[MD] == ID && "Inconsistent metadata value id"); 30817d523365SDimitry Andric continue; 30827d523365SDimitry Andric } 30837d523365SDimitry Andric MetadataToIDs[MD] = ID; 30847d523365SDimitry Andric } 30857d523365SDimitry Andric } 30867d523365SDimitry Andric } 30877d523365SDimitry Andric 30888f0fd8f6SDimitry Andric /// When we see the block for a function body, remember where it is and then 30898f0fd8f6SDimitry Andric /// skip it. This lets us lazily deserialize the functions. 30908f0fd8f6SDimitry Andric std::error_code BitcodeReader::rememberAndSkipFunctionBody() { 3091f22ef01cSRoman Divacky // Get the function we are talking about. 3092f22ef01cSRoman Divacky if (FunctionsWithBodies.empty()) 30938f0fd8f6SDimitry Andric return error("Insufficient function protos"); 3094f22ef01cSRoman Divacky 3095f22ef01cSRoman Divacky Function *Fn = FunctionsWithBodies.back(); 3096f22ef01cSRoman Divacky FunctionsWithBodies.pop_back(); 3097f22ef01cSRoman Divacky 3098f22ef01cSRoman Divacky // Save the current stream state. 3099f22ef01cSRoman Divacky uint64_t CurBit = Stream.GetCurrentBitNo(); 31007d523365SDimitry Andric assert( 31017d523365SDimitry Andric (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 31027d523365SDimitry Andric "Mismatch between VST and scanned function offsets"); 3103f22ef01cSRoman Divacky DeferredFunctionInfo[Fn] = CurBit; 3104f22ef01cSRoman Divacky 3105f22ef01cSRoman Divacky // Skip over the function block for now. 3106f22ef01cSRoman Divacky if (Stream.SkipBlock()) 31078f0fd8f6SDimitry Andric return error("Invalid record"); 310891bc56edSDimitry Andric return std::error_code(); 3109f22ef01cSRoman Divacky } 3110f22ef01cSRoman Divacky 31118f0fd8f6SDimitry Andric std::error_code BitcodeReader::globalCleanup() { 3112f22ef01cSRoman Divacky // Patch the initializers for globals and aliases up. 31138f0fd8f6SDimitry Andric resolveGlobalAndAliasInits(); 3114f22ef01cSRoman Divacky if (!GlobalInits.empty() || !AliasInits.empty()) 31158f0fd8f6SDimitry Andric return error("Malformed global initializer set"); 3116f22ef01cSRoman Divacky 3117f22ef01cSRoman Divacky // Look for intrinsic functions which need to be upgraded at some point 31188f0fd8f6SDimitry Andric for (Function &F : *TheModule) { 3119f22ef01cSRoman Divacky Function *NewFn; 31208f0fd8f6SDimitry Andric if (UpgradeIntrinsicFunction(&F, NewFn)) 31213dac3a9bSDimitry Andric UpgradedIntrinsics[&F] = NewFn; 3122f22ef01cSRoman Divacky } 3123f22ef01cSRoman Divacky 3124e580952dSDimitry Andric // Look for global variables which need to be renamed. 31258f0fd8f6SDimitry Andric for (GlobalVariable &GV : TheModule->globals()) 31268f0fd8f6SDimitry Andric UpgradeGlobalVariable(&GV); 312791bc56edSDimitry Andric 3128f22ef01cSRoman Divacky // Force deallocation of memory for these vectors to favor the client that 3129f22ef01cSRoman Divacky // want lazy deserialization. 3130f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 3131f22ef01cSRoman Divacky std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 313291bc56edSDimitry Andric return std::error_code(); 3133f22ef01cSRoman Divacky } 3134f22ef01cSRoman Divacky 31357d523365SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we 31367d523365SDimitry Andric /// either have an old bitcode file without a VST forward declaration record, 31377d523365SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous 31387d523365SDimitry Andric /// functions do not have a name and are therefore not in the VST. 31397d523365SDimitry Andric std::error_code BitcodeReader::rememberAndSkipFunctionBodies() { 3140dff0c46cSDimitry Andric Stream.JumpToBit(NextUnreadBit); 31417d523365SDimitry Andric 31427d523365SDimitry Andric if (Stream.AtEndOfStream()) 31437d523365SDimitry Andric return error("Could not find function in stream"); 31447d523365SDimitry Andric 31457d523365SDimitry Andric if (!SeenFirstFunctionBody) 31467d523365SDimitry Andric return error("Trying to materialize functions before seeing function blocks"); 31477d523365SDimitry Andric 31487d523365SDimitry Andric // An old bitcode file with the symbol table at the end would have 31497d523365SDimitry Andric // finished the parse greedily. 31507d523365SDimitry Andric assert(SeenValueSymbolTable); 31517d523365SDimitry Andric 31527d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 31537d523365SDimitry Andric 31547d523365SDimitry Andric while (1) { 31557d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 31567d523365SDimitry Andric switch (Entry.Kind) { 31577d523365SDimitry Andric default: 31587d523365SDimitry Andric return error("Expect SubBlock"); 31597d523365SDimitry Andric case BitstreamEntry::SubBlock: 31607d523365SDimitry Andric switch (Entry.ID) { 31617d523365SDimitry Andric default: 31627d523365SDimitry Andric return error("Expect function block"); 31637d523365SDimitry Andric case bitc::FUNCTION_BLOCK_ID: 31647d523365SDimitry Andric if (std::error_code EC = rememberAndSkipFunctionBody()) 31657d523365SDimitry Andric return EC; 31667d523365SDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 31677d523365SDimitry Andric return std::error_code(); 31687d523365SDimitry Andric } 31697d523365SDimitry Andric } 31707d523365SDimitry Andric } 31717d523365SDimitry Andric } 31727d523365SDimitry Andric 31737d523365SDimitry Andric std::error_code BitcodeReader::parseBitcodeVersion() { 31747d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 31757d523365SDimitry Andric return error("Invalid record"); 31767d523365SDimitry Andric 31777d523365SDimitry Andric // Read all the records. 31787d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 31797d523365SDimitry Andric while (1) { 31807d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 31817d523365SDimitry Andric 31827d523365SDimitry Andric switch (Entry.Kind) { 31837d523365SDimitry Andric default: 31847d523365SDimitry Andric case BitstreamEntry::Error: 31857d523365SDimitry Andric return error("Malformed block"); 31867d523365SDimitry Andric case BitstreamEntry::EndBlock: 31877d523365SDimitry Andric return std::error_code(); 31887d523365SDimitry Andric case BitstreamEntry::Record: 31897d523365SDimitry Andric // The interesting case. 31907d523365SDimitry Andric break; 31917d523365SDimitry Andric } 31927d523365SDimitry Andric 31937d523365SDimitry Andric // Read a record. 31947d523365SDimitry Andric Record.clear(); 31957d523365SDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 31967d523365SDimitry Andric switch (BitCode) { 31977d523365SDimitry Andric default: // Default behavior: reject 31987d523365SDimitry Andric return error("Invalid value"); 31997d523365SDimitry Andric case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x 32007d523365SDimitry Andric // N] 32017d523365SDimitry Andric convertToString(Record, 0, ProducerIdentification); 32027d523365SDimitry Andric break; 32037d523365SDimitry Andric } 32047d523365SDimitry Andric case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 32057d523365SDimitry Andric unsigned epoch = (unsigned)Record[0]; 32067d523365SDimitry Andric if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 32077d523365SDimitry Andric return error( 32087d523365SDimitry Andric Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 32097d523365SDimitry Andric "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 32107d523365SDimitry Andric } 32117d523365SDimitry Andric } 32127d523365SDimitry Andric } 32137d523365SDimitry Andric } 32147d523365SDimitry Andric } 32157d523365SDimitry Andric 32167d523365SDimitry Andric std::error_code BitcodeReader::parseModule(uint64_t ResumeBit, 32177d523365SDimitry Andric bool ShouldLazyLoadMetadata) { 32187d523365SDimitry Andric if (ResumeBit) 32197d523365SDimitry Andric Stream.JumpToBit(ResumeBit); 3220dff0c46cSDimitry Andric else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 32218f0fd8f6SDimitry Andric return error("Invalid record"); 3222dff0c46cSDimitry Andric 3223dff0c46cSDimitry Andric SmallVector<uint64_t, 64> Record; 3224dff0c46cSDimitry Andric std::vector<std::string> SectionTable; 3225dff0c46cSDimitry Andric std::vector<std::string> GCTable; 3226dff0c46cSDimitry Andric 3227dff0c46cSDimitry Andric // Read all the records for this module. 3228139f7f9bSDimitry Andric while (1) { 3229139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3230dff0c46cSDimitry Andric 3231139f7f9bSDimitry Andric switch (Entry.Kind) { 3232139f7f9bSDimitry Andric case BitstreamEntry::Error: 32338f0fd8f6SDimitry Andric return error("Malformed block"); 3234139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 32358f0fd8f6SDimitry Andric return globalCleanup(); 3236dff0c46cSDimitry Andric 3237139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3238139f7f9bSDimitry Andric switch (Entry.ID) { 3239f22ef01cSRoman Divacky default: // Skip unknown content. 3240f22ef01cSRoman Divacky if (Stream.SkipBlock()) 32418f0fd8f6SDimitry Andric return error("Invalid record"); 3242f22ef01cSRoman Divacky break; 3243f22ef01cSRoman Divacky case bitc::BLOCKINFO_BLOCK_ID: 3244f22ef01cSRoman Divacky if (Stream.ReadBlockInfoBlock()) 32458f0fd8f6SDimitry Andric return error("Malformed block"); 3246f22ef01cSRoman Divacky break; 3247f22ef01cSRoman Divacky case bitc::PARAMATTR_BLOCK_ID: 32488f0fd8f6SDimitry Andric if (std::error_code EC = parseAttributeBlock()) 3249f785676fSDimitry Andric return EC; 3250f22ef01cSRoman Divacky break; 3251139f7f9bSDimitry Andric case bitc::PARAMATTR_GROUP_BLOCK_ID: 32528f0fd8f6SDimitry Andric if (std::error_code EC = parseAttributeGroupBlock()) 3253f785676fSDimitry Andric return EC; 3254139f7f9bSDimitry Andric break; 325517a519f9SDimitry Andric case bitc::TYPE_BLOCK_ID_NEW: 32568f0fd8f6SDimitry Andric if (std::error_code EC = parseTypeTable()) 3257f785676fSDimitry Andric return EC; 3258f22ef01cSRoman Divacky break; 3259f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 32607d523365SDimitry Andric if (!SeenValueSymbolTable) { 32617d523365SDimitry Andric // Either this is an old form VST without function index and an 32627d523365SDimitry Andric // associated VST forward declaration record (which would have caused 32637d523365SDimitry Andric // the VST to be jumped to and parsed before it was encountered 32647d523365SDimitry Andric // normally in the stream), or there were no function blocks to 32657d523365SDimitry Andric // trigger an earlier parsing of the VST. 32667d523365SDimitry Andric assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 32678f0fd8f6SDimitry Andric if (std::error_code EC = parseValueSymbolTable()) 3268f785676fSDimitry Andric return EC; 3269dff0c46cSDimitry Andric SeenValueSymbolTable = true; 32707d523365SDimitry Andric } else { 32717d523365SDimitry Andric // We must have had a VST forward declaration record, which caused 32727d523365SDimitry Andric // the parser to jump to and parse the VST earlier. 32737d523365SDimitry Andric assert(VSTOffset > 0); 32747d523365SDimitry Andric if (Stream.SkipBlock()) 32757d523365SDimitry Andric return error("Invalid record"); 32767d523365SDimitry Andric } 3277f22ef01cSRoman Divacky break; 3278f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 32798f0fd8f6SDimitry Andric if (std::error_code EC = parseConstants()) 3280f785676fSDimitry Andric return EC; 32818f0fd8f6SDimitry Andric if (std::error_code EC = resolveGlobalAndAliasInits()) 3282f785676fSDimitry Andric return EC; 3283f22ef01cSRoman Divacky break; 3284f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 3285ff0cc061SDimitry Andric if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) { 3286ff0cc061SDimitry Andric if (std::error_code EC = rememberAndSkipMetadata()) 3287ff0cc061SDimitry Andric return EC; 3288ff0cc061SDimitry Andric break; 3289ff0cc061SDimitry Andric } 3290ff0cc061SDimitry Andric assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 32917d523365SDimitry Andric if (std::error_code EC = parseMetadata(true)) 32927d523365SDimitry Andric return EC; 32937d523365SDimitry Andric break; 32947d523365SDimitry Andric case bitc::METADATA_KIND_BLOCK_ID: 32957d523365SDimitry Andric if (std::error_code EC = parseMetadataKinds()) 3296f785676fSDimitry Andric return EC; 3297f22ef01cSRoman Divacky break; 3298f22ef01cSRoman Divacky case bitc::FUNCTION_BLOCK_ID: 3299f22ef01cSRoman Divacky // If this is the first function body we've seen, reverse the 3300f22ef01cSRoman Divacky // FunctionsWithBodies list. 3301dff0c46cSDimitry Andric if (!SeenFirstFunctionBody) { 3302f22ef01cSRoman Divacky std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 33038f0fd8f6SDimitry Andric if (std::error_code EC = globalCleanup()) 3304f785676fSDimitry Andric return EC; 3305dff0c46cSDimitry Andric SeenFirstFunctionBody = true; 3306f22ef01cSRoman Divacky } 3307f22ef01cSRoman Divacky 33087d523365SDimitry Andric if (VSTOffset > 0) { 33097d523365SDimitry Andric // If we have a VST forward declaration record, make sure we 33107d523365SDimitry Andric // parse the VST now if we haven't already. It is needed to 33117d523365SDimitry Andric // set up the DeferredFunctionInfo vector for lazy reading. 33127d523365SDimitry Andric if (!SeenValueSymbolTable) { 33137d523365SDimitry Andric if (std::error_code EC = 33147d523365SDimitry Andric BitcodeReader::parseValueSymbolTable(VSTOffset)) 33157d523365SDimitry Andric return EC; 33167d523365SDimitry Andric SeenValueSymbolTable = true; 33177d523365SDimitry Andric // Fall through so that we record the NextUnreadBit below. 33187d523365SDimitry Andric // This is necessary in case we have an anonymous function that 33197d523365SDimitry Andric // is later materialized. Since it will not have a VST entry we 33207d523365SDimitry Andric // need to fall back to the lazy parse to find its offset. 33217d523365SDimitry Andric } else { 33227d523365SDimitry Andric // If we have a VST forward declaration record, but have already 33237d523365SDimitry Andric // parsed the VST (just above, when the first function body was 33247d523365SDimitry Andric // encountered here), then we are resuming the parse after 33257d523365SDimitry Andric // materializing functions. The ResumeBit points to the 33267d523365SDimitry Andric // start of the last function block recorded in the 33277d523365SDimitry Andric // DeferredFunctionInfo map. Skip it. 33287d523365SDimitry Andric if (Stream.SkipBlock()) 33297d523365SDimitry Andric return error("Invalid record"); 33307d523365SDimitry Andric continue; 33317d523365SDimitry Andric } 33327d523365SDimitry Andric } 33337d523365SDimitry Andric 33347d523365SDimitry Andric // Support older bitcode files that did not have the function 33357d523365SDimitry Andric // index in the VST, nor a VST forward declaration record, as 33367d523365SDimitry Andric // well as anonymous functions that do not have VST entries. 33377d523365SDimitry Andric // Build the DeferredFunctionInfo vector on the fly. 33388f0fd8f6SDimitry Andric if (std::error_code EC = rememberAndSkipFunctionBody()) 3339f785676fSDimitry Andric return EC; 33407d523365SDimitry Andric 33413dac3a9bSDimitry Andric // Suspend parsing when we reach the function bodies. Subsequent 33423dac3a9bSDimitry Andric // materialization calls will resume it when necessary. If the bitcode 33433dac3a9bSDimitry Andric // file is old, the symbol table will be at the end instead and will not 33443dac3a9bSDimitry Andric // have been seen yet. In this case, just finish the parse now. 33453dac3a9bSDimitry Andric if (SeenValueSymbolTable) { 3346dff0c46cSDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo(); 334791bc56edSDimitry Andric return std::error_code(); 3348dff0c46cSDimitry Andric } 3349dff0c46cSDimitry Andric break; 3350dff0c46cSDimitry Andric case bitc::USELIST_BLOCK_ID: 33518f0fd8f6SDimitry Andric if (std::error_code EC = parseUseLists()) 3352f785676fSDimitry Andric return EC; 3353f22ef01cSRoman Divacky break; 33547d523365SDimitry Andric case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 33557d523365SDimitry Andric if (std::error_code EC = parseOperandBundleTags()) 33567d523365SDimitry Andric return EC; 33577d523365SDimitry Andric break; 3358f22ef01cSRoman Divacky } 3359f22ef01cSRoman Divacky continue; 3360139f7f9bSDimitry Andric 3361139f7f9bSDimitry Andric case BitstreamEntry::Record: 3362139f7f9bSDimitry Andric // The interesting case. 3363139f7f9bSDimitry Andric break; 3364f22ef01cSRoman Divacky } 3365f22ef01cSRoman Divacky 3366f22ef01cSRoman Divacky 3367f22ef01cSRoman Divacky // Read a record. 33687d523365SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record); 33697d523365SDimitry Andric switch (BitCode) { 3370f22ef01cSRoman Divacky default: break; // Default behavior, ignore unknown content. 33713861d79fSDimitry Andric case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 3372f22ef01cSRoman Divacky if (Record.size() < 1) 33738f0fd8f6SDimitry Andric return error("Invalid record"); 33743861d79fSDimitry Andric // Only version #0 and #1 are supported so far. 33753861d79fSDimitry Andric unsigned module_version = Record[0]; 33763861d79fSDimitry Andric switch (module_version) { 3377f785676fSDimitry Andric default: 33788f0fd8f6SDimitry Andric return error("Invalid value"); 33793861d79fSDimitry Andric case 0: 33803861d79fSDimitry Andric UseRelativeIDs = false; 3381f22ef01cSRoman Divacky break; 33823861d79fSDimitry Andric case 1: 33833861d79fSDimitry Andric UseRelativeIDs = true; 33843861d79fSDimitry Andric break; 33853861d79fSDimitry Andric } 33863861d79fSDimitry Andric break; 33873861d79fSDimitry Andric } 3388f22ef01cSRoman Divacky case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3389f22ef01cSRoman Divacky std::string S; 33908f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 33918f0fd8f6SDimitry Andric return error("Invalid record"); 3392f22ef01cSRoman Divacky TheModule->setTargetTriple(S); 3393f22ef01cSRoman Divacky break; 3394f22ef01cSRoman Divacky } 3395f22ef01cSRoman Divacky case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 3396f22ef01cSRoman Divacky std::string S; 33978f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 33988f0fd8f6SDimitry Andric return error("Invalid record"); 3399f22ef01cSRoman Divacky TheModule->setDataLayout(S); 3400f22ef01cSRoman Divacky break; 3401f22ef01cSRoman Divacky } 3402f22ef01cSRoman Divacky case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 3403f22ef01cSRoman Divacky std::string S; 34048f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34058f0fd8f6SDimitry Andric return error("Invalid record"); 3406f22ef01cSRoman Divacky TheModule->setModuleInlineAsm(S); 3407f22ef01cSRoman Divacky break; 3408f22ef01cSRoman Divacky } 3409f22ef01cSRoman Divacky case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 3410139f7f9bSDimitry Andric // FIXME: Remove in 4.0. 3411f22ef01cSRoman Divacky std::string S; 34128f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34138f0fd8f6SDimitry Andric return error("Invalid record"); 3414139f7f9bSDimitry Andric // Ignore value. 3415f22ef01cSRoman Divacky break; 3416f22ef01cSRoman Divacky } 3417f22ef01cSRoman Divacky case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 3418f22ef01cSRoman Divacky std::string S; 34198f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34208f0fd8f6SDimitry Andric return error("Invalid record"); 3421f22ef01cSRoman Divacky SectionTable.push_back(S); 3422f22ef01cSRoman Divacky break; 3423f22ef01cSRoman Divacky } 3424f22ef01cSRoman Divacky case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 3425f22ef01cSRoman Divacky std::string S; 34268f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 34278f0fd8f6SDimitry Andric return error("Invalid record"); 3428f22ef01cSRoman Divacky GCTable.push_back(S); 3429f22ef01cSRoman Divacky break; 3430f22ef01cSRoman Divacky } 343191bc56edSDimitry Andric case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] 343291bc56edSDimitry Andric if (Record.size() < 2) 34338f0fd8f6SDimitry Andric return error("Invalid record"); 343491bc56edSDimitry Andric Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 343591bc56edSDimitry Andric unsigned ComdatNameSize = Record[1]; 343691bc56edSDimitry Andric std::string ComdatName; 343791bc56edSDimitry Andric ComdatName.reserve(ComdatNameSize); 343891bc56edSDimitry Andric for (unsigned i = 0; i != ComdatNameSize; ++i) 343991bc56edSDimitry Andric ComdatName += (char)Record[2 + i]; 344091bc56edSDimitry Andric Comdat *C = TheModule->getOrInsertComdat(ComdatName); 344191bc56edSDimitry Andric C->setSelectionKind(SK); 344291bc56edSDimitry Andric ComdatList.push_back(C); 344391bc56edSDimitry Andric break; 344491bc56edSDimitry Andric } 3445f22ef01cSRoman Divacky // GLOBALVAR: [pointer type, isconst, initid, 34462754fe60SDimitry Andric // linkage, alignment, section, visibility, threadlocal, 3447ff0cc061SDimitry Andric // unnamed_addr, externally_initialized, dllstorageclass, 3448ff0cc061SDimitry Andric // comdat] 3449f22ef01cSRoman Divacky case bitc::MODULE_CODE_GLOBALVAR: { 3450f22ef01cSRoman Divacky if (Record.size() < 6) 34518f0fd8f6SDimitry Andric return error("Invalid record"); 34526122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 3453f785676fSDimitry Andric if (!Ty) 34548f0fd8f6SDimitry Andric return error("Invalid record"); 3455ff0cc061SDimitry Andric bool isConstant = Record[1] & 1; 3456ff0cc061SDimitry Andric bool explicitType = Record[1] & 2; 3457ff0cc061SDimitry Andric unsigned AddressSpace; 3458ff0cc061SDimitry Andric if (explicitType) { 3459ff0cc061SDimitry Andric AddressSpace = Record[1] >> 2; 3460ff0cc061SDimitry Andric } else { 3461f22ef01cSRoman Divacky if (!Ty->isPointerTy()) 34628f0fd8f6SDimitry Andric return error("Invalid type for value"); 3463ff0cc061SDimitry Andric AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 3464f22ef01cSRoman Divacky Ty = cast<PointerType>(Ty)->getElementType(); 3465ff0cc061SDimitry Andric } 3466f22ef01cSRoman Divacky 3467ff0cc061SDimitry Andric uint64_t RawLinkage = Record[3]; 3468ff0cc061SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 3469ff0cc061SDimitry Andric unsigned Alignment; 3470ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[4], Alignment)) 3471ff0cc061SDimitry Andric return EC; 3472f22ef01cSRoman Divacky std::string Section; 3473f22ef01cSRoman Divacky if (Record[5]) { 3474f22ef01cSRoman Divacky if (Record[5]-1 >= SectionTable.size()) 34758f0fd8f6SDimitry Andric return error("Invalid ID"); 3476f22ef01cSRoman Divacky Section = SectionTable[Record[5]-1]; 3477f22ef01cSRoman Divacky } 3478f22ef01cSRoman Divacky GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 347991bc56edSDimitry Andric // Local linkage must have default visibility. 348091bc56edSDimitry Andric if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 348191bc56edSDimitry Andric // FIXME: Change to an error if non-default in 4.0. 34828f0fd8f6SDimitry Andric Visibility = getDecodedVisibility(Record[6]); 34837ae0e2c9SDimitry Andric 34847ae0e2c9SDimitry Andric GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 3485f22ef01cSRoman Divacky if (Record.size() > 7) 34868f0fd8f6SDimitry Andric TLM = getDecodedThreadLocalMode(Record[7]); 3487f22ef01cSRoman Divacky 34882754fe60SDimitry Andric bool UnnamedAddr = false; 34892754fe60SDimitry Andric if (Record.size() > 8) 34902754fe60SDimitry Andric UnnamedAddr = Record[8]; 34912754fe60SDimitry Andric 3492139f7f9bSDimitry Andric bool ExternallyInitialized = false; 3493139f7f9bSDimitry Andric if (Record.size() > 9) 3494139f7f9bSDimitry Andric ExternallyInitialized = Record[9]; 3495139f7f9bSDimitry Andric 3496f22ef01cSRoman Divacky GlobalVariable *NewGV = 349791bc56edSDimitry Andric new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 3498139f7f9bSDimitry Andric TLM, AddressSpace, ExternallyInitialized); 3499f22ef01cSRoman Divacky NewGV->setAlignment(Alignment); 3500f22ef01cSRoman Divacky if (!Section.empty()) 3501f22ef01cSRoman Divacky NewGV->setSection(Section); 3502f22ef01cSRoman Divacky NewGV->setVisibility(Visibility); 35032754fe60SDimitry Andric NewGV->setUnnamedAddr(UnnamedAddr); 3504f22ef01cSRoman Divacky 350591bc56edSDimitry Andric if (Record.size() > 10) 35068f0fd8f6SDimitry Andric NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 350791bc56edSDimitry Andric else 35088f0fd8f6SDimitry Andric upgradeDLLImportExportLinkage(NewGV, RawLinkage); 350991bc56edSDimitry Andric 3510f22ef01cSRoman Divacky ValueList.push_back(NewGV); 3511f22ef01cSRoman Divacky 3512f22ef01cSRoman Divacky // Remember which value to use for the global initializer. 3513f22ef01cSRoman Divacky if (unsigned InitID = Record[2]) 3514f22ef01cSRoman Divacky GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 351591bc56edSDimitry Andric 3516ff0cc061SDimitry Andric if (Record.size() > 11) { 351791bc56edSDimitry Andric if (unsigned ComdatID = Record[11]) { 3518ff0cc061SDimitry Andric if (ComdatID > ComdatList.size()) 35198f0fd8f6SDimitry Andric return error("Invalid global variable comdat ID"); 352091bc56edSDimitry Andric NewGV->setComdat(ComdatList[ComdatID - 1]); 352191bc56edSDimitry Andric } 3522ff0cc061SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 3523ff0cc061SDimitry Andric NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 3524ff0cc061SDimitry Andric } 3525f22ef01cSRoman Divacky break; 3526f22ef01cSRoman Divacky } 3527f22ef01cSRoman Divacky // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 352891bc56edSDimitry Andric // alignment, section, visibility, gc, unnamed_addr, 352939d628a0SDimitry Andric // prologuedata, dllstorageclass, comdat, prefixdata] 3530f22ef01cSRoman Divacky case bitc::MODULE_CODE_FUNCTION: { 3531f22ef01cSRoman Divacky if (Record.size() < 8) 35328f0fd8f6SDimitry Andric return error("Invalid record"); 35336122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 3534f785676fSDimitry Andric if (!Ty) 35358f0fd8f6SDimitry Andric return error("Invalid record"); 3536ff0cc061SDimitry Andric if (auto *PTy = dyn_cast<PointerType>(Ty)) 3537ff0cc061SDimitry Andric Ty = PTy->getElementType(); 3538ff0cc061SDimitry Andric auto *FTy = dyn_cast<FunctionType>(Ty); 3539f22ef01cSRoman Divacky if (!FTy) 35408f0fd8f6SDimitry Andric return error("Invalid type for value"); 35417d523365SDimitry Andric auto CC = static_cast<CallingConv::ID>(Record[1]); 35427d523365SDimitry Andric if (CC & ~CallingConv::MaxID) 35437d523365SDimitry Andric return error("Invalid calling convention ID"); 3544f22ef01cSRoman Divacky 3545f22ef01cSRoman Divacky Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 3546f22ef01cSRoman Divacky "", TheModule); 3547f22ef01cSRoman Divacky 35487d523365SDimitry Andric Func->setCallingConv(CC); 3549f22ef01cSRoman Divacky bool isProto = Record[2]; 3550ff0cc061SDimitry Andric uint64_t RawLinkage = Record[3]; 3551ff0cc061SDimitry Andric Func->setLinkage(getDecodedLinkage(RawLinkage)); 3552f22ef01cSRoman Divacky Func->setAttributes(getAttributes(Record[4])); 3553f22ef01cSRoman Divacky 3554ff0cc061SDimitry Andric unsigned Alignment; 3555ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[5], Alignment)) 3556ff0cc061SDimitry Andric return EC; 3557ff0cc061SDimitry Andric Func->setAlignment(Alignment); 3558f22ef01cSRoman Divacky if (Record[6]) { 3559f22ef01cSRoman Divacky if (Record[6]-1 >= SectionTable.size()) 35608f0fd8f6SDimitry Andric return error("Invalid ID"); 3561f22ef01cSRoman Divacky Func->setSection(SectionTable[Record[6]-1]); 3562f22ef01cSRoman Divacky } 356391bc56edSDimitry Andric // Local linkage must have default visibility. 356491bc56edSDimitry Andric if (!Func->hasLocalLinkage()) 356591bc56edSDimitry Andric // FIXME: Change to an error if non-default in 4.0. 35668f0fd8f6SDimitry Andric Func->setVisibility(getDecodedVisibility(Record[7])); 3567f22ef01cSRoman Divacky if (Record.size() > 8 && Record[8]) { 3568ff0cc061SDimitry Andric if (Record[8]-1 >= GCTable.size()) 35698f0fd8f6SDimitry Andric return error("Invalid ID"); 3570f22ef01cSRoman Divacky Func->setGC(GCTable[Record[8]-1].c_str()); 3571f22ef01cSRoman Divacky } 35722754fe60SDimitry Andric bool UnnamedAddr = false; 35732754fe60SDimitry Andric if (Record.size() > 9) 35742754fe60SDimitry Andric UnnamedAddr = Record[9]; 35752754fe60SDimitry Andric Func->setUnnamedAddr(UnnamedAddr); 3576f785676fSDimitry Andric if (Record.size() > 10 && Record[10] != 0) 357739d628a0SDimitry Andric FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1)); 357891bc56edSDimitry Andric 357991bc56edSDimitry Andric if (Record.size() > 11) 35808f0fd8f6SDimitry Andric Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 358191bc56edSDimitry Andric else 35828f0fd8f6SDimitry Andric upgradeDLLImportExportLinkage(Func, RawLinkage); 358391bc56edSDimitry Andric 3584ff0cc061SDimitry Andric if (Record.size() > 12) { 358591bc56edSDimitry Andric if (unsigned ComdatID = Record[12]) { 3586ff0cc061SDimitry Andric if (ComdatID > ComdatList.size()) 35878f0fd8f6SDimitry Andric return error("Invalid function comdat ID"); 358891bc56edSDimitry Andric Func->setComdat(ComdatList[ComdatID - 1]); 358991bc56edSDimitry Andric } 3590ff0cc061SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) { 3591ff0cc061SDimitry Andric Func->setComdat(reinterpret_cast<Comdat *>(1)); 3592ff0cc061SDimitry Andric } 359391bc56edSDimitry Andric 359439d628a0SDimitry Andric if (Record.size() > 13 && Record[13] != 0) 359539d628a0SDimitry Andric FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1)); 359639d628a0SDimitry Andric 35978f0fd8f6SDimitry Andric if (Record.size() > 14 && Record[14] != 0) 35988f0fd8f6SDimitry Andric FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); 35998f0fd8f6SDimitry Andric 3600f22ef01cSRoman Divacky ValueList.push_back(Func); 3601f22ef01cSRoman Divacky 3602f22ef01cSRoman Divacky // If this is a function with a body, remember the prototype we are 3603f22ef01cSRoman Divacky // creating now, so that we can match up the body with them later. 3604dff0c46cSDimitry Andric if (!isProto) { 360539d628a0SDimitry Andric Func->setIsMaterializable(true); 3606f22ef01cSRoman Divacky FunctionsWithBodies.push_back(Func); 360739d628a0SDimitry Andric DeferredFunctionInfo[Func] = 0; 3608dff0c46cSDimitry Andric } 3609f22ef01cSRoman Divacky break; 3610f22ef01cSRoman Divacky } 36117d523365SDimitry Andric // ALIAS: [alias type, addrspace, aliasee val#, linkage] 36127d523365SDimitry Andric // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass] 36137d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS: 36147d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS_OLD: { 36157d523365SDimitry Andric bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS; 36167d523365SDimitry Andric if (Record.size() < (3 + (unsigned)NewRecord)) 36178f0fd8f6SDimitry Andric return error("Invalid record"); 36187d523365SDimitry Andric unsigned OpNum = 0; 36197d523365SDimitry Andric Type *Ty = getTypeByID(Record[OpNum++]); 3620f785676fSDimitry Andric if (!Ty) 36218f0fd8f6SDimitry Andric return error("Invalid record"); 36227d523365SDimitry Andric 36237d523365SDimitry Andric unsigned AddrSpace; 36247d523365SDimitry Andric if (!NewRecord) { 362591bc56edSDimitry Andric auto *PTy = dyn_cast<PointerType>(Ty); 362691bc56edSDimitry Andric if (!PTy) 36278f0fd8f6SDimitry Andric return error("Invalid type for value"); 36287d523365SDimitry Andric Ty = PTy->getElementType(); 36297d523365SDimitry Andric AddrSpace = PTy->getAddressSpace(); 36307d523365SDimitry Andric } else { 36317d523365SDimitry Andric AddrSpace = Record[OpNum++]; 36327d523365SDimitry Andric } 3633f22ef01cSRoman Divacky 36347d523365SDimitry Andric auto Val = Record[OpNum++]; 36357d523365SDimitry Andric auto Linkage = Record[OpNum++]; 36367d523365SDimitry Andric auto *NewGA = GlobalAlias::create( 36377d523365SDimitry Andric Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule); 3638f22ef01cSRoman Divacky // Old bitcode files didn't have visibility field. 363991bc56edSDimitry Andric // Local linkage must have default visibility. 36407d523365SDimitry Andric if (OpNum != Record.size()) { 36417d523365SDimitry Andric auto VisInd = OpNum++; 36427d523365SDimitry Andric if (!NewGA->hasLocalLinkage()) 364391bc56edSDimitry Andric // FIXME: Change to an error if non-default in 4.0. 36447d523365SDimitry Andric NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 36457d523365SDimitry Andric } 36467d523365SDimitry Andric if (OpNum != Record.size()) 36477d523365SDimitry Andric NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); 364891bc56edSDimitry Andric else 36497d523365SDimitry Andric upgradeDLLImportExportLinkage(NewGA, Linkage); 36507d523365SDimitry Andric if (OpNum != Record.size()) 36517d523365SDimitry Andric NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 36527d523365SDimitry Andric if (OpNum != Record.size()) 36537d523365SDimitry Andric NewGA->setUnnamedAddr(Record[OpNum++]); 3654f22ef01cSRoman Divacky ValueList.push_back(NewGA); 36557d523365SDimitry Andric AliasInits.push_back(std::make_pair(NewGA, Val)); 3656f22ef01cSRoman Divacky break; 3657f22ef01cSRoman Divacky } 3658f22ef01cSRoman Divacky /// MODULE_CODE_PURGEVALS: [numvals] 3659f22ef01cSRoman Divacky case bitc::MODULE_CODE_PURGEVALS: 3660f22ef01cSRoman Divacky // Trim down the value list to the specified size. 3661f22ef01cSRoman Divacky if (Record.size() < 1 || Record[0] > ValueList.size()) 36628f0fd8f6SDimitry Andric return error("Invalid record"); 3663f22ef01cSRoman Divacky ValueList.shrinkTo(Record[0]); 3664f22ef01cSRoman Divacky break; 36657d523365SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset] 36667d523365SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET: 36677d523365SDimitry Andric if (Record.size() < 1) 36687d523365SDimitry Andric return error("Invalid record"); 36697d523365SDimitry Andric VSTOffset = Record[0]; 36707d523365SDimitry Andric break; 36717d523365SDimitry Andric /// MODULE_CODE_METADATA_VALUES: [numvals] 36727d523365SDimitry Andric case bitc::MODULE_CODE_METADATA_VALUES: 36737d523365SDimitry Andric if (Record.size() < 1) 36747d523365SDimitry Andric return error("Invalid record"); 36757d523365SDimitry Andric assert(!IsMetadataMaterialized); 36767d523365SDimitry Andric // This record contains the number of metadata values in the module-level 36777d523365SDimitry Andric // METADATA_BLOCK. It is used to support lazy parsing of metadata as 36787d523365SDimitry Andric // a postpass, where we will parse function-level metadata first. 36797d523365SDimitry Andric // This is needed because the ids of metadata are assigned implicitly 36807d523365SDimitry Andric // based on their ordering in the bitcode, with the function-level 36817d523365SDimitry Andric // metadata ids starting after the module-level metadata ids. Otherwise, 36827d523365SDimitry Andric // we would have to parse the module-level metadata block to prime the 36837d523365SDimitry Andric // MetadataList when we are lazy loading metadata during function 36847d523365SDimitry Andric // importing. Initialize the MetadataList size here based on the 36857d523365SDimitry Andric // record value, regardless of whether we are doing lazy metadata 36867d523365SDimitry Andric // loading, so that we have consistent handling and assertion 36877d523365SDimitry Andric // checking in parseMetadata for module-level metadata. 36887d523365SDimitry Andric NumModuleMDs = Record[0]; 36897d523365SDimitry Andric SeenModuleValuesRecord = true; 36907d523365SDimitry Andric assert(MetadataList.size() == 0); 36917d523365SDimitry Andric MetadataList.resize(NumModuleMDs); 36927d523365SDimitry Andric break; 3693f22ef01cSRoman Divacky } 3694f22ef01cSRoman Divacky Record.clear(); 3695f22ef01cSRoman Divacky } 3696f22ef01cSRoman Divacky } 3697f22ef01cSRoman Divacky 36987d523365SDimitry Andric /// Helper to read the header common to all bitcode files. 36997d523365SDimitry Andric static bool hasValidBitcodeHeader(BitstreamCursor &Stream) { 37007d523365SDimitry Andric // Sniff for the signature. 37017d523365SDimitry Andric if (Stream.Read(8) != 'B' || 37027d523365SDimitry Andric Stream.Read(8) != 'C' || 37037d523365SDimitry Andric Stream.Read(4) != 0x0 || 37047d523365SDimitry Andric Stream.Read(4) != 0xC || 37057d523365SDimitry Andric Stream.Read(4) != 0xE || 37067d523365SDimitry Andric Stream.Read(4) != 0xD) 37077d523365SDimitry Andric return false; 37087d523365SDimitry Andric return true; 37097d523365SDimitry Andric } 37107d523365SDimitry Andric 37118f0fd8f6SDimitry Andric std::error_code 37128f0fd8f6SDimitry Andric BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer, 37138f0fd8f6SDimitry Andric Module *M, bool ShouldLazyLoadMetadata) { 37148f0fd8f6SDimitry Andric TheModule = M; 3715f22ef01cSRoman Divacky 37168f0fd8f6SDimitry Andric if (std::error_code EC = initStream(std::move(Streamer))) 3717f785676fSDimitry Andric return EC; 3718f22ef01cSRoman Divacky 3719f22ef01cSRoman Divacky // Sniff for the signature. 37207d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 37218f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 3722f22ef01cSRoman Divacky 3723f22ef01cSRoman Divacky // We expect a number of well-defined blocks, though we don't necessarily 3724f22ef01cSRoman Divacky // need to understand them all. 3725139f7f9bSDimitry Andric while (1) { 3726ff0cc061SDimitry Andric if (Stream.AtEndOfStream()) { 3727ff0cc061SDimitry Andric // We didn't really read a proper Module. 37288f0fd8f6SDimitry Andric return error("Malformed IR file"); 3729ff0cc061SDimitry Andric } 3730bd5abe19SDimitry Andric 3731139f7f9bSDimitry Andric BitstreamEntry Entry = 3732139f7f9bSDimitry Andric Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 3733f22ef01cSRoman Divacky 37348f0fd8f6SDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock) 37358f0fd8f6SDimitry Andric return error("Malformed block"); 3736f22ef01cSRoman Divacky 37377d523365SDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 37387d523365SDimitry Andric parseBitcodeVersion(); 37397d523365SDimitry Andric continue; 37407d523365SDimitry Andric } 37417d523365SDimitry Andric 37428f0fd8f6SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 37437d523365SDimitry Andric return parseModule(0, ShouldLazyLoadMetadata); 37448f0fd8f6SDimitry Andric 3745f22ef01cSRoman Divacky if (Stream.SkipBlock()) 37468f0fd8f6SDimitry Andric return error("Invalid record"); 3747139f7f9bSDimitry Andric } 3748f22ef01cSRoman Divacky } 3749f22ef01cSRoman Divacky 375091bc56edSDimitry Andric ErrorOr<std::string> BitcodeReader::parseModuleTriple() { 37512754fe60SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 37528f0fd8f6SDimitry Andric return error("Invalid record"); 37532754fe60SDimitry Andric 37542754fe60SDimitry Andric SmallVector<uint64_t, 64> Record; 37552754fe60SDimitry Andric 375691bc56edSDimitry Andric std::string Triple; 37572754fe60SDimitry Andric // Read all the records for this module. 3758139f7f9bSDimitry Andric while (1) { 3759139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 37602754fe60SDimitry Andric 3761139f7f9bSDimitry Andric switch (Entry.Kind) { 3762139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 3763139f7f9bSDimitry Andric case BitstreamEntry::Error: 37648f0fd8f6SDimitry Andric return error("Malformed block"); 3765139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 376691bc56edSDimitry Andric return Triple; 3767139f7f9bSDimitry Andric case BitstreamEntry::Record: 3768139f7f9bSDimitry Andric // The interesting case. 37692754fe60SDimitry Andric break; 37702754fe60SDimitry Andric } 37712754fe60SDimitry Andric 37722754fe60SDimitry Andric // Read a record. 3773139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 37742754fe60SDimitry Andric default: break; // Default behavior, ignore unknown content. 37752754fe60SDimitry Andric case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 37762754fe60SDimitry Andric std::string S; 37778f0fd8f6SDimitry Andric if (convertToString(Record, 0, S)) 37788f0fd8f6SDimitry Andric return error("Invalid record"); 37792754fe60SDimitry Andric Triple = S; 37802754fe60SDimitry Andric break; 37812754fe60SDimitry Andric } 37822754fe60SDimitry Andric } 37832754fe60SDimitry Andric Record.clear(); 37842754fe60SDimitry Andric } 378591bc56edSDimitry Andric llvm_unreachable("Exit infinite loop"); 37862754fe60SDimitry Andric } 37872754fe60SDimitry Andric 378891bc56edSDimitry Andric ErrorOr<std::string> BitcodeReader::parseTriple() { 37898f0fd8f6SDimitry Andric if (std::error_code EC = initStream(nullptr)) 3790f785676fSDimitry Andric return EC; 37912754fe60SDimitry Andric 37922754fe60SDimitry Andric // Sniff for the signature. 37937d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 37948f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 37952754fe60SDimitry Andric 37962754fe60SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 37972754fe60SDimitry Andric // need to understand them all. 3798139f7f9bSDimitry Andric while (1) { 3799139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 38002754fe60SDimitry Andric 3801139f7f9bSDimitry Andric switch (Entry.Kind) { 3802139f7f9bSDimitry Andric case BitstreamEntry::Error: 38038f0fd8f6SDimitry Andric return error("Malformed block"); 3804139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 380591bc56edSDimitry Andric return std::error_code(); 3806139f7f9bSDimitry Andric 3807139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3808139f7f9bSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 380991bc56edSDimitry Andric return parseModuleTriple(); 3810139f7f9bSDimitry Andric 3811139f7f9bSDimitry Andric // Ignore other sub-blocks. 3812f785676fSDimitry Andric if (Stream.SkipBlock()) 38138f0fd8f6SDimitry Andric return error("Malformed block"); 3814139f7f9bSDimitry Andric continue; 3815139f7f9bSDimitry Andric 3816139f7f9bSDimitry Andric case BitstreamEntry::Record: 3817139f7f9bSDimitry Andric Stream.skipRecord(Entry.ID); 3818139f7f9bSDimitry Andric continue; 3819139f7f9bSDimitry Andric } 3820139f7f9bSDimitry Andric } 38212754fe60SDimitry Andric } 38222754fe60SDimitry Andric 38237d523365SDimitry Andric ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() { 38247d523365SDimitry Andric if (std::error_code EC = initStream(nullptr)) 38257d523365SDimitry Andric return EC; 38267d523365SDimitry Andric 38277d523365SDimitry Andric // Sniff for the signature. 38287d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 38297d523365SDimitry Andric return error("Invalid bitcode signature"); 38307d523365SDimitry Andric 38317d523365SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 38327d523365SDimitry Andric // need to understand them all. 38337d523365SDimitry Andric while (1) { 38347d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 38357d523365SDimitry Andric switch (Entry.Kind) { 38367d523365SDimitry Andric case BitstreamEntry::Error: 38377d523365SDimitry Andric return error("Malformed block"); 38387d523365SDimitry Andric case BitstreamEntry::EndBlock: 38397d523365SDimitry Andric return std::error_code(); 38407d523365SDimitry Andric 38417d523365SDimitry Andric case BitstreamEntry::SubBlock: 38427d523365SDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 38437d523365SDimitry Andric if (std::error_code EC = parseBitcodeVersion()) 38447d523365SDimitry Andric return EC; 38457d523365SDimitry Andric return ProducerIdentification; 38467d523365SDimitry Andric } 38477d523365SDimitry Andric // Ignore other sub-blocks. 38487d523365SDimitry Andric if (Stream.SkipBlock()) 38497d523365SDimitry Andric return error("Malformed block"); 38507d523365SDimitry Andric continue; 38517d523365SDimitry Andric case BitstreamEntry::Record: 38527d523365SDimitry Andric Stream.skipRecord(Entry.ID); 38537d523365SDimitry Andric continue; 38547d523365SDimitry Andric } 38557d523365SDimitry Andric } 38567d523365SDimitry Andric } 38577d523365SDimitry Andric 38588f0fd8f6SDimitry Andric /// Parse metadata attachments. 38598f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseMetadataAttachment(Function &F) { 3860f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 38618f0fd8f6SDimitry Andric return error("Invalid record"); 3862f22ef01cSRoman Divacky 3863f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 3864f22ef01cSRoman Divacky while (1) { 3865139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3866139f7f9bSDimitry Andric 3867139f7f9bSDimitry Andric switch (Entry.Kind) { 3868139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 3869139f7f9bSDimitry Andric case BitstreamEntry::Error: 38708f0fd8f6SDimitry Andric return error("Malformed block"); 3871139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 387291bc56edSDimitry Andric return std::error_code(); 3873139f7f9bSDimitry Andric case BitstreamEntry::Record: 3874139f7f9bSDimitry Andric // The interesting case. 3875f22ef01cSRoman Divacky break; 3876f22ef01cSRoman Divacky } 3877139f7f9bSDimitry Andric 3878f22ef01cSRoman Divacky // Read a metadata attachment record. 3879f22ef01cSRoman Divacky Record.clear(); 3880139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 3881f22ef01cSRoman Divacky default: // Default behavior: ignore. 3882f22ef01cSRoman Divacky break; 388317a519f9SDimitry Andric case bitc::METADATA_ATTACHMENT: { 3884f22ef01cSRoman Divacky unsigned RecordLength = Record.size(); 3885ff0cc061SDimitry Andric if (Record.empty()) 38868f0fd8f6SDimitry Andric return error("Invalid record"); 3887ff0cc061SDimitry Andric if (RecordLength % 2 == 0) { 3888ff0cc061SDimitry Andric // A function attachment. 3889ff0cc061SDimitry Andric for (unsigned I = 0; I != RecordLength; I += 2) { 3890ff0cc061SDimitry Andric auto K = MDKindMap.find(Record[I]); 3891ff0cc061SDimitry Andric if (K == MDKindMap.end()) 38928f0fd8f6SDimitry Andric return error("Invalid ID"); 38937d523365SDimitry Andric Metadata *MD = MetadataList.getValueFwdRef(Record[I + 1]); 3894ff0cc061SDimitry Andric F.setMetadata(K->second, cast<MDNode>(MD)); 3895ff0cc061SDimitry Andric } 3896ff0cc061SDimitry Andric continue; 3897ff0cc061SDimitry Andric } 3898ff0cc061SDimitry Andric 3899ff0cc061SDimitry Andric // An instruction attachment. 3900f22ef01cSRoman Divacky Instruction *Inst = InstructionList[Record[0]]; 3901f22ef01cSRoman Divacky for (unsigned i = 1; i != RecordLength; i = i+2) { 3902f22ef01cSRoman Divacky unsigned Kind = Record[i]; 3903e580952dSDimitry Andric DenseMap<unsigned, unsigned>::iterator I = 3904e580952dSDimitry Andric MDKindMap.find(Kind); 3905e580952dSDimitry Andric if (I == MDKindMap.end()) 39068f0fd8f6SDimitry Andric return error("Invalid ID"); 39077d523365SDimitry Andric Metadata *Node = MetadataList.getValueFwdRef(Record[i + 1]); 390839d628a0SDimitry Andric if (isa<LocalAsMetadata>(Node)) 390939d628a0SDimitry Andric // Drop the attachment. This used to be legal, but there's no 391039d628a0SDimitry Andric // upgrade path. 391139d628a0SDimitry Andric break; 3912e580952dSDimitry Andric Inst->setMetadata(I->second, cast<MDNode>(Node)); 3913f785676fSDimitry Andric if (I->second == LLVMContext::MD_tbaa) 3914f785676fSDimitry Andric InstsWithTBAATag.push_back(Inst); 3915f22ef01cSRoman Divacky } 3916f22ef01cSRoman Divacky break; 3917f22ef01cSRoman Divacky } 3918f22ef01cSRoman Divacky } 3919f22ef01cSRoman Divacky } 3920f22ef01cSRoman Divacky } 3921f22ef01cSRoman Divacky 39227d523365SDimitry Andric static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 39237d523365SDimitry Andric LLVMContext &Context = PtrType->getContext(); 3924ff0cc061SDimitry Andric if (!isa<PointerType>(PtrType)) 39257d523365SDimitry Andric return error(Context, "Load/Store operand is not a pointer type"); 3926ff0cc061SDimitry Andric Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 3927ff0cc061SDimitry Andric 3928ff0cc061SDimitry Andric if (ValType && ValType != ElemType) 39297d523365SDimitry Andric return error(Context, "Explicit load/store type does not match pointee " 39307d523365SDimitry Andric "type of pointer operand"); 3931ff0cc061SDimitry Andric if (!PointerType::isLoadableOrStorableType(ElemType)) 39327d523365SDimitry Andric return error(Context, "Cannot load/store from pointer"); 3933ff0cc061SDimitry Andric return std::error_code(); 3934ff0cc061SDimitry Andric } 3935ff0cc061SDimitry Andric 39368f0fd8f6SDimitry Andric /// Lazily parse the specified function body block. 39378f0fd8f6SDimitry Andric std::error_code BitcodeReader::parseFunctionBody(Function *F) { 3938f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 39398f0fd8f6SDimitry Andric return error("Invalid record"); 3940f22ef01cSRoman Divacky 3941f22ef01cSRoman Divacky InstructionList.clear(); 3942f22ef01cSRoman Divacky unsigned ModuleValueListSize = ValueList.size(); 39437d523365SDimitry Andric unsigned ModuleMetadataListSize = MetadataList.size(); 3944f22ef01cSRoman Divacky 3945f22ef01cSRoman Divacky // Add all the function arguments to the value table. 39467d523365SDimitry Andric for (Argument &I : F->args()) 39477d523365SDimitry Andric ValueList.push_back(&I); 3948f22ef01cSRoman Divacky 3949f22ef01cSRoman Divacky unsigned NextValueNo = ValueList.size(); 395091bc56edSDimitry Andric BasicBlock *CurBB = nullptr; 3951f22ef01cSRoman Divacky unsigned CurBBNo = 0; 3952f22ef01cSRoman Divacky 3953f22ef01cSRoman Divacky DebugLoc LastLoc; 395439d628a0SDimitry Andric auto getLastInstruction = [&]() -> Instruction * { 395539d628a0SDimitry Andric if (CurBB && !CurBB->empty()) 395639d628a0SDimitry Andric return &CurBB->back(); 395739d628a0SDimitry Andric else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 395839d628a0SDimitry Andric !FunctionBBs[CurBBNo - 1]->empty()) 395939d628a0SDimitry Andric return &FunctionBBs[CurBBNo - 1]->back(); 396039d628a0SDimitry Andric return nullptr; 396139d628a0SDimitry Andric }; 3962f22ef01cSRoman Divacky 39637d523365SDimitry Andric std::vector<OperandBundleDef> OperandBundles; 39647d523365SDimitry Andric 3965f22ef01cSRoman Divacky // Read all the records. 3966f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record; 3967f22ef01cSRoman Divacky while (1) { 3968139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance(); 3969f22ef01cSRoman Divacky 3970139f7f9bSDimitry Andric switch (Entry.Kind) { 3971139f7f9bSDimitry Andric case BitstreamEntry::Error: 39728f0fd8f6SDimitry Andric return error("Malformed block"); 3973139f7f9bSDimitry Andric case BitstreamEntry::EndBlock: 3974139f7f9bSDimitry Andric goto OutOfRecordLoop; 3975139f7f9bSDimitry Andric 3976139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: 3977139f7f9bSDimitry Andric switch (Entry.ID) { 3978f22ef01cSRoman Divacky default: // Skip unknown content. 3979f22ef01cSRoman Divacky if (Stream.SkipBlock()) 39808f0fd8f6SDimitry Andric return error("Invalid record"); 3981f22ef01cSRoman Divacky break; 3982f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID: 39838f0fd8f6SDimitry Andric if (std::error_code EC = parseConstants()) 3984f785676fSDimitry Andric return EC; 3985f22ef01cSRoman Divacky NextValueNo = ValueList.size(); 3986f22ef01cSRoman Divacky break; 3987f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID: 39888f0fd8f6SDimitry Andric if (std::error_code EC = parseValueSymbolTable()) 3989f785676fSDimitry Andric return EC; 3990f22ef01cSRoman Divacky break; 3991f22ef01cSRoman Divacky case bitc::METADATA_ATTACHMENT_ID: 39928f0fd8f6SDimitry Andric if (std::error_code EC = parseMetadataAttachment(*F)) 3993f785676fSDimitry Andric return EC; 3994f22ef01cSRoman Divacky break; 3995f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID: 39968f0fd8f6SDimitry Andric if (std::error_code EC = parseMetadata()) 3997f785676fSDimitry Andric return EC; 3998f22ef01cSRoman Divacky break; 399939d628a0SDimitry Andric case bitc::USELIST_BLOCK_ID: 40008f0fd8f6SDimitry Andric if (std::error_code EC = parseUseLists()) 400139d628a0SDimitry Andric return EC; 400239d628a0SDimitry Andric break; 4003f22ef01cSRoman Divacky } 4004f22ef01cSRoman Divacky continue; 4005f22ef01cSRoman Divacky 4006139f7f9bSDimitry Andric case BitstreamEntry::Record: 4007139f7f9bSDimitry Andric // The interesting case. 4008139f7f9bSDimitry Andric break; 4009f22ef01cSRoman Divacky } 4010f22ef01cSRoman Divacky 4011f22ef01cSRoman Divacky // Read a record. 4012f22ef01cSRoman Divacky Record.clear(); 401391bc56edSDimitry Andric Instruction *I = nullptr; 4014139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record); 4015f22ef01cSRoman Divacky switch (BitCode) { 4016f22ef01cSRoman Divacky default: // Default behavior: reject 40178f0fd8f6SDimitry Andric return error("Invalid value"); 401839d628a0SDimitry Andric case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 4019f22ef01cSRoman Divacky if (Record.size() < 1 || Record[0] == 0) 40208f0fd8f6SDimitry Andric return error("Invalid record"); 4021f22ef01cSRoman Divacky // Create all the basic blocks for the function. 4022f22ef01cSRoman Divacky FunctionBBs.resize(Record[0]); 402339d628a0SDimitry Andric 402439d628a0SDimitry Andric // See if anything took the address of blocks in this function. 402539d628a0SDimitry Andric auto BBFRI = BasicBlockFwdRefs.find(F); 402639d628a0SDimitry Andric if (BBFRI == BasicBlockFwdRefs.end()) { 4027f22ef01cSRoman Divacky for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 4028f22ef01cSRoman Divacky FunctionBBs[i] = BasicBlock::Create(Context, "", F); 402939d628a0SDimitry Andric } else { 403039d628a0SDimitry Andric auto &BBRefs = BBFRI->second; 403139d628a0SDimitry Andric // Check for invalid basic block references. 403239d628a0SDimitry Andric if (BBRefs.size() > FunctionBBs.size()) 40338f0fd8f6SDimitry Andric return error("Invalid ID"); 403439d628a0SDimitry Andric assert(!BBRefs.empty() && "Unexpected empty array"); 403539d628a0SDimitry Andric assert(!BBRefs.front() && "Invalid reference to entry block"); 403639d628a0SDimitry Andric for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 403739d628a0SDimitry Andric ++I) 403839d628a0SDimitry Andric if (I < RE && BBRefs[I]) { 403939d628a0SDimitry Andric BBRefs[I]->insertInto(F); 404039d628a0SDimitry Andric FunctionBBs[I] = BBRefs[I]; 404139d628a0SDimitry Andric } else { 404239d628a0SDimitry Andric FunctionBBs[I] = BasicBlock::Create(Context, "", F); 404339d628a0SDimitry Andric } 404439d628a0SDimitry Andric 404539d628a0SDimitry Andric // Erase from the table. 404639d628a0SDimitry Andric BasicBlockFwdRefs.erase(BBFRI); 404739d628a0SDimitry Andric } 404839d628a0SDimitry Andric 4049f22ef01cSRoman Divacky CurBB = FunctionBBs[0]; 4050f22ef01cSRoman Divacky continue; 405139d628a0SDimitry Andric } 4052f22ef01cSRoman Divacky 4053f22ef01cSRoman Divacky case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 4054f22ef01cSRoman Divacky // This record indicates that the last instruction is at the same 4055f22ef01cSRoman Divacky // location as the previous instruction with a location. 405639d628a0SDimitry Andric I = getLastInstruction(); 4057f22ef01cSRoman Divacky 405891bc56edSDimitry Andric if (!I) 40598f0fd8f6SDimitry Andric return error("Invalid record"); 4060f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 406191bc56edSDimitry Andric I = nullptr; 4062f22ef01cSRoman Divacky continue; 4063f22ef01cSRoman Divacky 406417a519f9SDimitry Andric case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 406539d628a0SDimitry Andric I = getLastInstruction(); 406691bc56edSDimitry Andric if (!I || Record.size() < 4) 40678f0fd8f6SDimitry Andric return error("Invalid record"); 4068f22ef01cSRoman Divacky 4069f22ef01cSRoman Divacky unsigned Line = Record[0], Col = Record[1]; 4070f22ef01cSRoman Divacky unsigned ScopeID = Record[2], IAID = Record[3]; 4071f22ef01cSRoman Divacky 407291bc56edSDimitry Andric MDNode *Scope = nullptr, *IA = nullptr; 40737d523365SDimitry Andric if (ScopeID) 40747d523365SDimitry Andric Scope = cast<MDNode>(MetadataList.getValueFwdRef(ScopeID - 1)); 40757d523365SDimitry Andric if (IAID) 40767d523365SDimitry Andric IA = cast<MDNode>(MetadataList.getValueFwdRef(IAID - 1)); 4077f22ef01cSRoman Divacky LastLoc = DebugLoc::get(Line, Col, Scope, IA); 4078f22ef01cSRoman Divacky I->setDebugLoc(LastLoc); 407991bc56edSDimitry Andric I = nullptr; 4080f22ef01cSRoman Divacky continue; 4081f22ef01cSRoman Divacky } 4082f22ef01cSRoman Divacky 4083f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 4084f22ef01cSRoman Divacky unsigned OpNum = 0; 4085f22ef01cSRoman Divacky Value *LHS, *RHS; 4086f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 40873861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 4088f22ef01cSRoman Divacky OpNum+1 > Record.size()) 40898f0fd8f6SDimitry Andric return error("Invalid record"); 4090f22ef01cSRoman Divacky 40918f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 4092f785676fSDimitry Andric if (Opc == -1) 40938f0fd8f6SDimitry Andric return error("Invalid record"); 4094f22ef01cSRoman Divacky I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 4095f22ef01cSRoman Divacky InstructionList.push_back(I); 4096f22ef01cSRoman Divacky if (OpNum < Record.size()) { 4097f22ef01cSRoman Divacky if (Opc == Instruction::Add || 4098f22ef01cSRoman Divacky Opc == Instruction::Sub || 40992754fe60SDimitry Andric Opc == Instruction::Mul || 41002754fe60SDimitry Andric Opc == Instruction::Shl) { 4101f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 4102f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 4103f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 4104f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 41052754fe60SDimitry Andric } else if (Opc == Instruction::SDiv || 41062754fe60SDimitry Andric Opc == Instruction::UDiv || 41072754fe60SDimitry Andric Opc == Instruction::LShr || 41082754fe60SDimitry Andric Opc == Instruction::AShr) { 41092754fe60SDimitry Andric if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 4110f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setIsExact(true); 4111139f7f9bSDimitry Andric } else if (isa<FPMathOperator>(I)) { 4112875ed548SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4113139f7f9bSDimitry Andric if (FMF.any()) 4114139f7f9bSDimitry Andric I->setFastMathFlags(FMF); 4115f22ef01cSRoman Divacky } 4116139f7f9bSDimitry Andric 4117f22ef01cSRoman Divacky } 4118f22ef01cSRoman Divacky break; 4119f22ef01cSRoman Divacky } 4120f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 4121f22ef01cSRoman Divacky unsigned OpNum = 0; 4122f22ef01cSRoman Divacky Value *Op; 4123f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4124f22ef01cSRoman Divacky OpNum+2 != Record.size()) 41258f0fd8f6SDimitry Andric return error("Invalid record"); 4126f22ef01cSRoman Divacky 41276122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[OpNum]); 41288f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 412991bc56edSDimitry Andric if (Opc == -1 || !ResTy) 41308f0fd8f6SDimitry Andric return error("Invalid record"); 413191bc56edSDimitry Andric Instruction *Temp = nullptr; 4132f785676fSDimitry Andric if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4133f785676fSDimitry Andric if (Temp) { 4134f785676fSDimitry Andric InstructionList.push_back(Temp); 4135f785676fSDimitry Andric CurBB->getInstList().push_back(Temp); 4136f785676fSDimitry Andric } 4137f785676fSDimitry Andric } else { 41387d523365SDimitry Andric auto CastOp = (Instruction::CastOps)Opc; 41397d523365SDimitry Andric if (!CastInst::castIsValid(CastOp, Op, ResTy)) 41407d523365SDimitry Andric return error("Invalid cast"); 41417d523365SDimitry Andric I = CastInst::Create(CastOp, Op, ResTy); 4142f785676fSDimitry Andric } 4143f22ef01cSRoman Divacky InstructionList.push_back(I); 4144f22ef01cSRoman Divacky break; 4145f22ef01cSRoman Divacky } 4146ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4147ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP_OLD: 4148ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4149f22ef01cSRoman Divacky unsigned OpNum = 0; 4150ff0cc061SDimitry Andric 4151ff0cc061SDimitry Andric Type *Ty; 4152ff0cc061SDimitry Andric bool InBounds; 4153ff0cc061SDimitry Andric 4154ff0cc061SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4155ff0cc061SDimitry Andric InBounds = Record[OpNum++]; 4156ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 4157ff0cc061SDimitry Andric } else { 4158ff0cc061SDimitry Andric InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4159ff0cc061SDimitry Andric Ty = nullptr; 4160ff0cc061SDimitry Andric } 4161ff0cc061SDimitry Andric 4162f22ef01cSRoman Divacky Value *BasePtr; 4163f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 41648f0fd8f6SDimitry Andric return error("Invalid record"); 4165f22ef01cSRoman Divacky 4166ff0cc061SDimitry Andric if (!Ty) 4167ff0cc061SDimitry Andric Ty = cast<SequentialType>(BasePtr->getType()->getScalarType()) 4168ff0cc061SDimitry Andric ->getElementType(); 4169ff0cc061SDimitry Andric else if (Ty != 4170ff0cc061SDimitry Andric cast<SequentialType>(BasePtr->getType()->getScalarType()) 4171ff0cc061SDimitry Andric ->getElementType()) 41728f0fd8f6SDimitry Andric return error( 4173ff0cc061SDimitry Andric "Explicit gep type does not match pointee type of pointer operand"); 4174ff0cc061SDimitry Andric 4175f22ef01cSRoman Divacky SmallVector<Value*, 16> GEPIdx; 4176f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4177f22ef01cSRoman Divacky Value *Op; 4178f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 41798f0fd8f6SDimitry Andric return error("Invalid record"); 4180f22ef01cSRoman Divacky GEPIdx.push_back(Op); 4181f22ef01cSRoman Divacky } 4182f22ef01cSRoman Divacky 4183ff0cc061SDimitry Andric I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4184ff0cc061SDimitry Andric 4185f22ef01cSRoman Divacky InstructionList.push_back(I); 4186ff0cc061SDimitry Andric if (InBounds) 4187f22ef01cSRoman Divacky cast<GetElementPtrInst>(I)->setIsInBounds(true); 4188f22ef01cSRoman Divacky break; 4189f22ef01cSRoman Divacky } 4190f22ef01cSRoman Divacky 4191f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4192f22ef01cSRoman Divacky // EXTRACTVAL: [opty, opval, n x indices] 4193f22ef01cSRoman Divacky unsigned OpNum = 0; 4194f22ef01cSRoman Divacky Value *Agg; 4195f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 41968f0fd8f6SDimitry Andric return error("Invalid record"); 4197f22ef01cSRoman Divacky 4198ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 4199ff0cc061SDimitry Andric if (OpNum == RecSize) 42008f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4201ff0cc061SDimitry Andric 4202f22ef01cSRoman Divacky SmallVector<unsigned, 4> EXTRACTVALIdx; 4203ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 4204ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 4205ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 4206ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 4207f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 4208ff0cc061SDimitry Andric 4209ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 42108f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid type"); 4211f22ef01cSRoman Divacky if ((unsigned)Index != Index) 42128f0fd8f6SDimitry Andric return error("Invalid value"); 4213ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 42148f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid struct index"); 4215ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 42168f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid array index"); 4217f22ef01cSRoman Divacky EXTRACTVALIdx.push_back((unsigned)Index); 4218ff0cc061SDimitry Andric 4219ff0cc061SDimitry Andric if (IsStruct) 4220ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 4221ff0cc061SDimitry Andric else 4222ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 4223f22ef01cSRoman Divacky } 4224f22ef01cSRoman Divacky 422517a519f9SDimitry Andric I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 4226f22ef01cSRoman Divacky InstructionList.push_back(I); 4227f22ef01cSRoman Divacky break; 4228f22ef01cSRoman Divacky } 4229f22ef01cSRoman Divacky 4230f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTVAL: { 4231f22ef01cSRoman Divacky // INSERTVAL: [opty, opval, opty, opval, n x indices] 4232f22ef01cSRoman Divacky unsigned OpNum = 0; 4233f22ef01cSRoman Divacky Value *Agg; 4234f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 42358f0fd8f6SDimitry Andric return error("Invalid record"); 4236f22ef01cSRoman Divacky Value *Val; 4237f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 42388f0fd8f6SDimitry Andric return error("Invalid record"); 4239f22ef01cSRoman Divacky 4240ff0cc061SDimitry Andric unsigned RecSize = Record.size(); 4241ff0cc061SDimitry Andric if (OpNum == RecSize) 42428f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid instruction with 0 indices"); 4243ff0cc061SDimitry Andric 4244f22ef01cSRoman Divacky SmallVector<unsigned, 4> INSERTVALIdx; 4245ff0cc061SDimitry Andric Type *CurTy = Agg->getType(); 4246ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) { 4247ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy(); 4248ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy(); 4249f22ef01cSRoman Divacky uint64_t Index = Record[OpNum]; 4250ff0cc061SDimitry Andric 4251ff0cc061SDimitry Andric if (!IsStruct && !IsArray) 42528f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid type"); 4253f22ef01cSRoman Divacky if ((unsigned)Index != Index) 42548f0fd8f6SDimitry Andric return error("Invalid value"); 4255ff0cc061SDimitry Andric if (IsStruct && Index >= CurTy->subtypes().size()) 42568f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid struct index"); 4257ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements()) 42588f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid array index"); 4259ff0cc061SDimitry Andric 4260f22ef01cSRoman Divacky INSERTVALIdx.push_back((unsigned)Index); 4261ff0cc061SDimitry Andric if (IsStruct) 4262ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[Index]; 4263ff0cc061SDimitry Andric else 4264ff0cc061SDimitry Andric CurTy = CurTy->subtypes()[0]; 4265f22ef01cSRoman Divacky } 4266f22ef01cSRoman Divacky 4267ff0cc061SDimitry Andric if (CurTy != Val->getType()) 42688f0fd8f6SDimitry Andric return error("Inserted value type doesn't match aggregate type"); 4269ff0cc061SDimitry Andric 427017a519f9SDimitry Andric I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 4271f22ef01cSRoman Divacky InstructionList.push_back(I); 4272f22ef01cSRoman Divacky break; 4273f22ef01cSRoman Divacky } 4274f22ef01cSRoman Divacky 4275f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 4276f22ef01cSRoman Divacky // obsolete form of select 4277f22ef01cSRoman Divacky // handles select i1 ... in old bitcode 4278f22ef01cSRoman Divacky unsigned OpNum = 0; 4279f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 4280f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 42813861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 42823861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 42838f0fd8f6SDimitry Andric return error("Invalid record"); 4284f22ef01cSRoman Divacky 4285f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 4286f22ef01cSRoman Divacky InstructionList.push_back(I); 4287f22ef01cSRoman Divacky break; 4288f22ef01cSRoman Divacky } 4289f22ef01cSRoman Divacky 4290f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 4291f22ef01cSRoman Divacky // new form of select 4292f22ef01cSRoman Divacky // handles select i1 or select [N x i1] 4293f22ef01cSRoman Divacky unsigned OpNum = 0; 4294f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond; 4295f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 42963861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4297f22ef01cSRoman Divacky getValueTypePair(Record, OpNum, NextValueNo, Cond)) 42988f0fd8f6SDimitry Andric return error("Invalid record"); 4299f22ef01cSRoman Divacky 4300f22ef01cSRoman Divacky // select condition can be either i1 or [N x i1] 43016122f3e6SDimitry Andric if (VectorType* vector_type = 43026122f3e6SDimitry Andric dyn_cast<VectorType>(Cond->getType())) { 4303f22ef01cSRoman Divacky // expect <n x i1> 4304f22ef01cSRoman Divacky if (vector_type->getElementType() != Type::getInt1Ty(Context)) 43058f0fd8f6SDimitry Andric return error("Invalid type for value"); 4306f22ef01cSRoman Divacky } else { 4307f22ef01cSRoman Divacky // expect i1 4308f22ef01cSRoman Divacky if (Cond->getType() != Type::getInt1Ty(Context)) 43098f0fd8f6SDimitry Andric return error("Invalid type for value"); 4310f22ef01cSRoman Divacky } 4311f22ef01cSRoman Divacky 4312f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal); 4313f22ef01cSRoman Divacky InstructionList.push_back(I); 4314f22ef01cSRoman Divacky break; 4315f22ef01cSRoman Divacky } 4316f22ef01cSRoman Divacky 4317f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 4318f22ef01cSRoman Divacky unsigned OpNum = 0; 4319f22ef01cSRoman Divacky Value *Vec, *Idx; 4320f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 432191bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 43228f0fd8f6SDimitry Andric return error("Invalid record"); 4323ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 43248f0fd8f6SDimitry Andric return error("Invalid type for value"); 4325f22ef01cSRoman Divacky I = ExtractElementInst::Create(Vec, Idx); 4326f22ef01cSRoman Divacky InstructionList.push_back(I); 4327f22ef01cSRoman Divacky break; 4328f22ef01cSRoman Divacky } 4329f22ef01cSRoman Divacky 4330f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 4331f22ef01cSRoman Divacky unsigned OpNum = 0; 4332f22ef01cSRoman Divacky Value *Vec, *Elt, *Idx; 4333ff0cc061SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 43348f0fd8f6SDimitry Andric return error("Invalid record"); 4335ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy()) 43368f0fd8f6SDimitry Andric return error("Invalid type for value"); 4337ff0cc061SDimitry Andric if (popValue(Record, OpNum, NextValueNo, 4338f22ef01cSRoman Divacky cast<VectorType>(Vec->getType())->getElementType(), Elt) || 433991bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx)) 43408f0fd8f6SDimitry Andric return error("Invalid record"); 4341f22ef01cSRoman Divacky I = InsertElementInst::Create(Vec, Elt, Idx); 4342f22ef01cSRoman Divacky InstructionList.push_back(I); 4343f22ef01cSRoman Divacky break; 4344f22ef01cSRoman Divacky } 4345f22ef01cSRoman Divacky 4346f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 4347f22ef01cSRoman Divacky unsigned OpNum = 0; 4348f22ef01cSRoman Divacky Value *Vec1, *Vec2, *Mask; 4349f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 43503861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 43518f0fd8f6SDimitry Andric return error("Invalid record"); 4352f22ef01cSRoman Divacky 4353f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 43548f0fd8f6SDimitry Andric return error("Invalid record"); 4355ff0cc061SDimitry Andric if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 43568f0fd8f6SDimitry Andric return error("Invalid type for value"); 4357f22ef01cSRoman Divacky I = new ShuffleVectorInst(Vec1, Vec2, Mask); 4358f22ef01cSRoman Divacky InstructionList.push_back(I); 4359f22ef01cSRoman Divacky break; 4360f22ef01cSRoman Divacky } 4361f22ef01cSRoman Divacky 4362f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 4363f22ef01cSRoman Divacky // Old form of ICmp/FCmp returning bool 4364f22ef01cSRoman Divacky // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 4365f22ef01cSRoman Divacky // both legal on vectors but had different behaviour. 4366f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 4367f22ef01cSRoman Divacky // FCmp/ICmp returning bool or vector of bool 4368f22ef01cSRoman Divacky 4369f22ef01cSRoman Divacky unsigned OpNum = 0; 4370f22ef01cSRoman Divacky Value *LHS, *RHS; 4371f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4372875ed548SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 4373875ed548SDimitry Andric return error("Invalid record"); 4374875ed548SDimitry Andric 4375875ed548SDimitry Andric unsigned PredVal = Record[OpNum]; 4376875ed548SDimitry Andric bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 4377875ed548SDimitry Andric FastMathFlags FMF; 4378875ed548SDimitry Andric if (IsFP && Record.size() > OpNum+1) 4379875ed548SDimitry Andric FMF = getDecodedFastMathFlags(Record[++OpNum]); 4380875ed548SDimitry Andric 4381875ed548SDimitry Andric if (OpNum+1 != Record.size()) 43828f0fd8f6SDimitry Andric return error("Invalid record"); 4383f22ef01cSRoman Divacky 4384f22ef01cSRoman Divacky if (LHS->getType()->isFPOrFPVectorTy()) 4385875ed548SDimitry Andric I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 4386f22ef01cSRoman Divacky else 4387875ed548SDimitry Andric I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 4388875ed548SDimitry Andric 4389875ed548SDimitry Andric if (FMF.any()) 4390875ed548SDimitry Andric I->setFastMathFlags(FMF); 4391f22ef01cSRoman Divacky InstructionList.push_back(I); 4392f22ef01cSRoman Divacky break; 4393f22ef01cSRoman Divacky } 4394f22ef01cSRoman Divacky 4395f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 4396f22ef01cSRoman Divacky { 4397f22ef01cSRoman Divacky unsigned Size = Record.size(); 4398f22ef01cSRoman Divacky if (Size == 0) { 4399f22ef01cSRoman Divacky I = ReturnInst::Create(Context); 4400f22ef01cSRoman Divacky InstructionList.push_back(I); 4401f22ef01cSRoman Divacky break; 4402f22ef01cSRoman Divacky } 4403f22ef01cSRoman Divacky 4404f22ef01cSRoman Divacky unsigned OpNum = 0; 440591bc56edSDimitry Andric Value *Op = nullptr; 4406f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 44078f0fd8f6SDimitry Andric return error("Invalid record"); 440817a519f9SDimitry Andric if (OpNum != Record.size()) 44098f0fd8f6SDimitry Andric return error("Invalid record"); 4410f22ef01cSRoman Divacky 441117a519f9SDimitry Andric I = ReturnInst::Create(Context, Op); 4412f22ef01cSRoman Divacky InstructionList.push_back(I); 4413f22ef01cSRoman Divacky break; 4414f22ef01cSRoman Divacky } 4415f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 4416f22ef01cSRoman Divacky if (Record.size() != 1 && Record.size() != 3) 44178f0fd8f6SDimitry Andric return error("Invalid record"); 4418f22ef01cSRoman Divacky BasicBlock *TrueDest = getBasicBlock(Record[0]); 441991bc56edSDimitry Andric if (!TrueDest) 44208f0fd8f6SDimitry Andric return error("Invalid record"); 4421f22ef01cSRoman Divacky 4422f22ef01cSRoman Divacky if (Record.size() == 1) { 4423f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest); 4424f22ef01cSRoman Divacky InstructionList.push_back(I); 4425f22ef01cSRoman Divacky } 4426f22ef01cSRoman Divacky else { 4427f22ef01cSRoman Divacky BasicBlock *FalseDest = getBasicBlock(Record[1]); 44283861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, 44293861d79fSDimitry Andric Type::getInt1Ty(Context)); 443091bc56edSDimitry Andric if (!FalseDest || !Cond) 44318f0fd8f6SDimitry Andric return error("Invalid record"); 4432f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest, FalseDest, Cond); 4433f22ef01cSRoman Divacky InstructionList.push_back(I); 4434f22ef01cSRoman Divacky } 4435f22ef01cSRoman Divacky break; 4436f22ef01cSRoman Divacky } 44377d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 44387d523365SDimitry Andric if (Record.size() != 1 && Record.size() != 2) 44397d523365SDimitry Andric return error("Invalid record"); 44407d523365SDimitry Andric unsigned Idx = 0; 44417d523365SDimitry Andric Value *CleanupPad = 44427d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 44437d523365SDimitry Andric if (!CleanupPad) 44447d523365SDimitry Andric return error("Invalid record"); 44457d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 44467d523365SDimitry Andric if (Record.size() == 2) { 44477d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 44487d523365SDimitry Andric if (!UnwindDest) 44497d523365SDimitry Andric return error("Invalid record"); 44507d523365SDimitry Andric } 44517d523365SDimitry Andric 44527d523365SDimitry Andric I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 44537d523365SDimitry Andric InstructionList.push_back(I); 44547d523365SDimitry Andric break; 44557d523365SDimitry Andric } 44567d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 44577d523365SDimitry Andric if (Record.size() != 2) 44587d523365SDimitry Andric return error("Invalid record"); 44597d523365SDimitry Andric unsigned Idx = 0; 44607d523365SDimitry Andric Value *CatchPad = 44617d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 44627d523365SDimitry Andric if (!CatchPad) 44637d523365SDimitry Andric return error("Invalid record"); 44647d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 44657d523365SDimitry Andric if (!BB) 44667d523365SDimitry Andric return error("Invalid record"); 44677d523365SDimitry Andric 44687d523365SDimitry Andric I = CatchReturnInst::Create(CatchPad, BB); 44697d523365SDimitry Andric InstructionList.push_back(I); 44707d523365SDimitry Andric break; 44717d523365SDimitry Andric } 44727d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 44737d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 44747d523365SDimitry Andric if (Record.size() < 2) 44757d523365SDimitry Andric return error("Invalid record"); 44767d523365SDimitry Andric 44777d523365SDimitry Andric unsigned Idx = 0; 44787d523365SDimitry Andric 44797d523365SDimitry Andric Value *ParentPad = 44807d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 44817d523365SDimitry Andric 44827d523365SDimitry Andric unsigned NumHandlers = Record[Idx++]; 44837d523365SDimitry Andric 44847d523365SDimitry Andric SmallVector<BasicBlock *, 2> Handlers; 44857d523365SDimitry Andric for (unsigned Op = 0; Op != NumHandlers; ++Op) { 44867d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]); 44877d523365SDimitry Andric if (!BB) 44887d523365SDimitry Andric return error("Invalid record"); 44897d523365SDimitry Andric Handlers.push_back(BB); 44907d523365SDimitry Andric } 44917d523365SDimitry Andric 44927d523365SDimitry Andric BasicBlock *UnwindDest = nullptr; 44937d523365SDimitry Andric if (Idx + 1 == Record.size()) { 44947d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]); 44957d523365SDimitry Andric if (!UnwindDest) 44967d523365SDimitry Andric return error("Invalid record"); 44977d523365SDimitry Andric } 44987d523365SDimitry Andric 44997d523365SDimitry Andric if (Record.size() != Idx) 45007d523365SDimitry Andric return error("Invalid record"); 45017d523365SDimitry Andric 45027d523365SDimitry Andric auto *CatchSwitch = 45037d523365SDimitry Andric CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 45047d523365SDimitry Andric for (BasicBlock *Handler : Handlers) 45057d523365SDimitry Andric CatchSwitch->addHandler(Handler); 45067d523365SDimitry Andric I = CatchSwitch; 45077d523365SDimitry Andric InstructionList.push_back(I); 45087d523365SDimitry Andric break; 45097d523365SDimitry Andric } 45107d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHPAD: 45117d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 45127d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments. 45137d523365SDimitry Andric if (Record.size() < 2) 45147d523365SDimitry Andric return error("Invalid record"); 45157d523365SDimitry Andric 45167d523365SDimitry Andric unsigned Idx = 0; 45177d523365SDimitry Andric 45187d523365SDimitry Andric Value *ParentPad = 45197d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 45207d523365SDimitry Andric 45217d523365SDimitry Andric unsigned NumArgOperands = Record[Idx++]; 45227d523365SDimitry Andric 45237d523365SDimitry Andric SmallVector<Value *, 2> Args; 45247d523365SDimitry Andric for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 45257d523365SDimitry Andric Value *Val; 45267d523365SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 45277d523365SDimitry Andric return error("Invalid record"); 45287d523365SDimitry Andric Args.push_back(Val); 45297d523365SDimitry Andric } 45307d523365SDimitry Andric 45317d523365SDimitry Andric if (Record.size() != Idx) 45327d523365SDimitry Andric return error("Invalid record"); 45337d523365SDimitry Andric 45347d523365SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 45357d523365SDimitry Andric I = CleanupPadInst::Create(ParentPad, Args); 45367d523365SDimitry Andric else 45377d523365SDimitry Andric I = CatchPadInst::Create(ParentPad, Args); 45387d523365SDimitry Andric InstructionList.push_back(I); 45397d523365SDimitry Andric break; 45407d523365SDimitry Andric } 4541f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 45427ae0e2c9SDimitry Andric // Check magic 45437ae0e2c9SDimitry Andric if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 4544f785676fSDimitry Andric // "New" SwitchInst format with case ranges. The changes to write this 4545f785676fSDimitry Andric // format were reverted but we still recognize bitcode that uses it. 4546f785676fSDimitry Andric // Hopefully someday we will have support for case ranges and can use 4547f785676fSDimitry Andric // this format again. 45487ae0e2c9SDimitry Andric 45497ae0e2c9SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 45507ae0e2c9SDimitry Andric unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 45517ae0e2c9SDimitry Andric 45523861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 45537ae0e2c9SDimitry Andric BasicBlock *Default = getBasicBlock(Record[3]); 455491bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 45558f0fd8f6SDimitry Andric return error("Invalid record"); 45567ae0e2c9SDimitry Andric 45577ae0e2c9SDimitry Andric unsigned NumCases = Record[4]; 45587ae0e2c9SDimitry Andric 45597ae0e2c9SDimitry Andric SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 45607ae0e2c9SDimitry Andric InstructionList.push_back(SI); 45617ae0e2c9SDimitry Andric 45627ae0e2c9SDimitry Andric unsigned CurIdx = 5; 45637ae0e2c9SDimitry Andric for (unsigned i = 0; i != NumCases; ++i) { 4564f785676fSDimitry Andric SmallVector<ConstantInt*, 1> CaseVals; 45657ae0e2c9SDimitry Andric unsigned NumItems = Record[CurIdx++]; 45667ae0e2c9SDimitry Andric for (unsigned ci = 0; ci != NumItems; ++ci) { 45677ae0e2c9SDimitry Andric bool isSingleNumber = Record[CurIdx++]; 45687ae0e2c9SDimitry Andric 45697ae0e2c9SDimitry Andric APInt Low; 45707ae0e2c9SDimitry Andric unsigned ActiveWords = 1; 45717ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 45727ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 45738f0fd8f6SDimitry Andric Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 45747ae0e2c9SDimitry Andric ValueBitWidth); 45757ae0e2c9SDimitry Andric CurIdx += ActiveWords; 45767ae0e2c9SDimitry Andric 45777ae0e2c9SDimitry Andric if (!isSingleNumber) { 45787ae0e2c9SDimitry Andric ActiveWords = 1; 45797ae0e2c9SDimitry Andric if (ValueBitWidth > 64) 45807ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++]; 45818f0fd8f6SDimitry Andric APInt High = readWideAPInt( 45828f0fd8f6SDimitry Andric makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 45837ae0e2c9SDimitry Andric CurIdx += ActiveWords; 4584f785676fSDimitry Andric 4585f785676fSDimitry Andric // FIXME: It is not clear whether values in the range should be 4586f785676fSDimitry Andric // compared as signed or unsigned values. The partially 4587f785676fSDimitry Andric // implemented changes that used this format in the past used 4588f785676fSDimitry Andric // unsigned comparisons. 4589f785676fSDimitry Andric for ( ; Low.ule(High); ++Low) 4590f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 45917ae0e2c9SDimitry Andric } else 4592f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low)); 45937ae0e2c9SDimitry Andric } 45947ae0e2c9SDimitry Andric BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 4595f785676fSDimitry Andric for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 4596f785676fSDimitry Andric cve = CaseVals.end(); cvi != cve; ++cvi) 4597f785676fSDimitry Andric SI->addCase(*cvi, DestBB); 45987ae0e2c9SDimitry Andric } 45997ae0e2c9SDimitry Andric I = SI; 46007ae0e2c9SDimitry Andric break; 46017ae0e2c9SDimitry Andric } 46027ae0e2c9SDimitry Andric 46037ae0e2c9SDimitry Andric // Old SwitchInst format without case ranges. 46047ae0e2c9SDimitry Andric 4605f22ef01cSRoman Divacky if (Record.size() < 3 || (Record.size() & 1) == 0) 46068f0fd8f6SDimitry Andric return error("Invalid record"); 46076122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 46083861d79fSDimitry Andric Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 4609f22ef01cSRoman Divacky BasicBlock *Default = getBasicBlock(Record[2]); 461091bc56edSDimitry Andric if (!OpTy || !Cond || !Default) 46118f0fd8f6SDimitry Andric return error("Invalid record"); 4612f22ef01cSRoman Divacky unsigned NumCases = (Record.size()-3)/2; 4613f22ef01cSRoman Divacky SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4614f22ef01cSRoman Divacky InstructionList.push_back(SI); 4615f22ef01cSRoman Divacky for (unsigned i = 0, e = NumCases; i != e; ++i) { 4616f22ef01cSRoman Divacky ConstantInt *CaseVal = 4617f22ef01cSRoman Divacky dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 4618f22ef01cSRoman Divacky BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 461991bc56edSDimitry Andric if (!CaseVal || !DestBB) { 4620f22ef01cSRoman Divacky delete SI; 46218f0fd8f6SDimitry Andric return error("Invalid record"); 4622f22ef01cSRoman Divacky } 4623f22ef01cSRoman Divacky SI->addCase(CaseVal, DestBB); 4624f22ef01cSRoman Divacky } 4625f22ef01cSRoman Divacky I = SI; 4626f22ef01cSRoman Divacky break; 4627f22ef01cSRoman Divacky } 4628f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4629f22ef01cSRoman Divacky if (Record.size() < 2) 46308f0fd8f6SDimitry Andric return error("Invalid record"); 46316122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 46323861d79fSDimitry Andric Value *Address = getValue(Record, 1, NextValueNo, OpTy); 463391bc56edSDimitry Andric if (!OpTy || !Address) 46348f0fd8f6SDimitry Andric return error("Invalid record"); 4635f22ef01cSRoman Divacky unsigned NumDests = Record.size()-2; 4636f22ef01cSRoman Divacky IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4637f22ef01cSRoman Divacky InstructionList.push_back(IBI); 4638f22ef01cSRoman Divacky for (unsigned i = 0, e = NumDests; i != e; ++i) { 4639f22ef01cSRoman Divacky if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4640f22ef01cSRoman Divacky IBI->addDestination(DestBB); 4641f22ef01cSRoman Divacky } else { 4642f22ef01cSRoman Divacky delete IBI; 46438f0fd8f6SDimitry Andric return error("Invalid record"); 4644f22ef01cSRoman Divacky } 4645f22ef01cSRoman Divacky } 4646f22ef01cSRoman Divacky I = IBI; 4647f22ef01cSRoman Divacky break; 4648f22ef01cSRoman Divacky } 4649f22ef01cSRoman Divacky 4650f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INVOKE: { 4651f22ef01cSRoman Divacky // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4652f785676fSDimitry Andric if (Record.size() < 4) 46538f0fd8f6SDimitry Andric return error("Invalid record"); 4654ff0cc061SDimitry Andric unsigned OpNum = 0; 4655ff0cc061SDimitry Andric AttributeSet PAL = getAttributes(Record[OpNum++]); 4656ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 4657ff0cc061SDimitry Andric BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4658ff0cc061SDimitry Andric BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4659f22ef01cSRoman Divacky 4660ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 4661ff0cc061SDimitry Andric if (CCInfo >> 13 & 1 && 4662ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 46638f0fd8f6SDimitry Andric return error("Explicit invoke type is not a function type"); 4664ff0cc061SDimitry Andric 4665f22ef01cSRoman Divacky Value *Callee; 4666f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 46678f0fd8f6SDimitry Andric return error("Invalid record"); 4668f22ef01cSRoman Divacky 46696122f3e6SDimitry Andric PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4670ff0cc061SDimitry Andric if (!CalleeTy) 46718f0fd8f6SDimitry Andric return error("Callee is not a pointer"); 4672ff0cc061SDimitry Andric if (!FTy) { 4673ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 4674ff0cc061SDimitry Andric if (!FTy) 46758f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 4676ff0cc061SDimitry Andric } else if (CalleeTy->getElementType() != FTy) 46778f0fd8f6SDimitry Andric return error("Explicit invoke type does not match pointee type of " 4678ff0cc061SDimitry Andric "callee operand"); 4679ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 46808f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 4681f22ef01cSRoman Divacky 4682f22ef01cSRoman Divacky SmallVector<Value*, 16> Ops; 4683f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 46843861d79fSDimitry Andric Ops.push_back(getValue(Record, OpNum, NextValueNo, 46853861d79fSDimitry Andric FTy->getParamType(i))); 468691bc56edSDimitry Andric if (!Ops.back()) 46878f0fd8f6SDimitry Andric return error("Invalid record"); 4688f22ef01cSRoman Divacky } 4689f22ef01cSRoman Divacky 4690f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 4691f22ef01cSRoman Divacky if (Record.size() != OpNum) 46928f0fd8f6SDimitry Andric return error("Invalid record"); 4693f22ef01cSRoman Divacky } else { 4694f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 4695f22ef01cSRoman Divacky while (OpNum != Record.size()) { 4696f22ef01cSRoman Divacky Value *Op; 4697f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 46988f0fd8f6SDimitry Andric return error("Invalid record"); 4699f22ef01cSRoman Divacky Ops.push_back(Op); 4700f22ef01cSRoman Divacky } 4701f22ef01cSRoman Divacky } 4702f22ef01cSRoman Divacky 47037d523365SDimitry Andric I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 47047d523365SDimitry Andric OperandBundles.clear(); 4705f22ef01cSRoman Divacky InstructionList.push_back(I); 47067d523365SDimitry Andric cast<InvokeInst>(I)->setCallingConv( 47077d523365SDimitry Andric static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 4708f22ef01cSRoman Divacky cast<InvokeInst>(I)->setAttributes(PAL); 4709f22ef01cSRoman Divacky break; 4710f22ef01cSRoman Divacky } 47116122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 47126122f3e6SDimitry Andric unsigned Idx = 0; 471391bc56edSDimitry Andric Value *Val = nullptr; 47146122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) 47158f0fd8f6SDimitry Andric return error("Invalid record"); 47166122f3e6SDimitry Andric I = ResumeInst::Create(Val); 47176122f3e6SDimitry Andric InstructionList.push_back(I); 47186122f3e6SDimitry Andric break; 47196122f3e6SDimitry Andric } 4720f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4721f22ef01cSRoman Divacky I = new UnreachableInst(Context); 4722f22ef01cSRoman Divacky InstructionList.push_back(I); 4723f22ef01cSRoman Divacky break; 4724f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4725f22ef01cSRoman Divacky if (Record.size() < 1 || ((Record.size()-1)&1)) 47268f0fd8f6SDimitry Andric return error("Invalid record"); 47276122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4728f785676fSDimitry Andric if (!Ty) 47298f0fd8f6SDimitry Andric return error("Invalid record"); 4730f22ef01cSRoman Divacky 47313b0f4066SDimitry Andric PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 4732f22ef01cSRoman Divacky InstructionList.push_back(PN); 4733f22ef01cSRoman Divacky 4734f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 47353861d79fSDimitry Andric Value *V; 47363861d79fSDimitry Andric // With the new function encoding, it is possible that operands have 47373861d79fSDimitry Andric // negative IDs (for forward references). Use a signed VBR 47383861d79fSDimitry Andric // representation to keep the encoding small. 47393861d79fSDimitry Andric if (UseRelativeIDs) 47403861d79fSDimitry Andric V = getValueSigned(Record, 1+i, NextValueNo, Ty); 47413861d79fSDimitry Andric else 47423861d79fSDimitry Andric V = getValue(Record, 1+i, NextValueNo, Ty); 4743f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[2+i]); 4744f785676fSDimitry Andric if (!V || !BB) 47458f0fd8f6SDimitry Andric return error("Invalid record"); 4746f22ef01cSRoman Divacky PN->addIncoming(V, BB); 4747f22ef01cSRoman Divacky } 4748f22ef01cSRoman Divacky I = PN; 4749f22ef01cSRoman Divacky break; 4750f22ef01cSRoman Divacky } 4751f22ef01cSRoman Divacky 47528f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD: 47538f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 47546122f3e6SDimitry Andric // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 47556122f3e6SDimitry Andric unsigned Idx = 0; 47568f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 47578f0fd8f6SDimitry Andric if (Record.size() < 3) 47588f0fd8f6SDimitry Andric return error("Invalid record"); 47598f0fd8f6SDimitry Andric } else { 47608f0fd8f6SDimitry Andric assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 47616122f3e6SDimitry Andric if (Record.size() < 4) 47628f0fd8f6SDimitry Andric return error("Invalid record"); 47638f0fd8f6SDimitry Andric } 47646122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[Idx++]); 4765f785676fSDimitry Andric if (!Ty) 47668f0fd8f6SDimitry Andric return error("Invalid record"); 47678f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 476891bc56edSDimitry Andric Value *PersFn = nullptr; 47696122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 47708f0fd8f6SDimitry Andric return error("Invalid record"); 47718f0fd8f6SDimitry Andric 47728f0fd8f6SDimitry Andric if (!F->hasPersonalityFn()) 47738f0fd8f6SDimitry Andric F->setPersonalityFn(cast<Constant>(PersFn)); 47748f0fd8f6SDimitry Andric else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 47758f0fd8f6SDimitry Andric return error("Personality function mismatch"); 47768f0fd8f6SDimitry Andric } 47776122f3e6SDimitry Andric 47786122f3e6SDimitry Andric bool IsCleanup = !!Record[Idx++]; 47796122f3e6SDimitry Andric unsigned NumClauses = Record[Idx++]; 47808f0fd8f6SDimitry Andric LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 47816122f3e6SDimitry Andric LP->setCleanup(IsCleanup); 47826122f3e6SDimitry Andric for (unsigned J = 0; J != NumClauses; ++J) { 47836122f3e6SDimitry Andric LandingPadInst::ClauseType CT = 47846122f3e6SDimitry Andric LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 47856122f3e6SDimitry Andric Value *Val; 47866122f3e6SDimitry Andric 47876122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 47886122f3e6SDimitry Andric delete LP; 47898f0fd8f6SDimitry Andric return error("Invalid record"); 47906122f3e6SDimitry Andric } 47916122f3e6SDimitry Andric 47926122f3e6SDimitry Andric assert((CT != LandingPadInst::Catch || 47936122f3e6SDimitry Andric !isa<ArrayType>(Val->getType())) && 47946122f3e6SDimitry Andric "Catch clause has a invalid type!"); 47956122f3e6SDimitry Andric assert((CT != LandingPadInst::Filter || 47966122f3e6SDimitry Andric isa<ArrayType>(Val->getType())) && 47976122f3e6SDimitry Andric "Filter clause has invalid type!"); 479891bc56edSDimitry Andric LP->addClause(cast<Constant>(Val)); 47996122f3e6SDimitry Andric } 48006122f3e6SDimitry Andric 48016122f3e6SDimitry Andric I = LP; 48026122f3e6SDimitry Andric InstructionList.push_back(I); 48036122f3e6SDimitry Andric break; 48046122f3e6SDimitry Andric } 48056122f3e6SDimitry Andric 480617a519f9SDimitry Andric case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 480717a519f9SDimitry Andric if (Record.size() != 4) 48088f0fd8f6SDimitry Andric return error("Invalid record"); 4809ff0cc061SDimitry Andric uint64_t AlignRecord = Record[3]; 4810ff0cc061SDimitry Andric const uint64_t InAllocaMask = uint64_t(1) << 5; 4811ff0cc061SDimitry Andric const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 48127d523365SDimitry Andric // Reserve bit 7 for SwiftError flag. 48137d523365SDimitry Andric // const uint64_t SwiftErrorMask = uint64_t(1) << 7; 4814ff0cc061SDimitry Andric const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask; 4815ff0cc061SDimitry Andric bool InAlloca = AlignRecord & InAllocaMask; 4816ff0cc061SDimitry Andric Type *Ty = getTypeByID(Record[0]); 4817ff0cc061SDimitry Andric if ((AlignRecord & ExplicitTypeMask) == 0) { 4818ff0cc061SDimitry Andric auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4819ff0cc061SDimitry Andric if (!PTy) 48208f0fd8f6SDimitry Andric return error("Old-style alloca with a non-pointer type"); 4821ff0cc061SDimitry Andric Ty = PTy->getElementType(); 4822ff0cc061SDimitry Andric } 48236122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]); 482417a519f9SDimitry Andric Value *Size = getFnValueByID(Record[2], OpTy); 4825ff0cc061SDimitry Andric unsigned Align; 4826ff0cc061SDimitry Andric if (std::error_code EC = 4827ff0cc061SDimitry Andric parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 4828ff0cc061SDimitry Andric return EC; 4829ff0cc061SDimitry Andric } 4830f785676fSDimitry Andric if (!Ty || !Size) 48318f0fd8f6SDimitry Andric return error("Invalid record"); 4832ff0cc061SDimitry Andric AllocaInst *AI = new AllocaInst(Ty, Size, Align); 483391bc56edSDimitry Andric AI->setUsedWithInAlloca(InAlloca); 483491bc56edSDimitry Andric I = AI; 4835f22ef01cSRoman Divacky InstructionList.push_back(I); 4836f22ef01cSRoman Divacky break; 4837f22ef01cSRoman Divacky } 4838f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4839f22ef01cSRoman Divacky unsigned OpNum = 0; 4840f22ef01cSRoman Divacky Value *Op; 4841f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4842ff0cc061SDimitry Andric (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 48438f0fd8f6SDimitry Andric return error("Invalid record"); 4844f22ef01cSRoman Divacky 4845ff0cc061SDimitry Andric Type *Ty = nullptr; 4846ff0cc061SDimitry Andric if (OpNum + 3 == Record.size()) 4847ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 48487d523365SDimitry Andric if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType())) 4849ff0cc061SDimitry Andric return EC; 4850ff0cc061SDimitry Andric if (!Ty) 4851ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4852ff0cc061SDimitry Andric 4853ff0cc061SDimitry Andric unsigned Align; 4854ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4855ff0cc061SDimitry Andric return EC; 4856ff0cc061SDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 4857ff0cc061SDimitry Andric 4858f22ef01cSRoman Divacky InstructionList.push_back(I); 4859f22ef01cSRoman Divacky break; 4860f22ef01cSRoman Divacky } 48616122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_LOADATOMIC: { 48626122f3e6SDimitry Andric // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 48636122f3e6SDimitry Andric unsigned OpNum = 0; 48646122f3e6SDimitry Andric Value *Op; 48656122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4866ff0cc061SDimitry Andric (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 48678f0fd8f6SDimitry Andric return error("Invalid record"); 48686122f3e6SDimitry Andric 4869ff0cc061SDimitry Andric Type *Ty = nullptr; 4870ff0cc061SDimitry Andric if (OpNum + 5 == Record.size()) 4871ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]); 48727d523365SDimitry Andric if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType())) 4873ff0cc061SDimitry Andric return EC; 4874ff0cc061SDimitry Andric if (!Ty) 4875ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType(); 4876ff0cc061SDimitry Andric 48778f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 48786122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Release || 48796122f3e6SDimitry Andric Ordering == AcquireRelease) 48808f0fd8f6SDimitry Andric return error("Invalid record"); 48816122f3e6SDimitry Andric if (Ordering != NotAtomic && Record[OpNum] == 0) 48828f0fd8f6SDimitry Andric return error("Invalid record"); 48838f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 48846122f3e6SDimitry Andric 4885ff0cc061SDimitry Andric unsigned Align; 4886ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4887ff0cc061SDimitry Andric return EC; 4888ff0cc061SDimitry Andric I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope); 4889ff0cc061SDimitry Andric 48906122f3e6SDimitry Andric InstructionList.push_back(I); 48916122f3e6SDimitry Andric break; 48926122f3e6SDimitry Andric } 4893ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE: 4894ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 4895f22ef01cSRoman Divacky unsigned OpNum = 0; 4896f22ef01cSRoman Divacky Value *Val, *Ptr; 4897f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4898ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STORE 4899ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4900ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4901ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4902ff0cc061SDimitry Andric Val)) || 4903f22ef01cSRoman Divacky OpNum + 2 != Record.size()) 49048f0fd8f6SDimitry Andric return error("Invalid record"); 4905f22ef01cSRoman Divacky 49067d523365SDimitry Andric if (std::error_code EC = 49077d523365SDimitry Andric typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4908ff0cc061SDimitry Andric return EC; 4909ff0cc061SDimitry Andric unsigned Align; 4910ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4911ff0cc061SDimitry Andric return EC; 4912ff0cc061SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 4913f22ef01cSRoman Divacky InstructionList.push_back(I); 4914f22ef01cSRoman Divacky break; 4915f22ef01cSRoman Divacky } 4916ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC: 4917ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 49186122f3e6SDimitry Andric // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 49196122f3e6SDimitry Andric unsigned OpNum = 0; 49206122f3e6SDimitry Andric Value *Val, *Ptr; 49216122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4922ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 4923ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4924ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4925ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4926ff0cc061SDimitry Andric Val)) || 49276122f3e6SDimitry Andric OpNum + 4 != Record.size()) 49288f0fd8f6SDimitry Andric return error("Invalid record"); 49296122f3e6SDimitry Andric 49307d523365SDimitry Andric if (std::error_code EC = 49317d523365SDimitry Andric typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4932ff0cc061SDimitry Andric return EC; 49338f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 49346122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Acquire || 49356122f3e6SDimitry Andric Ordering == AcquireRelease) 49368f0fd8f6SDimitry Andric return error("Invalid record"); 49378f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 49386122f3e6SDimitry Andric if (Ordering != NotAtomic && Record[OpNum] == 0) 49398f0fd8f6SDimitry Andric return error("Invalid record"); 49406122f3e6SDimitry Andric 4941ff0cc061SDimitry Andric unsigned Align; 4942ff0cc061SDimitry Andric if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4943ff0cc061SDimitry Andric return EC; 4944ff0cc061SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope); 49456122f3e6SDimitry Andric InstructionList.push_back(I); 49466122f3e6SDimitry Andric break; 49476122f3e6SDimitry Andric } 4948ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 49496122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG: { 495091bc56edSDimitry Andric // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 495191bc56edSDimitry Andric // failureordering?, isweak?] 49526122f3e6SDimitry Andric unsigned OpNum = 0; 49536122f3e6SDimitry Andric Value *Ptr, *Cmp, *New; 49546122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4955ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 4956ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 4957ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo, 4958ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), 4959ff0cc061SDimitry Andric Cmp)) || 4960ff0cc061SDimitry Andric popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 4961ff0cc061SDimitry Andric Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 49628f0fd8f6SDimitry Andric return error("Invalid record"); 49638f0fd8f6SDimitry Andric AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 496491bc56edSDimitry Andric if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered) 49658f0fd8f6SDimitry Andric return error("Invalid record"); 49668f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]); 496791bc56edSDimitry Andric 49687d523365SDimitry Andric if (std::error_code EC = 49697d523365SDimitry Andric typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 4970ff0cc061SDimitry Andric return EC; 497191bc56edSDimitry Andric AtomicOrdering FailureOrdering; 497291bc56edSDimitry Andric if (Record.size() < 7) 497391bc56edSDimitry Andric FailureOrdering = 497491bc56edSDimitry Andric AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 497591bc56edSDimitry Andric else 49768f0fd8f6SDimitry Andric FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 497791bc56edSDimitry Andric 497891bc56edSDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 497991bc56edSDimitry Andric SynchScope); 49806122f3e6SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 498191bc56edSDimitry Andric 498291bc56edSDimitry Andric if (Record.size() < 8) { 498391bc56edSDimitry Andric // Before weak cmpxchgs existed, the instruction simply returned the 498491bc56edSDimitry Andric // value loaded from memory, so bitcode files from that era will be 498591bc56edSDimitry Andric // expecting the first component of a modern cmpxchg. 498691bc56edSDimitry Andric CurBB->getInstList().push_back(I); 498791bc56edSDimitry Andric I = ExtractValueInst::Create(I, 0); 498891bc56edSDimitry Andric } else { 498991bc56edSDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 499091bc56edSDimitry Andric } 499191bc56edSDimitry Andric 49926122f3e6SDimitry Andric InstructionList.push_back(I); 49936122f3e6SDimitry Andric break; 49946122f3e6SDimitry Andric } 49956122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW: { 49966122f3e6SDimitry Andric // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 49976122f3e6SDimitry Andric unsigned OpNum = 0; 49986122f3e6SDimitry Andric Value *Ptr, *Val; 49996122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 50003861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, 50016122f3e6SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), Val) || 50026122f3e6SDimitry Andric OpNum+4 != Record.size()) 50038f0fd8f6SDimitry Andric return error("Invalid record"); 50048f0fd8f6SDimitry Andric AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 50056122f3e6SDimitry Andric if (Operation < AtomicRMWInst::FIRST_BINOP || 50066122f3e6SDimitry Andric Operation > AtomicRMWInst::LAST_BINOP) 50078f0fd8f6SDimitry Andric return error("Invalid record"); 50088f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 50096122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Unordered) 50108f0fd8f6SDimitry Andric return error("Invalid record"); 50118f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 50126122f3e6SDimitry Andric I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 50136122f3e6SDimitry Andric cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 50146122f3e6SDimitry Andric InstructionList.push_back(I); 50156122f3e6SDimitry Andric break; 50166122f3e6SDimitry Andric } 50176122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 50186122f3e6SDimitry Andric if (2 != Record.size()) 50198f0fd8f6SDimitry Andric return error("Invalid record"); 50208f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 50216122f3e6SDimitry Andric if (Ordering == NotAtomic || Ordering == Unordered || 50226122f3e6SDimitry Andric Ordering == Monotonic) 50238f0fd8f6SDimitry Andric return error("Invalid record"); 50248f0fd8f6SDimitry Andric SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]); 50256122f3e6SDimitry Andric I = new FenceInst(Context, Ordering, SynchScope); 50266122f3e6SDimitry Andric InstructionList.push_back(I); 50276122f3e6SDimitry Andric break; 50286122f3e6SDimitry Andric } 502917a519f9SDimitry Andric case bitc::FUNC_CODE_INST_CALL: { 50307d523365SDimitry Andric // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 5031f22ef01cSRoman Divacky if (Record.size() < 3) 50328f0fd8f6SDimitry Andric return error("Invalid record"); 5033f22ef01cSRoman Divacky 5034ff0cc061SDimitry Andric unsigned OpNum = 0; 5035ff0cc061SDimitry Andric AttributeSet PAL = getAttributes(Record[OpNum++]); 5036ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++]; 5037f22ef01cSRoman Divacky 50387d523365SDimitry Andric FastMathFlags FMF; 50397d523365SDimitry Andric if ((CCInfo >> bitc::CALL_FMF) & 1) { 50407d523365SDimitry Andric FMF = getDecodedFastMathFlags(Record[OpNum++]); 50417d523365SDimitry Andric if (!FMF.any()) 50427d523365SDimitry Andric return error("Fast math flags indicator set for call with no FMF"); 50437d523365SDimitry Andric } 50447d523365SDimitry Andric 5045ff0cc061SDimitry Andric FunctionType *FTy = nullptr; 50467d523365SDimitry Andric if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 5047ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 50488f0fd8f6SDimitry Andric return error("Explicit call type is not a function type"); 5049ff0cc061SDimitry Andric 5050f22ef01cSRoman Divacky Value *Callee; 5051f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 50528f0fd8f6SDimitry Andric return error("Invalid record"); 5053f22ef01cSRoman Divacky 50546122f3e6SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5055ff0cc061SDimitry Andric if (!OpTy) 50568f0fd8f6SDimitry Andric return error("Callee is not a pointer type"); 5057ff0cc061SDimitry Andric if (!FTy) { 5058ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 5059ff0cc061SDimitry Andric if (!FTy) 50608f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type"); 5061ff0cc061SDimitry Andric } else if (OpTy->getElementType() != FTy) 50628f0fd8f6SDimitry Andric return error("Explicit call type does not match pointee type of " 5063ff0cc061SDimitry Andric "callee operand"); 5064ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum) 50658f0fd8f6SDimitry Andric return error("Insufficient operands to call"); 5066f22ef01cSRoman Divacky 5067f22ef01cSRoman Divacky SmallVector<Value*, 16> Args; 5068f22ef01cSRoman Divacky // Read the fixed params. 5069f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 507017a519f9SDimitry Andric if (FTy->getParamType(i)->isLabelTy()) 5071f22ef01cSRoman Divacky Args.push_back(getBasicBlock(Record[OpNum])); 5072f22ef01cSRoman Divacky else 50733861d79fSDimitry Andric Args.push_back(getValue(Record, OpNum, NextValueNo, 50743861d79fSDimitry Andric FTy->getParamType(i))); 507591bc56edSDimitry Andric if (!Args.back()) 50768f0fd8f6SDimitry Andric return error("Invalid record"); 5077f22ef01cSRoman Divacky } 5078f22ef01cSRoman Divacky 5079f22ef01cSRoman Divacky // Read type/value pairs for varargs params. 5080f22ef01cSRoman Divacky if (!FTy->isVarArg()) { 5081f22ef01cSRoman Divacky if (OpNum != Record.size()) 50828f0fd8f6SDimitry Andric return error("Invalid record"); 5083f22ef01cSRoman Divacky } else { 5084f22ef01cSRoman Divacky while (OpNum != Record.size()) { 5085f22ef01cSRoman Divacky Value *Op; 5086f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 50878f0fd8f6SDimitry Andric return error("Invalid record"); 5088f22ef01cSRoman Divacky Args.push_back(Op); 5089f22ef01cSRoman Divacky } 5090f22ef01cSRoman Divacky } 5091f22ef01cSRoman Divacky 50927d523365SDimitry Andric I = CallInst::Create(FTy, Callee, Args, OperandBundles); 50937d523365SDimitry Andric OperandBundles.clear(); 5094f22ef01cSRoman Divacky InstructionList.push_back(I); 5095f22ef01cSRoman Divacky cast<CallInst>(I)->setCallingConv( 50967d523365SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 509791bc56edSDimitry Andric CallInst::TailCallKind TCK = CallInst::TCK_None; 50987d523365SDimitry Andric if (CCInfo & 1 << bitc::CALL_TAIL) 509991bc56edSDimitry Andric TCK = CallInst::TCK_Tail; 51007d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 510191bc56edSDimitry Andric TCK = CallInst::TCK_MustTail; 51027d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_NOTAIL)) 51037d523365SDimitry Andric TCK = CallInst::TCK_NoTail; 510491bc56edSDimitry Andric cast<CallInst>(I)->setTailCallKind(TCK); 5105f22ef01cSRoman Divacky cast<CallInst>(I)->setAttributes(PAL); 51067d523365SDimitry Andric if (FMF.any()) { 51077d523365SDimitry Andric if (!isa<FPMathOperator>(I)) 51087d523365SDimitry Andric return error("Fast-math-flags specified for call without " 51097d523365SDimitry Andric "floating-point scalar or vector return type"); 51107d523365SDimitry Andric I->setFastMathFlags(FMF); 51117d523365SDimitry Andric } 5112f22ef01cSRoman Divacky break; 5113f22ef01cSRoman Divacky } 5114f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 5115f22ef01cSRoman Divacky if (Record.size() < 3) 51168f0fd8f6SDimitry Andric return error("Invalid record"); 51176122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]); 51183861d79fSDimitry Andric Value *Op = getValue(Record, 1, NextValueNo, OpTy); 51196122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[2]); 5120f22ef01cSRoman Divacky if (!OpTy || !Op || !ResTy) 51218f0fd8f6SDimitry Andric return error("Invalid record"); 5122f22ef01cSRoman Divacky I = new VAArgInst(Op, ResTy); 5123f22ef01cSRoman Divacky InstructionList.push_back(I); 5124f22ef01cSRoman Divacky break; 5125f22ef01cSRoman Divacky } 51267d523365SDimitry Andric 51277d523365SDimitry Andric case bitc::FUNC_CODE_OPERAND_BUNDLE: { 51287d523365SDimitry Andric // A call or an invoke can be optionally prefixed with some variable 51297d523365SDimitry Andric // number of operand bundle blocks. These blocks are read into 51307d523365SDimitry Andric // OperandBundles and consumed at the next call or invoke instruction. 51317d523365SDimitry Andric 51327d523365SDimitry Andric if (Record.size() < 1 || Record[0] >= BundleTags.size()) 51337d523365SDimitry Andric return error("Invalid record"); 51347d523365SDimitry Andric 51357d523365SDimitry Andric std::vector<Value *> Inputs; 51367d523365SDimitry Andric 51377d523365SDimitry Andric unsigned OpNum = 1; 51387d523365SDimitry Andric while (OpNum != Record.size()) { 51397d523365SDimitry Andric Value *Op; 51407d523365SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 51417d523365SDimitry Andric return error("Invalid record"); 51427d523365SDimitry Andric Inputs.push_back(Op); 51437d523365SDimitry Andric } 51447d523365SDimitry Andric 51457d523365SDimitry Andric OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 51467d523365SDimitry Andric continue; 51477d523365SDimitry Andric } 5148f22ef01cSRoman Divacky } 5149f22ef01cSRoman Divacky 5150f22ef01cSRoman Divacky // Add instruction to end of current BB. If there is no current BB, reject 5151f22ef01cSRoman Divacky // this file. 515291bc56edSDimitry Andric if (!CurBB) { 5153f22ef01cSRoman Divacky delete I; 51548f0fd8f6SDimitry Andric return error("Invalid instruction with no BB"); 5155f22ef01cSRoman Divacky } 51567d523365SDimitry Andric if (!OperandBundles.empty()) { 51577d523365SDimitry Andric delete I; 51587d523365SDimitry Andric return error("Operand bundles found with no consumer"); 51597d523365SDimitry Andric } 5160f22ef01cSRoman Divacky CurBB->getInstList().push_back(I); 5161f22ef01cSRoman Divacky 5162f22ef01cSRoman Divacky // If this was a terminator instruction, move to the next block. 5163f22ef01cSRoman Divacky if (isa<TerminatorInst>(I)) { 5164f22ef01cSRoman Divacky ++CurBBNo; 516591bc56edSDimitry Andric CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 5166f22ef01cSRoman Divacky } 5167f22ef01cSRoman Divacky 5168f22ef01cSRoman Divacky // Non-void values get registered in the value table for future use. 5169f22ef01cSRoman Divacky if (I && !I->getType()->isVoidTy()) 51708f0fd8f6SDimitry Andric ValueList.assignValue(I, NextValueNo++); 5171f22ef01cSRoman Divacky } 5172f22ef01cSRoman Divacky 5173139f7f9bSDimitry Andric OutOfRecordLoop: 5174139f7f9bSDimitry Andric 51757d523365SDimitry Andric if (!OperandBundles.empty()) 51767d523365SDimitry Andric return error("Operand bundles found with no consumer"); 51777d523365SDimitry Andric 5178f22ef01cSRoman Divacky // Check the function list for unresolved values. 5179f22ef01cSRoman Divacky if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 518091bc56edSDimitry Andric if (!A->getParent()) { 5181f22ef01cSRoman Divacky // We found at least one unresolved value. Nuke them all to avoid leaks. 5182f22ef01cSRoman Divacky for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 518391bc56edSDimitry Andric if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 5184f22ef01cSRoman Divacky A->replaceAllUsesWith(UndefValue::get(A->getType())); 5185f22ef01cSRoman Divacky delete A; 5186f22ef01cSRoman Divacky } 5187f22ef01cSRoman Divacky } 51888f0fd8f6SDimitry Andric return error("Never resolved value found in function"); 5189f22ef01cSRoman Divacky } 5190f22ef01cSRoman Divacky } 5191f22ef01cSRoman Divacky 5192e580952dSDimitry Andric // FIXME: Check for unresolved forward-declared metadata references 5193e580952dSDimitry Andric // and clean up leaks. 5194e580952dSDimitry Andric 5195f22ef01cSRoman Divacky // Trim the value list down to the size it was before we parsed this function. 5196f22ef01cSRoman Divacky ValueList.shrinkTo(ModuleValueListSize); 51977d523365SDimitry Andric MetadataList.shrinkTo(ModuleMetadataListSize); 5198f22ef01cSRoman Divacky std::vector<BasicBlock*>().swap(FunctionBBs); 519991bc56edSDimitry Andric return std::error_code(); 5200f22ef01cSRoman Divacky } 5201f22ef01cSRoman Divacky 5202f785676fSDimitry Andric /// Find the function body in the bitcode stream 52038f0fd8f6SDimitry Andric std::error_code BitcodeReader::findFunctionInStream( 520491bc56edSDimitry Andric Function *F, 5205dff0c46cSDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 5206dff0c46cSDimitry Andric while (DeferredFunctionInfoIterator->second == 0) { 52077d523365SDimitry Andric // This is the fallback handling for the old format bitcode that 52087d523365SDimitry Andric // didn't contain the function index in the VST, or when we have 52097d523365SDimitry Andric // an anonymous function which would not have a VST entry. 52107d523365SDimitry Andric // Assert that we have one of those two cases. 52117d523365SDimitry Andric assert(VSTOffset == 0 || !F->hasName()); 52127d523365SDimitry Andric // Parse the next body in the stream and set its position in the 52137d523365SDimitry Andric // DeferredFunctionInfo map. 52147d523365SDimitry Andric if (std::error_code EC = rememberAndSkipFunctionBodies()) 5215f785676fSDimitry Andric return EC; 5216dff0c46cSDimitry Andric } 521791bc56edSDimitry Andric return std::error_code(); 5218dff0c46cSDimitry Andric } 5219dff0c46cSDimitry Andric 5220f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5221f22ef01cSRoman Divacky // GVMaterializer implementation 5222f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5223f22ef01cSRoman Divacky 522491bc56edSDimitry Andric void BitcodeReader::releaseBuffer() { Buffer.release(); } 5225f22ef01cSRoman Divacky 522639d628a0SDimitry Andric std::error_code BitcodeReader::materialize(GlobalValue *GV) { 52277d523365SDimitry Andric // In older bitcode we must materialize the metadata before parsing 52287d523365SDimitry Andric // any functions, in order to set up the MetadataList properly. 52297d523365SDimitry Andric if (!SeenModuleValuesRecord) { 5230ff0cc061SDimitry Andric if (std::error_code EC = materializeMetadata()) 5231ff0cc061SDimitry Andric return EC; 52327d523365SDimitry Andric } 5233ff0cc061SDimitry Andric 5234f22ef01cSRoman Divacky Function *F = dyn_cast<Function>(GV); 5235f22ef01cSRoman Divacky // If it's not a function or is already material, ignore the request. 5236f785676fSDimitry Andric if (!F || !F->isMaterializable()) 523791bc56edSDimitry Andric return std::error_code(); 5238f22ef01cSRoman Divacky 5239f22ef01cSRoman Divacky DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 5240f22ef01cSRoman Divacky assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 5241dff0c46cSDimitry Andric // If its position is recorded as 0, its body is somewhere in the stream 5242dff0c46cSDimitry Andric // but we haven't seen it yet. 52433dac3a9bSDimitry Andric if (DFII->second == 0) 52448f0fd8f6SDimitry Andric if (std::error_code EC = findFunctionInStream(F, DFII)) 5245f785676fSDimitry Andric return EC; 5246f22ef01cSRoman Divacky 5247f22ef01cSRoman Divacky // Move the bit stream to the saved position of the deferred function body. 5248f22ef01cSRoman Divacky Stream.JumpToBit(DFII->second); 5249f22ef01cSRoman Divacky 52508f0fd8f6SDimitry Andric if (std::error_code EC = parseFunctionBody(F)) 5251f785676fSDimitry Andric return EC; 525239d628a0SDimitry Andric F->setIsMaterializable(false); 5253f22ef01cSRoman Divacky 5254ff0cc061SDimitry Andric if (StripDebugInfo) 5255ff0cc061SDimitry Andric stripDebugInfo(*F); 5256ff0cc061SDimitry Andric 5257f22ef01cSRoman Divacky // Upgrade any old intrinsic calls in the function. 52583dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 52597d523365SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 52607d523365SDimitry Andric UI != UE;) { 52613dac3a9bSDimitry Andric User *U = *UI; 52623dac3a9bSDimitry Andric ++UI; 52633dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 52643dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 5265f22ef01cSRoman Divacky } 5266f22ef01cSRoman Divacky } 5267f22ef01cSRoman Divacky 52687d523365SDimitry Andric // Finish fn->subprogram upgrade for materialized functions. 52697d523365SDimitry Andric if (DISubprogram *SP = FunctionsWithSPs.lookup(F)) 52707d523365SDimitry Andric F->setSubprogram(SP); 52717d523365SDimitry Andric 527239d628a0SDimitry Andric // Bring in any functions that this function forward-referenced via 527339d628a0SDimitry Andric // blockaddresses. 527439d628a0SDimitry Andric return materializeForwardReferencedFunctions(); 5275f22ef01cSRoman Divacky } 5276f22ef01cSRoman Divacky 52777d523365SDimitry Andric std::error_code BitcodeReader::materializeModule() { 5278ff0cc061SDimitry Andric if (std::error_code EC = materializeMetadata()) 5279ff0cc061SDimitry Andric return EC; 5280ff0cc061SDimitry Andric 528139d628a0SDimitry Andric // Promise to materialize all forward references. 528239d628a0SDimitry Andric WillMaterializeAllForwardRefs = true; 528339d628a0SDimitry Andric 5284f22ef01cSRoman Divacky // Iterate over the module, deserializing any functions that are still on 5285f22ef01cSRoman Divacky // disk. 52867d523365SDimitry Andric for (Function &F : *TheModule) { 52877d523365SDimitry Andric if (std::error_code EC = materialize(&F)) 5288f785676fSDimitry Andric return EC; 5289f785676fSDimitry Andric } 52907d523365SDimitry Andric // At this point, if there are any function bodies, parse the rest of 52917d523365SDimitry Andric // the bits in the module past the last function block we have recorded 52927d523365SDimitry Andric // through either lazy scanning or the VST. 52937d523365SDimitry Andric if (LastFunctionBlockBit || NextUnreadBit) 52947d523365SDimitry Andric parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit 52957d523365SDimitry Andric : NextUnreadBit); 5296dff0c46cSDimitry Andric 529739d628a0SDimitry Andric // Check that all block address forward references got resolved (as we 529839d628a0SDimitry Andric // promised above). 529939d628a0SDimitry Andric if (!BasicBlockFwdRefs.empty()) 53008f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress"); 530139d628a0SDimitry Andric 5302f22ef01cSRoman Divacky // Upgrade any intrinsic calls that slipped through (should not happen!) and 5303f22ef01cSRoman Divacky // delete the old functions to clean up. We can't do this unless the entire 5304f22ef01cSRoman Divacky // module is materialized because there could always be another function body 5305f22ef01cSRoman Divacky // with calls to the old function. 53063dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) { 53073dac3a9bSDimitry Andric for (auto *U : I.first->users()) { 53083dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U)) 53093dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second); 5310f22ef01cSRoman Divacky } 53113dac3a9bSDimitry Andric if (!I.first->use_empty()) 53123dac3a9bSDimitry Andric I.first->replaceAllUsesWith(I.second); 53133dac3a9bSDimitry Andric I.first->eraseFromParent(); 5314f22ef01cSRoman Divacky } 53153dac3a9bSDimitry Andric UpgradedIntrinsics.clear(); 5316f22ef01cSRoman Divacky 5317f785676fSDimitry Andric for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 5318f785676fSDimitry Andric UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 5319f785676fSDimitry Andric 53207d523365SDimitry Andric UpgradeDebugInfo(*TheModule); 532191bc56edSDimitry Andric return std::error_code(); 5322dff0c46cSDimitry Andric } 53236122f3e6SDimitry Andric 532439d628a0SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 532539d628a0SDimitry Andric return IdentifiedStructTypes; 532639d628a0SDimitry Andric } 532739d628a0SDimitry Andric 53288f0fd8f6SDimitry Andric std::error_code 53298f0fd8f6SDimitry Andric BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) { 53308f0fd8f6SDimitry Andric if (Streamer) 53318f0fd8f6SDimitry Andric return initLazyStream(std::move(Streamer)); 53328f0fd8f6SDimitry Andric return initStreamFromBuffer(); 5333dff0c46cSDimitry Andric } 5334dff0c46cSDimitry Andric 53358f0fd8f6SDimitry Andric std::error_code BitcodeReader::initStreamFromBuffer() { 53363861d79fSDimitry Andric const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 5337dff0c46cSDimitry Andric const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 5338dff0c46cSDimitry Andric 533939d628a0SDimitry Andric if (Buffer->getBufferSize() & 3) 53408f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 5341dff0c46cSDimitry Andric 5342dff0c46cSDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents. 5343dff0c46cSDimitry Andric // The magic number is 0x0B17C0DE stored in little endian. 5344dff0c46cSDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd)) 5345dff0c46cSDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 53468f0fd8f6SDimitry Andric return error("Invalid bitcode wrapper header"); 5347dff0c46cSDimitry Andric 5348dff0c46cSDimitry Andric StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 534939d628a0SDimitry Andric Stream.init(&*StreamFile); 5350f22ef01cSRoman Divacky 535191bc56edSDimitry Andric return std::error_code(); 5352f22ef01cSRoman Divacky } 5353f22ef01cSRoman Divacky 53548f0fd8f6SDimitry Andric std::error_code 53558f0fd8f6SDimitry Andric BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) { 5356dff0c46cSDimitry Andric // Check and strip off the bitcode wrapper; BitstreamReader expects never to 5357dff0c46cSDimitry Andric // see it. 53588f0fd8f6SDimitry Andric auto OwnedBytes = 53598f0fd8f6SDimitry Andric llvm::make_unique<StreamingMemoryObject>(std::move(Streamer)); 536039d628a0SDimitry Andric StreamingMemoryObject &Bytes = *OwnedBytes; 536139d628a0SDimitry Andric StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 536239d628a0SDimitry Andric Stream.init(&*StreamFile); 5363dff0c46cSDimitry Andric 5364dff0c46cSDimitry Andric unsigned char buf[16]; 536539d628a0SDimitry Andric if (Bytes.readBytes(buf, 16, 0) != 16) 53668f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 5367dff0c46cSDimitry Andric 5368dff0c46cSDimitry Andric if (!isBitcode(buf, buf + 16)) 53698f0fd8f6SDimitry Andric return error("Invalid bitcode signature"); 5370dff0c46cSDimitry Andric 5371dff0c46cSDimitry Andric if (isBitcodeWrapper(buf, buf + 4)) { 5372dff0c46cSDimitry Andric const unsigned char *bitcodeStart = buf; 5373dff0c46cSDimitry Andric const unsigned char *bitcodeEnd = buf + 16; 5374dff0c46cSDimitry Andric SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 537539d628a0SDimitry Andric Bytes.dropLeadingBytes(bitcodeStart - buf); 537639d628a0SDimitry Andric Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 5377dff0c46cSDimitry Andric } 537891bc56edSDimitry Andric return std::error_code(); 5379f785676fSDimitry Andric } 5380f785676fSDimitry Andric 53817d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::error(BitcodeError E, 53827d523365SDimitry Andric const Twine &Message) { 53837d523365SDimitry Andric return ::error(DiagnosticHandler, make_error_code(E), Message); 53847d523365SDimitry Andric } 53857d523365SDimitry Andric 53867d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) { 53877d523365SDimitry Andric return ::error(DiagnosticHandler, 53887d523365SDimitry Andric make_error_code(BitcodeError::CorruptedBitcode), Message); 53897d523365SDimitry Andric } 53907d523365SDimitry Andric 53917d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) { 53927d523365SDimitry Andric return ::error(DiagnosticHandler, make_error_code(E)); 53937d523365SDimitry Andric } 53947d523365SDimitry Andric 53957d523365SDimitry Andric FunctionIndexBitcodeReader::FunctionIndexBitcodeReader( 53967d523365SDimitry Andric MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler, 53977d523365SDimitry Andric bool IsLazy, bool CheckFuncSummaryPresenceOnly) 53987d523365SDimitry Andric : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy), 53997d523365SDimitry Andric CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {} 54007d523365SDimitry Andric 54017d523365SDimitry Andric FunctionIndexBitcodeReader::FunctionIndexBitcodeReader( 54027d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy, 54037d523365SDimitry Andric bool CheckFuncSummaryPresenceOnly) 54047d523365SDimitry Andric : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy), 54057d523365SDimitry Andric CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {} 54067d523365SDimitry Andric 54077d523365SDimitry Andric void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; } 54087d523365SDimitry Andric 54097d523365SDimitry Andric void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); } 54107d523365SDimitry Andric 54117d523365SDimitry Andric // Specialized value symbol table parser used when reading function index 54127d523365SDimitry Andric // blocks where we don't actually create global values. 54137d523365SDimitry Andric // At the end of this routine the function index is populated with a map 54147d523365SDimitry Andric // from function name to FunctionInfo. The function info contains 54157d523365SDimitry Andric // the function block's bitcode offset as well as the offset into the 54167d523365SDimitry Andric // function summary section. 54177d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() { 54187d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 54197d523365SDimitry Andric return error("Invalid record"); 54207d523365SDimitry Andric 54217d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 54227d523365SDimitry Andric 54237d523365SDimitry Andric // Read all the records for this value table. 54247d523365SDimitry Andric SmallString<128> ValueName; 54257d523365SDimitry Andric while (1) { 54267d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 54277d523365SDimitry Andric 54287d523365SDimitry Andric switch (Entry.Kind) { 54297d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 54307d523365SDimitry Andric case BitstreamEntry::Error: 54317d523365SDimitry Andric return error("Malformed block"); 54327d523365SDimitry Andric case BitstreamEntry::EndBlock: 54337d523365SDimitry Andric return std::error_code(); 54347d523365SDimitry Andric case BitstreamEntry::Record: 54357d523365SDimitry Andric // The interesting case. 54367d523365SDimitry Andric break; 54377d523365SDimitry Andric } 54387d523365SDimitry Andric 54397d523365SDimitry Andric // Read a record. 54407d523365SDimitry Andric Record.clear(); 54417d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 54427d523365SDimitry Andric default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 54437d523365SDimitry Andric break; 54447d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: { 54457d523365SDimitry Andric // VST_FNENTRY: [valueid, offset, namechar x N] 54467d523365SDimitry Andric if (convertToString(Record, 2, ValueName)) 54477d523365SDimitry Andric return error("Invalid record"); 54487d523365SDimitry Andric unsigned ValueID = Record[0]; 54497d523365SDimitry Andric uint64_t FuncOffset = Record[1]; 54507d523365SDimitry Andric std::unique_ptr<FunctionInfo> FuncInfo = 54517d523365SDimitry Andric llvm::make_unique<FunctionInfo>(FuncOffset); 54527d523365SDimitry Andric if (foundFuncSummary() && !IsLazy) { 54537d523365SDimitry Andric DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI = 54547d523365SDimitry Andric SummaryMap.find(ValueID); 54557d523365SDimitry Andric assert(SMI != SummaryMap.end() && "Summary info not found"); 54567d523365SDimitry Andric FuncInfo->setFunctionSummary(std::move(SMI->second)); 54577d523365SDimitry Andric } 54587d523365SDimitry Andric TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo)); 54597d523365SDimitry Andric 54607d523365SDimitry Andric ValueName.clear(); 54617d523365SDimitry Andric break; 54627d523365SDimitry Andric } 54637d523365SDimitry Andric case bitc::VST_CODE_COMBINED_FNENTRY: { 54647d523365SDimitry Andric // VST_FNENTRY: [offset, namechar x N] 54657d523365SDimitry Andric if (convertToString(Record, 1, ValueName)) 54667d523365SDimitry Andric return error("Invalid record"); 54677d523365SDimitry Andric uint64_t FuncSummaryOffset = Record[0]; 54687d523365SDimitry Andric std::unique_ptr<FunctionInfo> FuncInfo = 54697d523365SDimitry Andric llvm::make_unique<FunctionInfo>(FuncSummaryOffset); 54707d523365SDimitry Andric if (foundFuncSummary() && !IsLazy) { 54717d523365SDimitry Andric DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI = 54727d523365SDimitry Andric SummaryMap.find(FuncSummaryOffset); 54737d523365SDimitry Andric assert(SMI != SummaryMap.end() && "Summary info not found"); 54747d523365SDimitry Andric FuncInfo->setFunctionSummary(std::move(SMI->second)); 54757d523365SDimitry Andric } 54767d523365SDimitry Andric TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo)); 54777d523365SDimitry Andric 54787d523365SDimitry Andric ValueName.clear(); 54797d523365SDimitry Andric break; 54807d523365SDimitry Andric } 54817d523365SDimitry Andric } 54827d523365SDimitry Andric } 54837d523365SDimitry Andric } 54847d523365SDimitry Andric 54857d523365SDimitry Andric // Parse just the blocks needed for function index building out of the module. 54867d523365SDimitry Andric // At the end of this routine the function Index is populated with a map 54877d523365SDimitry Andric // from function name to FunctionInfo. The function info contains 54887d523365SDimitry Andric // either the parsed function summary information (when parsing summaries 54897d523365SDimitry Andric // eagerly), or just to the function summary record's offset 54907d523365SDimitry Andric // if parsing lazily (IsLazy). 54917d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseModule() { 54927d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 54937d523365SDimitry Andric return error("Invalid record"); 54947d523365SDimitry Andric 54957d523365SDimitry Andric // Read the function index for this module. 54967d523365SDimitry Andric while (1) { 54977d523365SDimitry Andric BitstreamEntry Entry = Stream.advance(); 54987d523365SDimitry Andric 54997d523365SDimitry Andric switch (Entry.Kind) { 55007d523365SDimitry Andric case BitstreamEntry::Error: 55017d523365SDimitry Andric return error("Malformed block"); 55027d523365SDimitry Andric case BitstreamEntry::EndBlock: 55037d523365SDimitry Andric return std::error_code(); 55047d523365SDimitry Andric 55057d523365SDimitry Andric case BitstreamEntry::SubBlock: 55067d523365SDimitry Andric if (CheckFuncSummaryPresenceOnly) { 55077d523365SDimitry Andric if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID) { 55087d523365SDimitry Andric SeenFuncSummary = true; 55097d523365SDimitry Andric // No need to parse the rest since we found the summary. 55107d523365SDimitry Andric return std::error_code(); 55117d523365SDimitry Andric } 55127d523365SDimitry Andric if (Stream.SkipBlock()) 55137d523365SDimitry Andric return error("Invalid record"); 55147d523365SDimitry Andric continue; 55157d523365SDimitry Andric } 55167d523365SDimitry Andric switch (Entry.ID) { 55177d523365SDimitry Andric default: // Skip unknown content. 55187d523365SDimitry Andric if (Stream.SkipBlock()) 55197d523365SDimitry Andric return error("Invalid record"); 55207d523365SDimitry Andric break; 55217d523365SDimitry Andric case bitc::BLOCKINFO_BLOCK_ID: 55227d523365SDimitry Andric // Need to parse these to get abbrev ids (e.g. for VST) 55237d523365SDimitry Andric if (Stream.ReadBlockInfoBlock()) 55247d523365SDimitry Andric return error("Malformed block"); 55257d523365SDimitry Andric break; 55267d523365SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID: 55277d523365SDimitry Andric if (std::error_code EC = parseValueSymbolTable()) 55287d523365SDimitry Andric return EC; 55297d523365SDimitry Andric break; 55307d523365SDimitry Andric case bitc::FUNCTION_SUMMARY_BLOCK_ID: 55317d523365SDimitry Andric SeenFuncSummary = true; 55327d523365SDimitry Andric if (IsLazy) { 55337d523365SDimitry Andric // Lazy parsing of summary info, skip it. 55347d523365SDimitry Andric if (Stream.SkipBlock()) 55357d523365SDimitry Andric return error("Invalid record"); 55367d523365SDimitry Andric } else if (std::error_code EC = parseEntireSummary()) 55377d523365SDimitry Andric return EC; 55387d523365SDimitry Andric break; 55397d523365SDimitry Andric case bitc::MODULE_STRTAB_BLOCK_ID: 55407d523365SDimitry Andric if (std::error_code EC = parseModuleStringTable()) 55417d523365SDimitry Andric return EC; 55427d523365SDimitry Andric break; 55437d523365SDimitry Andric } 55447d523365SDimitry Andric continue; 55457d523365SDimitry Andric 55467d523365SDimitry Andric case BitstreamEntry::Record: 55477d523365SDimitry Andric Stream.skipRecord(Entry.ID); 55487d523365SDimitry Andric continue; 55497d523365SDimitry Andric } 55507d523365SDimitry Andric } 55517d523365SDimitry Andric } 55527d523365SDimitry Andric 55537d523365SDimitry Andric // Eagerly parse the entire function summary block (i.e. for all functions 55547d523365SDimitry Andric // in the index). This populates the FunctionSummary objects in 55557d523365SDimitry Andric // the index. 55567d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseEntireSummary() { 55577d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID)) 55587d523365SDimitry Andric return error("Invalid record"); 55597d523365SDimitry Andric 55607d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 55617d523365SDimitry Andric 55627d523365SDimitry Andric while (1) { 55637d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 55647d523365SDimitry Andric 55657d523365SDimitry Andric switch (Entry.Kind) { 55667d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 55677d523365SDimitry Andric case BitstreamEntry::Error: 55687d523365SDimitry Andric return error("Malformed block"); 55697d523365SDimitry Andric case BitstreamEntry::EndBlock: 55707d523365SDimitry Andric return std::error_code(); 55717d523365SDimitry Andric case BitstreamEntry::Record: 55727d523365SDimitry Andric // The interesting case. 55737d523365SDimitry Andric break; 55747d523365SDimitry Andric } 55757d523365SDimitry Andric 55767d523365SDimitry Andric // Read a record. The record format depends on whether this 55777d523365SDimitry Andric // is a per-module index or a combined index file. In the per-module 55787d523365SDimitry Andric // case the records contain the associated value's ID for correlation 55797d523365SDimitry Andric // with VST entries. In the combined index the correlation is done 55807d523365SDimitry Andric // via the bitcode offset of the summary records (which were saved 55817d523365SDimitry Andric // in the combined index VST entries). The records also contain 55827d523365SDimitry Andric // information used for ThinLTO renaming and importing. 55837d523365SDimitry Andric Record.clear(); 55847d523365SDimitry Andric uint64_t CurRecordBit = Stream.GetCurrentBitNo(); 55857d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 55867d523365SDimitry Andric default: // Default behavior: ignore. 55877d523365SDimitry Andric break; 55887d523365SDimitry Andric // FS_PERMODULE_ENTRY: [valueid, islocal, instcount] 55897d523365SDimitry Andric case bitc::FS_CODE_PERMODULE_ENTRY: { 55907d523365SDimitry Andric unsigned ValueID = Record[0]; 55917d523365SDimitry Andric bool IsLocal = Record[1]; 55927d523365SDimitry Andric unsigned InstCount = Record[2]; 55937d523365SDimitry Andric std::unique_ptr<FunctionSummary> FS = 55947d523365SDimitry Andric llvm::make_unique<FunctionSummary>(InstCount); 55957d523365SDimitry Andric FS->setLocalFunction(IsLocal); 55967d523365SDimitry Andric // The module path string ref set in the summary must be owned by the 55977d523365SDimitry Andric // index's module string table. Since we don't have a module path 55987d523365SDimitry Andric // string table section in the per-module index, we create a single 55997d523365SDimitry Andric // module path string table entry with an empty (0) ID to take 56007d523365SDimitry Andric // ownership. 56017d523365SDimitry Andric FS->setModulePath( 56027d523365SDimitry Andric TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)); 56037d523365SDimitry Andric SummaryMap[ValueID] = std::move(FS); 56047d523365SDimitry Andric } 56057d523365SDimitry Andric // FS_COMBINED_ENTRY: [modid, instcount] 56067d523365SDimitry Andric case bitc::FS_CODE_COMBINED_ENTRY: { 56077d523365SDimitry Andric uint64_t ModuleId = Record[0]; 56087d523365SDimitry Andric unsigned InstCount = Record[1]; 56097d523365SDimitry Andric std::unique_ptr<FunctionSummary> FS = 56107d523365SDimitry Andric llvm::make_unique<FunctionSummary>(InstCount); 56117d523365SDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]); 56127d523365SDimitry Andric SummaryMap[CurRecordBit] = std::move(FS); 56137d523365SDimitry Andric } 56147d523365SDimitry Andric } 56157d523365SDimitry Andric } 56167d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 56177d523365SDimitry Andric } 56187d523365SDimitry Andric 56197d523365SDimitry Andric // Parse the module string table block into the Index. 56207d523365SDimitry Andric // This populates the ModulePathStringTable map in the index. 56217d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() { 56227d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 56237d523365SDimitry Andric return error("Invalid record"); 56247d523365SDimitry Andric 56257d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 56267d523365SDimitry Andric 56277d523365SDimitry Andric SmallString<128> ModulePath; 56287d523365SDimitry Andric while (1) { 56297d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 56307d523365SDimitry Andric 56317d523365SDimitry Andric switch (Entry.Kind) { 56327d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already. 56337d523365SDimitry Andric case BitstreamEntry::Error: 56347d523365SDimitry Andric return error("Malformed block"); 56357d523365SDimitry Andric case BitstreamEntry::EndBlock: 56367d523365SDimitry Andric return std::error_code(); 56377d523365SDimitry Andric case BitstreamEntry::Record: 56387d523365SDimitry Andric // The interesting case. 56397d523365SDimitry Andric break; 56407d523365SDimitry Andric } 56417d523365SDimitry Andric 56427d523365SDimitry Andric Record.clear(); 56437d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 56447d523365SDimitry Andric default: // Default behavior: ignore. 56457d523365SDimitry Andric break; 56467d523365SDimitry Andric case bitc::MST_CODE_ENTRY: { 56477d523365SDimitry Andric // MST_ENTRY: [modid, namechar x N] 56487d523365SDimitry Andric if (convertToString(Record, 1, ModulePath)) 56497d523365SDimitry Andric return error("Invalid record"); 56507d523365SDimitry Andric uint64_t ModuleId = Record[0]; 56517d523365SDimitry Andric StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId); 56527d523365SDimitry Andric ModuleIdMap[ModuleId] = ModulePathInMap; 56537d523365SDimitry Andric ModulePath.clear(); 56547d523365SDimitry Andric break; 56557d523365SDimitry Andric } 56567d523365SDimitry Andric } 56577d523365SDimitry Andric } 56587d523365SDimitry Andric llvm_unreachable("Exit infinite loop"); 56597d523365SDimitry Andric } 56607d523365SDimitry Andric 56617d523365SDimitry Andric // Parse the function info index from the bitcode streamer into the given index. 56627d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto( 56637d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) { 56647d523365SDimitry Andric TheIndex = I; 56657d523365SDimitry Andric 56667d523365SDimitry Andric if (std::error_code EC = initStream(std::move(Streamer))) 56677d523365SDimitry Andric return EC; 56687d523365SDimitry Andric 56697d523365SDimitry Andric // Sniff for the signature. 56707d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 56717d523365SDimitry Andric return error("Invalid bitcode signature"); 56727d523365SDimitry Andric 56737d523365SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily 56747d523365SDimitry Andric // need to understand them all. 56757d523365SDimitry Andric while (1) { 56767d523365SDimitry Andric if (Stream.AtEndOfStream()) { 56777d523365SDimitry Andric // We didn't really read a proper Module block. 56787d523365SDimitry Andric return error("Malformed block"); 56797d523365SDimitry Andric } 56807d523365SDimitry Andric 56817d523365SDimitry Andric BitstreamEntry Entry = 56827d523365SDimitry Andric Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 56837d523365SDimitry Andric 56847d523365SDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock) 56857d523365SDimitry Andric return error("Malformed block"); 56867d523365SDimitry Andric 56877d523365SDimitry Andric // If we see a MODULE_BLOCK, parse it to find the blocks needed for 56887d523365SDimitry Andric // building the function summary index. 56897d523365SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) 56907d523365SDimitry Andric return parseModule(); 56917d523365SDimitry Andric 56927d523365SDimitry Andric if (Stream.SkipBlock()) 56937d523365SDimitry Andric return error("Invalid record"); 56947d523365SDimitry Andric } 56957d523365SDimitry Andric } 56967d523365SDimitry Andric 56977d523365SDimitry Andric // Parse the function information at the given offset in the buffer into 56987d523365SDimitry Andric // the index. Used to support lazy parsing of function summaries from the 56997d523365SDimitry Andric // combined index during importing. 57007d523365SDimitry Andric // TODO: This function is not yet complete as it won't have a consumer 57017d523365SDimitry Andric // until ThinLTO function importing is added. 57027d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::parseFunctionSummary( 57037d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I, 57047d523365SDimitry Andric size_t FunctionSummaryOffset) { 57057d523365SDimitry Andric TheIndex = I; 57067d523365SDimitry Andric 57077d523365SDimitry Andric if (std::error_code EC = initStream(std::move(Streamer))) 57087d523365SDimitry Andric return EC; 57097d523365SDimitry Andric 57107d523365SDimitry Andric // Sniff for the signature. 57117d523365SDimitry Andric if (!hasValidBitcodeHeader(Stream)) 57127d523365SDimitry Andric return error("Invalid bitcode signature"); 57137d523365SDimitry Andric 57147d523365SDimitry Andric Stream.JumpToBit(FunctionSummaryOffset); 57157d523365SDimitry Andric 57167d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 57177d523365SDimitry Andric 57187d523365SDimitry Andric switch (Entry.Kind) { 57197d523365SDimitry Andric default: 57207d523365SDimitry Andric return error("Malformed block"); 57217d523365SDimitry Andric case BitstreamEntry::Record: 57227d523365SDimitry Andric // The expected case. 57237d523365SDimitry Andric break; 57247d523365SDimitry Andric } 57257d523365SDimitry Andric 57267d523365SDimitry Andric // TODO: Read a record. This interface will be completed when ThinLTO 57277d523365SDimitry Andric // importing is added so that it can be tested. 57287d523365SDimitry Andric SmallVector<uint64_t, 64> Record; 57297d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) { 57307d523365SDimitry Andric case bitc::FS_CODE_COMBINED_ENTRY: 57317d523365SDimitry Andric default: 57327d523365SDimitry Andric return error("Invalid record"); 57337d523365SDimitry Andric } 57347d523365SDimitry Andric 57357d523365SDimitry Andric return std::error_code(); 57367d523365SDimitry Andric } 57377d523365SDimitry Andric 57387d523365SDimitry Andric std::error_code 57397d523365SDimitry Andric FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) { 57407d523365SDimitry Andric if (Streamer) 57417d523365SDimitry Andric return initLazyStream(std::move(Streamer)); 57427d523365SDimitry Andric return initStreamFromBuffer(); 57437d523365SDimitry Andric } 57447d523365SDimitry Andric 57457d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() { 57467d523365SDimitry Andric const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart(); 57477d523365SDimitry Andric const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize(); 57487d523365SDimitry Andric 57497d523365SDimitry Andric if (Buffer->getBufferSize() & 3) 57507d523365SDimitry Andric return error("Invalid bitcode signature"); 57517d523365SDimitry Andric 57527d523365SDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents. 57537d523365SDimitry Andric // The magic number is 0x0B17C0DE stored in little endian. 57547d523365SDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd)) 57557d523365SDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 57567d523365SDimitry Andric return error("Invalid bitcode wrapper header"); 57577d523365SDimitry Andric 57587d523365SDimitry Andric StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 57597d523365SDimitry Andric Stream.init(&*StreamFile); 57607d523365SDimitry Andric 57617d523365SDimitry Andric return std::error_code(); 57627d523365SDimitry Andric } 57637d523365SDimitry Andric 57647d523365SDimitry Andric std::error_code FunctionIndexBitcodeReader::initLazyStream( 57657d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer) { 57667d523365SDimitry Andric // Check and strip off the bitcode wrapper; BitstreamReader expects never to 57677d523365SDimitry Andric // see it. 57687d523365SDimitry Andric auto OwnedBytes = 57697d523365SDimitry Andric llvm::make_unique<StreamingMemoryObject>(std::move(Streamer)); 57707d523365SDimitry Andric StreamingMemoryObject &Bytes = *OwnedBytes; 57717d523365SDimitry Andric StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 57727d523365SDimitry Andric Stream.init(&*StreamFile); 57737d523365SDimitry Andric 57747d523365SDimitry Andric unsigned char buf[16]; 57757d523365SDimitry Andric if (Bytes.readBytes(buf, 16, 0) != 16) 57767d523365SDimitry Andric return error("Invalid bitcode signature"); 57777d523365SDimitry Andric 57787d523365SDimitry Andric if (!isBitcode(buf, buf + 16)) 57797d523365SDimitry Andric return error("Invalid bitcode signature"); 57807d523365SDimitry Andric 57817d523365SDimitry Andric if (isBitcodeWrapper(buf, buf + 4)) { 57827d523365SDimitry Andric const unsigned char *bitcodeStart = buf; 57837d523365SDimitry Andric const unsigned char *bitcodeEnd = buf + 16; 57847d523365SDimitry Andric SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 57857d523365SDimitry Andric Bytes.dropLeadingBytes(bitcodeStart - buf); 57867d523365SDimitry Andric Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 57877d523365SDimitry Andric } 57887d523365SDimitry Andric return std::error_code(); 57897d523365SDimitry Andric } 57907d523365SDimitry Andric 5791f785676fSDimitry Andric namespace { 579291bc56edSDimitry Andric class BitcodeErrorCategoryType : public std::error_category { 579391bc56edSDimitry Andric const char *name() const LLVM_NOEXCEPT override { 5794f785676fSDimitry Andric return "llvm.bitcode"; 5795f785676fSDimitry Andric } 579691bc56edSDimitry Andric std::string message(int IE) const override { 579739d628a0SDimitry Andric BitcodeError E = static_cast<BitcodeError>(IE); 5798f785676fSDimitry Andric switch (E) { 579939d628a0SDimitry Andric case BitcodeError::InvalidBitcodeSignature: 5800f785676fSDimitry Andric return "Invalid bitcode signature"; 580139d628a0SDimitry Andric case BitcodeError::CorruptedBitcode: 580239d628a0SDimitry Andric return "Corrupted bitcode"; 5803f785676fSDimitry Andric } 5804f785676fSDimitry Andric llvm_unreachable("Unknown error type!"); 5805f785676fSDimitry Andric } 5806f785676fSDimitry Andric }; 58073dac3a9bSDimitry Andric } 5808f785676fSDimitry Andric 580939d628a0SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 581039d628a0SDimitry Andric 581139d628a0SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() { 581239d628a0SDimitry Andric return *ErrorCategory; 5813dff0c46cSDimitry Andric } 5814f22ef01cSRoman Divacky 5815f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5816f22ef01cSRoman Divacky // External interface 5817f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 5818f22ef01cSRoman Divacky 58198f0fd8f6SDimitry Andric static ErrorOr<std::unique_ptr<Module>> 58208f0fd8f6SDimitry Andric getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name, 58218f0fd8f6SDimitry Andric BitcodeReader *R, LLVMContext &Context, 58228f0fd8f6SDimitry Andric bool MaterializeAll, bool ShouldLazyLoadMetadata) { 58238f0fd8f6SDimitry Andric std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 58248f0fd8f6SDimitry Andric M->setMaterializer(R); 58258f0fd8f6SDimitry Andric 58268f0fd8f6SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 58278f0fd8f6SDimitry Andric R->releaseBuffer(); // Never take ownership on error. 58288f0fd8f6SDimitry Andric return EC; 58298f0fd8f6SDimitry Andric }; 58308f0fd8f6SDimitry Andric 58318f0fd8f6SDimitry Andric // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 58328f0fd8f6SDimitry Andric if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(), 58338f0fd8f6SDimitry Andric ShouldLazyLoadMetadata)) 58348f0fd8f6SDimitry Andric return cleanupOnError(EC); 58358f0fd8f6SDimitry Andric 58368f0fd8f6SDimitry Andric if (MaterializeAll) { 58378f0fd8f6SDimitry Andric // Read in the entire module, and destroy the BitcodeReader. 58387d523365SDimitry Andric if (std::error_code EC = M->materializeAll()) 58398f0fd8f6SDimitry Andric return cleanupOnError(EC); 58408f0fd8f6SDimitry Andric } else { 58418f0fd8f6SDimitry Andric // Resolve forward references from blockaddresses. 58428f0fd8f6SDimitry Andric if (std::error_code EC = R->materializeForwardReferencedFunctions()) 58438f0fd8f6SDimitry Andric return cleanupOnError(EC); 58448f0fd8f6SDimitry Andric } 58458f0fd8f6SDimitry Andric return std::move(M); 58468f0fd8f6SDimitry Andric } 58478f0fd8f6SDimitry Andric 584839d628a0SDimitry Andric /// \brief Get a lazy one-at-time loading module from bitcode. 5849f22ef01cSRoman Divacky /// 585039d628a0SDimitry Andric /// This isn't always used in a lazy context. In particular, it's also used by 585139d628a0SDimitry Andric /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull 585239d628a0SDimitry Andric /// in forward-referenced functions from block address references. 585339d628a0SDimitry Andric /// 58548f0fd8f6SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize 58558f0fd8f6SDimitry Andric /// everything. 58568f0fd8f6SDimitry Andric static ErrorOr<std::unique_ptr<Module>> 585739d628a0SDimitry Andric getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer, 58588f0fd8f6SDimitry Andric LLVMContext &Context, bool MaterializeAll, 5859ff0cc061SDimitry Andric bool ShouldLazyLoadMetadata = false) { 58607d523365SDimitry Andric BitcodeReader *R = new BitcodeReader(Buffer.get(), Context); 586139d628a0SDimitry Andric 58628f0fd8f6SDimitry Andric ErrorOr<std::unique_ptr<Module>> Ret = 58638f0fd8f6SDimitry Andric getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context, 58648f0fd8f6SDimitry Andric MaterializeAll, ShouldLazyLoadMetadata); 58658f0fd8f6SDimitry Andric if (!Ret) 58668f0fd8f6SDimitry Andric return Ret; 586739d628a0SDimitry Andric 586839d628a0SDimitry Andric Buffer.release(); // The BitcodeReader owns it now. 58698f0fd8f6SDimitry Andric return Ret; 5870dff0c46cSDimitry Andric } 5871dff0c46cSDimitry Andric 58727d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>> 58737d523365SDimitry Andric llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 58747d523365SDimitry Andric LLVMContext &Context, bool ShouldLazyLoadMetadata) { 587539d628a0SDimitry Andric return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false, 58767d523365SDimitry Andric ShouldLazyLoadMetadata); 5877f22ef01cSRoman Divacky } 5878f22ef01cSRoman Divacky 58797d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>> 58807d523365SDimitry Andric llvm::getStreamedBitcodeModule(StringRef Name, 58817d523365SDimitry Andric std::unique_ptr<DataStreamer> Streamer, 58827d523365SDimitry Andric LLVMContext &Context) { 588339d628a0SDimitry Andric std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 58847d523365SDimitry Andric BitcodeReader *R = new BitcodeReader(Context); 58858f0fd8f6SDimitry Andric 58868f0fd8f6SDimitry Andric return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false, 58878f0fd8f6SDimitry Andric false); 588839d628a0SDimitry Andric } 588939d628a0SDimitry Andric 58907d523365SDimitry Andric ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 58917d523365SDimitry Andric LLVMContext &Context) { 589239d628a0SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 58937d523365SDimitry Andric return getLazyBitcodeModuleImpl(std::move(Buf), Context, true); 5894dff0c46cSDimitry Andric // TODO: Restore the use-lists to the in-memory state when the bitcode was 5895dff0c46cSDimitry Andric // written. We must defer until the Module has been fully materialized. 5896f22ef01cSRoman Divacky } 58972754fe60SDimitry Andric 58987d523365SDimitry Andric std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, 58997d523365SDimitry Andric LLVMContext &Context) { 590039d628a0SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59017d523365SDimitry Andric auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context); 590291bc56edSDimitry Andric ErrorOr<std::string> Triple = R->parseTriple(); 590391bc56edSDimitry Andric if (Triple.getError()) 590491bc56edSDimitry Andric return ""; 590591bc56edSDimitry Andric return Triple.get(); 59062754fe60SDimitry Andric } 59077d523365SDimitry Andric 59087d523365SDimitry Andric std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer, 59097d523365SDimitry Andric LLVMContext &Context) { 59107d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59117d523365SDimitry Andric BitcodeReader R(Buf.release(), Context); 59127d523365SDimitry Andric ErrorOr<std::string> ProducerString = R.parseIdentificationBlock(); 59137d523365SDimitry Andric if (ProducerString.getError()) 59147d523365SDimitry Andric return ""; 59157d523365SDimitry Andric return ProducerString.get(); 59167d523365SDimitry Andric } 59177d523365SDimitry Andric 59187d523365SDimitry Andric // Parse the specified bitcode buffer, returning the function info index. 59197d523365SDimitry Andric // If IsLazy is false, parse the entire function summary into 59207d523365SDimitry Andric // the index. Otherwise skip the function summary section, and only create 59217d523365SDimitry Andric // an index object with a map from function name to function summary offset. 59227d523365SDimitry Andric // The index is used to perform lazy function summary reading later. 59237d523365SDimitry Andric ErrorOr<std::unique_ptr<FunctionInfoIndex>> 59247d523365SDimitry Andric llvm::getFunctionInfoIndex(MemoryBufferRef Buffer, 59257d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler, 59267d523365SDimitry Andric bool IsLazy) { 59277d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59287d523365SDimitry Andric FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy); 59297d523365SDimitry Andric 59307d523365SDimitry Andric auto Index = llvm::make_unique<FunctionInfoIndex>(); 59317d523365SDimitry Andric 59327d523365SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 59337d523365SDimitry Andric R.releaseBuffer(); // Never take ownership on error. 59347d523365SDimitry Andric return EC; 59357d523365SDimitry Andric }; 59367d523365SDimitry Andric 59377d523365SDimitry Andric if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get())) 59387d523365SDimitry Andric return cleanupOnError(EC); 59397d523365SDimitry Andric 59407d523365SDimitry Andric Buf.release(); // The FunctionIndexBitcodeReader owns it now. 59417d523365SDimitry Andric return std::move(Index); 59427d523365SDimitry Andric } 59437d523365SDimitry Andric 59447d523365SDimitry Andric // Check if the given bitcode buffer contains a function summary block. 59457d523365SDimitry Andric bool llvm::hasFunctionSummary(MemoryBufferRef Buffer, 59467d523365SDimitry Andric DiagnosticHandlerFunction DiagnosticHandler) { 59477d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59487d523365SDimitry Andric FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true); 59497d523365SDimitry Andric 59507d523365SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 59517d523365SDimitry Andric R.releaseBuffer(); // Never take ownership on error. 59527d523365SDimitry Andric return false; 59537d523365SDimitry Andric }; 59547d523365SDimitry Andric 59557d523365SDimitry Andric if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr)) 59567d523365SDimitry Andric return cleanupOnError(EC); 59577d523365SDimitry Andric 59587d523365SDimitry Andric Buf.release(); // The FunctionIndexBitcodeReader owns it now. 59597d523365SDimitry Andric return R.foundFuncSummary(); 59607d523365SDimitry Andric } 59617d523365SDimitry Andric 59627d523365SDimitry Andric // This method supports lazy reading of function summary data from the combined 59637d523365SDimitry Andric // index during ThinLTO function importing. When reading the combined index 59647d523365SDimitry Andric // file, getFunctionInfoIndex is first invoked with IsLazy=true. 59657d523365SDimitry Andric // Then this method is called for each function considered for importing, 59667d523365SDimitry Andric // to parse the summary information for the given function name into 59677d523365SDimitry Andric // the index. 59687d523365SDimitry Andric std::error_code llvm::readFunctionSummary( 59697d523365SDimitry Andric MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler, 59707d523365SDimitry Andric StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) { 59717d523365SDimitry Andric std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 59727d523365SDimitry Andric FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler); 59737d523365SDimitry Andric 59747d523365SDimitry Andric auto cleanupOnError = [&](std::error_code EC) { 59757d523365SDimitry Andric R.releaseBuffer(); // Never take ownership on error. 59767d523365SDimitry Andric return EC; 59777d523365SDimitry Andric }; 59787d523365SDimitry Andric 59797d523365SDimitry Andric // Lookup the given function name in the FunctionMap, which may 59807d523365SDimitry Andric // contain a list of function infos in the case of a COMDAT. Walk through 59817d523365SDimitry Andric // and parse each function summary info at the function summary offset 59827d523365SDimitry Andric // recorded when parsing the value symbol table. 59837d523365SDimitry Andric for (const auto &FI : Index->getFunctionInfoList(FunctionName)) { 59847d523365SDimitry Andric size_t FunctionSummaryOffset = FI->bitcodeIndex(); 59857d523365SDimitry Andric if (std::error_code EC = 59867d523365SDimitry Andric R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset)) 59877d523365SDimitry Andric return cleanupOnError(EC); 59887d523365SDimitry Andric } 59897d523365SDimitry Andric 59907d523365SDimitry Andric Buf.release(); // The FunctionIndexBitcodeReader owns it now. 59917d523365SDimitry Andric return std::error_code(); 59927d523365SDimitry Andric } 5993