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