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