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