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