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