1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/ADT/STLExtras.h" 11 #include "llvm/ADT/SmallString.h" 12 #include "llvm/ADT/SmallVector.h" 13 #include "llvm/ADT/Triple.h" 14 #include "llvm/Bitcode/BitstreamReader.h" 15 #include "llvm/Bitcode/LLVMBitCodes.h" 16 #include "llvm/Bitcode/ReaderWriter.h" 17 #include "llvm/IR/AutoUpgrade.h" 18 #include "llvm/IR/Constants.h" 19 #include "llvm/IR/DebugInfo.h" 20 #include "llvm/IR/DebugInfoMetadata.h" 21 #include "llvm/IR/DerivedTypes.h" 22 #include "llvm/IR/DiagnosticPrinter.h" 23 #include "llvm/IR/GVMaterializer.h" 24 #include "llvm/IR/InlineAsm.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/IR/Module.h" 28 #include "llvm/IR/ModuleSummaryIndex.h" 29 #include "llvm/IR/OperandTraits.h" 30 #include "llvm/IR/Operator.h" 31 #include "llvm/IR/ValueHandle.h" 32 #include "llvm/Support/DataStream.h" 33 #include "llvm/Support/ManagedStatic.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/MemoryBuffer.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <deque> 38 39 using namespace llvm; 40 41 namespace { 42 enum { 43 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 44 }; 45 46 class BitcodeReaderValueList { 47 std::vector<WeakVH> ValuePtrs; 48 49 /// As we resolve forward-referenced constants, we add information about them 50 /// to this vector. This allows us to resolve them in bulk instead of 51 /// resolving each reference at a time. See the code in 52 /// ResolveConstantForwardRefs for more information about this. 53 /// 54 /// The key of this vector is the placeholder constant, the value is the slot 55 /// number that holds the resolved value. 56 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy; 57 ResolveConstantsTy ResolveConstants; 58 LLVMContext &Context; 59 public: 60 BitcodeReaderValueList(LLVMContext &C) : Context(C) {} 61 ~BitcodeReaderValueList() { 62 assert(ResolveConstants.empty() && "Constants not resolved?"); 63 } 64 65 // vector compatibility methods 66 unsigned size() const { return ValuePtrs.size(); } 67 void resize(unsigned N) { ValuePtrs.resize(N); } 68 void push_back(Value *V) { ValuePtrs.emplace_back(V); } 69 70 void clear() { 71 assert(ResolveConstants.empty() && "Constants not resolved?"); 72 ValuePtrs.clear(); 73 } 74 75 Value *operator[](unsigned i) const { 76 assert(i < ValuePtrs.size()); 77 return ValuePtrs[i]; 78 } 79 80 Value *back() const { return ValuePtrs.back(); } 81 void pop_back() { ValuePtrs.pop_back(); } 82 bool empty() const { return ValuePtrs.empty(); } 83 void shrinkTo(unsigned N) { 84 assert(N <= size() && "Invalid shrinkTo request!"); 85 ValuePtrs.resize(N); 86 } 87 88 Constant *getConstantFwdRef(unsigned Idx, Type *Ty); 89 Value *getValueFwdRef(unsigned Idx, Type *Ty); 90 91 void assignValue(Value *V, unsigned Idx); 92 93 /// Once all constants are read, this method bulk resolves any forward 94 /// references. 95 void resolveConstantForwardRefs(); 96 }; 97 98 class BitcodeReaderMetadataList { 99 unsigned NumFwdRefs; 100 bool AnyFwdRefs; 101 unsigned MinFwdRef; 102 unsigned MaxFwdRef; 103 std::vector<TrackingMDRef> MetadataPtrs; 104 105 LLVMContext &Context; 106 public: 107 BitcodeReaderMetadataList(LLVMContext &C) 108 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {} 109 110 // vector compatibility methods 111 unsigned size() const { return MetadataPtrs.size(); } 112 void resize(unsigned N) { MetadataPtrs.resize(N); } 113 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); } 114 void clear() { MetadataPtrs.clear(); } 115 Metadata *back() const { return MetadataPtrs.back(); } 116 void pop_back() { MetadataPtrs.pop_back(); } 117 bool empty() const { return MetadataPtrs.empty(); } 118 119 Metadata *operator[](unsigned i) const { 120 assert(i < MetadataPtrs.size()); 121 return MetadataPtrs[i]; 122 } 123 124 void shrinkTo(unsigned N) { 125 assert(N <= size() && "Invalid shrinkTo request!"); 126 MetadataPtrs.resize(N); 127 } 128 129 Metadata *getMetadataFwdRef(unsigned Idx); 130 MDNode *getMDNodeFwdRefOrNull(unsigned Idx); 131 void assignValue(Metadata *MD, unsigned Idx); 132 void tryToResolveCycles(); 133 }; 134 135 class BitcodeReader : public GVMaterializer { 136 LLVMContext &Context; 137 Module *TheModule = nullptr; 138 std::unique_ptr<MemoryBuffer> Buffer; 139 std::unique_ptr<BitstreamReader> StreamFile; 140 BitstreamCursor Stream; 141 // Next offset to start scanning for lazy parsing of function bodies. 142 uint64_t NextUnreadBit = 0; 143 // Last function offset found in the VST. 144 uint64_t LastFunctionBlockBit = 0; 145 bool SeenValueSymbolTable = false; 146 uint64_t VSTOffset = 0; 147 // Contains an arbitrary and optional string identifying the bitcode producer 148 std::string ProducerIdentification; 149 150 std::vector<Type*> TypeList; 151 BitcodeReaderValueList ValueList; 152 BitcodeReaderMetadataList MetadataList; 153 std::vector<Comdat *> ComdatList; 154 SmallVector<Instruction *, 64> InstructionList; 155 156 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits; 157 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits; 158 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes; 159 std::vector<std::pair<Function*, unsigned> > FunctionPrologues; 160 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns; 161 162 SmallVector<Instruction*, 64> InstsWithTBAATag; 163 164 bool HasSeenOldLoopTags = false; 165 166 /// The set of attributes by index. Index zero in the file is for null, and 167 /// is thus not represented here. As such all indices are off by one. 168 std::vector<AttributeSet> MAttributes; 169 170 /// The set of attribute groups. 171 std::map<unsigned, AttributeSet> MAttributeGroups; 172 173 /// While parsing a function body, this is a list of the basic blocks for the 174 /// function. 175 std::vector<BasicBlock*> FunctionBBs; 176 177 // When reading the module header, this list is populated with functions that 178 // have bodies later in the file. 179 std::vector<Function*> FunctionsWithBodies; 180 181 // When intrinsic functions are encountered which require upgrading they are 182 // stored here with their replacement function. 183 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap; 184 UpgradedIntrinsicMap UpgradedIntrinsics; 185 186 // Map the bitcode's custom MDKind ID to the Module's MDKind ID. 187 DenseMap<unsigned, unsigned> MDKindMap; 188 189 // Several operations happen after the module header has been read, but 190 // before function bodies are processed. This keeps track of whether 191 // we've done this yet. 192 bool SeenFirstFunctionBody = false; 193 194 /// When function bodies are initially scanned, this map contains info about 195 /// where to find deferred function body in the stream. 196 DenseMap<Function*, uint64_t> DeferredFunctionInfo; 197 198 /// When Metadata block is initially scanned when parsing the module, we may 199 /// choose to defer parsing of the metadata. This vector contains info about 200 /// which Metadata blocks are deferred. 201 std::vector<uint64_t> DeferredMetadataInfo; 202 203 /// These are basic blocks forward-referenced by block addresses. They are 204 /// inserted lazily into functions when they're loaded. The basic block ID is 205 /// its index into the vector. 206 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs; 207 std::deque<Function *> BasicBlockFwdRefQueue; 208 209 /// Indicates that we are using a new encoding for instruction operands where 210 /// most operands in the current FUNCTION_BLOCK are encoded relative to the 211 /// instruction number, for a more compact encoding. Some instruction 212 /// operands are not relative to the instruction ID: basic block numbers, and 213 /// types. Once the old style function blocks have been phased out, we would 214 /// not need this flag. 215 bool UseRelativeIDs = false; 216 217 /// True if all functions will be materialized, negating the need to process 218 /// (e.g.) blockaddress forward references. 219 bool WillMaterializeAllForwardRefs = false; 220 221 /// True if any Metadata block has been materialized. 222 bool IsMetadataMaterialized = false; 223 224 bool StripDebugInfo = false; 225 226 /// Functions that need to be matched with subprograms when upgrading old 227 /// metadata. 228 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs; 229 230 std::vector<std::string> BundleTags; 231 232 public: 233 std::error_code error(BitcodeError E, const Twine &Message); 234 std::error_code error(BitcodeError E); 235 std::error_code error(const Twine &Message); 236 237 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context); 238 BitcodeReader(LLVMContext &Context); 239 ~BitcodeReader() override { freeState(); } 240 241 std::error_code materializeForwardReferencedFunctions(); 242 243 void freeState(); 244 245 void releaseBuffer(); 246 247 std::error_code materialize(GlobalValue *GV) override; 248 std::error_code materializeModule() override; 249 std::vector<StructType *> getIdentifiedStructTypes() const override; 250 251 /// \brief Main interface to parsing a bitcode buffer. 252 /// \returns true if an error occurred. 253 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer, 254 Module *M, 255 bool ShouldLazyLoadMetadata = false); 256 257 /// \brief Cheap mechanism to just extract module triple 258 /// \returns true if an error occurred. 259 ErrorOr<std::string> parseTriple(); 260 261 /// Cheap mechanism to just extract the identification block out of bitcode. 262 ErrorOr<std::string> parseIdentificationBlock(); 263 264 static uint64_t decodeSignRotatedValue(uint64_t V); 265 266 /// Materialize any deferred Metadata block. 267 std::error_code materializeMetadata() override; 268 269 void setStripDebugInfo() override; 270 271 /// Save the mapping between the metadata values and the corresponding 272 /// value id that were recorded in the MetadataList during parsing. If 273 /// OnlyTempMD is true, then only record those entries that are still 274 /// temporary metadata. This interface is used when metadata linking is 275 /// performed as a postpass, such as during function importing. 276 void saveMetadataList(DenseMap<const Metadata *, unsigned> &MetadataToIDs, 277 bool OnlyTempMD) override; 278 279 private: 280 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the 281 // ProducerIdentification data member, and do some basic enforcement on the 282 // "epoch" encoded in the bitcode. 283 std::error_code parseBitcodeVersion(); 284 285 std::vector<StructType *> IdentifiedStructTypes; 286 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); 287 StructType *createIdentifiedStructType(LLVMContext &Context); 288 289 Type *getTypeByID(unsigned ID); 290 Value *getFnValueByID(unsigned ID, Type *Ty) { 291 if (Ty && Ty->isMetadataTy()) 292 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID)); 293 return ValueList.getValueFwdRef(ID, Ty); 294 } 295 Metadata *getFnMetadataByID(unsigned ID) { 296 return MetadataList.getMetadataFwdRef(ID); 297 } 298 BasicBlock *getBasicBlock(unsigned ID) const { 299 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID 300 return FunctionBBs[ID]; 301 } 302 AttributeSet getAttributes(unsigned i) const { 303 if (i-1 < MAttributes.size()) 304 return MAttributes[i-1]; 305 return AttributeSet(); 306 } 307 308 /// Read a value/type pair out of the specified record from slot 'Slot'. 309 /// Increment Slot past the number of slots used in the record. Return true on 310 /// failure. 311 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 312 unsigned InstNum, Value *&ResVal) { 313 if (Slot == Record.size()) return true; 314 unsigned ValNo = (unsigned)Record[Slot++]; 315 // Adjust the ValNo, if it was encoded relative to the InstNum. 316 if (UseRelativeIDs) 317 ValNo = InstNum - ValNo; 318 if (ValNo < InstNum) { 319 // If this is not a forward reference, just return the value we already 320 // have. 321 ResVal = getFnValueByID(ValNo, nullptr); 322 return ResVal == nullptr; 323 } 324 if (Slot == Record.size()) 325 return true; 326 327 unsigned TypeNo = (unsigned)Record[Slot++]; 328 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo)); 329 return ResVal == nullptr; 330 } 331 332 /// Read a value out of the specified record from slot 'Slot'. Increment Slot 333 /// past the number of slots used by the value in the record. Return true if 334 /// there is an error. 335 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot, 336 unsigned InstNum, Type *Ty, Value *&ResVal) { 337 if (getValue(Record, Slot, InstNum, Ty, ResVal)) 338 return true; 339 // All values currently take a single record slot. 340 ++Slot; 341 return false; 342 } 343 344 /// Like popValue, but does not increment the Slot number. 345 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 346 unsigned InstNum, Type *Ty, Value *&ResVal) { 347 ResVal = getValue(Record, Slot, InstNum, Ty); 348 return ResVal == nullptr; 349 } 350 351 /// Version of getValue that returns ResVal directly, or 0 if there is an 352 /// error. 353 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 354 unsigned InstNum, Type *Ty) { 355 if (Slot == Record.size()) return nullptr; 356 unsigned ValNo = (unsigned)Record[Slot]; 357 // Adjust the ValNo, if it was encoded relative to the InstNum. 358 if (UseRelativeIDs) 359 ValNo = InstNum - ValNo; 360 return getFnValueByID(ValNo, Ty); 361 } 362 363 /// Like getValue, but decodes signed VBRs. 364 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot, 365 unsigned InstNum, Type *Ty) { 366 if (Slot == Record.size()) return nullptr; 367 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); 368 // Adjust the ValNo, if it was encoded relative to the InstNum. 369 if (UseRelativeIDs) 370 ValNo = InstNum - ValNo; 371 return getFnValueByID(ValNo, Ty); 372 } 373 374 /// Converts alignment exponent (i.e. power of two (or zero)) to the 375 /// corresponding alignment to use. If alignment is too large, returns 376 /// a corresponding error code. 377 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment); 378 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind); 379 std::error_code parseModule(uint64_t ResumeBit, 380 bool ShouldLazyLoadMetadata = false); 381 std::error_code parseAttributeBlock(); 382 std::error_code parseAttributeGroupBlock(); 383 std::error_code parseTypeTable(); 384 std::error_code parseTypeTableBody(); 385 std::error_code parseOperandBundleTags(); 386 387 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record, 388 unsigned NameIndex, Triple &TT); 389 std::error_code parseValueSymbolTable(uint64_t Offset = 0); 390 std::error_code parseConstants(); 391 std::error_code rememberAndSkipFunctionBodies(); 392 std::error_code rememberAndSkipFunctionBody(); 393 /// Save the positions of the Metadata blocks and skip parsing the blocks. 394 std::error_code rememberAndSkipMetadata(); 395 std::error_code parseFunctionBody(Function *F); 396 std::error_code globalCleanup(); 397 std::error_code resolveGlobalAndAliasInits(); 398 std::error_code parseMetadata(bool ModuleLevel = false); 399 std::error_code parseMetadataKinds(); 400 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record); 401 std::error_code parseMetadataAttachment(Function &F); 402 ErrorOr<std::string> parseModuleTriple(); 403 std::error_code parseUseLists(); 404 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer); 405 std::error_code initStreamFromBuffer(); 406 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer); 407 std::error_code findFunctionInStream( 408 Function *F, 409 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator); 410 }; 411 412 /// Class to manage reading and parsing function summary index bitcode 413 /// files/sections. 414 class ModuleSummaryIndexBitcodeReader { 415 DiagnosticHandlerFunction DiagnosticHandler; 416 417 /// Eventually points to the module index built during parsing. 418 ModuleSummaryIndex *TheIndex = nullptr; 419 420 std::unique_ptr<MemoryBuffer> Buffer; 421 std::unique_ptr<BitstreamReader> StreamFile; 422 BitstreamCursor Stream; 423 424 /// \brief Used to indicate whether we are doing lazy parsing of summary data. 425 /// 426 /// If false, the summary section is fully parsed into the index during 427 /// the initial parse. Otherwise, if true, the caller is expected to 428 /// invoke \a readGlobalValueSummary for each summary needed, and the summary 429 /// section is thus parsed lazily. 430 bool IsLazy = false; 431 432 /// Used to indicate whether caller only wants to check for the presence 433 /// of the global value summary bitcode section. All blocks are skipped, 434 /// but the SeenGlobalValSummary boolean is set. 435 bool CheckGlobalValSummaryPresenceOnly = false; 436 437 /// Indicates whether we have encountered a global value summary section 438 /// yet during parsing, used when checking if file contains global value 439 /// summary section. 440 bool SeenGlobalValSummary = false; 441 442 /// Indicates whether we have already parsed the VST, used for error checking. 443 bool SeenValueSymbolTable = false; 444 445 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record. 446 /// Used to enable on-demand parsing of the VST. 447 uint64_t VSTOffset = 0; 448 449 // Map to save ValueId to GUID association that was recorded in the 450 // ValueSymbolTable. It is used after the VST is parsed to convert 451 // call graph edges read from the function summary from referencing 452 // callees by their ValueId to using the GUID instead, which is how 453 // they are recorded in the summary index being built. 454 DenseMap<unsigned, uint64_t> ValueIdToCallGraphGUIDMap; 455 456 /// Map to save the association between summary offset in the VST to the 457 /// GlobalValueInfo object created when parsing it. Used to access the 458 /// info object when parsing the summary section. 459 DenseMap<uint64_t, GlobalValueInfo *> SummaryOffsetToInfoMap; 460 461 /// Map populated during module path string table parsing, from the 462 /// module ID to a string reference owned by the index's module 463 /// path string table, used to correlate with combined index 464 /// summary records. 465 DenseMap<uint64_t, StringRef> ModuleIdMap; 466 467 /// Original source file name recorded in a bitcode record. 468 std::string SourceFileName; 469 470 public: 471 std::error_code error(BitcodeError E, const Twine &Message); 472 std::error_code error(BitcodeError E); 473 std::error_code error(const Twine &Message); 474 475 ModuleSummaryIndexBitcodeReader( 476 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler, 477 bool IsLazy = false, bool CheckGlobalValSummaryPresenceOnly = false); 478 ModuleSummaryIndexBitcodeReader( 479 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy = false, 480 bool CheckGlobalValSummaryPresenceOnly = false); 481 ~ModuleSummaryIndexBitcodeReader() { freeState(); } 482 483 void freeState(); 484 485 void releaseBuffer(); 486 487 /// Check if the parser has encountered a summary section. 488 bool foundGlobalValSummary() { return SeenGlobalValSummary; } 489 490 /// \brief Main interface to parsing a bitcode buffer. 491 /// \returns true if an error occurred. 492 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer, 493 ModuleSummaryIndex *I); 494 495 /// \brief Interface for parsing a summary lazily. 496 std::error_code 497 parseGlobalValueSummary(std::unique_ptr<DataStreamer> Streamer, 498 ModuleSummaryIndex *I, size_t SummaryOffset); 499 500 private: 501 std::error_code parseModule(); 502 std::error_code parseValueSymbolTable( 503 uint64_t Offset, 504 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap); 505 std::error_code parseEntireSummary(); 506 std::error_code parseModuleStringTable(); 507 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer); 508 std::error_code initStreamFromBuffer(); 509 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer); 510 uint64_t getGUIDFromValueId(unsigned ValueId); 511 GlobalValueInfo *getInfoFromSummaryOffset(uint64_t Offset); 512 }; 513 } // end anonymous namespace 514 515 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC, 516 DiagnosticSeverity Severity, 517 const Twine &Msg) 518 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {} 519 520 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 521 522 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler, 523 std::error_code EC, const Twine &Message) { 524 BitcodeDiagnosticInfo DI(EC, DS_Error, Message); 525 DiagnosticHandler(DI); 526 return EC; 527 } 528 529 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler, 530 std::error_code EC) { 531 return error(DiagnosticHandler, EC, EC.message()); 532 } 533 534 static std::error_code error(LLVMContext &Context, std::error_code EC, 535 const Twine &Message) { 536 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC, 537 Message); 538 } 539 540 static std::error_code error(LLVMContext &Context, std::error_code EC) { 541 return error(Context, EC, EC.message()); 542 } 543 544 static std::error_code error(LLVMContext &Context, const Twine &Message) { 545 return error(Context, make_error_code(BitcodeError::CorruptedBitcode), 546 Message); 547 } 548 549 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) { 550 if (!ProducerIdentification.empty()) { 551 return ::error(Context, make_error_code(E), 552 Message + " (Producer: '" + ProducerIdentification + 553 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')"); 554 } 555 return ::error(Context, make_error_code(E), Message); 556 } 557 558 std::error_code BitcodeReader::error(const Twine &Message) { 559 if (!ProducerIdentification.empty()) { 560 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode), 561 Message + " (Producer: '" + ProducerIdentification + 562 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')"); 563 } 564 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode), 565 Message); 566 } 567 568 std::error_code BitcodeReader::error(BitcodeError E) { 569 return ::error(Context, make_error_code(E)); 570 } 571 572 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context) 573 : Context(Context), Buffer(Buffer), ValueList(Context), 574 MetadataList(Context) {} 575 576 BitcodeReader::BitcodeReader(LLVMContext &Context) 577 : Context(Context), Buffer(nullptr), ValueList(Context), 578 MetadataList(Context) {} 579 580 std::error_code BitcodeReader::materializeForwardReferencedFunctions() { 581 if (WillMaterializeAllForwardRefs) 582 return std::error_code(); 583 584 // Prevent recursion. 585 WillMaterializeAllForwardRefs = true; 586 587 while (!BasicBlockFwdRefQueue.empty()) { 588 Function *F = BasicBlockFwdRefQueue.front(); 589 BasicBlockFwdRefQueue.pop_front(); 590 assert(F && "Expected valid function"); 591 if (!BasicBlockFwdRefs.count(F)) 592 // Already materialized. 593 continue; 594 595 // Check for a function that isn't materializable to prevent an infinite 596 // loop. When parsing a blockaddress stored in a global variable, there 597 // isn't a trivial way to check if a function will have a body without a 598 // linear search through FunctionsWithBodies, so just check it here. 599 if (!F->isMaterializable()) 600 return error("Never resolved function from blockaddress"); 601 602 // Try to materialize F. 603 if (std::error_code EC = materialize(F)) 604 return EC; 605 } 606 assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 607 608 // Reset state. 609 WillMaterializeAllForwardRefs = false; 610 return std::error_code(); 611 } 612 613 void BitcodeReader::freeState() { 614 Buffer = nullptr; 615 std::vector<Type*>().swap(TypeList); 616 ValueList.clear(); 617 MetadataList.clear(); 618 std::vector<Comdat *>().swap(ComdatList); 619 620 std::vector<AttributeSet>().swap(MAttributes); 621 std::vector<BasicBlock*>().swap(FunctionBBs); 622 std::vector<Function*>().swap(FunctionsWithBodies); 623 DeferredFunctionInfo.clear(); 624 DeferredMetadataInfo.clear(); 625 MDKindMap.clear(); 626 627 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references"); 628 BasicBlockFwdRefQueue.clear(); 629 } 630 631 //===----------------------------------------------------------------------===// 632 // Helper functions to implement forward reference resolution, etc. 633 //===----------------------------------------------------------------------===// 634 635 /// Convert a string from a record into an std::string, return true on failure. 636 template <typename StrTy> 637 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx, 638 StrTy &Result) { 639 if (Idx > Record.size()) 640 return true; 641 642 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 643 Result += (char)Record[i]; 644 return false; 645 } 646 647 static bool hasImplicitComdat(size_t Val) { 648 switch (Val) { 649 default: 650 return false; 651 case 1: // Old WeakAnyLinkage 652 case 4: // Old LinkOnceAnyLinkage 653 case 10: // Old WeakODRLinkage 654 case 11: // Old LinkOnceODRLinkage 655 return true; 656 } 657 } 658 659 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 660 switch (Val) { 661 default: // Map unknown/new linkages to external 662 case 0: 663 return GlobalValue::ExternalLinkage; 664 case 2: 665 return GlobalValue::AppendingLinkage; 666 case 3: 667 return GlobalValue::InternalLinkage; 668 case 5: 669 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 670 case 6: 671 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 672 case 7: 673 return GlobalValue::ExternalWeakLinkage; 674 case 8: 675 return GlobalValue::CommonLinkage; 676 case 9: 677 return GlobalValue::PrivateLinkage; 678 case 12: 679 return GlobalValue::AvailableExternallyLinkage; 680 case 13: 681 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 682 case 14: 683 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 684 case 15: 685 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 686 case 1: // Old value with implicit comdat. 687 case 16: 688 return GlobalValue::WeakAnyLinkage; 689 case 10: // Old value with implicit comdat. 690 case 17: 691 return GlobalValue::WeakODRLinkage; 692 case 4: // Old value with implicit comdat. 693 case 18: 694 return GlobalValue::LinkOnceAnyLinkage; 695 case 11: // Old value with implicit comdat. 696 case 19: 697 return GlobalValue::LinkOnceODRLinkage; 698 } 699 } 700 701 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { 702 switch (Val) { 703 default: // Map unknown visibilities to default. 704 case 0: return GlobalValue::DefaultVisibility; 705 case 1: return GlobalValue::HiddenVisibility; 706 case 2: return GlobalValue::ProtectedVisibility; 707 } 708 } 709 710 static GlobalValue::DLLStorageClassTypes 711 getDecodedDLLStorageClass(unsigned Val) { 712 switch (Val) { 713 default: // Map unknown values to default. 714 case 0: return GlobalValue::DefaultStorageClass; 715 case 1: return GlobalValue::DLLImportStorageClass; 716 case 2: return GlobalValue::DLLExportStorageClass; 717 } 718 } 719 720 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { 721 switch (Val) { 722 case 0: return GlobalVariable::NotThreadLocal; 723 default: // Map unknown non-zero value to general dynamic. 724 case 1: return GlobalVariable::GeneralDynamicTLSModel; 725 case 2: return GlobalVariable::LocalDynamicTLSModel; 726 case 3: return GlobalVariable::InitialExecTLSModel; 727 case 4: return GlobalVariable::LocalExecTLSModel; 728 } 729 } 730 731 static int getDecodedCastOpcode(unsigned Val) { 732 switch (Val) { 733 default: return -1; 734 case bitc::CAST_TRUNC : return Instruction::Trunc; 735 case bitc::CAST_ZEXT : return Instruction::ZExt; 736 case bitc::CAST_SEXT : return Instruction::SExt; 737 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 738 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 739 case bitc::CAST_UITOFP : return Instruction::UIToFP; 740 case bitc::CAST_SITOFP : return Instruction::SIToFP; 741 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 742 case bitc::CAST_FPEXT : return Instruction::FPExt; 743 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 744 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 745 case bitc::CAST_BITCAST : return Instruction::BitCast; 746 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 747 } 748 } 749 750 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) { 751 bool IsFP = Ty->isFPOrFPVectorTy(); 752 // BinOps are only valid for int/fp or vector of int/fp types 753 if (!IsFP && !Ty->isIntOrIntVectorTy()) 754 return -1; 755 756 switch (Val) { 757 default: 758 return -1; 759 case bitc::BINOP_ADD: 760 return IsFP ? Instruction::FAdd : Instruction::Add; 761 case bitc::BINOP_SUB: 762 return IsFP ? Instruction::FSub : Instruction::Sub; 763 case bitc::BINOP_MUL: 764 return IsFP ? Instruction::FMul : Instruction::Mul; 765 case bitc::BINOP_UDIV: 766 return IsFP ? -1 : Instruction::UDiv; 767 case bitc::BINOP_SDIV: 768 return IsFP ? Instruction::FDiv : Instruction::SDiv; 769 case bitc::BINOP_UREM: 770 return IsFP ? -1 : Instruction::URem; 771 case bitc::BINOP_SREM: 772 return IsFP ? Instruction::FRem : Instruction::SRem; 773 case bitc::BINOP_SHL: 774 return IsFP ? -1 : Instruction::Shl; 775 case bitc::BINOP_LSHR: 776 return IsFP ? -1 : Instruction::LShr; 777 case bitc::BINOP_ASHR: 778 return IsFP ? -1 : Instruction::AShr; 779 case bitc::BINOP_AND: 780 return IsFP ? -1 : Instruction::And; 781 case bitc::BINOP_OR: 782 return IsFP ? -1 : Instruction::Or; 783 case bitc::BINOP_XOR: 784 return IsFP ? -1 : Instruction::Xor; 785 } 786 } 787 788 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { 789 switch (Val) { 790 default: return AtomicRMWInst::BAD_BINOP; 791 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 792 case bitc::RMW_ADD: return AtomicRMWInst::Add; 793 case bitc::RMW_SUB: return AtomicRMWInst::Sub; 794 case bitc::RMW_AND: return AtomicRMWInst::And; 795 case bitc::RMW_NAND: return AtomicRMWInst::Nand; 796 case bitc::RMW_OR: return AtomicRMWInst::Or; 797 case bitc::RMW_XOR: return AtomicRMWInst::Xor; 798 case bitc::RMW_MAX: return AtomicRMWInst::Max; 799 case bitc::RMW_MIN: return AtomicRMWInst::Min; 800 case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 801 case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 802 } 803 } 804 805 static AtomicOrdering getDecodedOrdering(unsigned Val) { 806 switch (Val) { 807 case bitc::ORDERING_NOTATOMIC: return NotAtomic; 808 case bitc::ORDERING_UNORDERED: return Unordered; 809 case bitc::ORDERING_MONOTONIC: return Monotonic; 810 case bitc::ORDERING_ACQUIRE: return Acquire; 811 case bitc::ORDERING_RELEASE: return Release; 812 case bitc::ORDERING_ACQREL: return AcquireRelease; 813 default: // Map unknown orderings to sequentially-consistent. 814 case bitc::ORDERING_SEQCST: return SequentiallyConsistent; 815 } 816 } 817 818 static SynchronizationScope getDecodedSynchScope(unsigned Val) { 819 switch (Val) { 820 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread; 821 default: // Map unknown scopes to cross-thread. 822 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread; 823 } 824 } 825 826 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 827 switch (Val) { 828 default: // Map unknown selection kinds to any. 829 case bitc::COMDAT_SELECTION_KIND_ANY: 830 return Comdat::Any; 831 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 832 return Comdat::ExactMatch; 833 case bitc::COMDAT_SELECTION_KIND_LARGEST: 834 return Comdat::Largest; 835 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 836 return Comdat::NoDuplicates; 837 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 838 return Comdat::SameSize; 839 } 840 } 841 842 static FastMathFlags getDecodedFastMathFlags(unsigned Val) { 843 FastMathFlags FMF; 844 if (0 != (Val & FastMathFlags::UnsafeAlgebra)) 845 FMF.setUnsafeAlgebra(); 846 if (0 != (Val & FastMathFlags::NoNaNs)) 847 FMF.setNoNaNs(); 848 if (0 != (Val & FastMathFlags::NoInfs)) 849 FMF.setNoInfs(); 850 if (0 != (Val & FastMathFlags::NoSignedZeros)) 851 FMF.setNoSignedZeros(); 852 if (0 != (Val & FastMathFlags::AllowReciprocal)) 853 FMF.setAllowReciprocal(); 854 return FMF; 855 } 856 857 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) { 858 switch (Val) { 859 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 860 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 861 } 862 } 863 864 namespace llvm { 865 namespace { 866 /// \brief A class for maintaining the slot number definition 867 /// as a placeholder for the actual definition for forward constants defs. 868 class ConstantPlaceHolder : public ConstantExpr { 869 void operator=(const ConstantPlaceHolder &) = delete; 870 871 public: 872 // allocate space for exactly one operand 873 void *operator new(size_t s) { return User::operator new(s, 1); } 874 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context) 875 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 876 Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 877 } 878 879 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast. 880 static bool classof(const Value *V) { 881 return isa<ConstantExpr>(V) && 882 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 883 } 884 885 /// Provide fast operand accessors 886 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 887 }; 888 } // end anonymous namespace 889 890 // FIXME: can we inherit this from ConstantExpr? 891 template <> 892 struct OperandTraits<ConstantPlaceHolder> : 893 public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 894 }; 895 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value) 896 } // end namespace llvm 897 898 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) { 899 if (Idx == size()) { 900 push_back(V); 901 return; 902 } 903 904 if (Idx >= size()) 905 resize(Idx+1); 906 907 WeakVH &OldV = ValuePtrs[Idx]; 908 if (!OldV) { 909 OldV = V; 910 return; 911 } 912 913 // Handle constants and non-constants (e.g. instrs) differently for 914 // efficiency. 915 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 916 ResolveConstants.push_back(std::make_pair(PHC, Idx)); 917 OldV = V; 918 } else { 919 // If there was a forward reference to this value, replace it. 920 Value *PrevVal = OldV; 921 OldV->replaceAllUsesWith(V); 922 delete PrevVal; 923 } 924 } 925 926 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 927 Type *Ty) { 928 if (Idx >= size()) 929 resize(Idx + 1); 930 931 if (Value *V = ValuePtrs[Idx]) { 932 if (Ty != V->getType()) 933 report_fatal_error("Type mismatch in constant table!"); 934 return cast<Constant>(V); 935 } 936 937 // Create and return a placeholder, which will later be RAUW'd. 938 Constant *C = new ConstantPlaceHolder(Ty, Context); 939 ValuePtrs[Idx] = C; 940 return C; 941 } 942 943 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 944 // Bail out for a clearly invalid value. This would make us call resize(0) 945 if (Idx == UINT_MAX) 946 return nullptr; 947 948 if (Idx >= size()) 949 resize(Idx + 1); 950 951 if (Value *V = ValuePtrs[Idx]) { 952 // If the types don't match, it's invalid. 953 if (Ty && Ty != V->getType()) 954 return nullptr; 955 return V; 956 } 957 958 // No type specified, must be invalid reference. 959 if (!Ty) return nullptr; 960 961 // Create and return a placeholder, which will later be RAUW'd. 962 Value *V = new Argument(Ty); 963 ValuePtrs[Idx] = V; 964 return V; 965 } 966 967 /// Once all constants are read, this method bulk resolves any forward 968 /// references. The idea behind this is that we sometimes get constants (such 969 /// as large arrays) which reference *many* forward ref constants. Replacing 970 /// each of these causes a lot of thrashing when building/reuniquing the 971 /// constant. Instead of doing this, we look at all the uses and rewrite all 972 /// the place holders at once for any constant that uses a placeholder. 973 void BitcodeReaderValueList::resolveConstantForwardRefs() { 974 // Sort the values by-pointer so that they are efficient to look up with a 975 // binary search. 976 std::sort(ResolveConstants.begin(), ResolveConstants.end()); 977 978 SmallVector<Constant*, 64> NewOps; 979 980 while (!ResolveConstants.empty()) { 981 Value *RealVal = operator[](ResolveConstants.back().second); 982 Constant *Placeholder = ResolveConstants.back().first; 983 ResolveConstants.pop_back(); 984 985 // Loop over all users of the placeholder, updating them to reference the 986 // new value. If they reference more than one placeholder, update them all 987 // at once. 988 while (!Placeholder->use_empty()) { 989 auto UI = Placeholder->user_begin(); 990 User *U = *UI; 991 992 // If the using object isn't uniqued, just update the operands. This 993 // handles instructions and initializers for global variables. 994 if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 995 UI.getUse().set(RealVal); 996 continue; 997 } 998 999 // Otherwise, we have a constant that uses the placeholder. Replace that 1000 // constant with a new constant that has *all* placeholder uses updated. 1001 Constant *UserC = cast<Constant>(U); 1002 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 1003 I != E; ++I) { 1004 Value *NewOp; 1005 if (!isa<ConstantPlaceHolder>(*I)) { 1006 // Not a placeholder reference. 1007 NewOp = *I; 1008 } else if (*I == Placeholder) { 1009 // Common case is that it just references this one placeholder. 1010 NewOp = RealVal; 1011 } else { 1012 // Otherwise, look up the placeholder in ResolveConstants. 1013 ResolveConstantsTy::iterator It = 1014 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 1015 std::pair<Constant*, unsigned>(cast<Constant>(*I), 1016 0)); 1017 assert(It != ResolveConstants.end() && It->first == *I); 1018 NewOp = operator[](It->second); 1019 } 1020 1021 NewOps.push_back(cast<Constant>(NewOp)); 1022 } 1023 1024 // Make the new constant. 1025 Constant *NewC; 1026 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 1027 NewC = ConstantArray::get(UserCA->getType(), NewOps); 1028 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 1029 NewC = ConstantStruct::get(UserCS->getType(), NewOps); 1030 } else if (isa<ConstantVector>(UserC)) { 1031 NewC = ConstantVector::get(NewOps); 1032 } else { 1033 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 1034 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 1035 } 1036 1037 UserC->replaceAllUsesWith(NewC); 1038 UserC->destroyConstant(); 1039 NewOps.clear(); 1040 } 1041 1042 // Update all ValueHandles, they should be the only users at this point. 1043 Placeholder->replaceAllUsesWith(RealVal); 1044 delete Placeholder; 1045 } 1046 } 1047 1048 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) { 1049 if (Idx == size()) { 1050 push_back(MD); 1051 return; 1052 } 1053 1054 if (Idx >= size()) 1055 resize(Idx+1); 1056 1057 TrackingMDRef &OldMD = MetadataPtrs[Idx]; 1058 if (!OldMD) { 1059 OldMD.reset(MD); 1060 return; 1061 } 1062 1063 // If there was a forward reference to this value, replace it. 1064 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get())); 1065 PrevMD->replaceAllUsesWith(MD); 1066 --NumFwdRefs; 1067 } 1068 1069 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) { 1070 if (Idx >= size()) 1071 resize(Idx + 1); 1072 1073 if (Metadata *MD = MetadataPtrs[Idx]) 1074 return MD; 1075 1076 // Track forward refs to be resolved later. 1077 if (AnyFwdRefs) { 1078 MinFwdRef = std::min(MinFwdRef, Idx); 1079 MaxFwdRef = std::max(MaxFwdRef, Idx); 1080 } else { 1081 AnyFwdRefs = true; 1082 MinFwdRef = MaxFwdRef = Idx; 1083 } 1084 ++NumFwdRefs; 1085 1086 // Create and return a placeholder, which will later be RAUW'd. 1087 Metadata *MD = MDNode::getTemporary(Context, None).release(); 1088 MetadataPtrs[Idx].reset(MD); 1089 return MD; 1090 } 1091 1092 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) { 1093 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx)); 1094 } 1095 1096 void BitcodeReaderMetadataList::tryToResolveCycles() { 1097 if (!AnyFwdRefs) 1098 // Nothing to do. 1099 return; 1100 1101 if (NumFwdRefs) 1102 // Still forward references... can't resolve cycles. 1103 return; 1104 1105 // Resolve any cycles. 1106 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) { 1107 auto &MD = MetadataPtrs[I]; 1108 auto *N = dyn_cast_or_null<MDNode>(MD); 1109 if (!N) 1110 continue; 1111 1112 assert(!N->isTemporary() && "Unexpected forward reference"); 1113 N->resolveCycles(); 1114 } 1115 1116 // Make sure we return early again until there's another forward ref. 1117 AnyFwdRefs = false; 1118 } 1119 1120 Type *BitcodeReader::getTypeByID(unsigned ID) { 1121 // The type table size is always specified correctly. 1122 if (ID >= TypeList.size()) 1123 return nullptr; 1124 1125 if (Type *Ty = TypeList[ID]) 1126 return Ty; 1127 1128 // If we have a forward reference, the only possible case is when it is to a 1129 // named struct. Just create a placeholder for now. 1130 return TypeList[ID] = createIdentifiedStructType(Context); 1131 } 1132 1133 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 1134 StringRef Name) { 1135 auto *Ret = StructType::create(Context, Name); 1136 IdentifiedStructTypes.push_back(Ret); 1137 return Ret; 1138 } 1139 1140 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 1141 auto *Ret = StructType::create(Context); 1142 IdentifiedStructTypes.push_back(Ret); 1143 return Ret; 1144 } 1145 1146 //===----------------------------------------------------------------------===// 1147 // Functions for parsing blocks from the bitcode file 1148 //===----------------------------------------------------------------------===// 1149 1150 1151 /// \brief This fills an AttrBuilder object with the LLVM attributes that have 1152 /// been decoded from the given integer. This function must stay in sync with 1153 /// 'encodeLLVMAttributesForBitcode'. 1154 static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 1155 uint64_t EncodedAttrs) { 1156 // FIXME: Remove in 4.0. 1157 1158 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 1159 // the bits above 31 down by 11 bits. 1160 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 1161 assert((!Alignment || isPowerOf2_32(Alignment)) && 1162 "Alignment must be a power of two."); 1163 1164 if (Alignment) 1165 B.addAlignmentAttr(Alignment); 1166 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 1167 (EncodedAttrs & 0xffff)); 1168 } 1169 1170 std::error_code BitcodeReader::parseAttributeBlock() { 1171 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 1172 return error("Invalid record"); 1173 1174 if (!MAttributes.empty()) 1175 return error("Invalid multiple blocks"); 1176 1177 SmallVector<uint64_t, 64> Record; 1178 1179 SmallVector<AttributeSet, 8> Attrs; 1180 1181 // Read all the records. 1182 while (1) { 1183 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1184 1185 switch (Entry.Kind) { 1186 case BitstreamEntry::SubBlock: // Handled for us already. 1187 case BitstreamEntry::Error: 1188 return error("Malformed block"); 1189 case BitstreamEntry::EndBlock: 1190 return std::error_code(); 1191 case BitstreamEntry::Record: 1192 // The interesting case. 1193 break; 1194 } 1195 1196 // Read a record. 1197 Record.clear(); 1198 switch (Stream.readRecord(Entry.ID, Record)) { 1199 default: // Default behavior: ignore. 1200 break; 1201 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 1202 // FIXME: Remove in 4.0. 1203 if (Record.size() & 1) 1204 return error("Invalid record"); 1205 1206 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1207 AttrBuilder B; 1208 decodeLLVMAttributesForBitcode(B, Record[i+1]); 1209 Attrs.push_back(AttributeSet::get(Context, Record[i], B)); 1210 } 1211 1212 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 1213 Attrs.clear(); 1214 break; 1215 } 1216 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 1217 for (unsigned i = 0, e = Record.size(); i != e; ++i) 1218 Attrs.push_back(MAttributeGroups[Record[i]]); 1219 1220 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 1221 Attrs.clear(); 1222 break; 1223 } 1224 } 1225 } 1226 } 1227 1228 // Returns Attribute::None on unrecognized codes. 1229 static Attribute::AttrKind getAttrFromCode(uint64_t Code) { 1230 switch (Code) { 1231 default: 1232 return Attribute::None; 1233 case bitc::ATTR_KIND_ALIGNMENT: 1234 return Attribute::Alignment; 1235 case bitc::ATTR_KIND_ALWAYS_INLINE: 1236 return Attribute::AlwaysInline; 1237 case bitc::ATTR_KIND_ARGMEMONLY: 1238 return Attribute::ArgMemOnly; 1239 case bitc::ATTR_KIND_BUILTIN: 1240 return Attribute::Builtin; 1241 case bitc::ATTR_KIND_BY_VAL: 1242 return Attribute::ByVal; 1243 case bitc::ATTR_KIND_IN_ALLOCA: 1244 return Attribute::InAlloca; 1245 case bitc::ATTR_KIND_COLD: 1246 return Attribute::Cold; 1247 case bitc::ATTR_KIND_CONVERGENT: 1248 return Attribute::Convergent; 1249 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY: 1250 return Attribute::InaccessibleMemOnly; 1251 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY: 1252 return Attribute::InaccessibleMemOrArgMemOnly; 1253 case bitc::ATTR_KIND_INLINE_HINT: 1254 return Attribute::InlineHint; 1255 case bitc::ATTR_KIND_IN_REG: 1256 return Attribute::InReg; 1257 case bitc::ATTR_KIND_JUMP_TABLE: 1258 return Attribute::JumpTable; 1259 case bitc::ATTR_KIND_MIN_SIZE: 1260 return Attribute::MinSize; 1261 case bitc::ATTR_KIND_NAKED: 1262 return Attribute::Naked; 1263 case bitc::ATTR_KIND_NEST: 1264 return Attribute::Nest; 1265 case bitc::ATTR_KIND_NO_ALIAS: 1266 return Attribute::NoAlias; 1267 case bitc::ATTR_KIND_NO_BUILTIN: 1268 return Attribute::NoBuiltin; 1269 case bitc::ATTR_KIND_NO_CAPTURE: 1270 return Attribute::NoCapture; 1271 case bitc::ATTR_KIND_NO_DUPLICATE: 1272 return Attribute::NoDuplicate; 1273 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 1274 return Attribute::NoImplicitFloat; 1275 case bitc::ATTR_KIND_NO_INLINE: 1276 return Attribute::NoInline; 1277 case bitc::ATTR_KIND_NO_RECURSE: 1278 return Attribute::NoRecurse; 1279 case bitc::ATTR_KIND_NON_LAZY_BIND: 1280 return Attribute::NonLazyBind; 1281 case bitc::ATTR_KIND_NON_NULL: 1282 return Attribute::NonNull; 1283 case bitc::ATTR_KIND_DEREFERENCEABLE: 1284 return Attribute::Dereferenceable; 1285 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL: 1286 return Attribute::DereferenceableOrNull; 1287 case bitc::ATTR_KIND_NO_RED_ZONE: 1288 return Attribute::NoRedZone; 1289 case bitc::ATTR_KIND_NO_RETURN: 1290 return Attribute::NoReturn; 1291 case bitc::ATTR_KIND_NO_UNWIND: 1292 return Attribute::NoUnwind; 1293 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 1294 return Attribute::OptimizeForSize; 1295 case bitc::ATTR_KIND_OPTIMIZE_NONE: 1296 return Attribute::OptimizeNone; 1297 case bitc::ATTR_KIND_READ_NONE: 1298 return Attribute::ReadNone; 1299 case bitc::ATTR_KIND_READ_ONLY: 1300 return Attribute::ReadOnly; 1301 case bitc::ATTR_KIND_RETURNED: 1302 return Attribute::Returned; 1303 case bitc::ATTR_KIND_RETURNS_TWICE: 1304 return Attribute::ReturnsTwice; 1305 case bitc::ATTR_KIND_S_EXT: 1306 return Attribute::SExt; 1307 case bitc::ATTR_KIND_STACK_ALIGNMENT: 1308 return Attribute::StackAlignment; 1309 case bitc::ATTR_KIND_STACK_PROTECT: 1310 return Attribute::StackProtect; 1311 case bitc::ATTR_KIND_STACK_PROTECT_REQ: 1312 return Attribute::StackProtectReq; 1313 case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 1314 return Attribute::StackProtectStrong; 1315 case bitc::ATTR_KIND_SAFESTACK: 1316 return Attribute::SafeStack; 1317 case bitc::ATTR_KIND_STRUCT_RET: 1318 return Attribute::StructRet; 1319 case bitc::ATTR_KIND_SANITIZE_ADDRESS: 1320 return Attribute::SanitizeAddress; 1321 case bitc::ATTR_KIND_SANITIZE_THREAD: 1322 return Attribute::SanitizeThread; 1323 case bitc::ATTR_KIND_SANITIZE_MEMORY: 1324 return Attribute::SanitizeMemory; 1325 case bitc::ATTR_KIND_UW_TABLE: 1326 return Attribute::UWTable; 1327 case bitc::ATTR_KIND_Z_EXT: 1328 return Attribute::ZExt; 1329 } 1330 } 1331 1332 std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent, 1333 unsigned &Alignment) { 1334 // Note: Alignment in bitcode files is incremented by 1, so that zero 1335 // can be used for default alignment. 1336 if (Exponent > Value::MaxAlignmentExponent + 1) 1337 return error("Invalid alignment value"); 1338 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1; 1339 return std::error_code(); 1340 } 1341 1342 std::error_code BitcodeReader::parseAttrKind(uint64_t Code, 1343 Attribute::AttrKind *Kind) { 1344 *Kind = getAttrFromCode(Code); 1345 if (*Kind == Attribute::None) 1346 return error(BitcodeError::CorruptedBitcode, 1347 "Unknown attribute kind (" + Twine(Code) + ")"); 1348 return std::error_code(); 1349 } 1350 1351 std::error_code BitcodeReader::parseAttributeGroupBlock() { 1352 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 1353 return error("Invalid record"); 1354 1355 if (!MAttributeGroups.empty()) 1356 return error("Invalid multiple blocks"); 1357 1358 SmallVector<uint64_t, 64> Record; 1359 1360 // Read all the records. 1361 while (1) { 1362 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1363 1364 switch (Entry.Kind) { 1365 case BitstreamEntry::SubBlock: // Handled for us already. 1366 case BitstreamEntry::Error: 1367 return error("Malformed block"); 1368 case BitstreamEntry::EndBlock: 1369 return std::error_code(); 1370 case BitstreamEntry::Record: 1371 // The interesting case. 1372 break; 1373 } 1374 1375 // Read a record. 1376 Record.clear(); 1377 switch (Stream.readRecord(Entry.ID, Record)) { 1378 default: // Default behavior: ignore. 1379 break; 1380 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 1381 if (Record.size() < 3) 1382 return error("Invalid record"); 1383 1384 uint64_t GrpID = Record[0]; 1385 uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 1386 1387 AttrBuilder B; 1388 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1389 if (Record[i] == 0) { // Enum attribute 1390 Attribute::AttrKind Kind; 1391 if (std::error_code EC = parseAttrKind(Record[++i], &Kind)) 1392 return EC; 1393 1394 B.addAttribute(Kind); 1395 } else if (Record[i] == 1) { // Integer attribute 1396 Attribute::AttrKind Kind; 1397 if (std::error_code EC = parseAttrKind(Record[++i], &Kind)) 1398 return EC; 1399 if (Kind == Attribute::Alignment) 1400 B.addAlignmentAttr(Record[++i]); 1401 else if (Kind == Attribute::StackAlignment) 1402 B.addStackAlignmentAttr(Record[++i]); 1403 else if (Kind == Attribute::Dereferenceable) 1404 B.addDereferenceableAttr(Record[++i]); 1405 else if (Kind == Attribute::DereferenceableOrNull) 1406 B.addDereferenceableOrNullAttr(Record[++i]); 1407 } else { // String attribute 1408 assert((Record[i] == 3 || Record[i] == 4) && 1409 "Invalid attribute group entry"); 1410 bool HasValue = (Record[i++] == 4); 1411 SmallString<64> KindStr; 1412 SmallString<64> ValStr; 1413 1414 while (Record[i] != 0 && i != e) 1415 KindStr += Record[i++]; 1416 assert(Record[i] == 0 && "Kind string not null terminated"); 1417 1418 if (HasValue) { 1419 // Has a value associated with it. 1420 ++i; // Skip the '0' that terminates the "kind" string. 1421 while (Record[i] != 0 && i != e) 1422 ValStr += Record[i++]; 1423 assert(Record[i] == 0 && "Value string not null terminated"); 1424 } 1425 1426 B.addAttribute(KindStr.str(), ValStr.str()); 1427 } 1428 } 1429 1430 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B); 1431 break; 1432 } 1433 } 1434 } 1435 } 1436 1437 std::error_code BitcodeReader::parseTypeTable() { 1438 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 1439 return error("Invalid record"); 1440 1441 return parseTypeTableBody(); 1442 } 1443 1444 std::error_code BitcodeReader::parseTypeTableBody() { 1445 if (!TypeList.empty()) 1446 return error("Invalid multiple blocks"); 1447 1448 SmallVector<uint64_t, 64> Record; 1449 unsigned NumRecords = 0; 1450 1451 SmallString<64> TypeName; 1452 1453 // Read all the records for this type table. 1454 while (1) { 1455 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1456 1457 switch (Entry.Kind) { 1458 case BitstreamEntry::SubBlock: // Handled for us already. 1459 case BitstreamEntry::Error: 1460 return error("Malformed block"); 1461 case BitstreamEntry::EndBlock: 1462 if (NumRecords != TypeList.size()) 1463 return error("Malformed block"); 1464 return std::error_code(); 1465 case BitstreamEntry::Record: 1466 // The interesting case. 1467 break; 1468 } 1469 1470 // Read a record. 1471 Record.clear(); 1472 Type *ResultTy = nullptr; 1473 switch (Stream.readRecord(Entry.ID, Record)) { 1474 default: 1475 return error("Invalid value"); 1476 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 1477 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 1478 // type list. This allows us to reserve space. 1479 if (Record.size() < 1) 1480 return error("Invalid record"); 1481 TypeList.resize(Record[0]); 1482 continue; 1483 case bitc::TYPE_CODE_VOID: // VOID 1484 ResultTy = Type::getVoidTy(Context); 1485 break; 1486 case bitc::TYPE_CODE_HALF: // HALF 1487 ResultTy = Type::getHalfTy(Context); 1488 break; 1489 case bitc::TYPE_CODE_FLOAT: // FLOAT 1490 ResultTy = Type::getFloatTy(Context); 1491 break; 1492 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 1493 ResultTy = Type::getDoubleTy(Context); 1494 break; 1495 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 1496 ResultTy = Type::getX86_FP80Ty(Context); 1497 break; 1498 case bitc::TYPE_CODE_FP128: // FP128 1499 ResultTy = Type::getFP128Ty(Context); 1500 break; 1501 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 1502 ResultTy = Type::getPPC_FP128Ty(Context); 1503 break; 1504 case bitc::TYPE_CODE_LABEL: // LABEL 1505 ResultTy = Type::getLabelTy(Context); 1506 break; 1507 case bitc::TYPE_CODE_METADATA: // METADATA 1508 ResultTy = Type::getMetadataTy(Context); 1509 break; 1510 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 1511 ResultTy = Type::getX86_MMXTy(Context); 1512 break; 1513 case bitc::TYPE_CODE_TOKEN: // TOKEN 1514 ResultTy = Type::getTokenTy(Context); 1515 break; 1516 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 1517 if (Record.size() < 1) 1518 return error("Invalid record"); 1519 1520 uint64_t NumBits = Record[0]; 1521 if (NumBits < IntegerType::MIN_INT_BITS || 1522 NumBits > IntegerType::MAX_INT_BITS) 1523 return error("Bitwidth for integer type out of range"); 1524 ResultTy = IntegerType::get(Context, NumBits); 1525 break; 1526 } 1527 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 1528 // [pointee type, address space] 1529 if (Record.size() < 1) 1530 return error("Invalid record"); 1531 unsigned AddressSpace = 0; 1532 if (Record.size() == 2) 1533 AddressSpace = Record[1]; 1534 ResultTy = getTypeByID(Record[0]); 1535 if (!ResultTy || 1536 !PointerType::isValidElementType(ResultTy)) 1537 return error("Invalid type"); 1538 ResultTy = PointerType::get(ResultTy, AddressSpace); 1539 break; 1540 } 1541 case bitc::TYPE_CODE_FUNCTION_OLD: { 1542 // FIXME: attrid is dead, remove it in LLVM 4.0 1543 // FUNCTION: [vararg, attrid, retty, paramty x N] 1544 if (Record.size() < 3) 1545 return error("Invalid record"); 1546 SmallVector<Type*, 8> ArgTys; 1547 for (unsigned i = 3, e = Record.size(); i != e; ++i) { 1548 if (Type *T = getTypeByID(Record[i])) 1549 ArgTys.push_back(T); 1550 else 1551 break; 1552 } 1553 1554 ResultTy = getTypeByID(Record[2]); 1555 if (!ResultTy || ArgTys.size() < Record.size()-3) 1556 return error("Invalid type"); 1557 1558 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 1559 break; 1560 } 1561 case bitc::TYPE_CODE_FUNCTION: { 1562 // FUNCTION: [vararg, retty, paramty x N] 1563 if (Record.size() < 2) 1564 return error("Invalid record"); 1565 SmallVector<Type*, 8> ArgTys; 1566 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1567 if (Type *T = getTypeByID(Record[i])) { 1568 if (!FunctionType::isValidArgumentType(T)) 1569 return error("Invalid function argument type"); 1570 ArgTys.push_back(T); 1571 } 1572 else 1573 break; 1574 } 1575 1576 ResultTy = getTypeByID(Record[1]); 1577 if (!ResultTy || ArgTys.size() < Record.size()-2) 1578 return error("Invalid type"); 1579 1580 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 1581 break; 1582 } 1583 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 1584 if (Record.size() < 1) 1585 return error("Invalid record"); 1586 SmallVector<Type*, 8> EltTys; 1587 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 1588 if (Type *T = getTypeByID(Record[i])) 1589 EltTys.push_back(T); 1590 else 1591 break; 1592 } 1593 if (EltTys.size() != Record.size()-1) 1594 return error("Invalid type"); 1595 ResultTy = StructType::get(Context, EltTys, Record[0]); 1596 break; 1597 } 1598 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 1599 if (convertToString(Record, 0, TypeName)) 1600 return error("Invalid record"); 1601 continue; 1602 1603 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 1604 if (Record.size() < 1) 1605 return error("Invalid record"); 1606 1607 if (NumRecords >= TypeList.size()) 1608 return error("Invalid TYPE table"); 1609 1610 // Check to see if this was forward referenced, if so fill in the temp. 1611 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 1612 if (Res) { 1613 Res->setName(TypeName); 1614 TypeList[NumRecords] = nullptr; 1615 } else // Otherwise, create a new struct. 1616 Res = createIdentifiedStructType(Context, TypeName); 1617 TypeName.clear(); 1618 1619 SmallVector<Type*, 8> EltTys; 1620 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 1621 if (Type *T = getTypeByID(Record[i])) 1622 EltTys.push_back(T); 1623 else 1624 break; 1625 } 1626 if (EltTys.size() != Record.size()-1) 1627 return error("Invalid record"); 1628 Res->setBody(EltTys, Record[0]); 1629 ResultTy = Res; 1630 break; 1631 } 1632 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 1633 if (Record.size() != 1) 1634 return error("Invalid record"); 1635 1636 if (NumRecords >= TypeList.size()) 1637 return error("Invalid TYPE table"); 1638 1639 // Check to see if this was forward referenced, if so fill in the temp. 1640 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 1641 if (Res) { 1642 Res->setName(TypeName); 1643 TypeList[NumRecords] = nullptr; 1644 } else // Otherwise, create a new struct with no body. 1645 Res = createIdentifiedStructType(Context, TypeName); 1646 TypeName.clear(); 1647 ResultTy = Res; 1648 break; 1649 } 1650 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 1651 if (Record.size() < 2) 1652 return error("Invalid record"); 1653 ResultTy = getTypeByID(Record[1]); 1654 if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) 1655 return error("Invalid type"); 1656 ResultTy = ArrayType::get(ResultTy, Record[0]); 1657 break; 1658 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 1659 if (Record.size() < 2) 1660 return error("Invalid record"); 1661 if (Record[0] == 0) 1662 return error("Invalid vector length"); 1663 ResultTy = getTypeByID(Record[1]); 1664 if (!ResultTy || !StructType::isValidElementType(ResultTy)) 1665 return error("Invalid type"); 1666 ResultTy = VectorType::get(ResultTy, Record[0]); 1667 break; 1668 } 1669 1670 if (NumRecords >= TypeList.size()) 1671 return error("Invalid TYPE table"); 1672 if (TypeList[NumRecords]) 1673 return error( 1674 "Invalid TYPE table: Only named structs can be forward referenced"); 1675 assert(ResultTy && "Didn't read a type?"); 1676 TypeList[NumRecords++] = ResultTy; 1677 } 1678 } 1679 1680 std::error_code BitcodeReader::parseOperandBundleTags() { 1681 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID)) 1682 return error("Invalid record"); 1683 1684 if (!BundleTags.empty()) 1685 return error("Invalid multiple blocks"); 1686 1687 SmallVector<uint64_t, 64> Record; 1688 1689 while (1) { 1690 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1691 1692 switch (Entry.Kind) { 1693 case BitstreamEntry::SubBlock: // Handled for us already. 1694 case BitstreamEntry::Error: 1695 return error("Malformed block"); 1696 case BitstreamEntry::EndBlock: 1697 return std::error_code(); 1698 case BitstreamEntry::Record: 1699 // The interesting case. 1700 break; 1701 } 1702 1703 // Tags are implicitly mapped to integers by their order. 1704 1705 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG) 1706 return error("Invalid record"); 1707 1708 // OPERAND_BUNDLE_TAG: [strchr x N] 1709 BundleTags.emplace_back(); 1710 if (convertToString(Record, 0, BundleTags.back())) 1711 return error("Invalid record"); 1712 Record.clear(); 1713 } 1714 } 1715 1716 /// Associate a value with its name from the given index in the provided record. 1717 ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record, 1718 unsigned NameIndex, Triple &TT) { 1719 SmallString<128> ValueName; 1720 if (convertToString(Record, NameIndex, ValueName)) 1721 return error("Invalid record"); 1722 unsigned ValueID = Record[0]; 1723 if (ValueID >= ValueList.size() || !ValueList[ValueID]) 1724 return error("Invalid record"); 1725 Value *V = ValueList[ValueID]; 1726 1727 StringRef NameStr(ValueName.data(), ValueName.size()); 1728 if (NameStr.find_first_of(0) != StringRef::npos) 1729 return error("Invalid value name"); 1730 V->setName(NameStr); 1731 auto *GO = dyn_cast<GlobalObject>(V); 1732 if (GO) { 1733 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) { 1734 if (TT.isOSBinFormatMachO()) 1735 GO->setComdat(nullptr); 1736 else 1737 GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 1738 } 1739 } 1740 return V; 1741 } 1742 1743 /// Helper to note and return the current location, and jump to the given 1744 /// offset. 1745 static uint64_t jumpToValueSymbolTable(uint64_t Offset, 1746 BitstreamCursor &Stream) { 1747 // Save the current parsing location so we can jump back at the end 1748 // of the VST read. 1749 uint64_t CurrentBit = Stream.GetCurrentBitNo(); 1750 Stream.JumpToBit(Offset * 32); 1751 #ifndef NDEBUG 1752 // Do some checking if we are in debug mode. 1753 BitstreamEntry Entry = Stream.advance(); 1754 assert(Entry.Kind == BitstreamEntry::SubBlock); 1755 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID); 1756 #else 1757 // In NDEBUG mode ignore the output so we don't get an unused variable 1758 // warning. 1759 Stream.advance(); 1760 #endif 1761 return CurrentBit; 1762 } 1763 1764 /// Parse the value symbol table at either the current parsing location or 1765 /// at the given bit offset if provided. 1766 std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) { 1767 uint64_t CurrentBit; 1768 // Pass in the Offset to distinguish between calling for the module-level 1769 // VST (where we want to jump to the VST offset) and the function-level 1770 // VST (where we don't). 1771 if (Offset > 0) 1772 CurrentBit = jumpToValueSymbolTable(Offset, Stream); 1773 1774 // Compute the delta between the bitcode indices in the VST (the word offset 1775 // to the word-aligned ENTER_SUBBLOCK for the function block, and that 1776 // expected by the lazy reader. The reader's EnterSubBlock expects to have 1777 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID 1778 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here 1779 // just before entering the VST subblock because: 1) the EnterSubBlock 1780 // changes the AbbrevID width; 2) the VST block is nested within the same 1781 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same 1782 // AbbrevID width before calling EnterSubBlock; and 3) when we want to 1783 // jump to the FUNCTION_BLOCK using this offset later, we don't want 1784 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK. 1785 unsigned FuncBitcodeOffsetDelta = 1786 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth; 1787 1788 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 1789 return error("Invalid record"); 1790 1791 SmallVector<uint64_t, 64> Record; 1792 1793 Triple TT(TheModule->getTargetTriple()); 1794 1795 // Read all the records for this value table. 1796 SmallString<128> ValueName; 1797 while (1) { 1798 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1799 1800 switch (Entry.Kind) { 1801 case BitstreamEntry::SubBlock: // Handled for us already. 1802 case BitstreamEntry::Error: 1803 return error("Malformed block"); 1804 case BitstreamEntry::EndBlock: 1805 if (Offset > 0) 1806 Stream.JumpToBit(CurrentBit); 1807 return std::error_code(); 1808 case BitstreamEntry::Record: 1809 // The interesting case. 1810 break; 1811 } 1812 1813 // Read a record. 1814 Record.clear(); 1815 switch (Stream.readRecord(Entry.ID, Record)) { 1816 default: // Default behavior: unknown type. 1817 break; 1818 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 1819 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT); 1820 if (std::error_code EC = ValOrErr.getError()) 1821 return EC; 1822 ValOrErr.get(); 1823 break; 1824 } 1825 case bitc::VST_CODE_FNENTRY: { 1826 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 1827 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT); 1828 if (std::error_code EC = ValOrErr.getError()) 1829 return EC; 1830 Value *V = ValOrErr.get(); 1831 1832 auto *GO = dyn_cast<GlobalObject>(V); 1833 if (!GO) { 1834 // If this is an alias, need to get the actual Function object 1835 // it aliases, in order to set up the DeferredFunctionInfo entry below. 1836 auto *GA = dyn_cast<GlobalAlias>(V); 1837 if (GA) 1838 GO = GA->getBaseObject(); 1839 assert(GO); 1840 } 1841 1842 uint64_t FuncWordOffset = Record[1]; 1843 Function *F = dyn_cast<Function>(GO); 1844 assert(F); 1845 uint64_t FuncBitOffset = FuncWordOffset * 32; 1846 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta; 1847 // Set the LastFunctionBlockBit to point to the last function block. 1848 // Later when parsing is resumed after function materialization, 1849 // we can simply skip that last function block. 1850 if (FuncBitOffset > LastFunctionBlockBit) 1851 LastFunctionBlockBit = FuncBitOffset; 1852 break; 1853 } 1854 case bitc::VST_CODE_BBENTRY: { 1855 if (convertToString(Record, 1, ValueName)) 1856 return error("Invalid record"); 1857 BasicBlock *BB = getBasicBlock(Record[0]); 1858 if (!BB) 1859 return error("Invalid record"); 1860 1861 BB->setName(StringRef(ValueName.data(), ValueName.size())); 1862 ValueName.clear(); 1863 break; 1864 } 1865 } 1866 } 1867 } 1868 1869 /// Parse a single METADATA_KIND record, inserting result in MDKindMap. 1870 std::error_code 1871 BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) { 1872 if (Record.size() < 2) 1873 return error("Invalid record"); 1874 1875 unsigned Kind = Record[0]; 1876 SmallString<8> Name(Record.begin() + 1, Record.end()); 1877 1878 unsigned NewKind = TheModule->getMDKindID(Name.str()); 1879 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1880 return error("Conflicting METADATA_KIND records"); 1881 return std::error_code(); 1882 } 1883 1884 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; } 1885 1886 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing 1887 /// module level metadata. 1888 std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) { 1889 IsMetadataMaterialized = true; 1890 unsigned NextMetadataNo = MetadataList.size(); 1891 1892 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 1893 return error("Invalid record"); 1894 1895 SmallVector<uint64_t, 64> Record; 1896 1897 auto getMD = [&](unsigned ID) -> Metadata * { 1898 return MetadataList.getMetadataFwdRef(ID); 1899 }; 1900 auto getMDOrNull = [&](unsigned ID) -> Metadata *{ 1901 if (ID) 1902 return getMD(ID - 1); 1903 return nullptr; 1904 }; 1905 auto getMDString = [&](unsigned ID) -> MDString *{ 1906 // This requires that the ID is not really a forward reference. In 1907 // particular, the MDString must already have been resolved. 1908 return cast_or_null<MDString>(getMDOrNull(ID)); 1909 }; 1910 1911 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \ 1912 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS) 1913 1914 // Read all the records. 1915 while (1) { 1916 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1917 1918 switch (Entry.Kind) { 1919 case BitstreamEntry::SubBlock: // Handled for us already. 1920 case BitstreamEntry::Error: 1921 return error("Malformed block"); 1922 case BitstreamEntry::EndBlock: 1923 MetadataList.tryToResolveCycles(); 1924 return std::error_code(); 1925 case BitstreamEntry::Record: 1926 // The interesting case. 1927 break; 1928 } 1929 1930 // Read a record. 1931 Record.clear(); 1932 unsigned Code = Stream.readRecord(Entry.ID, Record); 1933 bool IsDistinct = false; 1934 switch (Code) { 1935 default: // Default behavior: ignore. 1936 break; 1937 case bitc::METADATA_NAME: { 1938 // Read name of the named metadata. 1939 SmallString<8> Name(Record.begin(), Record.end()); 1940 Record.clear(); 1941 Code = Stream.ReadCode(); 1942 1943 unsigned NextBitCode = Stream.readRecord(Code, Record); 1944 if (NextBitCode != bitc::METADATA_NAMED_NODE) 1945 return error("METADATA_NAME not followed by METADATA_NAMED_NODE"); 1946 1947 // Read named metadata elements. 1948 unsigned Size = Record.size(); 1949 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 1950 for (unsigned i = 0; i != Size; ++i) { 1951 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]); 1952 if (!MD) 1953 return error("Invalid record"); 1954 NMD->addOperand(MD); 1955 } 1956 break; 1957 } 1958 case bitc::METADATA_OLD_FN_NODE: { 1959 // FIXME: Remove in 4.0. 1960 // This is a LocalAsMetadata record, the only type of function-local 1961 // metadata. 1962 if (Record.size() % 2 == 1) 1963 return error("Invalid record"); 1964 1965 // If this isn't a LocalAsMetadata record, we're dropping it. This used 1966 // to be legal, but there's no upgrade path. 1967 auto dropRecord = [&] { 1968 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++); 1969 }; 1970 if (Record.size() != 2) { 1971 dropRecord(); 1972 break; 1973 } 1974 1975 Type *Ty = getTypeByID(Record[0]); 1976 if (Ty->isMetadataTy() || Ty->isVoidTy()) { 1977 dropRecord(); 1978 break; 1979 } 1980 1981 MetadataList.assignValue( 1982 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 1983 NextMetadataNo++); 1984 break; 1985 } 1986 case bitc::METADATA_OLD_NODE: { 1987 // FIXME: Remove in 4.0. 1988 if (Record.size() % 2 == 1) 1989 return error("Invalid record"); 1990 1991 unsigned Size = Record.size(); 1992 SmallVector<Metadata *, 8> Elts; 1993 for (unsigned i = 0; i != Size; i += 2) { 1994 Type *Ty = getTypeByID(Record[i]); 1995 if (!Ty) 1996 return error("Invalid record"); 1997 if (Ty->isMetadataTy()) 1998 Elts.push_back(MetadataList.getMetadataFwdRef(Record[i + 1])); 1999 else if (!Ty->isVoidTy()) { 2000 auto *MD = 2001 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty)); 2002 assert(isa<ConstantAsMetadata>(MD) && 2003 "Expected non-function-local metadata"); 2004 Elts.push_back(MD); 2005 } else 2006 Elts.push_back(nullptr); 2007 } 2008 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++); 2009 break; 2010 } 2011 case bitc::METADATA_VALUE: { 2012 if (Record.size() != 2) 2013 return error("Invalid record"); 2014 2015 Type *Ty = getTypeByID(Record[0]); 2016 if (Ty->isMetadataTy() || Ty->isVoidTy()) 2017 return error("Invalid record"); 2018 2019 MetadataList.assignValue( 2020 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 2021 NextMetadataNo++); 2022 break; 2023 } 2024 case bitc::METADATA_DISTINCT_NODE: 2025 IsDistinct = true; 2026 // fallthrough... 2027 case bitc::METADATA_NODE: { 2028 SmallVector<Metadata *, 8> Elts; 2029 Elts.reserve(Record.size()); 2030 for (unsigned ID : Record) 2031 Elts.push_back(ID ? MetadataList.getMetadataFwdRef(ID - 1) : nullptr); 2032 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts) 2033 : MDNode::get(Context, Elts), 2034 NextMetadataNo++); 2035 break; 2036 } 2037 case bitc::METADATA_LOCATION: { 2038 if (Record.size() != 5) 2039 return error("Invalid record"); 2040 2041 unsigned Line = Record[1]; 2042 unsigned Column = Record[2]; 2043 MDNode *Scope = MetadataList.getMDNodeFwdRefOrNull(Record[3]); 2044 if (!Scope) 2045 return error("Invalid record"); 2046 Metadata *InlinedAt = 2047 Record[4] ? MetadataList.getMetadataFwdRef(Record[4] - 1) : nullptr; 2048 MetadataList.assignValue( 2049 GET_OR_DISTINCT(DILocation, Record[0], 2050 (Context, Line, Column, Scope, InlinedAt)), 2051 NextMetadataNo++); 2052 break; 2053 } 2054 case bitc::METADATA_GENERIC_DEBUG: { 2055 if (Record.size() < 4) 2056 return error("Invalid record"); 2057 2058 unsigned Tag = Record[1]; 2059 unsigned Version = Record[2]; 2060 2061 if (Tag >= 1u << 16 || Version != 0) 2062 return error("Invalid record"); 2063 2064 auto *Header = getMDString(Record[3]); 2065 SmallVector<Metadata *, 8> DwarfOps; 2066 for (unsigned I = 4, E = Record.size(); I != E; ++I) 2067 DwarfOps.push_back(Record[I] 2068 ? MetadataList.getMetadataFwdRef(Record[I] - 1) 2069 : nullptr); 2070 MetadataList.assignValue( 2071 GET_OR_DISTINCT(GenericDINode, Record[0], 2072 (Context, Tag, Header, DwarfOps)), 2073 NextMetadataNo++); 2074 break; 2075 } 2076 case bitc::METADATA_SUBRANGE: { 2077 if (Record.size() != 3) 2078 return error("Invalid record"); 2079 2080 MetadataList.assignValue( 2081 GET_OR_DISTINCT(DISubrange, Record[0], 2082 (Context, Record[1], unrotateSign(Record[2]))), 2083 NextMetadataNo++); 2084 break; 2085 } 2086 case bitc::METADATA_ENUMERATOR: { 2087 if (Record.size() != 3) 2088 return error("Invalid record"); 2089 2090 MetadataList.assignValue( 2091 GET_OR_DISTINCT( 2092 DIEnumerator, Record[0], 2093 (Context, unrotateSign(Record[1]), getMDString(Record[2]))), 2094 NextMetadataNo++); 2095 break; 2096 } 2097 case bitc::METADATA_BASIC_TYPE: { 2098 if (Record.size() != 6) 2099 return error("Invalid record"); 2100 2101 MetadataList.assignValue( 2102 GET_OR_DISTINCT(DIBasicType, Record[0], 2103 (Context, Record[1], getMDString(Record[2]), 2104 Record[3], Record[4], Record[5])), 2105 NextMetadataNo++); 2106 break; 2107 } 2108 case bitc::METADATA_DERIVED_TYPE: { 2109 if (Record.size() != 12) 2110 return error("Invalid record"); 2111 2112 MetadataList.assignValue( 2113 GET_OR_DISTINCT(DIDerivedType, Record[0], 2114 (Context, Record[1], getMDString(Record[2]), 2115 getMDOrNull(Record[3]), Record[4], 2116 getMDOrNull(Record[5]), getMDOrNull(Record[6]), 2117 Record[7], Record[8], Record[9], Record[10], 2118 getMDOrNull(Record[11]))), 2119 NextMetadataNo++); 2120 break; 2121 } 2122 case bitc::METADATA_COMPOSITE_TYPE: { 2123 if (Record.size() != 16) 2124 return error("Invalid record"); 2125 2126 MetadataList.assignValue( 2127 GET_OR_DISTINCT(DICompositeType, Record[0], 2128 (Context, Record[1], getMDString(Record[2]), 2129 getMDOrNull(Record[3]), Record[4], 2130 getMDOrNull(Record[5]), getMDOrNull(Record[6]), 2131 Record[7], Record[8], Record[9], Record[10], 2132 getMDOrNull(Record[11]), Record[12], 2133 getMDOrNull(Record[13]), getMDOrNull(Record[14]), 2134 getMDString(Record[15]))), 2135 NextMetadataNo++); 2136 break; 2137 } 2138 case bitc::METADATA_SUBROUTINE_TYPE: { 2139 if (Record.size() != 3) 2140 return error("Invalid record"); 2141 2142 MetadataList.assignValue( 2143 GET_OR_DISTINCT(DISubroutineType, Record[0], 2144 (Context, Record[1], getMDOrNull(Record[2]))), 2145 NextMetadataNo++); 2146 break; 2147 } 2148 2149 case bitc::METADATA_MODULE: { 2150 if (Record.size() != 6) 2151 return error("Invalid record"); 2152 2153 MetadataList.assignValue( 2154 GET_OR_DISTINCT(DIModule, Record[0], 2155 (Context, getMDOrNull(Record[1]), 2156 getMDString(Record[2]), getMDString(Record[3]), 2157 getMDString(Record[4]), getMDString(Record[5]))), 2158 NextMetadataNo++); 2159 break; 2160 } 2161 2162 case bitc::METADATA_FILE: { 2163 if (Record.size() != 3) 2164 return error("Invalid record"); 2165 2166 MetadataList.assignValue( 2167 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]), 2168 getMDString(Record[2]))), 2169 NextMetadataNo++); 2170 break; 2171 } 2172 case bitc::METADATA_COMPILE_UNIT: { 2173 if (Record.size() < 14 || Record.size() > 16) 2174 return error("Invalid record"); 2175 2176 // Ignore Record[0], which indicates whether this compile unit is 2177 // distinct. It's always distinct. 2178 MetadataList.assignValue( 2179 DICompileUnit::getDistinct( 2180 Context, Record[1], getMDOrNull(Record[2]), 2181 getMDString(Record[3]), Record[4], getMDString(Record[5]), 2182 Record[6], getMDString(Record[7]), Record[8], 2183 getMDOrNull(Record[9]), getMDOrNull(Record[10]), 2184 getMDOrNull(Record[11]), getMDOrNull(Record[12]), 2185 getMDOrNull(Record[13]), 2186 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]), 2187 Record.size() <= 14 ? 0 : Record[14]), 2188 NextMetadataNo++); 2189 break; 2190 } 2191 case bitc::METADATA_SUBPROGRAM: { 2192 if (Record.size() != 18 && Record.size() != 19) 2193 return error("Invalid record"); 2194 2195 bool HasFn = Record.size() == 19; 2196 DISubprogram *SP = GET_OR_DISTINCT( 2197 DISubprogram, 2198 Record[0] || Record[8], // All definitions should be distinct. 2199 (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 2200 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 2201 getMDOrNull(Record[6]), Record[7], Record[8], Record[9], 2202 getMDOrNull(Record[10]), Record[11], Record[12], Record[13], 2203 Record[14], getMDOrNull(Record[15 + HasFn]), 2204 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn]))); 2205 MetadataList.assignValue(SP, NextMetadataNo++); 2206 2207 // Upgrade sp->function mapping to function->sp mapping. 2208 if (HasFn && Record[15]) { 2209 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15]))) 2210 if (auto *F = dyn_cast<Function>(CMD->getValue())) { 2211 if (F->isMaterializable()) 2212 // Defer until materialized; unmaterialized functions may not have 2213 // metadata. 2214 FunctionsWithSPs[F] = SP; 2215 else if (!F->empty()) 2216 F->setSubprogram(SP); 2217 } 2218 } 2219 break; 2220 } 2221 case bitc::METADATA_LEXICAL_BLOCK: { 2222 if (Record.size() != 5) 2223 return error("Invalid record"); 2224 2225 MetadataList.assignValue( 2226 GET_OR_DISTINCT(DILexicalBlock, Record[0], 2227 (Context, getMDOrNull(Record[1]), 2228 getMDOrNull(Record[2]), Record[3], Record[4])), 2229 NextMetadataNo++); 2230 break; 2231 } 2232 case bitc::METADATA_LEXICAL_BLOCK_FILE: { 2233 if (Record.size() != 4) 2234 return error("Invalid record"); 2235 2236 MetadataList.assignValue( 2237 GET_OR_DISTINCT(DILexicalBlockFile, Record[0], 2238 (Context, getMDOrNull(Record[1]), 2239 getMDOrNull(Record[2]), Record[3])), 2240 NextMetadataNo++); 2241 break; 2242 } 2243 case bitc::METADATA_NAMESPACE: { 2244 if (Record.size() != 5) 2245 return error("Invalid record"); 2246 2247 MetadataList.assignValue( 2248 GET_OR_DISTINCT(DINamespace, Record[0], 2249 (Context, getMDOrNull(Record[1]), 2250 getMDOrNull(Record[2]), getMDString(Record[3]), 2251 Record[4])), 2252 NextMetadataNo++); 2253 break; 2254 } 2255 case bitc::METADATA_MACRO: { 2256 if (Record.size() != 5) 2257 return error("Invalid record"); 2258 2259 MetadataList.assignValue( 2260 GET_OR_DISTINCT(DIMacro, Record[0], 2261 (Context, Record[1], Record[2], 2262 getMDString(Record[3]), getMDString(Record[4]))), 2263 NextMetadataNo++); 2264 break; 2265 } 2266 case bitc::METADATA_MACRO_FILE: { 2267 if (Record.size() != 5) 2268 return error("Invalid record"); 2269 2270 MetadataList.assignValue( 2271 GET_OR_DISTINCT(DIMacroFile, Record[0], 2272 (Context, Record[1], Record[2], 2273 getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 2274 NextMetadataNo++); 2275 break; 2276 } 2277 case bitc::METADATA_TEMPLATE_TYPE: { 2278 if (Record.size() != 3) 2279 return error("Invalid record"); 2280 2281 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter, 2282 Record[0], 2283 (Context, getMDString(Record[1]), 2284 getMDOrNull(Record[2]))), 2285 NextMetadataNo++); 2286 break; 2287 } 2288 case bitc::METADATA_TEMPLATE_VALUE: { 2289 if (Record.size() != 5) 2290 return error("Invalid record"); 2291 2292 MetadataList.assignValue( 2293 GET_OR_DISTINCT(DITemplateValueParameter, Record[0], 2294 (Context, Record[1], getMDString(Record[2]), 2295 getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 2296 NextMetadataNo++); 2297 break; 2298 } 2299 case bitc::METADATA_GLOBAL_VAR: { 2300 if (Record.size() != 11) 2301 return error("Invalid record"); 2302 2303 MetadataList.assignValue( 2304 GET_OR_DISTINCT(DIGlobalVariable, Record[0], 2305 (Context, getMDOrNull(Record[1]), 2306 getMDString(Record[2]), getMDString(Record[3]), 2307 getMDOrNull(Record[4]), Record[5], 2308 getMDOrNull(Record[6]), Record[7], Record[8], 2309 getMDOrNull(Record[9]), getMDOrNull(Record[10]))), 2310 NextMetadataNo++); 2311 break; 2312 } 2313 case bitc::METADATA_LOCAL_VAR: { 2314 // 10th field is for the obseleted 'inlinedAt:' field. 2315 if (Record.size() < 8 || Record.size() > 10) 2316 return error("Invalid record"); 2317 2318 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or 2319 // DW_TAG_arg_variable. 2320 bool HasTag = Record.size() > 8; 2321 MetadataList.assignValue( 2322 GET_OR_DISTINCT(DILocalVariable, Record[0], 2323 (Context, getMDOrNull(Record[1 + HasTag]), 2324 getMDString(Record[2 + HasTag]), 2325 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag], 2326 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag], 2327 Record[7 + HasTag])), 2328 NextMetadataNo++); 2329 break; 2330 } 2331 case bitc::METADATA_EXPRESSION: { 2332 if (Record.size() < 1) 2333 return error("Invalid record"); 2334 2335 MetadataList.assignValue( 2336 GET_OR_DISTINCT(DIExpression, Record[0], 2337 (Context, makeArrayRef(Record).slice(1))), 2338 NextMetadataNo++); 2339 break; 2340 } 2341 case bitc::METADATA_OBJC_PROPERTY: { 2342 if (Record.size() != 8) 2343 return error("Invalid record"); 2344 2345 MetadataList.assignValue( 2346 GET_OR_DISTINCT(DIObjCProperty, Record[0], 2347 (Context, getMDString(Record[1]), 2348 getMDOrNull(Record[2]), Record[3], 2349 getMDString(Record[4]), getMDString(Record[5]), 2350 Record[6], getMDOrNull(Record[7]))), 2351 NextMetadataNo++); 2352 break; 2353 } 2354 case bitc::METADATA_IMPORTED_ENTITY: { 2355 if (Record.size() != 6) 2356 return error("Invalid record"); 2357 2358 MetadataList.assignValue( 2359 GET_OR_DISTINCT(DIImportedEntity, Record[0], 2360 (Context, Record[1], getMDOrNull(Record[2]), 2361 getMDOrNull(Record[3]), Record[4], 2362 getMDString(Record[5]))), 2363 NextMetadataNo++); 2364 break; 2365 } 2366 case bitc::METADATA_STRING_OLD: { 2367 std::string String(Record.begin(), Record.end()); 2368 2369 // Test for upgrading !llvm.loop. 2370 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String); 2371 2372 Metadata *MD = MDString::get(Context, String); 2373 MetadataList.assignValue(MD, NextMetadataNo++); 2374 break; 2375 } 2376 case bitc::METADATA_BULK_STRING_SIZES: { 2377 // This is a pair of records for an MDString block: SIZES, which is a 2378 // list of string lengths; and DATA, which is a blob with all the strings 2379 // concatenated together. 2380 // 2381 // Note: since this record type was introduced after the upgrade for 2382 // !llvm.loop, we don't need to change HasSeenOldLoopTags. 2383 if (Record.empty()) 2384 return error("Invalid record: missing bulk metadata string sizes"); 2385 2386 StringRef Blob; 2387 SmallVector<uint64_t, 1> BlobRecord; 2388 Code = Stream.ReadCode(); 2389 unsigned BlobCode = Stream.readRecord(Code, BlobRecord, &Blob); 2390 if (BlobCode != bitc::METADATA_BULK_STRING_DATA) 2391 return error("Invalid record: missing bulk metadata string data"); 2392 if (!BlobRecord.empty()) 2393 return error("Invalid record: unexpected bulk metadata arguments"); 2394 2395 for (uint64_t Size : Record) { 2396 if (Blob.size() < Size) 2397 return error("Invalid record: not enough bulk metadata string bytes"); 2398 2399 // Extract the current string. 2400 MetadataList.assignValue(MDString::get(Context, Blob.slice(0, Size)), 2401 NextMetadataNo++); 2402 Blob = Blob.drop_front(Size); 2403 } 2404 if (!Blob.empty()) 2405 return error("Invalid record: too many bulk metadata string bytes"); 2406 break; 2407 } 2408 case bitc::METADATA_KIND: { 2409 // Support older bitcode files that had METADATA_KIND records in a 2410 // block with METADATA_BLOCK_ID. 2411 if (std::error_code EC = parseMetadataKindRecord(Record)) 2412 return EC; 2413 break; 2414 } 2415 } 2416 } 2417 #undef GET_OR_DISTINCT 2418 } 2419 2420 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK. 2421 std::error_code BitcodeReader::parseMetadataKinds() { 2422 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID)) 2423 return error("Invalid record"); 2424 2425 SmallVector<uint64_t, 64> Record; 2426 2427 // Read all the records. 2428 while (1) { 2429 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2430 2431 switch (Entry.Kind) { 2432 case BitstreamEntry::SubBlock: // Handled for us already. 2433 case BitstreamEntry::Error: 2434 return error("Malformed block"); 2435 case BitstreamEntry::EndBlock: 2436 return std::error_code(); 2437 case BitstreamEntry::Record: 2438 // The interesting case. 2439 break; 2440 } 2441 2442 // Read a record. 2443 Record.clear(); 2444 unsigned Code = Stream.readRecord(Entry.ID, Record); 2445 switch (Code) { 2446 default: // Default behavior: ignore. 2447 break; 2448 case bitc::METADATA_KIND: { 2449 if (std::error_code EC = parseMetadataKindRecord(Record)) 2450 return EC; 2451 break; 2452 } 2453 } 2454 } 2455 } 2456 2457 /// Decode a signed value stored with the sign bit in the LSB for dense VBR 2458 /// encoding. 2459 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 2460 if ((V & 1) == 0) 2461 return V >> 1; 2462 if (V != 1) 2463 return -(V >> 1); 2464 // There is no such thing as -0 with integers. "-0" really means MININT. 2465 return 1ULL << 63; 2466 } 2467 2468 /// Resolve all of the initializers for global values and aliases that we can. 2469 std::error_code BitcodeReader::resolveGlobalAndAliasInits() { 2470 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 2471 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 2472 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 2473 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist; 2474 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist; 2475 2476 GlobalInitWorklist.swap(GlobalInits); 2477 AliasInitWorklist.swap(AliasInits); 2478 FunctionPrefixWorklist.swap(FunctionPrefixes); 2479 FunctionPrologueWorklist.swap(FunctionPrologues); 2480 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns); 2481 2482 while (!GlobalInitWorklist.empty()) { 2483 unsigned ValID = GlobalInitWorklist.back().second; 2484 if (ValID >= ValueList.size()) { 2485 // Not ready to resolve this yet, it requires something later in the file. 2486 GlobalInits.push_back(GlobalInitWorklist.back()); 2487 } else { 2488 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2489 GlobalInitWorklist.back().first->setInitializer(C); 2490 else 2491 return error("Expected a constant"); 2492 } 2493 GlobalInitWorklist.pop_back(); 2494 } 2495 2496 while (!AliasInitWorklist.empty()) { 2497 unsigned ValID = AliasInitWorklist.back().second; 2498 if (ValID >= ValueList.size()) { 2499 AliasInits.push_back(AliasInitWorklist.back()); 2500 } else { 2501 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]); 2502 if (!C) 2503 return error("Expected a constant"); 2504 GlobalAlias *Alias = AliasInitWorklist.back().first; 2505 if (C->getType() != Alias->getType()) 2506 return error("Alias and aliasee types don't match"); 2507 Alias->setAliasee(C); 2508 } 2509 AliasInitWorklist.pop_back(); 2510 } 2511 2512 while (!FunctionPrefixWorklist.empty()) { 2513 unsigned ValID = FunctionPrefixWorklist.back().second; 2514 if (ValID >= ValueList.size()) { 2515 FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 2516 } else { 2517 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2518 FunctionPrefixWorklist.back().first->setPrefixData(C); 2519 else 2520 return error("Expected a constant"); 2521 } 2522 FunctionPrefixWorklist.pop_back(); 2523 } 2524 2525 while (!FunctionPrologueWorklist.empty()) { 2526 unsigned ValID = FunctionPrologueWorklist.back().second; 2527 if (ValID >= ValueList.size()) { 2528 FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 2529 } else { 2530 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2531 FunctionPrologueWorklist.back().first->setPrologueData(C); 2532 else 2533 return error("Expected a constant"); 2534 } 2535 FunctionPrologueWorklist.pop_back(); 2536 } 2537 2538 while (!FunctionPersonalityFnWorklist.empty()) { 2539 unsigned ValID = FunctionPersonalityFnWorklist.back().second; 2540 if (ValID >= ValueList.size()) { 2541 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back()); 2542 } else { 2543 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 2544 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C); 2545 else 2546 return error("Expected a constant"); 2547 } 2548 FunctionPersonalityFnWorklist.pop_back(); 2549 } 2550 2551 return std::error_code(); 2552 } 2553 2554 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 2555 SmallVector<uint64_t, 8> Words(Vals.size()); 2556 std::transform(Vals.begin(), Vals.end(), Words.begin(), 2557 BitcodeReader::decodeSignRotatedValue); 2558 2559 return APInt(TypeBits, Words); 2560 } 2561 2562 std::error_code BitcodeReader::parseConstants() { 2563 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 2564 return error("Invalid record"); 2565 2566 SmallVector<uint64_t, 64> Record; 2567 2568 // Read all the records for this value table. 2569 Type *CurTy = Type::getInt32Ty(Context); 2570 unsigned NextCstNo = ValueList.size(); 2571 while (1) { 2572 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2573 2574 switch (Entry.Kind) { 2575 case BitstreamEntry::SubBlock: // Handled for us already. 2576 case BitstreamEntry::Error: 2577 return error("Malformed block"); 2578 case BitstreamEntry::EndBlock: 2579 if (NextCstNo != ValueList.size()) 2580 return error("Invalid constant reference"); 2581 2582 // Once all the constants have been read, go through and resolve forward 2583 // references. 2584 ValueList.resolveConstantForwardRefs(); 2585 return std::error_code(); 2586 case BitstreamEntry::Record: 2587 // The interesting case. 2588 break; 2589 } 2590 2591 // Read a record. 2592 Record.clear(); 2593 Value *V = nullptr; 2594 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2595 switch (BitCode) { 2596 default: // Default behavior: unknown constant 2597 case bitc::CST_CODE_UNDEF: // UNDEF 2598 V = UndefValue::get(CurTy); 2599 break; 2600 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 2601 if (Record.empty()) 2602 return error("Invalid record"); 2603 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 2604 return error("Invalid record"); 2605 CurTy = TypeList[Record[0]]; 2606 continue; // Skip the ValueList manipulation. 2607 case bitc::CST_CODE_NULL: // NULL 2608 V = Constant::getNullValue(CurTy); 2609 break; 2610 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 2611 if (!CurTy->isIntegerTy() || Record.empty()) 2612 return error("Invalid record"); 2613 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 2614 break; 2615 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 2616 if (!CurTy->isIntegerTy() || Record.empty()) 2617 return error("Invalid record"); 2618 2619 APInt VInt = 2620 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth()); 2621 V = ConstantInt::get(Context, VInt); 2622 2623 break; 2624 } 2625 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 2626 if (Record.empty()) 2627 return error("Invalid record"); 2628 if (CurTy->isHalfTy()) 2629 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 2630 APInt(16, (uint16_t)Record[0]))); 2631 else if (CurTy->isFloatTy()) 2632 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 2633 APInt(32, (uint32_t)Record[0]))); 2634 else if (CurTy->isDoubleTy()) 2635 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 2636 APInt(64, Record[0]))); 2637 else if (CurTy->isX86_FP80Ty()) { 2638 // Bits are not stored the same way as a normal i80 APInt, compensate. 2639 uint64_t Rearrange[2]; 2640 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 2641 Rearrange[1] = Record[0] >> 48; 2642 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 2643 APInt(80, Rearrange))); 2644 } else if (CurTy->isFP128Ty()) 2645 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 2646 APInt(128, Record))); 2647 else if (CurTy->isPPC_FP128Ty()) 2648 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 2649 APInt(128, Record))); 2650 else 2651 V = UndefValue::get(CurTy); 2652 break; 2653 } 2654 2655 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 2656 if (Record.empty()) 2657 return error("Invalid record"); 2658 2659 unsigned Size = Record.size(); 2660 SmallVector<Constant*, 16> Elts; 2661 2662 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 2663 for (unsigned i = 0; i != Size; ++i) 2664 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 2665 STy->getElementType(i))); 2666 V = ConstantStruct::get(STy, Elts); 2667 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 2668 Type *EltTy = ATy->getElementType(); 2669 for (unsigned i = 0; i != Size; ++i) 2670 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2671 V = ConstantArray::get(ATy, Elts); 2672 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 2673 Type *EltTy = VTy->getElementType(); 2674 for (unsigned i = 0; i != Size; ++i) 2675 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 2676 V = ConstantVector::get(Elts); 2677 } else { 2678 V = UndefValue::get(CurTy); 2679 } 2680 break; 2681 } 2682 case bitc::CST_CODE_STRING: // STRING: [values] 2683 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 2684 if (Record.empty()) 2685 return error("Invalid record"); 2686 2687 SmallString<16> Elts(Record.begin(), Record.end()); 2688 V = ConstantDataArray::getString(Context, Elts, 2689 BitCode == bitc::CST_CODE_CSTRING); 2690 break; 2691 } 2692 case bitc::CST_CODE_DATA: {// DATA: [n x value] 2693 if (Record.empty()) 2694 return error("Invalid record"); 2695 2696 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 2697 if (EltTy->isIntegerTy(8)) { 2698 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 2699 if (isa<VectorType>(CurTy)) 2700 V = ConstantDataVector::get(Context, Elts); 2701 else 2702 V = ConstantDataArray::get(Context, Elts); 2703 } else if (EltTy->isIntegerTy(16)) { 2704 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2705 if (isa<VectorType>(CurTy)) 2706 V = ConstantDataVector::get(Context, Elts); 2707 else 2708 V = ConstantDataArray::get(Context, Elts); 2709 } else if (EltTy->isIntegerTy(32)) { 2710 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2711 if (isa<VectorType>(CurTy)) 2712 V = ConstantDataVector::get(Context, Elts); 2713 else 2714 V = ConstantDataArray::get(Context, Elts); 2715 } else if (EltTy->isIntegerTy(64)) { 2716 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2717 if (isa<VectorType>(CurTy)) 2718 V = ConstantDataVector::get(Context, Elts); 2719 else 2720 V = ConstantDataArray::get(Context, Elts); 2721 } else if (EltTy->isHalfTy()) { 2722 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 2723 if (isa<VectorType>(CurTy)) 2724 V = ConstantDataVector::getFP(Context, Elts); 2725 else 2726 V = ConstantDataArray::getFP(Context, Elts); 2727 } else if (EltTy->isFloatTy()) { 2728 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 2729 if (isa<VectorType>(CurTy)) 2730 V = ConstantDataVector::getFP(Context, Elts); 2731 else 2732 V = ConstantDataArray::getFP(Context, Elts); 2733 } else if (EltTy->isDoubleTy()) { 2734 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 2735 if (isa<VectorType>(CurTy)) 2736 V = ConstantDataVector::getFP(Context, Elts); 2737 else 2738 V = ConstantDataArray::getFP(Context, Elts); 2739 } else { 2740 return error("Invalid type for value"); 2741 } 2742 break; 2743 } 2744 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 2745 if (Record.size() < 3) 2746 return error("Invalid record"); 2747 int Opc = getDecodedBinaryOpcode(Record[0], CurTy); 2748 if (Opc < 0) { 2749 V = UndefValue::get(CurTy); // Unknown binop. 2750 } else { 2751 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 2752 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 2753 unsigned Flags = 0; 2754 if (Record.size() >= 4) { 2755 if (Opc == Instruction::Add || 2756 Opc == Instruction::Sub || 2757 Opc == Instruction::Mul || 2758 Opc == Instruction::Shl) { 2759 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2760 Flags |= OverflowingBinaryOperator::NoSignedWrap; 2761 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2762 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 2763 } else if (Opc == Instruction::SDiv || 2764 Opc == Instruction::UDiv || 2765 Opc == Instruction::LShr || 2766 Opc == Instruction::AShr) { 2767 if (Record[3] & (1 << bitc::PEO_EXACT)) 2768 Flags |= SDivOperator::IsExact; 2769 } 2770 } 2771 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 2772 } 2773 break; 2774 } 2775 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 2776 if (Record.size() < 3) 2777 return error("Invalid record"); 2778 int Opc = getDecodedCastOpcode(Record[0]); 2779 if (Opc < 0) { 2780 V = UndefValue::get(CurTy); // Unknown cast. 2781 } else { 2782 Type *OpTy = getTypeByID(Record[1]); 2783 if (!OpTy) 2784 return error("Invalid record"); 2785 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 2786 V = UpgradeBitCastExpr(Opc, Op, CurTy); 2787 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 2788 } 2789 break; 2790 } 2791 case bitc::CST_CODE_CE_INBOUNDS_GEP: 2792 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 2793 unsigned OpNum = 0; 2794 Type *PointeeType = nullptr; 2795 if (Record.size() % 2) 2796 PointeeType = getTypeByID(Record[OpNum++]); 2797 SmallVector<Constant*, 16> Elts; 2798 while (OpNum != Record.size()) { 2799 Type *ElTy = getTypeByID(Record[OpNum++]); 2800 if (!ElTy) 2801 return error("Invalid record"); 2802 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy)); 2803 } 2804 2805 if (PointeeType && 2806 PointeeType != 2807 cast<SequentialType>(Elts[0]->getType()->getScalarType()) 2808 ->getElementType()) 2809 return error("Explicit gep operator type does not match pointee type " 2810 "of pointer operand"); 2811 2812 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 2813 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices, 2814 BitCode == 2815 bitc::CST_CODE_CE_INBOUNDS_GEP); 2816 break; 2817 } 2818 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 2819 if (Record.size() < 3) 2820 return error("Invalid record"); 2821 2822 Type *SelectorTy = Type::getInt1Ty(Context); 2823 2824 // The selector might be an i1 or an <n x i1> 2825 // Get the type from the ValueList before getting a forward ref. 2826 if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 2827 if (Value *V = ValueList[Record[0]]) 2828 if (SelectorTy != V->getType()) 2829 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements()); 2830 2831 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 2832 SelectorTy), 2833 ValueList.getConstantFwdRef(Record[1],CurTy), 2834 ValueList.getConstantFwdRef(Record[2],CurTy)); 2835 break; 2836 } 2837 case bitc::CST_CODE_CE_EXTRACTELT 2838 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 2839 if (Record.size() < 3) 2840 return error("Invalid record"); 2841 VectorType *OpTy = 2842 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 2843 if (!OpTy) 2844 return error("Invalid record"); 2845 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2846 Constant *Op1 = nullptr; 2847 if (Record.size() == 4) { 2848 Type *IdxTy = getTypeByID(Record[2]); 2849 if (!IdxTy) 2850 return error("Invalid record"); 2851 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 2852 } else // TODO: Remove with llvm 4.0 2853 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 2854 if (!Op1) 2855 return error("Invalid record"); 2856 V = ConstantExpr::getExtractElement(Op0, Op1); 2857 break; 2858 } 2859 case bitc::CST_CODE_CE_INSERTELT 2860 : { // CE_INSERTELT: [opval, opval, opty, opval] 2861 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 2862 if (Record.size() < 3 || !OpTy) 2863 return error("Invalid record"); 2864 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2865 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 2866 OpTy->getElementType()); 2867 Constant *Op2 = nullptr; 2868 if (Record.size() == 4) { 2869 Type *IdxTy = getTypeByID(Record[2]); 2870 if (!IdxTy) 2871 return error("Invalid record"); 2872 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 2873 } else // TODO: Remove with llvm 4.0 2874 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 2875 if (!Op2) 2876 return error("Invalid record"); 2877 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 2878 break; 2879 } 2880 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 2881 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 2882 if (Record.size() < 3 || !OpTy) 2883 return error("Invalid record"); 2884 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2885 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 2886 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2887 OpTy->getNumElements()); 2888 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 2889 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2890 break; 2891 } 2892 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 2893 VectorType *RTy = dyn_cast<VectorType>(CurTy); 2894 VectorType *OpTy = 2895 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 2896 if (Record.size() < 4 || !RTy || !OpTy) 2897 return error("Invalid record"); 2898 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2899 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2900 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2901 RTy->getNumElements()); 2902 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 2903 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2904 break; 2905 } 2906 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 2907 if (Record.size() < 4) 2908 return error("Invalid record"); 2909 Type *OpTy = getTypeByID(Record[0]); 2910 if (!OpTy) 2911 return error("Invalid record"); 2912 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2913 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2914 2915 if (OpTy->isFPOrFPVectorTy()) 2916 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 2917 else 2918 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 2919 break; 2920 } 2921 // This maintains backward compatibility, pre-asm dialect keywords. 2922 // FIXME: Remove with the 4.0 release. 2923 case bitc::CST_CODE_INLINEASM_OLD: { 2924 if (Record.size() < 2) 2925 return error("Invalid record"); 2926 std::string AsmStr, ConstrStr; 2927 bool HasSideEffects = Record[0] & 1; 2928 bool IsAlignStack = Record[0] >> 1; 2929 unsigned AsmStrSize = Record[1]; 2930 if (2+AsmStrSize >= Record.size()) 2931 return error("Invalid record"); 2932 unsigned ConstStrSize = Record[2+AsmStrSize]; 2933 if (3+AsmStrSize+ConstStrSize > Record.size()) 2934 return error("Invalid record"); 2935 2936 for (unsigned i = 0; i != AsmStrSize; ++i) 2937 AsmStr += (char)Record[2+i]; 2938 for (unsigned i = 0; i != ConstStrSize; ++i) 2939 ConstrStr += (char)Record[3+AsmStrSize+i]; 2940 PointerType *PTy = cast<PointerType>(CurTy); 2941 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2942 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 2943 break; 2944 } 2945 // This version adds support for the asm dialect keywords (e.g., 2946 // inteldialect). 2947 case bitc::CST_CODE_INLINEASM: { 2948 if (Record.size() < 2) 2949 return error("Invalid record"); 2950 std::string AsmStr, ConstrStr; 2951 bool HasSideEffects = Record[0] & 1; 2952 bool IsAlignStack = (Record[0] >> 1) & 1; 2953 unsigned AsmDialect = Record[0] >> 2; 2954 unsigned AsmStrSize = Record[1]; 2955 if (2+AsmStrSize >= Record.size()) 2956 return error("Invalid record"); 2957 unsigned ConstStrSize = Record[2+AsmStrSize]; 2958 if (3+AsmStrSize+ConstStrSize > Record.size()) 2959 return error("Invalid record"); 2960 2961 for (unsigned i = 0; i != AsmStrSize; ++i) 2962 AsmStr += (char)Record[2+i]; 2963 for (unsigned i = 0; i != ConstStrSize; ++i) 2964 ConstrStr += (char)Record[3+AsmStrSize+i]; 2965 PointerType *PTy = cast<PointerType>(CurTy); 2966 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2967 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 2968 InlineAsm::AsmDialect(AsmDialect)); 2969 break; 2970 } 2971 case bitc::CST_CODE_BLOCKADDRESS:{ 2972 if (Record.size() < 3) 2973 return error("Invalid record"); 2974 Type *FnTy = getTypeByID(Record[0]); 2975 if (!FnTy) 2976 return error("Invalid record"); 2977 Function *Fn = 2978 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 2979 if (!Fn) 2980 return error("Invalid record"); 2981 2982 // If the function is already parsed we can insert the block address right 2983 // away. 2984 BasicBlock *BB; 2985 unsigned BBID = Record[2]; 2986 if (!BBID) 2987 // Invalid reference to entry block. 2988 return error("Invalid ID"); 2989 if (!Fn->empty()) { 2990 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 2991 for (size_t I = 0, E = BBID; I != E; ++I) { 2992 if (BBI == BBE) 2993 return error("Invalid ID"); 2994 ++BBI; 2995 } 2996 BB = &*BBI; 2997 } else { 2998 // Otherwise insert a placeholder and remember it so it can be inserted 2999 // when the function is parsed. 3000 auto &FwdBBs = BasicBlockFwdRefs[Fn]; 3001 if (FwdBBs.empty()) 3002 BasicBlockFwdRefQueue.push_back(Fn); 3003 if (FwdBBs.size() < BBID + 1) 3004 FwdBBs.resize(BBID + 1); 3005 if (!FwdBBs[BBID]) 3006 FwdBBs[BBID] = BasicBlock::Create(Context); 3007 BB = FwdBBs[BBID]; 3008 } 3009 V = BlockAddress::get(Fn, BB); 3010 break; 3011 } 3012 } 3013 3014 ValueList.assignValue(V, NextCstNo); 3015 ++NextCstNo; 3016 } 3017 } 3018 3019 std::error_code BitcodeReader::parseUseLists() { 3020 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 3021 return error("Invalid record"); 3022 3023 // Read all the records. 3024 SmallVector<uint64_t, 64> Record; 3025 while (1) { 3026 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3027 3028 switch (Entry.Kind) { 3029 case BitstreamEntry::SubBlock: // Handled for us already. 3030 case BitstreamEntry::Error: 3031 return error("Malformed block"); 3032 case BitstreamEntry::EndBlock: 3033 return std::error_code(); 3034 case BitstreamEntry::Record: 3035 // The interesting case. 3036 break; 3037 } 3038 3039 // Read a use list record. 3040 Record.clear(); 3041 bool IsBB = false; 3042 switch (Stream.readRecord(Entry.ID, Record)) { 3043 default: // Default behavior: unknown type. 3044 break; 3045 case bitc::USELIST_CODE_BB: 3046 IsBB = true; 3047 // fallthrough 3048 case bitc::USELIST_CODE_DEFAULT: { 3049 unsigned RecordLength = Record.size(); 3050 if (RecordLength < 3) 3051 // Records should have at least an ID and two indexes. 3052 return error("Invalid record"); 3053 unsigned ID = Record.back(); 3054 Record.pop_back(); 3055 3056 Value *V; 3057 if (IsBB) { 3058 assert(ID < FunctionBBs.size() && "Basic block not found"); 3059 V = FunctionBBs[ID]; 3060 } else 3061 V = ValueList[ID]; 3062 unsigned NumUses = 0; 3063 SmallDenseMap<const Use *, unsigned, 16> Order; 3064 for (const Use &U : V->materialized_uses()) { 3065 if (++NumUses > Record.size()) 3066 break; 3067 Order[&U] = Record[NumUses - 1]; 3068 } 3069 if (Order.size() != Record.size() || NumUses > Record.size()) 3070 // Mismatches can happen if the functions are being materialized lazily 3071 // (out-of-order), or a value has been upgraded. 3072 break; 3073 3074 V->sortUseList([&](const Use &L, const Use &R) { 3075 return Order.lookup(&L) < Order.lookup(&R); 3076 }); 3077 break; 3078 } 3079 } 3080 } 3081 } 3082 3083 /// When we see the block for metadata, remember where it is and then skip it. 3084 /// This lets us lazily deserialize the metadata. 3085 std::error_code BitcodeReader::rememberAndSkipMetadata() { 3086 // Save the current stream state. 3087 uint64_t CurBit = Stream.GetCurrentBitNo(); 3088 DeferredMetadataInfo.push_back(CurBit); 3089 3090 // Skip over the block for now. 3091 if (Stream.SkipBlock()) 3092 return error("Invalid record"); 3093 return std::error_code(); 3094 } 3095 3096 std::error_code BitcodeReader::materializeMetadata() { 3097 for (uint64_t BitPos : DeferredMetadataInfo) { 3098 // Move the bit stream to the saved position. 3099 Stream.JumpToBit(BitPos); 3100 if (std::error_code EC = parseMetadata(true)) 3101 return EC; 3102 } 3103 DeferredMetadataInfo.clear(); 3104 return std::error_code(); 3105 } 3106 3107 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; } 3108 3109 void BitcodeReader::saveMetadataList( 3110 DenseMap<const Metadata *, unsigned> &MetadataToIDs, bool OnlyTempMD) { 3111 for (unsigned ID = 0; ID < MetadataList.size(); ++ID) { 3112 Metadata *MD = MetadataList[ID]; 3113 auto *N = dyn_cast_or_null<MDNode>(MD); 3114 assert((!N || (N->isResolved() || N->isTemporary())) && 3115 "Found non-resolved non-temp MDNode while saving metadata"); 3116 // Save all values if !OnlyTempMD, otherwise just the temporary metadata. 3117 // Note that in the !OnlyTempMD case we need to save all Metadata, not 3118 // just MDNode, as we may have references to other types of module-level 3119 // metadata (e.g. ValueAsMetadata) from instructions. 3120 if (!OnlyTempMD || (N && N->isTemporary())) { 3121 // Will call this after materializing each function, in order to 3122 // handle remapping of the function's instructions/metadata. 3123 auto IterBool = MetadataToIDs.insert(std::make_pair(MD, ID)); 3124 // See if we already have an entry in that case. 3125 if (OnlyTempMD && !IterBool.second) { 3126 assert(IterBool.first->second == ID && 3127 "Inconsistent metadata value id"); 3128 continue; 3129 } 3130 if (N && N->isTemporary()) 3131 // Ensure that we assert if someone tries to RAUW this temporary 3132 // metadata while it is the key of a map. The flag will be set back 3133 // to true when the saved metadata list is destroyed. 3134 N->setCanReplace(false); 3135 } 3136 } 3137 } 3138 3139 /// When we see the block for a function body, remember where it is and then 3140 /// skip it. This lets us lazily deserialize the functions. 3141 std::error_code BitcodeReader::rememberAndSkipFunctionBody() { 3142 // Get the function we are talking about. 3143 if (FunctionsWithBodies.empty()) 3144 return error("Insufficient function protos"); 3145 3146 Function *Fn = FunctionsWithBodies.back(); 3147 FunctionsWithBodies.pop_back(); 3148 3149 // Save the current stream state. 3150 uint64_t CurBit = Stream.GetCurrentBitNo(); 3151 assert( 3152 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) && 3153 "Mismatch between VST and scanned function offsets"); 3154 DeferredFunctionInfo[Fn] = CurBit; 3155 3156 // Skip over the function block for now. 3157 if (Stream.SkipBlock()) 3158 return error("Invalid record"); 3159 return std::error_code(); 3160 } 3161 3162 std::error_code BitcodeReader::globalCleanup() { 3163 // Patch the initializers for globals and aliases up. 3164 resolveGlobalAndAliasInits(); 3165 if (!GlobalInits.empty() || !AliasInits.empty()) 3166 return error("Malformed global initializer set"); 3167 3168 // Look for intrinsic functions which need to be upgraded at some point 3169 for (Function &F : *TheModule) { 3170 Function *NewFn; 3171 if (UpgradeIntrinsicFunction(&F, NewFn)) 3172 UpgradedIntrinsics[&F] = NewFn; 3173 } 3174 3175 // Look for global variables which need to be renamed. 3176 for (GlobalVariable &GV : TheModule->globals()) 3177 UpgradeGlobalVariable(&GV); 3178 3179 // Force deallocation of memory for these vectors to favor the client that 3180 // want lazy deserialization. 3181 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 3182 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 3183 return std::error_code(); 3184 } 3185 3186 /// Support for lazy parsing of function bodies. This is required if we 3187 /// either have an old bitcode file without a VST forward declaration record, 3188 /// or if we have an anonymous function being materialized, since anonymous 3189 /// functions do not have a name and are therefore not in the VST. 3190 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() { 3191 Stream.JumpToBit(NextUnreadBit); 3192 3193 if (Stream.AtEndOfStream()) 3194 return error("Could not find function in stream"); 3195 3196 if (!SeenFirstFunctionBody) 3197 return error("Trying to materialize functions before seeing function blocks"); 3198 3199 // An old bitcode file with the symbol table at the end would have 3200 // finished the parse greedily. 3201 assert(SeenValueSymbolTable); 3202 3203 SmallVector<uint64_t, 64> Record; 3204 3205 while (1) { 3206 BitstreamEntry Entry = Stream.advance(); 3207 switch (Entry.Kind) { 3208 default: 3209 return error("Expect SubBlock"); 3210 case BitstreamEntry::SubBlock: 3211 switch (Entry.ID) { 3212 default: 3213 return error("Expect function block"); 3214 case bitc::FUNCTION_BLOCK_ID: 3215 if (std::error_code EC = rememberAndSkipFunctionBody()) 3216 return EC; 3217 NextUnreadBit = Stream.GetCurrentBitNo(); 3218 return std::error_code(); 3219 } 3220 } 3221 } 3222 } 3223 3224 std::error_code BitcodeReader::parseBitcodeVersion() { 3225 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID)) 3226 return error("Invalid record"); 3227 3228 // Read all the records. 3229 SmallVector<uint64_t, 64> Record; 3230 while (1) { 3231 BitstreamEntry Entry = Stream.advance(); 3232 3233 switch (Entry.Kind) { 3234 default: 3235 case BitstreamEntry::Error: 3236 return error("Malformed block"); 3237 case BitstreamEntry::EndBlock: 3238 return std::error_code(); 3239 case BitstreamEntry::Record: 3240 // The interesting case. 3241 break; 3242 } 3243 3244 // Read a record. 3245 Record.clear(); 3246 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 3247 switch (BitCode) { 3248 default: // Default behavior: reject 3249 return error("Invalid value"); 3250 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x 3251 // N] 3252 convertToString(Record, 0, ProducerIdentification); 3253 break; 3254 } 3255 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] 3256 unsigned epoch = (unsigned)Record[0]; 3257 if (epoch != bitc::BITCODE_CURRENT_EPOCH) { 3258 return error( 3259 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + 3260 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); 3261 } 3262 } 3263 } 3264 } 3265 } 3266 3267 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit, 3268 bool ShouldLazyLoadMetadata) { 3269 if (ResumeBit) 3270 Stream.JumpToBit(ResumeBit); 3271 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 3272 return error("Invalid record"); 3273 3274 SmallVector<uint64_t, 64> Record; 3275 std::vector<std::string> SectionTable; 3276 std::vector<std::string> GCTable; 3277 3278 // Read all the records for this module. 3279 while (1) { 3280 BitstreamEntry Entry = Stream.advance(); 3281 3282 switch (Entry.Kind) { 3283 case BitstreamEntry::Error: 3284 return error("Malformed block"); 3285 case BitstreamEntry::EndBlock: 3286 return globalCleanup(); 3287 3288 case BitstreamEntry::SubBlock: 3289 switch (Entry.ID) { 3290 default: // Skip unknown content. 3291 if (Stream.SkipBlock()) 3292 return error("Invalid record"); 3293 break; 3294 case bitc::BLOCKINFO_BLOCK_ID: 3295 if (Stream.ReadBlockInfoBlock()) 3296 return error("Malformed block"); 3297 break; 3298 case bitc::PARAMATTR_BLOCK_ID: 3299 if (std::error_code EC = parseAttributeBlock()) 3300 return EC; 3301 break; 3302 case bitc::PARAMATTR_GROUP_BLOCK_ID: 3303 if (std::error_code EC = parseAttributeGroupBlock()) 3304 return EC; 3305 break; 3306 case bitc::TYPE_BLOCK_ID_NEW: 3307 if (std::error_code EC = parseTypeTable()) 3308 return EC; 3309 break; 3310 case bitc::VALUE_SYMTAB_BLOCK_ID: 3311 if (!SeenValueSymbolTable) { 3312 // Either this is an old form VST without function index and an 3313 // associated VST forward declaration record (which would have caused 3314 // the VST to be jumped to and parsed before it was encountered 3315 // normally in the stream), or there were no function blocks to 3316 // trigger an earlier parsing of the VST. 3317 assert(VSTOffset == 0 || FunctionsWithBodies.empty()); 3318 if (std::error_code EC = parseValueSymbolTable()) 3319 return EC; 3320 SeenValueSymbolTable = true; 3321 } else { 3322 // We must have had a VST forward declaration record, which caused 3323 // the parser to jump to and parse the VST earlier. 3324 assert(VSTOffset > 0); 3325 if (Stream.SkipBlock()) 3326 return error("Invalid record"); 3327 } 3328 break; 3329 case bitc::CONSTANTS_BLOCK_ID: 3330 if (std::error_code EC = parseConstants()) 3331 return EC; 3332 if (std::error_code EC = resolveGlobalAndAliasInits()) 3333 return EC; 3334 break; 3335 case bitc::METADATA_BLOCK_ID: 3336 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) { 3337 if (std::error_code EC = rememberAndSkipMetadata()) 3338 return EC; 3339 break; 3340 } 3341 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata"); 3342 if (std::error_code EC = parseMetadata(true)) 3343 return EC; 3344 break; 3345 case bitc::METADATA_KIND_BLOCK_ID: 3346 if (std::error_code EC = parseMetadataKinds()) 3347 return EC; 3348 break; 3349 case bitc::FUNCTION_BLOCK_ID: 3350 // If this is the first function body we've seen, reverse the 3351 // FunctionsWithBodies list. 3352 if (!SeenFirstFunctionBody) { 3353 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 3354 if (std::error_code EC = globalCleanup()) 3355 return EC; 3356 SeenFirstFunctionBody = true; 3357 } 3358 3359 if (VSTOffset > 0) { 3360 // If we have a VST forward declaration record, make sure we 3361 // parse the VST now if we haven't already. It is needed to 3362 // set up the DeferredFunctionInfo vector for lazy reading. 3363 if (!SeenValueSymbolTable) { 3364 if (std::error_code EC = 3365 BitcodeReader::parseValueSymbolTable(VSTOffset)) 3366 return EC; 3367 SeenValueSymbolTable = true; 3368 // Fall through so that we record the NextUnreadBit below. 3369 // This is necessary in case we have an anonymous function that 3370 // is later materialized. Since it will not have a VST entry we 3371 // need to fall back to the lazy parse to find its offset. 3372 } else { 3373 // If we have a VST forward declaration record, but have already 3374 // parsed the VST (just above, when the first function body was 3375 // encountered here), then we are resuming the parse after 3376 // materializing functions. The ResumeBit points to the 3377 // start of the last function block recorded in the 3378 // DeferredFunctionInfo map. Skip it. 3379 if (Stream.SkipBlock()) 3380 return error("Invalid record"); 3381 continue; 3382 } 3383 } 3384 3385 // Support older bitcode files that did not have the function 3386 // index in the VST, nor a VST forward declaration record, as 3387 // well as anonymous functions that do not have VST entries. 3388 // Build the DeferredFunctionInfo vector on the fly. 3389 if (std::error_code EC = rememberAndSkipFunctionBody()) 3390 return EC; 3391 3392 // Suspend parsing when we reach the function bodies. Subsequent 3393 // materialization calls will resume it when necessary. If the bitcode 3394 // file is old, the symbol table will be at the end instead and will not 3395 // have been seen yet. In this case, just finish the parse now. 3396 if (SeenValueSymbolTable) { 3397 NextUnreadBit = Stream.GetCurrentBitNo(); 3398 return std::error_code(); 3399 } 3400 break; 3401 case bitc::USELIST_BLOCK_ID: 3402 if (std::error_code EC = parseUseLists()) 3403 return EC; 3404 break; 3405 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID: 3406 if (std::error_code EC = parseOperandBundleTags()) 3407 return EC; 3408 break; 3409 } 3410 continue; 3411 3412 case BitstreamEntry::Record: 3413 // The interesting case. 3414 break; 3415 } 3416 3417 // Read a record. 3418 auto BitCode = Stream.readRecord(Entry.ID, Record); 3419 switch (BitCode) { 3420 default: break; // Default behavior, ignore unknown content. 3421 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 3422 if (Record.size() < 1) 3423 return error("Invalid record"); 3424 // Only version #0 and #1 are supported so far. 3425 unsigned module_version = Record[0]; 3426 switch (module_version) { 3427 default: 3428 return error("Invalid value"); 3429 case 0: 3430 UseRelativeIDs = false; 3431 break; 3432 case 1: 3433 UseRelativeIDs = true; 3434 break; 3435 } 3436 break; 3437 } 3438 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3439 std::string S; 3440 if (convertToString(Record, 0, S)) 3441 return error("Invalid record"); 3442 TheModule->setTargetTriple(S); 3443 break; 3444 } 3445 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 3446 std::string S; 3447 if (convertToString(Record, 0, S)) 3448 return error("Invalid record"); 3449 TheModule->setDataLayout(S); 3450 break; 3451 } 3452 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 3453 std::string S; 3454 if (convertToString(Record, 0, S)) 3455 return error("Invalid record"); 3456 TheModule->setModuleInlineAsm(S); 3457 break; 3458 } 3459 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 3460 // FIXME: Remove in 4.0. 3461 std::string S; 3462 if (convertToString(Record, 0, S)) 3463 return error("Invalid record"); 3464 // Ignore value. 3465 break; 3466 } 3467 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 3468 std::string S; 3469 if (convertToString(Record, 0, S)) 3470 return error("Invalid record"); 3471 SectionTable.push_back(S); 3472 break; 3473 } 3474 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 3475 std::string S; 3476 if (convertToString(Record, 0, S)) 3477 return error("Invalid record"); 3478 GCTable.push_back(S); 3479 break; 3480 } 3481 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] 3482 if (Record.size() < 2) 3483 return error("Invalid record"); 3484 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 3485 unsigned ComdatNameSize = Record[1]; 3486 std::string ComdatName; 3487 ComdatName.reserve(ComdatNameSize); 3488 for (unsigned i = 0; i != ComdatNameSize; ++i) 3489 ComdatName += (char)Record[2 + i]; 3490 Comdat *C = TheModule->getOrInsertComdat(ComdatName); 3491 C->setSelectionKind(SK); 3492 ComdatList.push_back(C); 3493 break; 3494 } 3495 // GLOBALVAR: [pointer type, isconst, initid, 3496 // linkage, alignment, section, visibility, threadlocal, 3497 // unnamed_addr, externally_initialized, dllstorageclass, 3498 // comdat] 3499 case bitc::MODULE_CODE_GLOBALVAR: { 3500 if (Record.size() < 6) 3501 return error("Invalid record"); 3502 Type *Ty = getTypeByID(Record[0]); 3503 if (!Ty) 3504 return error("Invalid record"); 3505 bool isConstant = Record[1] & 1; 3506 bool explicitType = Record[1] & 2; 3507 unsigned AddressSpace; 3508 if (explicitType) { 3509 AddressSpace = Record[1] >> 2; 3510 } else { 3511 if (!Ty->isPointerTy()) 3512 return error("Invalid type for value"); 3513 AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 3514 Ty = cast<PointerType>(Ty)->getElementType(); 3515 } 3516 3517 uint64_t RawLinkage = Record[3]; 3518 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 3519 unsigned Alignment; 3520 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment)) 3521 return EC; 3522 std::string Section; 3523 if (Record[5]) { 3524 if (Record[5]-1 >= SectionTable.size()) 3525 return error("Invalid ID"); 3526 Section = SectionTable[Record[5]-1]; 3527 } 3528 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 3529 // Local linkage must have default visibility. 3530 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 3531 // FIXME: Change to an error if non-default in 4.0. 3532 Visibility = getDecodedVisibility(Record[6]); 3533 3534 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 3535 if (Record.size() > 7) 3536 TLM = getDecodedThreadLocalMode(Record[7]); 3537 3538 bool UnnamedAddr = false; 3539 if (Record.size() > 8) 3540 UnnamedAddr = Record[8]; 3541 3542 bool ExternallyInitialized = false; 3543 if (Record.size() > 9) 3544 ExternallyInitialized = Record[9]; 3545 3546 GlobalVariable *NewGV = 3547 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 3548 TLM, AddressSpace, ExternallyInitialized); 3549 NewGV->setAlignment(Alignment); 3550 if (!Section.empty()) 3551 NewGV->setSection(Section); 3552 NewGV->setVisibility(Visibility); 3553 NewGV->setUnnamedAddr(UnnamedAddr); 3554 3555 if (Record.size() > 10) 3556 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10])); 3557 else 3558 upgradeDLLImportExportLinkage(NewGV, RawLinkage); 3559 3560 ValueList.push_back(NewGV); 3561 3562 // Remember which value to use for the global initializer. 3563 if (unsigned InitID = Record[2]) 3564 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 3565 3566 if (Record.size() > 11) { 3567 if (unsigned ComdatID = Record[11]) { 3568 if (ComdatID > ComdatList.size()) 3569 return error("Invalid global variable comdat ID"); 3570 NewGV->setComdat(ComdatList[ComdatID - 1]); 3571 } 3572 } else if (hasImplicitComdat(RawLinkage)) { 3573 NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 3574 } 3575 break; 3576 } 3577 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 3578 // alignment, section, visibility, gc, unnamed_addr, 3579 // prologuedata, dllstorageclass, comdat, prefixdata] 3580 case bitc::MODULE_CODE_FUNCTION: { 3581 if (Record.size() < 8) 3582 return error("Invalid record"); 3583 Type *Ty = getTypeByID(Record[0]); 3584 if (!Ty) 3585 return error("Invalid record"); 3586 if (auto *PTy = dyn_cast<PointerType>(Ty)) 3587 Ty = PTy->getElementType(); 3588 auto *FTy = dyn_cast<FunctionType>(Ty); 3589 if (!FTy) 3590 return error("Invalid type for value"); 3591 auto CC = static_cast<CallingConv::ID>(Record[1]); 3592 if (CC & ~CallingConv::MaxID) 3593 return error("Invalid calling convention ID"); 3594 3595 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 3596 "", TheModule); 3597 3598 Func->setCallingConv(CC); 3599 bool isProto = Record[2]; 3600 uint64_t RawLinkage = Record[3]; 3601 Func->setLinkage(getDecodedLinkage(RawLinkage)); 3602 Func->setAttributes(getAttributes(Record[4])); 3603 3604 unsigned Alignment; 3605 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment)) 3606 return EC; 3607 Func->setAlignment(Alignment); 3608 if (Record[6]) { 3609 if (Record[6]-1 >= SectionTable.size()) 3610 return error("Invalid ID"); 3611 Func->setSection(SectionTable[Record[6]-1]); 3612 } 3613 // Local linkage must have default visibility. 3614 if (!Func->hasLocalLinkage()) 3615 // FIXME: Change to an error if non-default in 4.0. 3616 Func->setVisibility(getDecodedVisibility(Record[7])); 3617 if (Record.size() > 8 && Record[8]) { 3618 if (Record[8]-1 >= GCTable.size()) 3619 return error("Invalid ID"); 3620 Func->setGC(GCTable[Record[8]-1].c_str()); 3621 } 3622 bool UnnamedAddr = false; 3623 if (Record.size() > 9) 3624 UnnamedAddr = Record[9]; 3625 Func->setUnnamedAddr(UnnamedAddr); 3626 if (Record.size() > 10 && Record[10] != 0) 3627 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1)); 3628 3629 if (Record.size() > 11) 3630 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11])); 3631 else 3632 upgradeDLLImportExportLinkage(Func, RawLinkage); 3633 3634 if (Record.size() > 12) { 3635 if (unsigned ComdatID = Record[12]) { 3636 if (ComdatID > ComdatList.size()) 3637 return error("Invalid function comdat ID"); 3638 Func->setComdat(ComdatList[ComdatID - 1]); 3639 } 3640 } else if (hasImplicitComdat(RawLinkage)) { 3641 Func->setComdat(reinterpret_cast<Comdat *>(1)); 3642 } 3643 3644 if (Record.size() > 13 && Record[13] != 0) 3645 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1)); 3646 3647 if (Record.size() > 14 && Record[14] != 0) 3648 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1)); 3649 3650 ValueList.push_back(Func); 3651 3652 // If this is a function with a body, remember the prototype we are 3653 // creating now, so that we can match up the body with them later. 3654 if (!isProto) { 3655 Func->setIsMaterializable(true); 3656 FunctionsWithBodies.push_back(Func); 3657 DeferredFunctionInfo[Func] = 0; 3658 } 3659 break; 3660 } 3661 // ALIAS: [alias type, addrspace, aliasee val#, linkage] 3662 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass] 3663 case bitc::MODULE_CODE_ALIAS: 3664 case bitc::MODULE_CODE_ALIAS_OLD: { 3665 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS; 3666 if (Record.size() < (3 + (unsigned)NewRecord)) 3667 return error("Invalid record"); 3668 unsigned OpNum = 0; 3669 Type *Ty = getTypeByID(Record[OpNum++]); 3670 if (!Ty) 3671 return error("Invalid record"); 3672 3673 unsigned AddrSpace; 3674 if (!NewRecord) { 3675 auto *PTy = dyn_cast<PointerType>(Ty); 3676 if (!PTy) 3677 return error("Invalid type for value"); 3678 Ty = PTy->getElementType(); 3679 AddrSpace = PTy->getAddressSpace(); 3680 } else { 3681 AddrSpace = Record[OpNum++]; 3682 } 3683 3684 auto Val = Record[OpNum++]; 3685 auto Linkage = Record[OpNum++]; 3686 auto *NewGA = GlobalAlias::create( 3687 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule); 3688 // Old bitcode files didn't have visibility field. 3689 // Local linkage must have default visibility. 3690 if (OpNum != Record.size()) { 3691 auto VisInd = OpNum++; 3692 if (!NewGA->hasLocalLinkage()) 3693 // FIXME: Change to an error if non-default in 4.0. 3694 NewGA->setVisibility(getDecodedVisibility(Record[VisInd])); 3695 } 3696 if (OpNum != Record.size()) 3697 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++])); 3698 else 3699 upgradeDLLImportExportLinkage(NewGA, Linkage); 3700 if (OpNum != Record.size()) 3701 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++])); 3702 if (OpNum != Record.size()) 3703 NewGA->setUnnamedAddr(Record[OpNum++]); 3704 ValueList.push_back(NewGA); 3705 AliasInits.push_back(std::make_pair(NewGA, Val)); 3706 break; 3707 } 3708 /// MODULE_CODE_PURGEVALS: [numvals] 3709 case bitc::MODULE_CODE_PURGEVALS: 3710 // Trim down the value list to the specified size. 3711 if (Record.size() < 1 || Record[0] > ValueList.size()) 3712 return error("Invalid record"); 3713 ValueList.shrinkTo(Record[0]); 3714 break; 3715 /// MODULE_CODE_VSTOFFSET: [offset] 3716 case bitc::MODULE_CODE_VSTOFFSET: 3717 if (Record.size() < 1) 3718 return error("Invalid record"); 3719 VSTOffset = Record[0]; 3720 break; 3721 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 3722 case bitc::MODULE_CODE_SOURCE_FILENAME: 3723 SmallString<128> ValueName; 3724 if (convertToString(Record, 0, ValueName)) 3725 return error("Invalid record"); 3726 TheModule->setSourceFileName(ValueName); 3727 break; 3728 } 3729 Record.clear(); 3730 } 3731 } 3732 3733 /// Helper to read the header common to all bitcode files. 3734 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) { 3735 // Sniff for the signature. 3736 if (Stream.Read(8) != 'B' || 3737 Stream.Read(8) != 'C' || 3738 Stream.Read(4) != 0x0 || 3739 Stream.Read(4) != 0xC || 3740 Stream.Read(4) != 0xE || 3741 Stream.Read(4) != 0xD) 3742 return false; 3743 return true; 3744 } 3745 3746 std::error_code 3747 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer, 3748 Module *M, bool ShouldLazyLoadMetadata) { 3749 TheModule = M; 3750 3751 if (std::error_code EC = initStream(std::move(Streamer))) 3752 return EC; 3753 3754 // Sniff for the signature. 3755 if (!hasValidBitcodeHeader(Stream)) 3756 return error("Invalid bitcode signature"); 3757 3758 // We expect a number of well-defined blocks, though we don't necessarily 3759 // need to understand them all. 3760 while (1) { 3761 if (Stream.AtEndOfStream()) { 3762 // We didn't really read a proper Module. 3763 return error("Malformed IR file"); 3764 } 3765 3766 BitstreamEntry Entry = 3767 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 3768 3769 if (Entry.Kind != BitstreamEntry::SubBlock) 3770 return error("Malformed block"); 3771 3772 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 3773 parseBitcodeVersion(); 3774 continue; 3775 } 3776 3777 if (Entry.ID == bitc::MODULE_BLOCK_ID) 3778 return parseModule(0, ShouldLazyLoadMetadata); 3779 3780 if (Stream.SkipBlock()) 3781 return error("Invalid record"); 3782 } 3783 } 3784 3785 ErrorOr<std::string> BitcodeReader::parseModuleTriple() { 3786 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 3787 return error("Invalid record"); 3788 3789 SmallVector<uint64_t, 64> Record; 3790 3791 std::string Triple; 3792 // Read all the records for this module. 3793 while (1) { 3794 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3795 3796 switch (Entry.Kind) { 3797 case BitstreamEntry::SubBlock: // Handled for us already. 3798 case BitstreamEntry::Error: 3799 return error("Malformed block"); 3800 case BitstreamEntry::EndBlock: 3801 return Triple; 3802 case BitstreamEntry::Record: 3803 // The interesting case. 3804 break; 3805 } 3806 3807 // Read a record. 3808 switch (Stream.readRecord(Entry.ID, Record)) { 3809 default: break; // Default behavior, ignore unknown content. 3810 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 3811 std::string S; 3812 if (convertToString(Record, 0, S)) 3813 return error("Invalid record"); 3814 Triple = S; 3815 break; 3816 } 3817 } 3818 Record.clear(); 3819 } 3820 llvm_unreachable("Exit infinite loop"); 3821 } 3822 3823 ErrorOr<std::string> BitcodeReader::parseTriple() { 3824 if (std::error_code EC = initStream(nullptr)) 3825 return EC; 3826 3827 // Sniff for the signature. 3828 if (!hasValidBitcodeHeader(Stream)) 3829 return error("Invalid bitcode signature"); 3830 3831 // We expect a number of well-defined blocks, though we don't necessarily 3832 // need to understand them all. 3833 while (1) { 3834 BitstreamEntry Entry = Stream.advance(); 3835 3836 switch (Entry.Kind) { 3837 case BitstreamEntry::Error: 3838 return error("Malformed block"); 3839 case BitstreamEntry::EndBlock: 3840 return std::error_code(); 3841 3842 case BitstreamEntry::SubBlock: 3843 if (Entry.ID == bitc::MODULE_BLOCK_ID) 3844 return parseModuleTriple(); 3845 3846 // Ignore other sub-blocks. 3847 if (Stream.SkipBlock()) 3848 return error("Malformed block"); 3849 continue; 3850 3851 case BitstreamEntry::Record: 3852 Stream.skipRecord(Entry.ID); 3853 continue; 3854 } 3855 } 3856 } 3857 3858 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() { 3859 if (std::error_code EC = initStream(nullptr)) 3860 return EC; 3861 3862 // Sniff for the signature. 3863 if (!hasValidBitcodeHeader(Stream)) 3864 return error("Invalid bitcode signature"); 3865 3866 // We expect a number of well-defined blocks, though we don't necessarily 3867 // need to understand them all. 3868 while (1) { 3869 BitstreamEntry Entry = Stream.advance(); 3870 switch (Entry.Kind) { 3871 case BitstreamEntry::Error: 3872 return error("Malformed block"); 3873 case BitstreamEntry::EndBlock: 3874 return std::error_code(); 3875 3876 case BitstreamEntry::SubBlock: 3877 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 3878 if (std::error_code EC = parseBitcodeVersion()) 3879 return EC; 3880 return ProducerIdentification; 3881 } 3882 // Ignore other sub-blocks. 3883 if (Stream.SkipBlock()) 3884 return error("Malformed block"); 3885 continue; 3886 case BitstreamEntry::Record: 3887 Stream.skipRecord(Entry.ID); 3888 continue; 3889 } 3890 } 3891 } 3892 3893 /// Parse metadata attachments. 3894 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) { 3895 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 3896 return error("Invalid record"); 3897 3898 SmallVector<uint64_t, 64> Record; 3899 while (1) { 3900 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 3901 3902 switch (Entry.Kind) { 3903 case BitstreamEntry::SubBlock: // Handled for us already. 3904 case BitstreamEntry::Error: 3905 return error("Malformed block"); 3906 case BitstreamEntry::EndBlock: 3907 return std::error_code(); 3908 case BitstreamEntry::Record: 3909 // The interesting case. 3910 break; 3911 } 3912 3913 // Read a metadata attachment record. 3914 Record.clear(); 3915 switch (Stream.readRecord(Entry.ID, Record)) { 3916 default: // Default behavior: ignore. 3917 break; 3918 case bitc::METADATA_ATTACHMENT: { 3919 unsigned RecordLength = Record.size(); 3920 if (Record.empty()) 3921 return error("Invalid record"); 3922 if (RecordLength % 2 == 0) { 3923 // A function attachment. 3924 for (unsigned I = 0; I != RecordLength; I += 2) { 3925 auto K = MDKindMap.find(Record[I]); 3926 if (K == MDKindMap.end()) 3927 return error("Invalid ID"); 3928 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]); 3929 if (!MD) 3930 return error("Invalid metadata attachment"); 3931 F.setMetadata(K->second, MD); 3932 } 3933 continue; 3934 } 3935 3936 // An instruction attachment. 3937 Instruction *Inst = InstructionList[Record[0]]; 3938 for (unsigned i = 1; i != RecordLength; i = i+2) { 3939 unsigned Kind = Record[i]; 3940 DenseMap<unsigned, unsigned>::iterator I = 3941 MDKindMap.find(Kind); 3942 if (I == MDKindMap.end()) 3943 return error("Invalid ID"); 3944 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]); 3945 if (isa<LocalAsMetadata>(Node)) 3946 // Drop the attachment. This used to be legal, but there's no 3947 // upgrade path. 3948 break; 3949 MDNode *MD = dyn_cast_or_null<MDNode>(Node); 3950 if (!MD) 3951 return error("Invalid metadata attachment"); 3952 3953 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop) 3954 MD = upgradeInstructionLoopAttachment(*MD); 3955 3956 Inst->setMetadata(I->second, MD); 3957 if (I->second == LLVMContext::MD_tbaa) { 3958 InstsWithTBAATag.push_back(Inst); 3959 continue; 3960 } 3961 } 3962 break; 3963 } 3964 } 3965 } 3966 } 3967 3968 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 3969 LLVMContext &Context = PtrType->getContext(); 3970 if (!isa<PointerType>(PtrType)) 3971 return error(Context, "Load/Store operand is not a pointer type"); 3972 Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 3973 3974 if (ValType && ValType != ElemType) 3975 return error(Context, "Explicit load/store type does not match pointee " 3976 "type of pointer operand"); 3977 if (!PointerType::isLoadableOrStorableType(ElemType)) 3978 return error(Context, "Cannot load/store from pointer"); 3979 return std::error_code(); 3980 } 3981 3982 /// Lazily parse the specified function body block. 3983 std::error_code BitcodeReader::parseFunctionBody(Function *F) { 3984 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 3985 return error("Invalid record"); 3986 3987 InstructionList.clear(); 3988 unsigned ModuleValueListSize = ValueList.size(); 3989 unsigned ModuleMetadataListSize = MetadataList.size(); 3990 3991 // Add all the function arguments to the value table. 3992 for (Argument &I : F->args()) 3993 ValueList.push_back(&I); 3994 3995 unsigned NextValueNo = ValueList.size(); 3996 BasicBlock *CurBB = nullptr; 3997 unsigned CurBBNo = 0; 3998 3999 DebugLoc LastLoc; 4000 auto getLastInstruction = [&]() -> Instruction * { 4001 if (CurBB && !CurBB->empty()) 4002 return &CurBB->back(); 4003 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 4004 !FunctionBBs[CurBBNo - 1]->empty()) 4005 return &FunctionBBs[CurBBNo - 1]->back(); 4006 return nullptr; 4007 }; 4008 4009 std::vector<OperandBundleDef> OperandBundles; 4010 4011 // Read all the records. 4012 SmallVector<uint64_t, 64> Record; 4013 while (1) { 4014 BitstreamEntry Entry = Stream.advance(); 4015 4016 switch (Entry.Kind) { 4017 case BitstreamEntry::Error: 4018 return error("Malformed block"); 4019 case BitstreamEntry::EndBlock: 4020 goto OutOfRecordLoop; 4021 4022 case BitstreamEntry::SubBlock: 4023 switch (Entry.ID) { 4024 default: // Skip unknown content. 4025 if (Stream.SkipBlock()) 4026 return error("Invalid record"); 4027 break; 4028 case bitc::CONSTANTS_BLOCK_ID: 4029 if (std::error_code EC = parseConstants()) 4030 return EC; 4031 NextValueNo = ValueList.size(); 4032 break; 4033 case bitc::VALUE_SYMTAB_BLOCK_ID: 4034 if (std::error_code EC = parseValueSymbolTable()) 4035 return EC; 4036 break; 4037 case bitc::METADATA_ATTACHMENT_ID: 4038 if (std::error_code EC = parseMetadataAttachment(*F)) 4039 return EC; 4040 break; 4041 case bitc::METADATA_BLOCK_ID: 4042 if (std::error_code EC = parseMetadata()) 4043 return EC; 4044 break; 4045 case bitc::USELIST_BLOCK_ID: 4046 if (std::error_code EC = parseUseLists()) 4047 return EC; 4048 break; 4049 } 4050 continue; 4051 4052 case BitstreamEntry::Record: 4053 // The interesting case. 4054 break; 4055 } 4056 4057 // Read a record. 4058 Record.clear(); 4059 Instruction *I = nullptr; 4060 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 4061 switch (BitCode) { 4062 default: // Default behavior: reject 4063 return error("Invalid value"); 4064 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 4065 if (Record.size() < 1 || Record[0] == 0) 4066 return error("Invalid record"); 4067 // Create all the basic blocks for the function. 4068 FunctionBBs.resize(Record[0]); 4069 4070 // See if anything took the address of blocks in this function. 4071 auto BBFRI = BasicBlockFwdRefs.find(F); 4072 if (BBFRI == BasicBlockFwdRefs.end()) { 4073 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 4074 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 4075 } else { 4076 auto &BBRefs = BBFRI->second; 4077 // Check for invalid basic block references. 4078 if (BBRefs.size() > FunctionBBs.size()) 4079 return error("Invalid ID"); 4080 assert(!BBRefs.empty() && "Unexpected empty array"); 4081 assert(!BBRefs.front() && "Invalid reference to entry block"); 4082 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 4083 ++I) 4084 if (I < RE && BBRefs[I]) { 4085 BBRefs[I]->insertInto(F); 4086 FunctionBBs[I] = BBRefs[I]; 4087 } else { 4088 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 4089 } 4090 4091 // Erase from the table. 4092 BasicBlockFwdRefs.erase(BBFRI); 4093 } 4094 4095 CurBB = FunctionBBs[0]; 4096 continue; 4097 } 4098 4099 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 4100 // This record indicates that the last instruction is at the same 4101 // location as the previous instruction with a location. 4102 I = getLastInstruction(); 4103 4104 if (!I) 4105 return error("Invalid record"); 4106 I->setDebugLoc(LastLoc); 4107 I = nullptr; 4108 continue; 4109 4110 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 4111 I = getLastInstruction(); 4112 if (!I || Record.size() < 4) 4113 return error("Invalid record"); 4114 4115 unsigned Line = Record[0], Col = Record[1]; 4116 unsigned ScopeID = Record[2], IAID = Record[3]; 4117 4118 MDNode *Scope = nullptr, *IA = nullptr; 4119 if (ScopeID) { 4120 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1); 4121 if (!Scope) 4122 return error("Invalid record"); 4123 } 4124 if (IAID) { 4125 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1); 4126 if (!IA) 4127 return error("Invalid record"); 4128 } 4129 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 4130 I->setDebugLoc(LastLoc); 4131 I = nullptr; 4132 continue; 4133 } 4134 4135 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 4136 unsigned OpNum = 0; 4137 Value *LHS, *RHS; 4138 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4139 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 4140 OpNum+1 > Record.size()) 4141 return error("Invalid record"); 4142 4143 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 4144 if (Opc == -1) 4145 return error("Invalid record"); 4146 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 4147 InstructionList.push_back(I); 4148 if (OpNum < Record.size()) { 4149 if (Opc == Instruction::Add || 4150 Opc == Instruction::Sub || 4151 Opc == Instruction::Mul || 4152 Opc == Instruction::Shl) { 4153 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 4154 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 4155 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 4156 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 4157 } else if (Opc == Instruction::SDiv || 4158 Opc == Instruction::UDiv || 4159 Opc == Instruction::LShr || 4160 Opc == Instruction::AShr) { 4161 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 4162 cast<BinaryOperator>(I)->setIsExact(true); 4163 } else if (isa<FPMathOperator>(I)) { 4164 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4165 if (FMF.any()) 4166 I->setFastMathFlags(FMF); 4167 } 4168 4169 } 4170 break; 4171 } 4172 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 4173 unsigned OpNum = 0; 4174 Value *Op; 4175 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4176 OpNum+2 != Record.size()) 4177 return error("Invalid record"); 4178 4179 Type *ResTy = getTypeByID(Record[OpNum]); 4180 int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 4181 if (Opc == -1 || !ResTy) 4182 return error("Invalid record"); 4183 Instruction *Temp = nullptr; 4184 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4185 if (Temp) { 4186 InstructionList.push_back(Temp); 4187 CurBB->getInstList().push_back(Temp); 4188 } 4189 } else { 4190 auto CastOp = (Instruction::CastOps)Opc; 4191 if (!CastInst::castIsValid(CastOp, Op, ResTy)) 4192 return error("Invalid cast"); 4193 I = CastInst::Create(CastOp, Op, ResTy); 4194 } 4195 InstructionList.push_back(I); 4196 break; 4197 } 4198 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4199 case bitc::FUNC_CODE_INST_GEP_OLD: 4200 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4201 unsigned OpNum = 0; 4202 4203 Type *Ty; 4204 bool InBounds; 4205 4206 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4207 InBounds = Record[OpNum++]; 4208 Ty = getTypeByID(Record[OpNum++]); 4209 } else { 4210 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4211 Ty = nullptr; 4212 } 4213 4214 Value *BasePtr; 4215 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 4216 return error("Invalid record"); 4217 4218 if (!Ty) 4219 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType()) 4220 ->getElementType(); 4221 else if (Ty != 4222 cast<SequentialType>(BasePtr->getType()->getScalarType()) 4223 ->getElementType()) 4224 return error( 4225 "Explicit gep type does not match pointee type of pointer operand"); 4226 4227 SmallVector<Value*, 16> GEPIdx; 4228 while (OpNum != Record.size()) { 4229 Value *Op; 4230 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4231 return error("Invalid record"); 4232 GEPIdx.push_back(Op); 4233 } 4234 4235 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4236 4237 InstructionList.push_back(I); 4238 if (InBounds) 4239 cast<GetElementPtrInst>(I)->setIsInBounds(true); 4240 break; 4241 } 4242 4243 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4244 // EXTRACTVAL: [opty, opval, n x indices] 4245 unsigned OpNum = 0; 4246 Value *Agg; 4247 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 4248 return error("Invalid record"); 4249 4250 unsigned RecSize = Record.size(); 4251 if (OpNum == RecSize) 4252 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4253 4254 SmallVector<unsigned, 4> EXTRACTVALIdx; 4255 Type *CurTy = Agg->getType(); 4256 for (; OpNum != RecSize; ++OpNum) { 4257 bool IsArray = CurTy->isArrayTy(); 4258 bool IsStruct = CurTy->isStructTy(); 4259 uint64_t Index = Record[OpNum]; 4260 4261 if (!IsStruct && !IsArray) 4262 return error("EXTRACTVAL: Invalid type"); 4263 if ((unsigned)Index != Index) 4264 return error("Invalid value"); 4265 if (IsStruct && Index >= CurTy->subtypes().size()) 4266 return error("EXTRACTVAL: Invalid struct index"); 4267 if (IsArray && Index >= CurTy->getArrayNumElements()) 4268 return error("EXTRACTVAL: Invalid array index"); 4269 EXTRACTVALIdx.push_back((unsigned)Index); 4270 4271 if (IsStruct) 4272 CurTy = CurTy->subtypes()[Index]; 4273 else 4274 CurTy = CurTy->subtypes()[0]; 4275 } 4276 4277 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 4278 InstructionList.push_back(I); 4279 break; 4280 } 4281 4282 case bitc::FUNC_CODE_INST_INSERTVAL: { 4283 // INSERTVAL: [opty, opval, opty, opval, n x indices] 4284 unsigned OpNum = 0; 4285 Value *Agg; 4286 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 4287 return error("Invalid record"); 4288 Value *Val; 4289 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 4290 return error("Invalid record"); 4291 4292 unsigned RecSize = Record.size(); 4293 if (OpNum == RecSize) 4294 return error("INSERTVAL: Invalid instruction with 0 indices"); 4295 4296 SmallVector<unsigned, 4> INSERTVALIdx; 4297 Type *CurTy = Agg->getType(); 4298 for (; OpNum != RecSize; ++OpNum) { 4299 bool IsArray = CurTy->isArrayTy(); 4300 bool IsStruct = CurTy->isStructTy(); 4301 uint64_t Index = Record[OpNum]; 4302 4303 if (!IsStruct && !IsArray) 4304 return error("INSERTVAL: Invalid type"); 4305 if ((unsigned)Index != Index) 4306 return error("Invalid value"); 4307 if (IsStruct && Index >= CurTy->subtypes().size()) 4308 return error("INSERTVAL: Invalid struct index"); 4309 if (IsArray && Index >= CurTy->getArrayNumElements()) 4310 return error("INSERTVAL: Invalid array index"); 4311 4312 INSERTVALIdx.push_back((unsigned)Index); 4313 if (IsStruct) 4314 CurTy = CurTy->subtypes()[Index]; 4315 else 4316 CurTy = CurTy->subtypes()[0]; 4317 } 4318 4319 if (CurTy != Val->getType()) 4320 return error("Inserted value type doesn't match aggregate type"); 4321 4322 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 4323 InstructionList.push_back(I); 4324 break; 4325 } 4326 4327 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 4328 // obsolete form of select 4329 // handles select i1 ... in old bitcode 4330 unsigned OpNum = 0; 4331 Value *TrueVal, *FalseVal, *Cond; 4332 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 4333 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4334 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 4335 return error("Invalid record"); 4336 4337 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4338 InstructionList.push_back(I); 4339 break; 4340 } 4341 4342 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 4343 // new form of select 4344 // handles select i1 or select [N x i1] 4345 unsigned OpNum = 0; 4346 Value *TrueVal, *FalseVal, *Cond; 4347 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 4348 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4349 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 4350 return error("Invalid record"); 4351 4352 // select condition can be either i1 or [N x i1] 4353 if (VectorType* vector_type = 4354 dyn_cast<VectorType>(Cond->getType())) { 4355 // expect <n x i1> 4356 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 4357 return error("Invalid type for value"); 4358 } else { 4359 // expect i1 4360 if (Cond->getType() != Type::getInt1Ty(Context)) 4361 return error("Invalid type for value"); 4362 } 4363 4364 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4365 InstructionList.push_back(I); 4366 break; 4367 } 4368 4369 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 4370 unsigned OpNum = 0; 4371 Value *Vec, *Idx; 4372 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 4373 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4374 return error("Invalid record"); 4375 if (!Vec->getType()->isVectorTy()) 4376 return error("Invalid type for value"); 4377 I = ExtractElementInst::Create(Vec, Idx); 4378 InstructionList.push_back(I); 4379 break; 4380 } 4381 4382 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 4383 unsigned OpNum = 0; 4384 Value *Vec, *Elt, *Idx; 4385 if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 4386 return error("Invalid record"); 4387 if (!Vec->getType()->isVectorTy()) 4388 return error("Invalid type for value"); 4389 if (popValue(Record, OpNum, NextValueNo, 4390 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 4391 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4392 return error("Invalid record"); 4393 I = InsertElementInst::Create(Vec, Elt, Idx); 4394 InstructionList.push_back(I); 4395 break; 4396 } 4397 4398 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 4399 unsigned OpNum = 0; 4400 Value *Vec1, *Vec2, *Mask; 4401 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 4402 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 4403 return error("Invalid record"); 4404 4405 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 4406 return error("Invalid record"); 4407 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 4408 return error("Invalid type for value"); 4409 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 4410 InstructionList.push_back(I); 4411 break; 4412 } 4413 4414 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 4415 // Old form of ICmp/FCmp returning bool 4416 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 4417 // both legal on vectors but had different behaviour. 4418 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 4419 // FCmp/ICmp returning bool or vector of bool 4420 4421 unsigned OpNum = 0; 4422 Value *LHS, *RHS; 4423 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4424 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 4425 return error("Invalid record"); 4426 4427 unsigned PredVal = Record[OpNum]; 4428 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 4429 FastMathFlags FMF; 4430 if (IsFP && Record.size() > OpNum+1) 4431 FMF = getDecodedFastMathFlags(Record[++OpNum]); 4432 4433 if (OpNum+1 != Record.size()) 4434 return error("Invalid record"); 4435 4436 if (LHS->getType()->isFPOrFPVectorTy()) 4437 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 4438 else 4439 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 4440 4441 if (FMF.any()) 4442 I->setFastMathFlags(FMF); 4443 InstructionList.push_back(I); 4444 break; 4445 } 4446 4447 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 4448 { 4449 unsigned Size = Record.size(); 4450 if (Size == 0) { 4451 I = ReturnInst::Create(Context); 4452 InstructionList.push_back(I); 4453 break; 4454 } 4455 4456 unsigned OpNum = 0; 4457 Value *Op = nullptr; 4458 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4459 return error("Invalid record"); 4460 if (OpNum != Record.size()) 4461 return error("Invalid record"); 4462 4463 I = ReturnInst::Create(Context, Op); 4464 InstructionList.push_back(I); 4465 break; 4466 } 4467 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 4468 if (Record.size() != 1 && Record.size() != 3) 4469 return error("Invalid record"); 4470 BasicBlock *TrueDest = getBasicBlock(Record[0]); 4471 if (!TrueDest) 4472 return error("Invalid record"); 4473 4474 if (Record.size() == 1) { 4475 I = BranchInst::Create(TrueDest); 4476 InstructionList.push_back(I); 4477 } 4478 else { 4479 BasicBlock *FalseDest = getBasicBlock(Record[1]); 4480 Value *Cond = getValue(Record, 2, NextValueNo, 4481 Type::getInt1Ty(Context)); 4482 if (!FalseDest || !Cond) 4483 return error("Invalid record"); 4484 I = BranchInst::Create(TrueDest, FalseDest, Cond); 4485 InstructionList.push_back(I); 4486 } 4487 break; 4488 } 4489 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 4490 if (Record.size() != 1 && Record.size() != 2) 4491 return error("Invalid record"); 4492 unsigned Idx = 0; 4493 Value *CleanupPad = 4494 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4495 if (!CleanupPad) 4496 return error("Invalid record"); 4497 BasicBlock *UnwindDest = nullptr; 4498 if (Record.size() == 2) { 4499 UnwindDest = getBasicBlock(Record[Idx++]); 4500 if (!UnwindDest) 4501 return error("Invalid record"); 4502 } 4503 4504 I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 4505 InstructionList.push_back(I); 4506 break; 4507 } 4508 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 4509 if (Record.size() != 2) 4510 return error("Invalid record"); 4511 unsigned Idx = 0; 4512 Value *CatchPad = 4513 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4514 if (!CatchPad) 4515 return error("Invalid record"); 4516 BasicBlock *BB = getBasicBlock(Record[Idx++]); 4517 if (!BB) 4518 return error("Invalid record"); 4519 4520 I = CatchReturnInst::Create(CatchPad, BB); 4521 InstructionList.push_back(I); 4522 break; 4523 } 4524 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 4525 // We must have, at minimum, the outer scope and the number of arguments. 4526 if (Record.size() < 2) 4527 return error("Invalid record"); 4528 4529 unsigned Idx = 0; 4530 4531 Value *ParentPad = 4532 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4533 4534 unsigned NumHandlers = Record[Idx++]; 4535 4536 SmallVector<BasicBlock *, 2> Handlers; 4537 for (unsigned Op = 0; Op != NumHandlers; ++Op) { 4538 BasicBlock *BB = getBasicBlock(Record[Idx++]); 4539 if (!BB) 4540 return error("Invalid record"); 4541 Handlers.push_back(BB); 4542 } 4543 4544 BasicBlock *UnwindDest = nullptr; 4545 if (Idx + 1 == Record.size()) { 4546 UnwindDest = getBasicBlock(Record[Idx++]); 4547 if (!UnwindDest) 4548 return error("Invalid record"); 4549 } 4550 4551 if (Record.size() != Idx) 4552 return error("Invalid record"); 4553 4554 auto *CatchSwitch = 4555 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 4556 for (BasicBlock *Handler : Handlers) 4557 CatchSwitch->addHandler(Handler); 4558 I = CatchSwitch; 4559 InstructionList.push_back(I); 4560 break; 4561 } 4562 case bitc::FUNC_CODE_INST_CATCHPAD: 4563 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 4564 // We must have, at minimum, the outer scope and the number of arguments. 4565 if (Record.size() < 2) 4566 return error("Invalid record"); 4567 4568 unsigned Idx = 0; 4569 4570 Value *ParentPad = 4571 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 4572 4573 unsigned NumArgOperands = Record[Idx++]; 4574 4575 SmallVector<Value *, 2> Args; 4576 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 4577 Value *Val; 4578 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 4579 return error("Invalid record"); 4580 Args.push_back(Val); 4581 } 4582 4583 if (Record.size() != Idx) 4584 return error("Invalid record"); 4585 4586 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 4587 I = CleanupPadInst::Create(ParentPad, Args); 4588 else 4589 I = CatchPadInst::Create(ParentPad, Args); 4590 InstructionList.push_back(I); 4591 break; 4592 } 4593 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 4594 // Check magic 4595 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 4596 // "New" SwitchInst format with case ranges. The changes to write this 4597 // format were reverted but we still recognize bitcode that uses it. 4598 // Hopefully someday we will have support for case ranges and can use 4599 // this format again. 4600 4601 Type *OpTy = getTypeByID(Record[1]); 4602 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 4603 4604 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 4605 BasicBlock *Default = getBasicBlock(Record[3]); 4606 if (!OpTy || !Cond || !Default) 4607 return error("Invalid record"); 4608 4609 unsigned NumCases = Record[4]; 4610 4611 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4612 InstructionList.push_back(SI); 4613 4614 unsigned CurIdx = 5; 4615 for (unsigned i = 0; i != NumCases; ++i) { 4616 SmallVector<ConstantInt*, 1> CaseVals; 4617 unsigned NumItems = Record[CurIdx++]; 4618 for (unsigned ci = 0; ci != NumItems; ++ci) { 4619 bool isSingleNumber = Record[CurIdx++]; 4620 4621 APInt Low; 4622 unsigned ActiveWords = 1; 4623 if (ValueBitWidth > 64) 4624 ActiveWords = Record[CurIdx++]; 4625 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 4626 ValueBitWidth); 4627 CurIdx += ActiveWords; 4628 4629 if (!isSingleNumber) { 4630 ActiveWords = 1; 4631 if (ValueBitWidth > 64) 4632 ActiveWords = Record[CurIdx++]; 4633 APInt High = readWideAPInt( 4634 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 4635 CurIdx += ActiveWords; 4636 4637 // FIXME: It is not clear whether values in the range should be 4638 // compared as signed or unsigned values. The partially 4639 // implemented changes that used this format in the past used 4640 // unsigned comparisons. 4641 for ( ; Low.ule(High); ++Low) 4642 CaseVals.push_back(ConstantInt::get(Context, Low)); 4643 } else 4644 CaseVals.push_back(ConstantInt::get(Context, Low)); 4645 } 4646 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 4647 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 4648 cve = CaseVals.end(); cvi != cve; ++cvi) 4649 SI->addCase(*cvi, DestBB); 4650 } 4651 I = SI; 4652 break; 4653 } 4654 4655 // Old SwitchInst format without case ranges. 4656 4657 if (Record.size() < 3 || (Record.size() & 1) == 0) 4658 return error("Invalid record"); 4659 Type *OpTy = getTypeByID(Record[0]); 4660 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 4661 BasicBlock *Default = getBasicBlock(Record[2]); 4662 if (!OpTy || !Cond || !Default) 4663 return error("Invalid record"); 4664 unsigned NumCases = (Record.size()-3)/2; 4665 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 4666 InstructionList.push_back(SI); 4667 for (unsigned i = 0, e = NumCases; i != e; ++i) { 4668 ConstantInt *CaseVal = 4669 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 4670 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 4671 if (!CaseVal || !DestBB) { 4672 delete SI; 4673 return error("Invalid record"); 4674 } 4675 SI->addCase(CaseVal, DestBB); 4676 } 4677 I = SI; 4678 break; 4679 } 4680 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 4681 if (Record.size() < 2) 4682 return error("Invalid record"); 4683 Type *OpTy = getTypeByID(Record[0]); 4684 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 4685 if (!OpTy || !Address) 4686 return error("Invalid record"); 4687 unsigned NumDests = Record.size()-2; 4688 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 4689 InstructionList.push_back(IBI); 4690 for (unsigned i = 0, e = NumDests; i != e; ++i) { 4691 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 4692 IBI->addDestination(DestBB); 4693 } else { 4694 delete IBI; 4695 return error("Invalid record"); 4696 } 4697 } 4698 I = IBI; 4699 break; 4700 } 4701 4702 case bitc::FUNC_CODE_INST_INVOKE: { 4703 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 4704 if (Record.size() < 4) 4705 return error("Invalid record"); 4706 unsigned OpNum = 0; 4707 AttributeSet PAL = getAttributes(Record[OpNum++]); 4708 unsigned CCInfo = Record[OpNum++]; 4709 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 4710 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 4711 4712 FunctionType *FTy = nullptr; 4713 if (CCInfo >> 13 & 1 && 4714 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 4715 return error("Explicit invoke type is not a function type"); 4716 4717 Value *Callee; 4718 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 4719 return error("Invalid record"); 4720 4721 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 4722 if (!CalleeTy) 4723 return error("Callee is not a pointer"); 4724 if (!FTy) { 4725 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 4726 if (!FTy) 4727 return error("Callee is not of pointer to function type"); 4728 } else if (CalleeTy->getElementType() != FTy) 4729 return error("Explicit invoke type does not match pointee type of " 4730 "callee operand"); 4731 if (Record.size() < FTy->getNumParams() + OpNum) 4732 return error("Insufficient operands to call"); 4733 4734 SmallVector<Value*, 16> Ops; 4735 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 4736 Ops.push_back(getValue(Record, OpNum, NextValueNo, 4737 FTy->getParamType(i))); 4738 if (!Ops.back()) 4739 return error("Invalid record"); 4740 } 4741 4742 if (!FTy->isVarArg()) { 4743 if (Record.size() != OpNum) 4744 return error("Invalid record"); 4745 } else { 4746 // Read type/value pairs for varargs params. 4747 while (OpNum != Record.size()) { 4748 Value *Op; 4749 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4750 return error("Invalid record"); 4751 Ops.push_back(Op); 4752 } 4753 } 4754 4755 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 4756 OperandBundles.clear(); 4757 InstructionList.push_back(I); 4758 cast<InvokeInst>(I)->setCallingConv( 4759 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 4760 cast<InvokeInst>(I)->setAttributes(PAL); 4761 break; 4762 } 4763 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 4764 unsigned Idx = 0; 4765 Value *Val = nullptr; 4766 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 4767 return error("Invalid record"); 4768 I = ResumeInst::Create(Val); 4769 InstructionList.push_back(I); 4770 break; 4771 } 4772 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 4773 I = new UnreachableInst(Context); 4774 InstructionList.push_back(I); 4775 break; 4776 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 4777 if (Record.size() < 1 || ((Record.size()-1)&1)) 4778 return error("Invalid record"); 4779 Type *Ty = getTypeByID(Record[0]); 4780 if (!Ty) 4781 return error("Invalid record"); 4782 4783 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 4784 InstructionList.push_back(PN); 4785 4786 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 4787 Value *V; 4788 // With the new function encoding, it is possible that operands have 4789 // negative IDs (for forward references). Use a signed VBR 4790 // representation to keep the encoding small. 4791 if (UseRelativeIDs) 4792 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 4793 else 4794 V = getValue(Record, 1+i, NextValueNo, Ty); 4795 BasicBlock *BB = getBasicBlock(Record[2+i]); 4796 if (!V || !BB) 4797 return error("Invalid record"); 4798 PN->addIncoming(V, BB); 4799 } 4800 I = PN; 4801 break; 4802 } 4803 4804 case bitc::FUNC_CODE_INST_LANDINGPAD: 4805 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 4806 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 4807 unsigned Idx = 0; 4808 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 4809 if (Record.size() < 3) 4810 return error("Invalid record"); 4811 } else { 4812 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 4813 if (Record.size() < 4) 4814 return error("Invalid record"); 4815 } 4816 Type *Ty = getTypeByID(Record[Idx++]); 4817 if (!Ty) 4818 return error("Invalid record"); 4819 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 4820 Value *PersFn = nullptr; 4821 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 4822 return error("Invalid record"); 4823 4824 if (!F->hasPersonalityFn()) 4825 F->setPersonalityFn(cast<Constant>(PersFn)); 4826 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 4827 return error("Personality function mismatch"); 4828 } 4829 4830 bool IsCleanup = !!Record[Idx++]; 4831 unsigned NumClauses = Record[Idx++]; 4832 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 4833 LP->setCleanup(IsCleanup); 4834 for (unsigned J = 0; J != NumClauses; ++J) { 4835 LandingPadInst::ClauseType CT = 4836 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 4837 Value *Val; 4838 4839 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 4840 delete LP; 4841 return error("Invalid record"); 4842 } 4843 4844 assert((CT != LandingPadInst::Catch || 4845 !isa<ArrayType>(Val->getType())) && 4846 "Catch clause has a invalid type!"); 4847 assert((CT != LandingPadInst::Filter || 4848 isa<ArrayType>(Val->getType())) && 4849 "Filter clause has invalid type!"); 4850 LP->addClause(cast<Constant>(Val)); 4851 } 4852 4853 I = LP; 4854 InstructionList.push_back(I); 4855 break; 4856 } 4857 4858 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 4859 if (Record.size() != 4) 4860 return error("Invalid record"); 4861 uint64_t AlignRecord = Record[3]; 4862 const uint64_t InAllocaMask = uint64_t(1) << 5; 4863 const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 4864 // Reserve bit 7 for SwiftError flag. 4865 // const uint64_t SwiftErrorMask = uint64_t(1) << 7; 4866 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask; 4867 bool InAlloca = AlignRecord & InAllocaMask; 4868 Type *Ty = getTypeByID(Record[0]); 4869 if ((AlignRecord & ExplicitTypeMask) == 0) { 4870 auto *PTy = dyn_cast_or_null<PointerType>(Ty); 4871 if (!PTy) 4872 return error("Old-style alloca with a non-pointer type"); 4873 Ty = PTy->getElementType(); 4874 } 4875 Type *OpTy = getTypeByID(Record[1]); 4876 Value *Size = getFnValueByID(Record[2], OpTy); 4877 unsigned Align; 4878 if (std::error_code EC = 4879 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 4880 return EC; 4881 } 4882 if (!Ty || !Size) 4883 return error("Invalid record"); 4884 AllocaInst *AI = new AllocaInst(Ty, Size, Align); 4885 AI->setUsedWithInAlloca(InAlloca); 4886 I = AI; 4887 InstructionList.push_back(I); 4888 break; 4889 } 4890 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 4891 unsigned OpNum = 0; 4892 Value *Op; 4893 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4894 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 4895 return error("Invalid record"); 4896 4897 Type *Ty = nullptr; 4898 if (OpNum + 3 == Record.size()) 4899 Ty = getTypeByID(Record[OpNum++]); 4900 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType())) 4901 return EC; 4902 if (!Ty) 4903 Ty = cast<PointerType>(Op->getType())->getElementType(); 4904 4905 unsigned Align; 4906 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4907 return EC; 4908 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 4909 4910 InstructionList.push_back(I); 4911 break; 4912 } 4913 case bitc::FUNC_CODE_INST_LOADATOMIC: { 4914 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 4915 unsigned OpNum = 0; 4916 Value *Op; 4917 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4918 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 4919 return error("Invalid record"); 4920 4921 Type *Ty = nullptr; 4922 if (OpNum + 5 == Record.size()) 4923 Ty = getTypeByID(Record[OpNum++]); 4924 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType())) 4925 return EC; 4926 if (!Ty) 4927 Ty = cast<PointerType>(Op->getType())->getElementType(); 4928 4929 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 4930 if (Ordering == NotAtomic || Ordering == Release || 4931 Ordering == AcquireRelease) 4932 return error("Invalid record"); 4933 if (Ordering != NotAtomic && Record[OpNum] == 0) 4934 return error("Invalid record"); 4935 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 4936 4937 unsigned Align; 4938 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4939 return EC; 4940 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope); 4941 4942 InstructionList.push_back(I); 4943 break; 4944 } 4945 case bitc::FUNC_CODE_INST_STORE: 4946 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 4947 unsigned OpNum = 0; 4948 Value *Val, *Ptr; 4949 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4950 (BitCode == bitc::FUNC_CODE_INST_STORE 4951 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4952 : popValue(Record, OpNum, NextValueNo, 4953 cast<PointerType>(Ptr->getType())->getElementType(), 4954 Val)) || 4955 OpNum + 2 != Record.size()) 4956 return error("Invalid record"); 4957 4958 if (std::error_code EC = 4959 typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4960 return EC; 4961 unsigned Align; 4962 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4963 return EC; 4964 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 4965 InstructionList.push_back(I); 4966 break; 4967 } 4968 case bitc::FUNC_CODE_INST_STOREATOMIC: 4969 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 4970 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 4971 unsigned OpNum = 0; 4972 Value *Val, *Ptr; 4973 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 4974 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 4975 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 4976 : popValue(Record, OpNum, NextValueNo, 4977 cast<PointerType>(Ptr->getType())->getElementType(), 4978 Val)) || 4979 OpNum + 4 != Record.size()) 4980 return error("Invalid record"); 4981 4982 if (std::error_code EC = 4983 typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 4984 return EC; 4985 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 4986 if (Ordering == NotAtomic || Ordering == Acquire || 4987 Ordering == AcquireRelease) 4988 return error("Invalid record"); 4989 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 4990 if (Ordering != NotAtomic && Record[OpNum] == 0) 4991 return error("Invalid record"); 4992 4993 unsigned Align; 4994 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align)) 4995 return EC; 4996 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope); 4997 InstructionList.push_back(I); 4998 break; 4999 } 5000 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 5001 case bitc::FUNC_CODE_INST_CMPXCHG: { 5002 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 5003 // failureordering?, isweak?] 5004 unsigned OpNum = 0; 5005 Value *Ptr, *Cmp, *New; 5006 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5007 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 5008 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 5009 : popValue(Record, OpNum, NextValueNo, 5010 cast<PointerType>(Ptr->getType())->getElementType(), 5011 Cmp)) || 5012 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 5013 Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 5014 return error("Invalid record"); 5015 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 5016 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered) 5017 return error("Invalid record"); 5018 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]); 5019 5020 if (std::error_code EC = 5021 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 5022 return EC; 5023 AtomicOrdering FailureOrdering; 5024 if (Record.size() < 7) 5025 FailureOrdering = 5026 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 5027 else 5028 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 5029 5030 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 5031 SynchScope); 5032 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 5033 5034 if (Record.size() < 8) { 5035 // Before weak cmpxchgs existed, the instruction simply returned the 5036 // value loaded from memory, so bitcode files from that era will be 5037 // expecting the first component of a modern cmpxchg. 5038 CurBB->getInstList().push_back(I); 5039 I = ExtractValueInst::Create(I, 0); 5040 } else { 5041 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 5042 } 5043 5044 InstructionList.push_back(I); 5045 break; 5046 } 5047 case bitc::FUNC_CODE_INST_ATOMICRMW: { 5048 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 5049 unsigned OpNum = 0; 5050 Value *Ptr, *Val; 5051 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5052 popValue(Record, OpNum, NextValueNo, 5053 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 5054 OpNum+4 != Record.size()) 5055 return error("Invalid record"); 5056 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 5057 if (Operation < AtomicRMWInst::FIRST_BINOP || 5058 Operation > AtomicRMWInst::LAST_BINOP) 5059 return error("Invalid record"); 5060 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5061 if (Ordering == NotAtomic || Ordering == Unordered) 5062 return error("Invalid record"); 5063 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 5064 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 5065 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 5066 InstructionList.push_back(I); 5067 break; 5068 } 5069 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 5070 if (2 != Record.size()) 5071 return error("Invalid record"); 5072 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 5073 if (Ordering == NotAtomic || Ordering == Unordered || 5074 Ordering == Monotonic) 5075 return error("Invalid record"); 5076 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]); 5077 I = new FenceInst(Context, Ordering, SynchScope); 5078 InstructionList.push_back(I); 5079 break; 5080 } 5081 case bitc::FUNC_CODE_INST_CALL: { 5082 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 5083 if (Record.size() < 3) 5084 return error("Invalid record"); 5085 5086 unsigned OpNum = 0; 5087 AttributeSet PAL = getAttributes(Record[OpNum++]); 5088 unsigned CCInfo = Record[OpNum++]; 5089 5090 FastMathFlags FMF; 5091 if ((CCInfo >> bitc::CALL_FMF) & 1) { 5092 FMF = getDecodedFastMathFlags(Record[OpNum++]); 5093 if (!FMF.any()) 5094 return error("Fast math flags indicator set for call with no FMF"); 5095 } 5096 5097 FunctionType *FTy = nullptr; 5098 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 5099 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 5100 return error("Explicit call type is not a function type"); 5101 5102 Value *Callee; 5103 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 5104 return error("Invalid record"); 5105 5106 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5107 if (!OpTy) 5108 return error("Callee is not a pointer type"); 5109 if (!FTy) { 5110 FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 5111 if (!FTy) 5112 return error("Callee is not of pointer to function type"); 5113 } else if (OpTy->getElementType() != FTy) 5114 return error("Explicit call type does not match pointee type of " 5115 "callee operand"); 5116 if (Record.size() < FTy->getNumParams() + OpNum) 5117 return error("Insufficient operands to call"); 5118 5119 SmallVector<Value*, 16> Args; 5120 // Read the fixed params. 5121 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5122 if (FTy->getParamType(i)->isLabelTy()) 5123 Args.push_back(getBasicBlock(Record[OpNum])); 5124 else 5125 Args.push_back(getValue(Record, OpNum, NextValueNo, 5126 FTy->getParamType(i))); 5127 if (!Args.back()) 5128 return error("Invalid record"); 5129 } 5130 5131 // Read type/value pairs for varargs params. 5132 if (!FTy->isVarArg()) { 5133 if (OpNum != Record.size()) 5134 return error("Invalid record"); 5135 } else { 5136 while (OpNum != Record.size()) { 5137 Value *Op; 5138 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5139 return error("Invalid record"); 5140 Args.push_back(Op); 5141 } 5142 } 5143 5144 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 5145 OperandBundles.clear(); 5146 InstructionList.push_back(I); 5147 cast<CallInst>(I)->setCallingConv( 5148 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 5149 CallInst::TailCallKind TCK = CallInst::TCK_None; 5150 if (CCInfo & 1 << bitc::CALL_TAIL) 5151 TCK = CallInst::TCK_Tail; 5152 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 5153 TCK = CallInst::TCK_MustTail; 5154 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 5155 TCK = CallInst::TCK_NoTail; 5156 cast<CallInst>(I)->setTailCallKind(TCK); 5157 cast<CallInst>(I)->setAttributes(PAL); 5158 if (FMF.any()) { 5159 if (!isa<FPMathOperator>(I)) 5160 return error("Fast-math-flags specified for call without " 5161 "floating-point scalar or vector return type"); 5162 I->setFastMathFlags(FMF); 5163 } 5164 break; 5165 } 5166 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 5167 if (Record.size() < 3) 5168 return error("Invalid record"); 5169 Type *OpTy = getTypeByID(Record[0]); 5170 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 5171 Type *ResTy = getTypeByID(Record[2]); 5172 if (!OpTy || !Op || !ResTy) 5173 return error("Invalid record"); 5174 I = new VAArgInst(Op, ResTy); 5175 InstructionList.push_back(I); 5176 break; 5177 } 5178 5179 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 5180 // A call or an invoke can be optionally prefixed with some variable 5181 // number of operand bundle blocks. These blocks are read into 5182 // OperandBundles and consumed at the next call or invoke instruction. 5183 5184 if (Record.size() < 1 || Record[0] >= BundleTags.size()) 5185 return error("Invalid record"); 5186 5187 std::vector<Value *> Inputs; 5188 5189 unsigned OpNum = 1; 5190 while (OpNum != Record.size()) { 5191 Value *Op; 5192 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5193 return error("Invalid record"); 5194 Inputs.push_back(Op); 5195 } 5196 5197 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 5198 continue; 5199 } 5200 } 5201 5202 // Add instruction to end of current BB. If there is no current BB, reject 5203 // this file. 5204 if (!CurBB) { 5205 delete I; 5206 return error("Invalid instruction with no BB"); 5207 } 5208 if (!OperandBundles.empty()) { 5209 delete I; 5210 return error("Operand bundles found with no consumer"); 5211 } 5212 CurBB->getInstList().push_back(I); 5213 5214 // If this was a terminator instruction, move to the next block. 5215 if (isa<TerminatorInst>(I)) { 5216 ++CurBBNo; 5217 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 5218 } 5219 5220 // Non-void values get registered in the value table for future use. 5221 if (I && !I->getType()->isVoidTy()) 5222 ValueList.assignValue(I, NextValueNo++); 5223 } 5224 5225 OutOfRecordLoop: 5226 5227 if (!OperandBundles.empty()) 5228 return error("Operand bundles found with no consumer"); 5229 5230 // Check the function list for unresolved values. 5231 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 5232 if (!A->getParent()) { 5233 // We found at least one unresolved value. Nuke them all to avoid leaks. 5234 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 5235 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 5236 A->replaceAllUsesWith(UndefValue::get(A->getType())); 5237 delete A; 5238 } 5239 } 5240 return error("Never resolved value found in function"); 5241 } 5242 } 5243 5244 // FIXME: Check for unresolved forward-declared metadata references 5245 // and clean up leaks. 5246 5247 // Trim the value list down to the size it was before we parsed this function. 5248 ValueList.shrinkTo(ModuleValueListSize); 5249 MetadataList.shrinkTo(ModuleMetadataListSize); 5250 std::vector<BasicBlock*>().swap(FunctionBBs); 5251 return std::error_code(); 5252 } 5253 5254 /// Find the function body in the bitcode stream 5255 std::error_code BitcodeReader::findFunctionInStream( 5256 Function *F, 5257 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 5258 while (DeferredFunctionInfoIterator->second == 0) { 5259 // This is the fallback handling for the old format bitcode that 5260 // didn't contain the function index in the VST, or when we have 5261 // an anonymous function which would not have a VST entry. 5262 // Assert that we have one of those two cases. 5263 assert(VSTOffset == 0 || !F->hasName()); 5264 // Parse the next body in the stream and set its position in the 5265 // DeferredFunctionInfo map. 5266 if (std::error_code EC = rememberAndSkipFunctionBodies()) 5267 return EC; 5268 } 5269 return std::error_code(); 5270 } 5271 5272 //===----------------------------------------------------------------------===// 5273 // GVMaterializer implementation 5274 //===----------------------------------------------------------------------===// 5275 5276 void BitcodeReader::releaseBuffer() { Buffer.release(); } 5277 5278 std::error_code BitcodeReader::materialize(GlobalValue *GV) { 5279 if (std::error_code EC = materializeMetadata()) 5280 return EC; 5281 5282 Function *F = dyn_cast<Function>(GV); 5283 // If it's not a function or is already material, ignore the request. 5284 if (!F || !F->isMaterializable()) 5285 return std::error_code(); 5286 5287 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 5288 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 5289 // If its position is recorded as 0, its body is somewhere in the stream 5290 // but we haven't seen it yet. 5291 if (DFII->second == 0) 5292 if (std::error_code EC = findFunctionInStream(F, DFII)) 5293 return EC; 5294 5295 // Move the bit stream to the saved position of the deferred function body. 5296 Stream.JumpToBit(DFII->second); 5297 5298 if (std::error_code EC = parseFunctionBody(F)) 5299 return EC; 5300 F->setIsMaterializable(false); 5301 5302 if (StripDebugInfo) 5303 stripDebugInfo(*F); 5304 5305 // Upgrade any old intrinsic calls in the function. 5306 for (auto &I : UpgradedIntrinsics) { 5307 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5308 UI != UE;) { 5309 User *U = *UI; 5310 ++UI; 5311 if (CallInst *CI = dyn_cast<CallInst>(U)) 5312 UpgradeIntrinsicCall(CI, I.second); 5313 } 5314 } 5315 5316 // Finish fn->subprogram upgrade for materialized functions. 5317 if (DISubprogram *SP = FunctionsWithSPs.lookup(F)) 5318 F->setSubprogram(SP); 5319 5320 // Bring in any functions that this function forward-referenced via 5321 // blockaddresses. 5322 return materializeForwardReferencedFunctions(); 5323 } 5324 5325 std::error_code BitcodeReader::materializeModule() { 5326 if (std::error_code EC = materializeMetadata()) 5327 return EC; 5328 5329 // Promise to materialize all forward references. 5330 WillMaterializeAllForwardRefs = true; 5331 5332 // Iterate over the module, deserializing any functions that are still on 5333 // disk. 5334 for (Function &F : *TheModule) { 5335 if (std::error_code EC = materialize(&F)) 5336 return EC; 5337 } 5338 // At this point, if there are any function bodies, parse the rest of 5339 // the bits in the module past the last function block we have recorded 5340 // through either lazy scanning or the VST. 5341 if (LastFunctionBlockBit || NextUnreadBit) 5342 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit 5343 : NextUnreadBit); 5344 5345 // Check that all block address forward references got resolved (as we 5346 // promised above). 5347 if (!BasicBlockFwdRefs.empty()) 5348 return error("Never resolved function from blockaddress"); 5349 5350 // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost, 5351 // to prevent this instructions with TBAA tags should be upgraded first. 5352 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 5353 UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 5354 5355 // Upgrade any intrinsic calls that slipped through (should not happen!) and 5356 // delete the old functions to clean up. We can't do this unless the entire 5357 // module is materialized because there could always be another function body 5358 // with calls to the old function. 5359 for (auto &I : UpgradedIntrinsics) { 5360 for (auto *U : I.first->users()) { 5361 if (CallInst *CI = dyn_cast<CallInst>(U)) 5362 UpgradeIntrinsicCall(CI, I.second); 5363 } 5364 if (!I.first->use_empty()) 5365 I.first->replaceAllUsesWith(I.second); 5366 I.first->eraseFromParent(); 5367 } 5368 UpgradedIntrinsics.clear(); 5369 5370 UpgradeDebugInfo(*TheModule); 5371 return std::error_code(); 5372 } 5373 5374 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 5375 return IdentifiedStructTypes; 5376 } 5377 5378 std::error_code 5379 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) { 5380 if (Streamer) 5381 return initLazyStream(std::move(Streamer)); 5382 return initStreamFromBuffer(); 5383 } 5384 5385 std::error_code BitcodeReader::initStreamFromBuffer() { 5386 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 5387 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 5388 5389 if (Buffer->getBufferSize() & 3) 5390 return error("Invalid bitcode signature"); 5391 5392 // If we have a wrapper header, parse it and ignore the non-bc file contents. 5393 // The magic number is 0x0B17C0DE stored in little endian. 5394 if (isBitcodeWrapper(BufPtr, BufEnd)) 5395 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 5396 return error("Invalid bitcode wrapper header"); 5397 5398 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 5399 Stream.init(&*StreamFile); 5400 5401 return std::error_code(); 5402 } 5403 5404 std::error_code 5405 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) { 5406 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 5407 // see it. 5408 auto OwnedBytes = 5409 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer)); 5410 StreamingMemoryObject &Bytes = *OwnedBytes; 5411 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 5412 Stream.init(&*StreamFile); 5413 5414 unsigned char buf[16]; 5415 if (Bytes.readBytes(buf, 16, 0) != 16) 5416 return error("Invalid bitcode signature"); 5417 5418 if (!isBitcode(buf, buf + 16)) 5419 return error("Invalid bitcode signature"); 5420 5421 if (isBitcodeWrapper(buf, buf + 4)) { 5422 const unsigned char *bitcodeStart = buf; 5423 const unsigned char *bitcodeEnd = buf + 16; 5424 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 5425 Bytes.dropLeadingBytes(bitcodeStart - buf); 5426 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 5427 } 5428 return std::error_code(); 5429 } 5430 5431 std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E, 5432 const Twine &Message) { 5433 return ::error(DiagnosticHandler, make_error_code(E), Message); 5434 } 5435 5436 std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) { 5437 return ::error(DiagnosticHandler, 5438 make_error_code(BitcodeError::CorruptedBitcode), Message); 5439 } 5440 5441 std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E) { 5442 return ::error(DiagnosticHandler, make_error_code(E)); 5443 } 5444 5445 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 5446 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler, 5447 bool IsLazy, bool CheckGlobalValSummaryPresenceOnly) 5448 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy), 5449 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {} 5450 5451 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 5452 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy, 5453 bool CheckGlobalValSummaryPresenceOnly) 5454 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy), 5455 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {} 5456 5457 void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; } 5458 5459 void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); } 5460 5461 uint64_t ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) { 5462 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId); 5463 assert(VGI != ValueIdToCallGraphGUIDMap.end()); 5464 return VGI->second; 5465 } 5466 5467 GlobalValueInfo * 5468 ModuleSummaryIndexBitcodeReader::getInfoFromSummaryOffset(uint64_t Offset) { 5469 auto I = SummaryOffsetToInfoMap.find(Offset); 5470 assert(I != SummaryOffsetToInfoMap.end()); 5471 return I->second; 5472 } 5473 5474 // Specialized value symbol table parser used when reading module index 5475 // blocks where we don't actually create global values. 5476 // At the end of this routine the module index is populated with a map 5477 // from global value name to GlobalValueInfo. The global value info contains 5478 // the function block's bitcode offset (if applicable), or the offset into the 5479 // summary section for the combined index. 5480 std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 5481 uint64_t Offset, 5482 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 5483 assert(Offset > 0 && "Expected non-zero VST offset"); 5484 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream); 5485 5486 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 5487 return error("Invalid record"); 5488 5489 SmallVector<uint64_t, 64> Record; 5490 5491 // Read all the records for this value table. 5492 SmallString<128> ValueName; 5493 while (1) { 5494 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 5495 5496 switch (Entry.Kind) { 5497 case BitstreamEntry::SubBlock: // Handled for us already. 5498 case BitstreamEntry::Error: 5499 return error("Malformed block"); 5500 case BitstreamEntry::EndBlock: 5501 // Done parsing VST, jump back to wherever we came from. 5502 Stream.JumpToBit(CurrentBit); 5503 return std::error_code(); 5504 case BitstreamEntry::Record: 5505 // The interesting case. 5506 break; 5507 } 5508 5509 // Read a record. 5510 Record.clear(); 5511 switch (Stream.readRecord(Entry.ID, Record)) { 5512 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 5513 break; 5514 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 5515 if (convertToString(Record, 1, ValueName)) 5516 return error("Invalid record"); 5517 unsigned ValueID = Record[0]; 5518 std::unique_ptr<GlobalValueInfo> GlobalValInfo = 5519 llvm::make_unique<GlobalValueInfo>(); 5520 assert(!SourceFileName.empty()); 5521 auto VLI = ValueIdToLinkageMap.find(ValueID); 5522 assert(VLI != ValueIdToLinkageMap.end() && 5523 "No linkage found for VST entry?"); 5524 std::string GlobalId = GlobalValue::getGlobalIdentifier( 5525 ValueName, VLI->second, SourceFileName); 5526 TheIndex->addGlobalValueInfo(GlobalId, std::move(GlobalValInfo)); 5527 ValueIdToCallGraphGUIDMap[ValueID] = GlobalValue::getGUID(GlobalId); 5528 ValueName.clear(); 5529 break; 5530 } 5531 case bitc::VST_CODE_FNENTRY: { 5532 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 5533 if (convertToString(Record, 2, ValueName)) 5534 return error("Invalid record"); 5535 unsigned ValueID = Record[0]; 5536 uint64_t FuncOffset = Record[1]; 5537 assert(!IsLazy && "Lazy summary read only supported for combined index"); 5538 std::unique_ptr<GlobalValueInfo> FuncInfo = 5539 llvm::make_unique<GlobalValueInfo>(FuncOffset); 5540 assert(!SourceFileName.empty()); 5541 auto VLI = ValueIdToLinkageMap.find(ValueID); 5542 assert(VLI != ValueIdToLinkageMap.end() && 5543 "No linkage found for VST entry?"); 5544 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier( 5545 ValueName, VLI->second, SourceFileName); 5546 TheIndex->addGlobalValueInfo(FunctionGlobalId, std::move(FuncInfo)); 5547 ValueIdToCallGraphGUIDMap[ValueID] = 5548 GlobalValue::getGUID(FunctionGlobalId); 5549 5550 ValueName.clear(); 5551 break; 5552 } 5553 case bitc::VST_CODE_COMBINED_GVDEFENTRY: { 5554 // VST_CODE_COMBINED_GVDEFENTRY: [valueid, offset, guid] 5555 unsigned ValueID = Record[0]; 5556 uint64_t GlobalValSummaryOffset = Record[1]; 5557 uint64_t GlobalValGUID = Record[2]; 5558 std::unique_ptr<GlobalValueInfo> GlobalValInfo = 5559 llvm::make_unique<GlobalValueInfo>(GlobalValSummaryOffset); 5560 SummaryOffsetToInfoMap[GlobalValSummaryOffset] = GlobalValInfo.get(); 5561 TheIndex->addGlobalValueInfo(GlobalValGUID, std::move(GlobalValInfo)); 5562 ValueIdToCallGraphGUIDMap[ValueID] = GlobalValGUID; 5563 break; 5564 } 5565 case bitc::VST_CODE_COMBINED_ENTRY: { 5566 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 5567 unsigned ValueID = Record[0]; 5568 uint64_t RefGUID = Record[1]; 5569 ValueIdToCallGraphGUIDMap[ValueID] = RefGUID; 5570 break; 5571 } 5572 } 5573 } 5574 } 5575 5576 // Parse just the blocks needed for building the index out of the module. 5577 // At the end of this routine the module Index is populated with a map 5578 // from global value name to GlobalValueInfo. The global value info contains 5579 // either the parsed summary information (when parsing summaries 5580 // eagerly), or just to the summary record's offset 5581 // if parsing lazily (IsLazy). 5582 std::error_code ModuleSummaryIndexBitcodeReader::parseModule() { 5583 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 5584 return error("Invalid record"); 5585 5586 SmallVector<uint64_t, 64> Record; 5587 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 5588 unsigned ValueId = 0; 5589 5590 // Read the index for this module. 5591 while (1) { 5592 BitstreamEntry Entry = Stream.advance(); 5593 5594 switch (Entry.Kind) { 5595 case BitstreamEntry::Error: 5596 return error("Malformed block"); 5597 case BitstreamEntry::EndBlock: 5598 return std::error_code(); 5599 5600 case BitstreamEntry::SubBlock: 5601 if (CheckGlobalValSummaryPresenceOnly) { 5602 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 5603 SeenGlobalValSummary = true; 5604 // No need to parse the rest since we found the summary. 5605 return std::error_code(); 5606 } 5607 if (Stream.SkipBlock()) 5608 return error("Invalid record"); 5609 continue; 5610 } 5611 switch (Entry.ID) { 5612 default: // Skip unknown content. 5613 if (Stream.SkipBlock()) 5614 return error("Invalid record"); 5615 break; 5616 case bitc::BLOCKINFO_BLOCK_ID: 5617 // Need to parse these to get abbrev ids (e.g. for VST) 5618 if (Stream.ReadBlockInfoBlock()) 5619 return error("Malformed block"); 5620 break; 5621 case bitc::VALUE_SYMTAB_BLOCK_ID: 5622 // Should have been parsed earlier via VSTOffset, unless there 5623 // is no summary section. 5624 assert(((SeenValueSymbolTable && VSTOffset > 0) || 5625 !SeenGlobalValSummary) && 5626 "Expected early VST parse via VSTOffset record"); 5627 if (Stream.SkipBlock()) 5628 return error("Invalid record"); 5629 break; 5630 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 5631 assert(VSTOffset > 0 && "Expected non-zero VST offset"); 5632 assert(!SeenValueSymbolTable && 5633 "Already read VST when parsing summary block?"); 5634 if (std::error_code EC = 5635 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 5636 return EC; 5637 SeenValueSymbolTable = true; 5638 SeenGlobalValSummary = true; 5639 if (IsLazy) { 5640 // Lazy parsing of summary info, skip it. 5641 if (Stream.SkipBlock()) 5642 return error("Invalid record"); 5643 } else if (std::error_code EC = parseEntireSummary()) 5644 return EC; 5645 break; 5646 case bitc::MODULE_STRTAB_BLOCK_ID: 5647 if (std::error_code EC = parseModuleStringTable()) 5648 return EC; 5649 break; 5650 } 5651 continue; 5652 5653 case BitstreamEntry::Record: 5654 // Once we find the last record of interest, skip the rest. 5655 if (VSTOffset > 0) 5656 Stream.skipRecord(Entry.ID); 5657 else { 5658 Record.clear(); 5659 auto BitCode = Stream.readRecord(Entry.ID, Record); 5660 switch (BitCode) { 5661 default: 5662 break; // Default behavior, ignore unknown content. 5663 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 5664 case bitc::MODULE_CODE_SOURCE_FILENAME: { 5665 SmallString<128> ValueName; 5666 if (convertToString(Record, 0, ValueName)) 5667 return error("Invalid record"); 5668 SourceFileName = ValueName.c_str(); 5669 break; 5670 } 5671 /// MODULE_CODE_VSTOFFSET: [offset] 5672 case bitc::MODULE_CODE_VSTOFFSET: 5673 if (Record.size() < 1) 5674 return error("Invalid record"); 5675 VSTOffset = Record[0]; 5676 break; 5677 // GLOBALVAR: [pointer type, isconst, initid, 5678 // linkage, alignment, section, visibility, threadlocal, 5679 // unnamed_addr, externally_initialized, dllstorageclass, 5680 // comdat] 5681 case bitc::MODULE_CODE_GLOBALVAR: { 5682 if (Record.size() < 6) 5683 return error("Invalid record"); 5684 uint64_t RawLinkage = Record[3]; 5685 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 5686 ValueIdToLinkageMap[ValueId++] = Linkage; 5687 break; 5688 } 5689 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 5690 // alignment, section, visibility, gc, unnamed_addr, 5691 // prologuedata, dllstorageclass, comdat, prefixdata] 5692 case bitc::MODULE_CODE_FUNCTION: { 5693 if (Record.size() < 8) 5694 return error("Invalid record"); 5695 uint64_t RawLinkage = Record[3]; 5696 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 5697 ValueIdToLinkageMap[ValueId++] = Linkage; 5698 break; 5699 } 5700 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 5701 // dllstorageclass] 5702 case bitc::MODULE_CODE_ALIAS: { 5703 if (Record.size() < 6) 5704 return error("Invalid record"); 5705 uint64_t RawLinkage = Record[3]; 5706 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 5707 ValueIdToLinkageMap[ValueId++] = Linkage; 5708 break; 5709 } 5710 } 5711 } 5712 continue; 5713 } 5714 } 5715 } 5716 5717 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 5718 // objects in the index. 5719 std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() { 5720 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID)) 5721 return error("Invalid record"); 5722 5723 SmallVector<uint64_t, 64> Record; 5724 5725 bool Combined = false; 5726 while (1) { 5727 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 5728 5729 switch (Entry.Kind) { 5730 case BitstreamEntry::SubBlock: // Handled for us already. 5731 case BitstreamEntry::Error: 5732 return error("Malformed block"); 5733 case BitstreamEntry::EndBlock: 5734 // For a per-module index, remove any entries that still have empty 5735 // summaries. The VST parsing creates entries eagerly for all symbols, 5736 // but not all have associated summaries (e.g. it doesn't know how to 5737 // distinguish between VST_CODE_ENTRY for function declarations vs global 5738 // variables with initializers that end up with a summary). Remove those 5739 // entries now so that we don't need to rely on the combined index merger 5740 // to clean them up (especially since that may not run for the first 5741 // module's index if we merge into that). 5742 if (!Combined) 5743 TheIndex->removeEmptySummaryEntries(); 5744 return std::error_code(); 5745 case BitstreamEntry::Record: 5746 // The interesting case. 5747 break; 5748 } 5749 5750 // Read a record. The record format depends on whether this 5751 // is a per-module index or a combined index file. In the per-module 5752 // case the records contain the associated value's ID for correlation 5753 // with VST entries. In the combined index the correlation is done 5754 // via the bitcode offset of the summary records (which were saved 5755 // in the combined index VST entries). The records also contain 5756 // information used for ThinLTO renaming and importing. 5757 Record.clear(); 5758 uint64_t CurRecordBit = Stream.GetCurrentBitNo(); 5759 auto BitCode = Stream.readRecord(Entry.ID, Record); 5760 switch (BitCode) { 5761 default: // Default behavior: ignore. 5762 break; 5763 // FS_PERMODULE: [valueid, linkage, instcount, numrefs, numrefs x valueid, 5764 // n x (valueid, callsitecount)] 5765 // FS_PERMODULE_PROFILE: [valueid, linkage, instcount, numrefs, 5766 // numrefs x valueid, 5767 // n x (valueid, callsitecount, profilecount)] 5768 case bitc::FS_PERMODULE: 5769 case bitc::FS_PERMODULE_PROFILE: { 5770 unsigned ValueID = Record[0]; 5771 uint64_t RawLinkage = Record[1]; 5772 unsigned InstCount = Record[2]; 5773 unsigned NumRefs = Record[3]; 5774 std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>( 5775 getDecodedLinkage(RawLinkage), InstCount); 5776 // The module path string ref set in the summary must be owned by the 5777 // index's module string table. Since we don't have a module path 5778 // string table section in the per-module index, we create a single 5779 // module path string table entry with an empty (0) ID to take 5780 // ownership. 5781 FS->setModulePath( 5782 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)); 5783 static int RefListStartIndex = 4; 5784 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 5785 assert(Record.size() >= RefListStartIndex + NumRefs && 5786 "Record size inconsistent with number of references"); 5787 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) { 5788 unsigned RefValueId = Record[I]; 5789 uint64_t RefGUID = getGUIDFromValueId(RefValueId); 5790 FS->addRefEdge(RefGUID); 5791 } 5792 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 5793 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E; 5794 ++I) { 5795 unsigned CalleeValueId = Record[I]; 5796 unsigned CallsiteCount = Record[++I]; 5797 uint64_t ProfileCount = HasProfile ? Record[++I] : 0; 5798 uint64_t CalleeGUID = getGUIDFromValueId(CalleeValueId); 5799 FS->addCallGraphEdge(CalleeGUID, 5800 CalleeInfo(CallsiteCount, ProfileCount)); 5801 } 5802 uint64_t GUID = getGUIDFromValueId(ValueID); 5803 auto InfoList = TheIndex->findGlobalValueInfoList(GUID); 5804 assert(InfoList != TheIndex->end() && 5805 "Expected VST parse to create GlobalValueInfo entry"); 5806 assert(InfoList->second.size() == 1 && 5807 "Expected a single GlobalValueInfo per GUID in module"); 5808 auto &Info = InfoList->second[0]; 5809 assert(!Info->summary() && "Expected a single summary per VST entry"); 5810 Info->setSummary(std::move(FS)); 5811 break; 5812 } 5813 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, linkage, n x valueid] 5814 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 5815 unsigned ValueID = Record[0]; 5816 uint64_t RawLinkage = Record[1]; 5817 std::unique_ptr<GlobalVarSummary> FS = 5818 llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage)); 5819 FS->setModulePath( 5820 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)); 5821 for (unsigned I = 2, E = Record.size(); I != E; ++I) { 5822 unsigned RefValueId = Record[I]; 5823 uint64_t RefGUID = getGUIDFromValueId(RefValueId); 5824 FS->addRefEdge(RefGUID); 5825 } 5826 uint64_t GUID = getGUIDFromValueId(ValueID); 5827 auto InfoList = TheIndex->findGlobalValueInfoList(GUID); 5828 assert(InfoList != TheIndex->end() && 5829 "Expected VST parse to create GlobalValueInfo entry"); 5830 assert(InfoList->second.size() == 1 && 5831 "Expected a single GlobalValueInfo per GUID in module"); 5832 auto &Info = InfoList->second[0]; 5833 assert(!Info->summary() && "Expected a single summary per VST entry"); 5834 Info->setSummary(std::move(FS)); 5835 break; 5836 } 5837 // FS_COMBINED: [modid, linkage, instcount, numrefs, numrefs x valueid, 5838 // n x (valueid, callsitecount)] 5839 // FS_COMBINED_PROFILE: [modid, linkage, instcount, numrefs, 5840 // numrefs x valueid, 5841 // n x (valueid, callsitecount, profilecount)] 5842 case bitc::FS_COMBINED: 5843 case bitc::FS_COMBINED_PROFILE: { 5844 uint64_t ModuleId = Record[0]; 5845 uint64_t RawLinkage = Record[1]; 5846 unsigned InstCount = Record[2]; 5847 unsigned NumRefs = Record[3]; 5848 std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>( 5849 getDecodedLinkage(RawLinkage), InstCount); 5850 FS->setModulePath(ModuleIdMap[ModuleId]); 5851 static int RefListStartIndex = 4; 5852 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 5853 assert(Record.size() >= RefListStartIndex + NumRefs && 5854 "Record size inconsistent with number of references"); 5855 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) { 5856 unsigned RefValueId = Record[I]; 5857 uint64_t RefGUID = getGUIDFromValueId(RefValueId); 5858 FS->addRefEdge(RefGUID); 5859 } 5860 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 5861 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E; 5862 ++I) { 5863 unsigned CalleeValueId = Record[I]; 5864 unsigned CallsiteCount = Record[++I]; 5865 uint64_t ProfileCount = HasProfile ? Record[++I] : 0; 5866 uint64_t CalleeGUID = getGUIDFromValueId(CalleeValueId); 5867 FS->addCallGraphEdge(CalleeGUID, 5868 CalleeInfo(CallsiteCount, ProfileCount)); 5869 } 5870 auto *Info = getInfoFromSummaryOffset(CurRecordBit); 5871 assert(!Info->summary() && "Expected a single summary per VST entry"); 5872 Info->setSummary(std::move(FS)); 5873 Combined = true; 5874 break; 5875 } 5876 // FS_COMBINED_GLOBALVAR_INIT_REFS: [modid, linkage, n x valueid] 5877 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 5878 uint64_t ModuleId = Record[0]; 5879 uint64_t RawLinkage = Record[1]; 5880 std::unique_ptr<GlobalVarSummary> FS = 5881 llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage)); 5882 FS->setModulePath(ModuleIdMap[ModuleId]); 5883 for (unsigned I = 2, E = Record.size(); I != E; ++I) { 5884 unsigned RefValueId = Record[I]; 5885 uint64_t RefGUID = getGUIDFromValueId(RefValueId); 5886 FS->addRefEdge(RefGUID); 5887 } 5888 auto *Info = getInfoFromSummaryOffset(CurRecordBit); 5889 assert(!Info->summary() && "Expected a single summary per VST entry"); 5890 Info->setSummary(std::move(FS)); 5891 Combined = true; 5892 break; 5893 } 5894 } 5895 } 5896 llvm_unreachable("Exit infinite loop"); 5897 } 5898 5899 // Parse the module string table block into the Index. 5900 // This populates the ModulePathStringTable map in the index. 5901 std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 5902 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 5903 return error("Invalid record"); 5904 5905 SmallVector<uint64_t, 64> Record; 5906 5907 SmallString<128> ModulePath; 5908 while (1) { 5909 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 5910 5911 switch (Entry.Kind) { 5912 case BitstreamEntry::SubBlock: // Handled for us already. 5913 case BitstreamEntry::Error: 5914 return error("Malformed block"); 5915 case BitstreamEntry::EndBlock: 5916 return std::error_code(); 5917 case BitstreamEntry::Record: 5918 // The interesting case. 5919 break; 5920 } 5921 5922 Record.clear(); 5923 switch (Stream.readRecord(Entry.ID, Record)) { 5924 default: // Default behavior: ignore. 5925 break; 5926 case bitc::MST_CODE_ENTRY: { 5927 // MST_ENTRY: [modid, namechar x N] 5928 if (convertToString(Record, 1, ModulePath)) 5929 return error("Invalid record"); 5930 uint64_t ModuleId = Record[0]; 5931 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId); 5932 ModuleIdMap[ModuleId] = ModulePathInMap; 5933 ModulePath.clear(); 5934 break; 5935 } 5936 } 5937 } 5938 llvm_unreachable("Exit infinite loop"); 5939 } 5940 5941 // Parse the function info index from the bitcode streamer into the given index. 5942 std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto( 5943 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) { 5944 TheIndex = I; 5945 5946 if (std::error_code EC = initStream(std::move(Streamer))) 5947 return EC; 5948 5949 // Sniff for the signature. 5950 if (!hasValidBitcodeHeader(Stream)) 5951 return error("Invalid bitcode signature"); 5952 5953 // We expect a number of well-defined blocks, though we don't necessarily 5954 // need to understand them all. 5955 while (1) { 5956 if (Stream.AtEndOfStream()) { 5957 // We didn't really read a proper Module block. 5958 return error("Malformed block"); 5959 } 5960 5961 BitstreamEntry Entry = 5962 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 5963 5964 if (Entry.Kind != BitstreamEntry::SubBlock) 5965 return error("Malformed block"); 5966 5967 // If we see a MODULE_BLOCK, parse it to find the blocks needed for 5968 // building the function summary index. 5969 if (Entry.ID == bitc::MODULE_BLOCK_ID) 5970 return parseModule(); 5971 5972 if (Stream.SkipBlock()) 5973 return error("Invalid record"); 5974 } 5975 } 5976 5977 // Parse the summary information at the given offset in the buffer into 5978 // the index. Used to support lazy parsing of summaries from the 5979 // combined index during importing. 5980 // TODO: This function is not yet complete as it won't have a consumer 5981 // until ThinLTO function importing is added. 5982 std::error_code ModuleSummaryIndexBitcodeReader::parseGlobalValueSummary( 5983 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I, 5984 size_t SummaryOffset) { 5985 TheIndex = I; 5986 5987 if (std::error_code EC = initStream(std::move(Streamer))) 5988 return EC; 5989 5990 // Sniff for the signature. 5991 if (!hasValidBitcodeHeader(Stream)) 5992 return error("Invalid bitcode signature"); 5993 5994 Stream.JumpToBit(SummaryOffset); 5995 5996 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 5997 5998 switch (Entry.Kind) { 5999 default: 6000 return error("Malformed block"); 6001 case BitstreamEntry::Record: 6002 // The expected case. 6003 break; 6004 } 6005 6006 // TODO: Read a record. This interface will be completed when ThinLTO 6007 // importing is added so that it can be tested. 6008 SmallVector<uint64_t, 64> Record; 6009 switch (Stream.readRecord(Entry.ID, Record)) { 6010 case bitc::FS_COMBINED: 6011 case bitc::FS_COMBINED_PROFILE: 6012 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: 6013 default: 6014 return error("Invalid record"); 6015 } 6016 6017 return std::error_code(); 6018 } 6019 6020 std::error_code ModuleSummaryIndexBitcodeReader::initStream( 6021 std::unique_ptr<DataStreamer> Streamer) { 6022 if (Streamer) 6023 return initLazyStream(std::move(Streamer)); 6024 return initStreamFromBuffer(); 6025 } 6026 6027 std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() { 6028 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart(); 6029 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize(); 6030 6031 if (Buffer->getBufferSize() & 3) 6032 return error("Invalid bitcode signature"); 6033 6034 // If we have a wrapper header, parse it and ignore the non-bc file contents. 6035 // The magic number is 0x0B17C0DE stored in little endian. 6036 if (isBitcodeWrapper(BufPtr, BufEnd)) 6037 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 6038 return error("Invalid bitcode wrapper header"); 6039 6040 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 6041 Stream.init(&*StreamFile); 6042 6043 return std::error_code(); 6044 } 6045 6046 std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream( 6047 std::unique_ptr<DataStreamer> Streamer) { 6048 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 6049 // see it. 6050 auto OwnedBytes = 6051 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer)); 6052 StreamingMemoryObject &Bytes = *OwnedBytes; 6053 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 6054 Stream.init(&*StreamFile); 6055 6056 unsigned char buf[16]; 6057 if (Bytes.readBytes(buf, 16, 0) != 16) 6058 return error("Invalid bitcode signature"); 6059 6060 if (!isBitcode(buf, buf + 16)) 6061 return error("Invalid bitcode signature"); 6062 6063 if (isBitcodeWrapper(buf, buf + 4)) { 6064 const unsigned char *bitcodeStart = buf; 6065 const unsigned char *bitcodeEnd = buf + 16; 6066 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 6067 Bytes.dropLeadingBytes(bitcodeStart - buf); 6068 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 6069 } 6070 return std::error_code(); 6071 } 6072 6073 namespace { 6074 class BitcodeErrorCategoryType : public std::error_category { 6075 const char *name() const LLVM_NOEXCEPT override { 6076 return "llvm.bitcode"; 6077 } 6078 std::string message(int IE) const override { 6079 BitcodeError E = static_cast<BitcodeError>(IE); 6080 switch (E) { 6081 case BitcodeError::InvalidBitcodeSignature: 6082 return "Invalid bitcode signature"; 6083 case BitcodeError::CorruptedBitcode: 6084 return "Corrupted bitcode"; 6085 } 6086 llvm_unreachable("Unknown error type!"); 6087 } 6088 }; 6089 } // end anonymous namespace 6090 6091 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 6092 6093 const std::error_category &llvm::BitcodeErrorCategory() { 6094 return *ErrorCategory; 6095 } 6096 6097 //===----------------------------------------------------------------------===// 6098 // External interface 6099 //===----------------------------------------------------------------------===// 6100 6101 static ErrorOr<std::unique_ptr<Module>> 6102 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name, 6103 BitcodeReader *R, LLVMContext &Context, 6104 bool MaterializeAll, bool ShouldLazyLoadMetadata) { 6105 std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 6106 M->setMaterializer(R); 6107 6108 auto cleanupOnError = [&](std::error_code EC) { 6109 R->releaseBuffer(); // Never take ownership on error. 6110 return EC; 6111 }; 6112 6113 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 6114 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(), 6115 ShouldLazyLoadMetadata)) 6116 return cleanupOnError(EC); 6117 6118 if (MaterializeAll) { 6119 // Read in the entire module, and destroy the BitcodeReader. 6120 if (std::error_code EC = M->materializeAll()) 6121 return cleanupOnError(EC); 6122 } else { 6123 // Resolve forward references from blockaddresses. 6124 if (std::error_code EC = R->materializeForwardReferencedFunctions()) 6125 return cleanupOnError(EC); 6126 } 6127 return std::move(M); 6128 } 6129 6130 /// \brief Get a lazy one-at-time loading module from bitcode. 6131 /// 6132 /// This isn't always used in a lazy context. In particular, it's also used by 6133 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull 6134 /// in forward-referenced functions from block address references. 6135 /// 6136 /// \param[in] MaterializeAll Set to \c true if we should materialize 6137 /// everything. 6138 static ErrorOr<std::unique_ptr<Module>> 6139 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer, 6140 LLVMContext &Context, bool MaterializeAll, 6141 bool ShouldLazyLoadMetadata = false) { 6142 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context); 6143 6144 ErrorOr<std::unique_ptr<Module>> Ret = 6145 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context, 6146 MaterializeAll, ShouldLazyLoadMetadata); 6147 if (!Ret) 6148 return Ret; 6149 6150 Buffer.release(); // The BitcodeReader owns it now. 6151 return Ret; 6152 } 6153 6154 ErrorOr<std::unique_ptr<Module>> 6155 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 6156 LLVMContext &Context, bool ShouldLazyLoadMetadata) { 6157 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false, 6158 ShouldLazyLoadMetadata); 6159 } 6160 6161 ErrorOr<std::unique_ptr<Module>> 6162 llvm::getStreamedBitcodeModule(StringRef Name, 6163 std::unique_ptr<DataStreamer> Streamer, 6164 LLVMContext &Context) { 6165 std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 6166 BitcodeReader *R = new BitcodeReader(Context); 6167 6168 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false, 6169 false); 6170 } 6171 6172 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 6173 LLVMContext &Context) { 6174 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6175 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true); 6176 // TODO: Restore the use-lists to the in-memory state when the bitcode was 6177 // written. We must defer until the Module has been fully materialized. 6178 } 6179 6180 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, 6181 LLVMContext &Context) { 6182 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6183 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context); 6184 ErrorOr<std::string> Triple = R->parseTriple(); 6185 if (Triple.getError()) 6186 return ""; 6187 return Triple.get(); 6188 } 6189 6190 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer, 6191 LLVMContext &Context) { 6192 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6193 BitcodeReader R(Buf.release(), Context); 6194 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock(); 6195 if (ProducerString.getError()) 6196 return ""; 6197 return ProducerString.get(); 6198 } 6199 6200 // Parse the specified bitcode buffer, returning the function info index. 6201 // If IsLazy is false, parse the entire function summary into 6202 // the index. Otherwise skip the function summary section, and only create 6203 // an index object with a map from function name to function summary offset. 6204 // The index is used to perform lazy function summary reading later. 6205 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> 6206 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer, 6207 DiagnosticHandlerFunction DiagnosticHandler, 6208 bool IsLazy) { 6209 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6210 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy); 6211 6212 auto Index = llvm::make_unique<ModuleSummaryIndex>(); 6213 6214 auto cleanupOnError = [&](std::error_code EC) { 6215 R.releaseBuffer(); // Never take ownership on error. 6216 return EC; 6217 }; 6218 6219 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get())) 6220 return cleanupOnError(EC); 6221 6222 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now. 6223 return std::move(Index); 6224 } 6225 6226 // Check if the given bitcode buffer contains a global value summary block. 6227 bool llvm::hasGlobalValueSummary(MemoryBufferRef Buffer, 6228 DiagnosticHandlerFunction DiagnosticHandler) { 6229 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6230 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true); 6231 6232 auto cleanupOnError = [&](std::error_code EC) { 6233 R.releaseBuffer(); // Never take ownership on error. 6234 return false; 6235 }; 6236 6237 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr)) 6238 return cleanupOnError(EC); 6239 6240 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now. 6241 return R.foundGlobalValSummary(); 6242 } 6243 6244 // This method supports lazy reading of summary data from the combined 6245 // index during ThinLTO function importing. When reading the combined index 6246 // file, getModuleSummaryIndex is first invoked with IsLazy=true. 6247 // Then this method is called for each value considered for importing, 6248 // to parse the summary information for the given value name into 6249 // the index. 6250 std::error_code llvm::readGlobalValueSummary( 6251 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler, 6252 StringRef ValueName, std::unique_ptr<ModuleSummaryIndex> Index) { 6253 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 6254 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler); 6255 6256 auto cleanupOnError = [&](std::error_code EC) { 6257 R.releaseBuffer(); // Never take ownership on error. 6258 return EC; 6259 }; 6260 6261 // Lookup the given value name in the GlobalValueMap, which may 6262 // contain a list of global value infos in the case of a COMDAT. Walk through 6263 // and parse each summary info at the summary offset 6264 // recorded when parsing the value symbol table. 6265 for (const auto &FI : Index->getGlobalValueInfoList(ValueName)) { 6266 size_t SummaryOffset = FI->bitcodeIndex(); 6267 if (std::error_code EC = 6268 R.parseGlobalValueSummary(nullptr, Index.get(), SummaryOffset)) 6269 return cleanupOnError(EC); 6270 } 6271 6272 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now. 6273 return std::error_code(); 6274 } 6275