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