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 BitstreamEntry Entry = Stream.advance(); 4351 switch (Entry.Kind) { 4352 case BitstreamEntry::Error: 4353 return error("Malformed block"); 4354 case BitstreamEntry::EndBlock: 4355 return Error::success(); 4356 4357 case BitstreamEntry::SubBlock: 4358 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) { 4359 if (Error Err = parseBitcodeVersion()) 4360 return std::move(Err); 4361 return ProducerIdentification; 4362 } 4363 // Ignore other sub-blocks. 4364 if (Stream.SkipBlock()) 4365 return error("Malformed block"); 4366 continue; 4367 case BitstreamEntry::Record: 4368 Stream.skipRecord(Entry.ID); 4369 continue; 4370 } 4371 } 4372 } 4373 4374 Error BitcodeReader::parseGlobalObjectAttachment(GlobalObject &GO, 4375 ArrayRef<uint64_t> Record) { 4376 assert(Record.size() % 2 == 0); 4377 for (unsigned I = 0, E = Record.size(); I != E; I += 2) { 4378 auto K = MDKindMap.find(Record[I]); 4379 if (K == MDKindMap.end()) 4380 return error("Invalid ID"); 4381 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]); 4382 if (!MD) 4383 return error("Invalid metadata attachment"); 4384 GO.addMetadata(K->second, *MD); 4385 } 4386 return Error::success(); 4387 } 4388 4389 Expected<bool> BitcodeReader::hasObjCCategory() { 4390 if (Error Err = initStream()) 4391 return std::move(Err); 4392 4393 // Sniff for the signature. 4394 if (!hasValidBitcodeHeader(Stream)) 4395 return error("Invalid bitcode signature"); 4396 4397 // We expect a number of well-defined blocks, though we don't necessarily 4398 // need to understand them all. 4399 while (true) { 4400 BitstreamEntry Entry = Stream.advance(); 4401 4402 switch (Entry.Kind) { 4403 case BitstreamEntry::Error: 4404 return error("Malformed block"); 4405 case BitstreamEntry::EndBlock: 4406 return Error::success(); 4407 4408 case BitstreamEntry::SubBlock: 4409 if (Entry.ID == bitc::MODULE_BLOCK_ID) 4410 return hasObjCCategoryInModule(); 4411 4412 // Ignore other sub-blocks. 4413 if (Stream.SkipBlock()) 4414 return error("Malformed block"); 4415 continue; 4416 4417 case BitstreamEntry::Record: 4418 Stream.skipRecord(Entry.ID); 4419 continue; 4420 } 4421 } 4422 } 4423 4424 Expected<bool> BitcodeReader::hasObjCCategoryInModule() { 4425 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 4426 return error("Invalid record"); 4427 4428 SmallVector<uint64_t, 64> Record; 4429 // Read all the records for this module. 4430 4431 while (true) { 4432 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4433 4434 switch (Entry.Kind) { 4435 case BitstreamEntry::SubBlock: // Handled for us already. 4436 case BitstreamEntry::Error: 4437 return error("Malformed block"); 4438 case BitstreamEntry::EndBlock: 4439 return false; 4440 case BitstreamEntry::Record: 4441 // The interesting case. 4442 break; 4443 } 4444 4445 // Read a record. 4446 switch (Stream.readRecord(Entry.ID, Record)) { 4447 default: 4448 break; // Default behavior, ignore unknown content. 4449 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 4450 std::string S; 4451 if (convertToString(Record, 0, S)) 4452 return error("Invalid record"); 4453 // Check for the i386 and other (x86_64, ARM) conventions 4454 if (S.find("__DATA, __objc_catlist") != std::string::npos || 4455 S.find("__OBJC,__category") != std::string::npos) 4456 return true; 4457 break; 4458 } 4459 } 4460 Record.clear(); 4461 } 4462 llvm_unreachable("Exit infinite loop"); 4463 } 4464 4465 /// Parse metadata attachments. 4466 Error BitcodeReader::parseMetadataAttachment(Function &F) { 4467 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 4468 return error("Invalid record"); 4469 4470 SmallVector<uint64_t, 64> Record; 4471 4472 while (true) { 4473 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 4474 4475 switch (Entry.Kind) { 4476 case BitstreamEntry::SubBlock: // Handled for us already. 4477 case BitstreamEntry::Error: 4478 return error("Malformed block"); 4479 case BitstreamEntry::EndBlock: 4480 return Error::success(); 4481 case BitstreamEntry::Record: 4482 // The interesting case. 4483 break; 4484 } 4485 4486 // Read a metadata attachment record. 4487 Record.clear(); 4488 switch (Stream.readRecord(Entry.ID, Record)) { 4489 default: // Default behavior: ignore. 4490 break; 4491 case bitc::METADATA_ATTACHMENT: { 4492 unsigned RecordLength = Record.size(); 4493 if (Record.empty()) 4494 return error("Invalid record"); 4495 if (RecordLength % 2 == 0) { 4496 // A function attachment. 4497 if (Error Err = parseGlobalObjectAttachment(F, Record)) 4498 return Err; 4499 continue; 4500 } 4501 4502 // An instruction attachment. 4503 Instruction *Inst = InstructionList[Record[0]]; 4504 for (unsigned i = 1; i != RecordLength; i = i+2) { 4505 unsigned Kind = Record[i]; 4506 DenseMap<unsigned, unsigned>::iterator I = 4507 MDKindMap.find(Kind); 4508 if (I == MDKindMap.end()) 4509 return error("Invalid ID"); 4510 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]); 4511 if (isa<LocalAsMetadata>(Node)) 4512 // Drop the attachment. This used to be legal, but there's no 4513 // upgrade path. 4514 break; 4515 MDNode *MD = dyn_cast_or_null<MDNode>(Node); 4516 if (!MD) 4517 return error("Invalid metadata attachment"); 4518 4519 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop) 4520 MD = upgradeInstructionLoopAttachment(*MD); 4521 4522 if (I->second == LLVMContext::MD_tbaa) { 4523 assert(!MD->isTemporary() && "should load MDs before attachments"); 4524 MD = UpgradeTBAANode(*MD); 4525 } 4526 Inst->setMetadata(I->second, MD); 4527 } 4528 break; 4529 } 4530 } 4531 } 4532 } 4533 4534 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) { 4535 if (!isa<PointerType>(PtrType)) 4536 return error("Load/Store operand is not a pointer type"); 4537 Type *ElemType = cast<PointerType>(PtrType)->getElementType(); 4538 4539 if (ValType && ValType != ElemType) 4540 return error("Explicit load/store type does not match pointee " 4541 "type of pointer operand"); 4542 if (!PointerType::isLoadableOrStorableType(ElemType)) 4543 return error("Cannot load/store from pointer"); 4544 return Error::success(); 4545 } 4546 4547 /// Lazily parse the specified function body block. 4548 Error BitcodeReader::parseFunctionBody(Function *F) { 4549 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 4550 return error("Invalid record"); 4551 4552 // Unexpected unresolved metadata when parsing function. 4553 if (MetadataList.hasFwdRefs()) 4554 return error("Invalid function metadata: incoming forward references"); 4555 4556 InstructionList.clear(); 4557 unsigned ModuleValueListSize = ValueList.size(); 4558 unsigned ModuleMetadataListSize = MetadataList.size(); 4559 4560 // Add all the function arguments to the value table. 4561 for (Argument &I : F->args()) 4562 ValueList.push_back(&I); 4563 4564 unsigned NextValueNo = ValueList.size(); 4565 BasicBlock *CurBB = nullptr; 4566 unsigned CurBBNo = 0; 4567 4568 DebugLoc LastLoc; 4569 auto getLastInstruction = [&]() -> Instruction * { 4570 if (CurBB && !CurBB->empty()) 4571 return &CurBB->back(); 4572 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 4573 !FunctionBBs[CurBBNo - 1]->empty()) 4574 return &FunctionBBs[CurBBNo - 1]->back(); 4575 return nullptr; 4576 }; 4577 4578 std::vector<OperandBundleDef> OperandBundles; 4579 4580 // Read all the records. 4581 SmallVector<uint64_t, 64> Record; 4582 4583 while (true) { 4584 BitstreamEntry Entry = Stream.advance(); 4585 4586 switch (Entry.Kind) { 4587 case BitstreamEntry::Error: 4588 return error("Malformed block"); 4589 case BitstreamEntry::EndBlock: 4590 goto OutOfRecordLoop; 4591 4592 case BitstreamEntry::SubBlock: 4593 switch (Entry.ID) { 4594 default: // Skip unknown content. 4595 if (Stream.SkipBlock()) 4596 return error("Invalid record"); 4597 break; 4598 case bitc::CONSTANTS_BLOCK_ID: 4599 if (Error Err = parseConstants()) 4600 return Err; 4601 NextValueNo = ValueList.size(); 4602 break; 4603 case bitc::VALUE_SYMTAB_BLOCK_ID: 4604 if (Error Err = parseValueSymbolTable()) 4605 return Err; 4606 break; 4607 case bitc::METADATA_ATTACHMENT_ID: 4608 if (Error Err = parseMetadataAttachment(*F)) 4609 return Err; 4610 break; 4611 case bitc::METADATA_BLOCK_ID: 4612 if (Error Err = parseMetadata()) 4613 return Err; 4614 break; 4615 case bitc::USELIST_BLOCK_ID: 4616 if (Error Err = parseUseLists()) 4617 return Err; 4618 break; 4619 } 4620 continue; 4621 4622 case BitstreamEntry::Record: 4623 // The interesting case. 4624 break; 4625 } 4626 4627 // Read a record. 4628 Record.clear(); 4629 Instruction *I = nullptr; 4630 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 4631 switch (BitCode) { 4632 default: // Default behavior: reject 4633 return error("Invalid value"); 4634 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 4635 if (Record.size() < 1 || Record[0] == 0) 4636 return error("Invalid record"); 4637 // Create all the basic blocks for the function. 4638 FunctionBBs.resize(Record[0]); 4639 4640 // See if anything took the address of blocks in this function. 4641 auto BBFRI = BasicBlockFwdRefs.find(F); 4642 if (BBFRI == BasicBlockFwdRefs.end()) { 4643 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 4644 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 4645 } else { 4646 auto &BBRefs = BBFRI->second; 4647 // Check for invalid basic block references. 4648 if (BBRefs.size() > FunctionBBs.size()) 4649 return error("Invalid ID"); 4650 assert(!BBRefs.empty() && "Unexpected empty array"); 4651 assert(!BBRefs.front() && "Invalid reference to entry block"); 4652 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 4653 ++I) 4654 if (I < RE && BBRefs[I]) { 4655 BBRefs[I]->insertInto(F); 4656 FunctionBBs[I] = BBRefs[I]; 4657 } else { 4658 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 4659 } 4660 4661 // Erase from the table. 4662 BasicBlockFwdRefs.erase(BBFRI); 4663 } 4664 4665 CurBB = FunctionBBs[0]; 4666 continue; 4667 } 4668 4669 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 4670 // This record indicates that the last instruction is at the same 4671 // location as the previous instruction with a location. 4672 I = getLastInstruction(); 4673 4674 if (!I) 4675 return error("Invalid record"); 4676 I->setDebugLoc(LastLoc); 4677 I = nullptr; 4678 continue; 4679 4680 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 4681 I = getLastInstruction(); 4682 if (!I || Record.size() < 4) 4683 return error("Invalid record"); 4684 4685 unsigned Line = Record[0], Col = Record[1]; 4686 unsigned ScopeID = Record[2], IAID = Record[3]; 4687 4688 MDNode *Scope = nullptr, *IA = nullptr; 4689 if (ScopeID) { 4690 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1); 4691 if (!Scope) 4692 return error("Invalid record"); 4693 } 4694 if (IAID) { 4695 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1); 4696 if (!IA) 4697 return error("Invalid record"); 4698 } 4699 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 4700 I->setDebugLoc(LastLoc); 4701 I = nullptr; 4702 continue; 4703 } 4704 4705 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 4706 unsigned OpNum = 0; 4707 Value *LHS, *RHS; 4708 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4709 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 4710 OpNum+1 > Record.size()) 4711 return error("Invalid record"); 4712 4713 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 4714 if (Opc == -1) 4715 return error("Invalid record"); 4716 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 4717 InstructionList.push_back(I); 4718 if (OpNum < Record.size()) { 4719 if (Opc == Instruction::Add || 4720 Opc == Instruction::Sub || 4721 Opc == Instruction::Mul || 4722 Opc == Instruction::Shl) { 4723 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 4724 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 4725 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 4726 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 4727 } else if (Opc == Instruction::SDiv || 4728 Opc == Instruction::UDiv || 4729 Opc == Instruction::LShr || 4730 Opc == Instruction::AShr) { 4731 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 4732 cast<BinaryOperator>(I)->setIsExact(true); 4733 } else if (isa<FPMathOperator>(I)) { 4734 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]); 4735 if (FMF.any()) 4736 I->setFastMathFlags(FMF); 4737 } 4738 4739 } 4740 break; 4741 } 4742 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 4743 unsigned OpNum = 0; 4744 Value *Op; 4745 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 4746 OpNum+2 != Record.size()) 4747 return error("Invalid record"); 4748 4749 Type *ResTy = getTypeByID(Record[OpNum]); 4750 int Opc = getDecodedCastOpcode(Record[OpNum + 1]); 4751 if (Opc == -1 || !ResTy) 4752 return error("Invalid record"); 4753 Instruction *Temp = nullptr; 4754 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 4755 if (Temp) { 4756 InstructionList.push_back(Temp); 4757 CurBB->getInstList().push_back(Temp); 4758 } 4759 } else { 4760 auto CastOp = (Instruction::CastOps)Opc; 4761 if (!CastInst::castIsValid(CastOp, Op, ResTy)) 4762 return error("Invalid cast"); 4763 I = CastInst::Create(CastOp, Op, ResTy); 4764 } 4765 InstructionList.push_back(I); 4766 break; 4767 } 4768 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD: 4769 case bitc::FUNC_CODE_INST_GEP_OLD: 4770 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands] 4771 unsigned OpNum = 0; 4772 4773 Type *Ty; 4774 bool InBounds; 4775 4776 if (BitCode == bitc::FUNC_CODE_INST_GEP) { 4777 InBounds = Record[OpNum++]; 4778 Ty = getTypeByID(Record[OpNum++]); 4779 } else { 4780 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD; 4781 Ty = nullptr; 4782 } 4783 4784 Value *BasePtr; 4785 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 4786 return error("Invalid record"); 4787 4788 if (!Ty) 4789 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType()) 4790 ->getElementType(); 4791 else if (Ty != 4792 cast<SequentialType>(BasePtr->getType()->getScalarType()) 4793 ->getElementType()) 4794 return error( 4795 "Explicit gep type does not match pointee type of pointer operand"); 4796 4797 SmallVector<Value*, 16> GEPIdx; 4798 while (OpNum != Record.size()) { 4799 Value *Op; 4800 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 4801 return error("Invalid record"); 4802 GEPIdx.push_back(Op); 4803 } 4804 4805 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx); 4806 4807 InstructionList.push_back(I); 4808 if (InBounds) 4809 cast<GetElementPtrInst>(I)->setIsInBounds(true); 4810 break; 4811 } 4812 4813 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 4814 // EXTRACTVAL: [opty, opval, n x indices] 4815 unsigned OpNum = 0; 4816 Value *Agg; 4817 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 4818 return error("Invalid record"); 4819 4820 unsigned RecSize = Record.size(); 4821 if (OpNum == RecSize) 4822 return error("EXTRACTVAL: Invalid instruction with 0 indices"); 4823 4824 SmallVector<unsigned, 4> EXTRACTVALIdx; 4825 Type *CurTy = Agg->getType(); 4826 for (; OpNum != RecSize; ++OpNum) { 4827 bool IsArray = CurTy->isArrayTy(); 4828 bool IsStruct = CurTy->isStructTy(); 4829 uint64_t Index = Record[OpNum]; 4830 4831 if (!IsStruct && !IsArray) 4832 return error("EXTRACTVAL: Invalid type"); 4833 if ((unsigned)Index != Index) 4834 return error("Invalid value"); 4835 if (IsStruct && Index >= CurTy->subtypes().size()) 4836 return error("EXTRACTVAL: Invalid struct index"); 4837 if (IsArray && Index >= CurTy->getArrayNumElements()) 4838 return error("EXTRACTVAL: Invalid array index"); 4839 EXTRACTVALIdx.push_back((unsigned)Index); 4840 4841 if (IsStruct) 4842 CurTy = CurTy->subtypes()[Index]; 4843 else 4844 CurTy = CurTy->subtypes()[0]; 4845 } 4846 4847 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 4848 InstructionList.push_back(I); 4849 break; 4850 } 4851 4852 case bitc::FUNC_CODE_INST_INSERTVAL: { 4853 // INSERTVAL: [opty, opval, opty, opval, n x indices] 4854 unsigned OpNum = 0; 4855 Value *Agg; 4856 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 4857 return error("Invalid record"); 4858 Value *Val; 4859 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 4860 return error("Invalid record"); 4861 4862 unsigned RecSize = Record.size(); 4863 if (OpNum == RecSize) 4864 return error("INSERTVAL: Invalid instruction with 0 indices"); 4865 4866 SmallVector<unsigned, 4> INSERTVALIdx; 4867 Type *CurTy = Agg->getType(); 4868 for (; OpNum != RecSize; ++OpNum) { 4869 bool IsArray = CurTy->isArrayTy(); 4870 bool IsStruct = CurTy->isStructTy(); 4871 uint64_t Index = Record[OpNum]; 4872 4873 if (!IsStruct && !IsArray) 4874 return error("INSERTVAL: Invalid type"); 4875 if ((unsigned)Index != Index) 4876 return error("Invalid value"); 4877 if (IsStruct && Index >= CurTy->subtypes().size()) 4878 return error("INSERTVAL: Invalid struct index"); 4879 if (IsArray && Index >= CurTy->getArrayNumElements()) 4880 return error("INSERTVAL: Invalid array index"); 4881 4882 INSERTVALIdx.push_back((unsigned)Index); 4883 if (IsStruct) 4884 CurTy = CurTy->subtypes()[Index]; 4885 else 4886 CurTy = CurTy->subtypes()[0]; 4887 } 4888 4889 if (CurTy != Val->getType()) 4890 return error("Inserted value type doesn't match aggregate type"); 4891 4892 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 4893 InstructionList.push_back(I); 4894 break; 4895 } 4896 4897 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 4898 // obsolete form of select 4899 // handles select i1 ... in old bitcode 4900 unsigned OpNum = 0; 4901 Value *TrueVal, *FalseVal, *Cond; 4902 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 4903 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4904 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 4905 return error("Invalid record"); 4906 4907 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4908 InstructionList.push_back(I); 4909 break; 4910 } 4911 4912 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 4913 // new form of select 4914 // handles select i1 or select [N x i1] 4915 unsigned OpNum = 0; 4916 Value *TrueVal, *FalseVal, *Cond; 4917 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 4918 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 4919 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 4920 return error("Invalid record"); 4921 4922 // select condition can be either i1 or [N x i1] 4923 if (VectorType* vector_type = 4924 dyn_cast<VectorType>(Cond->getType())) { 4925 // expect <n x i1> 4926 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 4927 return error("Invalid type for value"); 4928 } else { 4929 // expect i1 4930 if (Cond->getType() != Type::getInt1Ty(Context)) 4931 return error("Invalid type for value"); 4932 } 4933 4934 I = SelectInst::Create(Cond, TrueVal, FalseVal); 4935 InstructionList.push_back(I); 4936 break; 4937 } 4938 4939 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 4940 unsigned OpNum = 0; 4941 Value *Vec, *Idx; 4942 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 4943 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4944 return error("Invalid record"); 4945 if (!Vec->getType()->isVectorTy()) 4946 return error("Invalid type for value"); 4947 I = ExtractElementInst::Create(Vec, Idx); 4948 InstructionList.push_back(I); 4949 break; 4950 } 4951 4952 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 4953 unsigned OpNum = 0; 4954 Value *Vec, *Elt, *Idx; 4955 if (getValueTypePair(Record, OpNum, NextValueNo, Vec)) 4956 return error("Invalid record"); 4957 if (!Vec->getType()->isVectorTy()) 4958 return error("Invalid type for value"); 4959 if (popValue(Record, OpNum, NextValueNo, 4960 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 4961 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 4962 return error("Invalid record"); 4963 I = InsertElementInst::Create(Vec, Elt, Idx); 4964 InstructionList.push_back(I); 4965 break; 4966 } 4967 4968 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 4969 unsigned OpNum = 0; 4970 Value *Vec1, *Vec2, *Mask; 4971 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 4972 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 4973 return error("Invalid record"); 4974 4975 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 4976 return error("Invalid record"); 4977 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy()) 4978 return error("Invalid type for value"); 4979 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 4980 InstructionList.push_back(I); 4981 break; 4982 } 4983 4984 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 4985 // Old form of ICmp/FCmp returning bool 4986 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 4987 // both legal on vectors but had different behaviour. 4988 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 4989 // FCmp/ICmp returning bool or vector of bool 4990 4991 unsigned OpNum = 0; 4992 Value *LHS, *RHS; 4993 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 4994 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS)) 4995 return error("Invalid record"); 4996 4997 unsigned PredVal = Record[OpNum]; 4998 bool IsFP = LHS->getType()->isFPOrFPVectorTy(); 4999 FastMathFlags FMF; 5000 if (IsFP && Record.size() > OpNum+1) 5001 FMF = getDecodedFastMathFlags(Record[++OpNum]); 5002 5003 if (OpNum+1 != Record.size()) 5004 return error("Invalid record"); 5005 5006 if (LHS->getType()->isFPOrFPVectorTy()) 5007 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS); 5008 else 5009 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS); 5010 5011 if (FMF.any()) 5012 I->setFastMathFlags(FMF); 5013 InstructionList.push_back(I); 5014 break; 5015 } 5016 5017 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 5018 { 5019 unsigned Size = Record.size(); 5020 if (Size == 0) { 5021 I = ReturnInst::Create(Context); 5022 InstructionList.push_back(I); 5023 break; 5024 } 5025 5026 unsigned OpNum = 0; 5027 Value *Op = nullptr; 5028 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5029 return error("Invalid record"); 5030 if (OpNum != Record.size()) 5031 return error("Invalid record"); 5032 5033 I = ReturnInst::Create(Context, Op); 5034 InstructionList.push_back(I); 5035 break; 5036 } 5037 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 5038 if (Record.size() != 1 && Record.size() != 3) 5039 return error("Invalid record"); 5040 BasicBlock *TrueDest = getBasicBlock(Record[0]); 5041 if (!TrueDest) 5042 return error("Invalid record"); 5043 5044 if (Record.size() == 1) { 5045 I = BranchInst::Create(TrueDest); 5046 InstructionList.push_back(I); 5047 } 5048 else { 5049 BasicBlock *FalseDest = getBasicBlock(Record[1]); 5050 Value *Cond = getValue(Record, 2, NextValueNo, 5051 Type::getInt1Ty(Context)); 5052 if (!FalseDest || !Cond) 5053 return error("Invalid record"); 5054 I = BranchInst::Create(TrueDest, FalseDest, Cond); 5055 InstructionList.push_back(I); 5056 } 5057 break; 5058 } 5059 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#] 5060 if (Record.size() != 1 && Record.size() != 2) 5061 return error("Invalid record"); 5062 unsigned Idx = 0; 5063 Value *CleanupPad = 5064 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5065 if (!CleanupPad) 5066 return error("Invalid record"); 5067 BasicBlock *UnwindDest = nullptr; 5068 if (Record.size() == 2) { 5069 UnwindDest = getBasicBlock(Record[Idx++]); 5070 if (!UnwindDest) 5071 return error("Invalid record"); 5072 } 5073 5074 I = CleanupReturnInst::Create(CleanupPad, UnwindDest); 5075 InstructionList.push_back(I); 5076 break; 5077 } 5078 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#] 5079 if (Record.size() != 2) 5080 return error("Invalid record"); 5081 unsigned Idx = 0; 5082 Value *CatchPad = 5083 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5084 if (!CatchPad) 5085 return error("Invalid record"); 5086 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5087 if (!BB) 5088 return error("Invalid record"); 5089 5090 I = CatchReturnInst::Create(CatchPad, BB); 5091 InstructionList.push_back(I); 5092 break; 5093 } 5094 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?] 5095 // We must have, at minimum, the outer scope and the number of arguments. 5096 if (Record.size() < 2) 5097 return error("Invalid record"); 5098 5099 unsigned Idx = 0; 5100 5101 Value *ParentPad = 5102 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5103 5104 unsigned NumHandlers = Record[Idx++]; 5105 5106 SmallVector<BasicBlock *, 2> Handlers; 5107 for (unsigned Op = 0; Op != NumHandlers; ++Op) { 5108 BasicBlock *BB = getBasicBlock(Record[Idx++]); 5109 if (!BB) 5110 return error("Invalid record"); 5111 Handlers.push_back(BB); 5112 } 5113 5114 BasicBlock *UnwindDest = nullptr; 5115 if (Idx + 1 == Record.size()) { 5116 UnwindDest = getBasicBlock(Record[Idx++]); 5117 if (!UnwindDest) 5118 return error("Invalid record"); 5119 } 5120 5121 if (Record.size() != Idx) 5122 return error("Invalid record"); 5123 5124 auto *CatchSwitch = 5125 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers); 5126 for (BasicBlock *Handler : Handlers) 5127 CatchSwitch->addHandler(Handler); 5128 I = CatchSwitch; 5129 InstructionList.push_back(I); 5130 break; 5131 } 5132 case bitc::FUNC_CODE_INST_CATCHPAD: 5133 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*] 5134 // We must have, at minimum, the outer scope and the number of arguments. 5135 if (Record.size() < 2) 5136 return error("Invalid record"); 5137 5138 unsigned Idx = 0; 5139 5140 Value *ParentPad = 5141 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context)); 5142 5143 unsigned NumArgOperands = Record[Idx++]; 5144 5145 SmallVector<Value *, 2> Args; 5146 for (unsigned Op = 0; Op != NumArgOperands; ++Op) { 5147 Value *Val; 5148 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 5149 return error("Invalid record"); 5150 Args.push_back(Val); 5151 } 5152 5153 if (Record.size() != Idx) 5154 return error("Invalid record"); 5155 5156 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD) 5157 I = CleanupPadInst::Create(ParentPad, Args); 5158 else 5159 I = CatchPadInst::Create(ParentPad, Args); 5160 InstructionList.push_back(I); 5161 break; 5162 } 5163 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 5164 // Check magic 5165 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 5166 // "New" SwitchInst format with case ranges. The changes to write this 5167 // format were reverted but we still recognize bitcode that uses it. 5168 // Hopefully someday we will have support for case ranges and can use 5169 // this format again. 5170 5171 Type *OpTy = getTypeByID(Record[1]); 5172 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 5173 5174 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 5175 BasicBlock *Default = getBasicBlock(Record[3]); 5176 if (!OpTy || !Cond || !Default) 5177 return error("Invalid record"); 5178 5179 unsigned NumCases = Record[4]; 5180 5181 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5182 InstructionList.push_back(SI); 5183 5184 unsigned CurIdx = 5; 5185 for (unsigned i = 0; i != NumCases; ++i) { 5186 SmallVector<ConstantInt*, 1> CaseVals; 5187 unsigned NumItems = Record[CurIdx++]; 5188 for (unsigned ci = 0; ci != NumItems; ++ci) { 5189 bool isSingleNumber = Record[CurIdx++]; 5190 5191 APInt Low; 5192 unsigned ActiveWords = 1; 5193 if (ValueBitWidth > 64) 5194 ActiveWords = Record[CurIdx++]; 5195 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 5196 ValueBitWidth); 5197 CurIdx += ActiveWords; 5198 5199 if (!isSingleNumber) { 5200 ActiveWords = 1; 5201 if (ValueBitWidth > 64) 5202 ActiveWords = Record[CurIdx++]; 5203 APInt High = readWideAPInt( 5204 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth); 5205 CurIdx += ActiveWords; 5206 5207 // FIXME: It is not clear whether values in the range should be 5208 // compared as signed or unsigned values. The partially 5209 // implemented changes that used this format in the past used 5210 // unsigned comparisons. 5211 for ( ; Low.ule(High); ++Low) 5212 CaseVals.push_back(ConstantInt::get(Context, Low)); 5213 } else 5214 CaseVals.push_back(ConstantInt::get(Context, Low)); 5215 } 5216 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 5217 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 5218 cve = CaseVals.end(); cvi != cve; ++cvi) 5219 SI->addCase(*cvi, DestBB); 5220 } 5221 I = SI; 5222 break; 5223 } 5224 5225 // Old SwitchInst format without case ranges. 5226 5227 if (Record.size() < 3 || (Record.size() & 1) == 0) 5228 return error("Invalid record"); 5229 Type *OpTy = getTypeByID(Record[0]); 5230 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 5231 BasicBlock *Default = getBasicBlock(Record[2]); 5232 if (!OpTy || !Cond || !Default) 5233 return error("Invalid record"); 5234 unsigned NumCases = (Record.size()-3)/2; 5235 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 5236 InstructionList.push_back(SI); 5237 for (unsigned i = 0, e = NumCases; i != e; ++i) { 5238 ConstantInt *CaseVal = 5239 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 5240 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 5241 if (!CaseVal || !DestBB) { 5242 delete SI; 5243 return error("Invalid record"); 5244 } 5245 SI->addCase(CaseVal, DestBB); 5246 } 5247 I = SI; 5248 break; 5249 } 5250 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 5251 if (Record.size() < 2) 5252 return error("Invalid record"); 5253 Type *OpTy = getTypeByID(Record[0]); 5254 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 5255 if (!OpTy || !Address) 5256 return error("Invalid record"); 5257 unsigned NumDests = Record.size()-2; 5258 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 5259 InstructionList.push_back(IBI); 5260 for (unsigned i = 0, e = NumDests; i != e; ++i) { 5261 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 5262 IBI->addDestination(DestBB); 5263 } else { 5264 delete IBI; 5265 return error("Invalid record"); 5266 } 5267 } 5268 I = IBI; 5269 break; 5270 } 5271 5272 case bitc::FUNC_CODE_INST_INVOKE: { 5273 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 5274 if (Record.size() < 4) 5275 return error("Invalid record"); 5276 unsigned OpNum = 0; 5277 AttributeSet PAL = getAttributes(Record[OpNum++]); 5278 unsigned CCInfo = Record[OpNum++]; 5279 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]); 5280 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]); 5281 5282 FunctionType *FTy = nullptr; 5283 if (CCInfo >> 13 & 1 && 5284 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 5285 return error("Explicit invoke type is not a function type"); 5286 5287 Value *Callee; 5288 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 5289 return error("Invalid record"); 5290 5291 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 5292 if (!CalleeTy) 5293 return error("Callee is not a pointer"); 5294 if (!FTy) { 5295 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType()); 5296 if (!FTy) 5297 return error("Callee is not of pointer to function type"); 5298 } else if (CalleeTy->getElementType() != FTy) 5299 return error("Explicit invoke type does not match pointee type of " 5300 "callee operand"); 5301 if (Record.size() < FTy->getNumParams() + OpNum) 5302 return error("Insufficient operands to call"); 5303 5304 SmallVector<Value*, 16> Ops; 5305 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5306 Ops.push_back(getValue(Record, OpNum, NextValueNo, 5307 FTy->getParamType(i))); 5308 if (!Ops.back()) 5309 return error("Invalid record"); 5310 } 5311 5312 if (!FTy->isVarArg()) { 5313 if (Record.size() != OpNum) 5314 return error("Invalid record"); 5315 } else { 5316 // Read type/value pairs for varargs params. 5317 while (OpNum != Record.size()) { 5318 Value *Op; 5319 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5320 return error("Invalid record"); 5321 Ops.push_back(Op); 5322 } 5323 } 5324 5325 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles); 5326 OperandBundles.clear(); 5327 InstructionList.push_back(I); 5328 cast<InvokeInst>(I)->setCallingConv( 5329 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo)); 5330 cast<InvokeInst>(I)->setAttributes(PAL); 5331 break; 5332 } 5333 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 5334 unsigned Idx = 0; 5335 Value *Val = nullptr; 5336 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 5337 return error("Invalid record"); 5338 I = ResumeInst::Create(Val); 5339 InstructionList.push_back(I); 5340 break; 5341 } 5342 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 5343 I = new UnreachableInst(Context); 5344 InstructionList.push_back(I); 5345 break; 5346 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 5347 if (Record.size() < 1 || ((Record.size()-1)&1)) 5348 return error("Invalid record"); 5349 Type *Ty = getTypeByID(Record[0]); 5350 if (!Ty) 5351 return error("Invalid record"); 5352 5353 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 5354 InstructionList.push_back(PN); 5355 5356 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 5357 Value *V; 5358 // With the new function encoding, it is possible that operands have 5359 // negative IDs (for forward references). Use a signed VBR 5360 // representation to keep the encoding small. 5361 if (UseRelativeIDs) 5362 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 5363 else 5364 V = getValue(Record, 1+i, NextValueNo, Ty); 5365 BasicBlock *BB = getBasicBlock(Record[2+i]); 5366 if (!V || !BB) 5367 return error("Invalid record"); 5368 PN->addIncoming(V, BB); 5369 } 5370 I = PN; 5371 break; 5372 } 5373 5374 case bitc::FUNC_CODE_INST_LANDINGPAD: 5375 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: { 5376 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 5377 unsigned Idx = 0; 5378 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) { 5379 if (Record.size() < 3) 5380 return error("Invalid record"); 5381 } else { 5382 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD); 5383 if (Record.size() < 4) 5384 return error("Invalid record"); 5385 } 5386 Type *Ty = getTypeByID(Record[Idx++]); 5387 if (!Ty) 5388 return error("Invalid record"); 5389 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) { 5390 Value *PersFn = nullptr; 5391 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 5392 return error("Invalid record"); 5393 5394 if (!F->hasPersonalityFn()) 5395 F->setPersonalityFn(cast<Constant>(PersFn)); 5396 else if (F->getPersonalityFn() != cast<Constant>(PersFn)) 5397 return error("Personality function mismatch"); 5398 } 5399 5400 bool IsCleanup = !!Record[Idx++]; 5401 unsigned NumClauses = Record[Idx++]; 5402 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses); 5403 LP->setCleanup(IsCleanup); 5404 for (unsigned J = 0; J != NumClauses; ++J) { 5405 LandingPadInst::ClauseType CT = 5406 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 5407 Value *Val; 5408 5409 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 5410 delete LP; 5411 return error("Invalid record"); 5412 } 5413 5414 assert((CT != LandingPadInst::Catch || 5415 !isa<ArrayType>(Val->getType())) && 5416 "Catch clause has a invalid type!"); 5417 assert((CT != LandingPadInst::Filter || 5418 isa<ArrayType>(Val->getType())) && 5419 "Filter clause has invalid type!"); 5420 LP->addClause(cast<Constant>(Val)); 5421 } 5422 5423 I = LP; 5424 InstructionList.push_back(I); 5425 break; 5426 } 5427 5428 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 5429 if (Record.size() != 4) 5430 return error("Invalid record"); 5431 uint64_t AlignRecord = Record[3]; 5432 const uint64_t InAllocaMask = uint64_t(1) << 5; 5433 const uint64_t ExplicitTypeMask = uint64_t(1) << 6; 5434 const uint64_t SwiftErrorMask = uint64_t(1) << 7; 5435 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask | 5436 SwiftErrorMask; 5437 bool InAlloca = AlignRecord & InAllocaMask; 5438 bool SwiftError = AlignRecord & SwiftErrorMask; 5439 Type *Ty = getTypeByID(Record[0]); 5440 if ((AlignRecord & ExplicitTypeMask) == 0) { 5441 auto *PTy = dyn_cast_or_null<PointerType>(Ty); 5442 if (!PTy) 5443 return error("Old-style alloca with a non-pointer type"); 5444 Ty = PTy->getElementType(); 5445 } 5446 Type *OpTy = getTypeByID(Record[1]); 5447 Value *Size = getFnValueByID(Record[2], OpTy); 5448 unsigned Align; 5449 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) { 5450 return Err; 5451 } 5452 if (!Ty || !Size) 5453 return error("Invalid record"); 5454 AllocaInst *AI = new AllocaInst(Ty, Size, Align); 5455 AI->setUsedWithInAlloca(InAlloca); 5456 AI->setSwiftError(SwiftError); 5457 I = AI; 5458 InstructionList.push_back(I); 5459 break; 5460 } 5461 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 5462 unsigned OpNum = 0; 5463 Value *Op; 5464 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 5465 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size())) 5466 return error("Invalid record"); 5467 5468 Type *Ty = nullptr; 5469 if (OpNum + 3 == Record.size()) 5470 Ty = getTypeByID(Record[OpNum++]); 5471 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5472 return Err; 5473 if (!Ty) 5474 Ty = cast<PointerType>(Op->getType())->getElementType(); 5475 5476 unsigned Align; 5477 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5478 return Err; 5479 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align); 5480 5481 InstructionList.push_back(I); 5482 break; 5483 } 5484 case bitc::FUNC_CODE_INST_LOADATOMIC: { 5485 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 5486 unsigned OpNum = 0; 5487 Value *Op; 5488 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 5489 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size())) 5490 return error("Invalid record"); 5491 5492 Type *Ty = nullptr; 5493 if (OpNum + 5 == Record.size()) 5494 Ty = getTypeByID(Record[OpNum++]); 5495 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType())) 5496 return Err; 5497 if (!Ty) 5498 Ty = cast<PointerType>(Op->getType())->getElementType(); 5499 5500 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5501 if (Ordering == AtomicOrdering::NotAtomic || 5502 Ordering == AtomicOrdering::Release || 5503 Ordering == AtomicOrdering::AcquireRelease) 5504 return error("Invalid record"); 5505 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5506 return error("Invalid record"); 5507 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 5508 5509 unsigned Align; 5510 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5511 return Err; 5512 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope); 5513 5514 InstructionList.push_back(I); 5515 break; 5516 } 5517 case bitc::FUNC_CODE_INST_STORE: 5518 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] 5519 unsigned OpNum = 0; 5520 Value *Val, *Ptr; 5521 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5522 (BitCode == bitc::FUNC_CODE_INST_STORE 5523 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5524 : popValue(Record, OpNum, NextValueNo, 5525 cast<PointerType>(Ptr->getType())->getElementType(), 5526 Val)) || 5527 OpNum + 2 != Record.size()) 5528 return error("Invalid record"); 5529 5530 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5531 return Err; 5532 unsigned Align; 5533 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5534 return Err; 5535 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); 5536 InstructionList.push_back(I); 5537 break; 5538 } 5539 case bitc::FUNC_CODE_INST_STOREATOMIC: 5540 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: { 5541 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 5542 unsigned OpNum = 0; 5543 Value *Val, *Ptr; 5544 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5545 !isa<PointerType>(Ptr->getType()) || 5546 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC 5547 ? getValueTypePair(Record, OpNum, NextValueNo, Val) 5548 : popValue(Record, OpNum, NextValueNo, 5549 cast<PointerType>(Ptr->getType())->getElementType(), 5550 Val)) || 5551 OpNum + 4 != Record.size()) 5552 return error("Invalid record"); 5553 5554 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType())) 5555 return Err; 5556 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5557 if (Ordering == AtomicOrdering::NotAtomic || 5558 Ordering == AtomicOrdering::Acquire || 5559 Ordering == AtomicOrdering::AcquireRelease) 5560 return error("Invalid record"); 5561 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 5562 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0) 5563 return error("Invalid record"); 5564 5565 unsigned Align; 5566 if (Error Err = parseAlignmentValue(Record[OpNum], Align)) 5567 return Err; 5568 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope); 5569 InstructionList.push_back(I); 5570 break; 5571 } 5572 case bitc::FUNC_CODE_INST_CMPXCHG_OLD: 5573 case bitc::FUNC_CODE_INST_CMPXCHG: { 5574 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 5575 // failureordering?, isweak?] 5576 unsigned OpNum = 0; 5577 Value *Ptr, *Cmp, *New; 5578 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5579 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG 5580 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp) 5581 : popValue(Record, OpNum, NextValueNo, 5582 cast<PointerType>(Ptr->getType())->getElementType(), 5583 Cmp)) || 5584 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) || 5585 Record.size() < OpNum + 3 || Record.size() > OpNum + 5) 5586 return error("Invalid record"); 5587 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]); 5588 if (SuccessOrdering == AtomicOrdering::NotAtomic || 5589 SuccessOrdering == AtomicOrdering::Unordered) 5590 return error("Invalid record"); 5591 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]); 5592 5593 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType())) 5594 return Err; 5595 AtomicOrdering FailureOrdering; 5596 if (Record.size() < 7) 5597 FailureOrdering = 5598 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 5599 else 5600 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]); 5601 5602 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 5603 SynchScope); 5604 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 5605 5606 if (Record.size() < 8) { 5607 // Before weak cmpxchgs existed, the instruction simply returned the 5608 // value loaded from memory, so bitcode files from that era will be 5609 // expecting the first component of a modern cmpxchg. 5610 CurBB->getInstList().push_back(I); 5611 I = ExtractValueInst::Create(I, 0); 5612 } else { 5613 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 5614 } 5615 5616 InstructionList.push_back(I); 5617 break; 5618 } 5619 case bitc::FUNC_CODE_INST_ATOMICRMW: { 5620 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 5621 unsigned OpNum = 0; 5622 Value *Ptr, *Val; 5623 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 5624 !isa<PointerType>(Ptr->getType()) || 5625 popValue(Record, OpNum, NextValueNo, 5626 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 5627 OpNum+4 != Record.size()) 5628 return error("Invalid record"); 5629 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); 5630 if (Operation < AtomicRMWInst::FIRST_BINOP || 5631 Operation > AtomicRMWInst::LAST_BINOP) 5632 return error("Invalid record"); 5633 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]); 5634 if (Ordering == AtomicOrdering::NotAtomic || 5635 Ordering == AtomicOrdering::Unordered) 5636 return error("Invalid record"); 5637 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]); 5638 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 5639 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 5640 InstructionList.push_back(I); 5641 break; 5642 } 5643 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 5644 if (2 != Record.size()) 5645 return error("Invalid record"); 5646 AtomicOrdering Ordering = getDecodedOrdering(Record[0]); 5647 if (Ordering == AtomicOrdering::NotAtomic || 5648 Ordering == AtomicOrdering::Unordered || 5649 Ordering == AtomicOrdering::Monotonic) 5650 return error("Invalid record"); 5651 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]); 5652 I = new FenceInst(Context, Ordering, SynchScope); 5653 InstructionList.push_back(I); 5654 break; 5655 } 5656 case bitc::FUNC_CODE_INST_CALL: { 5657 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...] 5658 if (Record.size() < 3) 5659 return error("Invalid record"); 5660 5661 unsigned OpNum = 0; 5662 AttributeSet PAL = getAttributes(Record[OpNum++]); 5663 unsigned CCInfo = Record[OpNum++]; 5664 5665 FastMathFlags FMF; 5666 if ((CCInfo >> bitc::CALL_FMF) & 1) { 5667 FMF = getDecodedFastMathFlags(Record[OpNum++]); 5668 if (!FMF.any()) 5669 return error("Fast math flags indicator set for call with no FMF"); 5670 } 5671 5672 FunctionType *FTy = nullptr; 5673 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 && 5674 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++])))) 5675 return error("Explicit call type is not a function type"); 5676 5677 Value *Callee; 5678 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 5679 return error("Invalid record"); 5680 5681 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 5682 if (!OpTy) 5683 return error("Callee is not a pointer type"); 5684 if (!FTy) { 5685 FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 5686 if (!FTy) 5687 return error("Callee is not of pointer to function type"); 5688 } else if (OpTy->getElementType() != FTy) 5689 return error("Explicit call type does not match pointee type of " 5690 "callee operand"); 5691 if (Record.size() < FTy->getNumParams() + OpNum) 5692 return error("Insufficient operands to call"); 5693 5694 SmallVector<Value*, 16> Args; 5695 // Read the fixed params. 5696 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 5697 if (FTy->getParamType(i)->isLabelTy()) 5698 Args.push_back(getBasicBlock(Record[OpNum])); 5699 else 5700 Args.push_back(getValue(Record, OpNum, NextValueNo, 5701 FTy->getParamType(i))); 5702 if (!Args.back()) 5703 return error("Invalid record"); 5704 } 5705 5706 // Read type/value pairs for varargs params. 5707 if (!FTy->isVarArg()) { 5708 if (OpNum != Record.size()) 5709 return error("Invalid record"); 5710 } else { 5711 while (OpNum != Record.size()) { 5712 Value *Op; 5713 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5714 return error("Invalid record"); 5715 Args.push_back(Op); 5716 } 5717 } 5718 5719 I = CallInst::Create(FTy, Callee, Args, OperandBundles); 5720 OperandBundles.clear(); 5721 InstructionList.push_back(I); 5722 cast<CallInst>(I)->setCallingConv( 5723 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV)); 5724 CallInst::TailCallKind TCK = CallInst::TCK_None; 5725 if (CCInfo & 1 << bitc::CALL_TAIL) 5726 TCK = CallInst::TCK_Tail; 5727 if (CCInfo & (1 << bitc::CALL_MUSTTAIL)) 5728 TCK = CallInst::TCK_MustTail; 5729 if (CCInfo & (1 << bitc::CALL_NOTAIL)) 5730 TCK = CallInst::TCK_NoTail; 5731 cast<CallInst>(I)->setTailCallKind(TCK); 5732 cast<CallInst>(I)->setAttributes(PAL); 5733 if (FMF.any()) { 5734 if (!isa<FPMathOperator>(I)) 5735 return error("Fast-math-flags specified for call without " 5736 "floating-point scalar or vector return type"); 5737 I->setFastMathFlags(FMF); 5738 } 5739 break; 5740 } 5741 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 5742 if (Record.size() < 3) 5743 return error("Invalid record"); 5744 Type *OpTy = getTypeByID(Record[0]); 5745 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 5746 Type *ResTy = getTypeByID(Record[2]); 5747 if (!OpTy || !Op || !ResTy) 5748 return error("Invalid record"); 5749 I = new VAArgInst(Op, ResTy); 5750 InstructionList.push_back(I); 5751 break; 5752 } 5753 5754 case bitc::FUNC_CODE_OPERAND_BUNDLE: { 5755 // A call or an invoke can be optionally prefixed with some variable 5756 // number of operand bundle blocks. These blocks are read into 5757 // OperandBundles and consumed at the next call or invoke instruction. 5758 5759 if (Record.size() < 1 || Record[0] >= BundleTags.size()) 5760 return error("Invalid record"); 5761 5762 std::vector<Value *> Inputs; 5763 5764 unsigned OpNum = 1; 5765 while (OpNum != Record.size()) { 5766 Value *Op; 5767 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 5768 return error("Invalid record"); 5769 Inputs.push_back(Op); 5770 } 5771 5772 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs)); 5773 continue; 5774 } 5775 } 5776 5777 // Add instruction to end of current BB. If there is no current BB, reject 5778 // this file. 5779 if (!CurBB) { 5780 delete I; 5781 return error("Invalid instruction with no BB"); 5782 } 5783 if (!OperandBundles.empty()) { 5784 delete I; 5785 return error("Operand bundles found with no consumer"); 5786 } 5787 CurBB->getInstList().push_back(I); 5788 5789 // If this was a terminator instruction, move to the next block. 5790 if (isa<TerminatorInst>(I)) { 5791 ++CurBBNo; 5792 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 5793 } 5794 5795 // Non-void values get registered in the value table for future use. 5796 if (I && !I->getType()->isVoidTy()) 5797 ValueList.assignValue(I, NextValueNo++); 5798 } 5799 5800 OutOfRecordLoop: 5801 5802 if (!OperandBundles.empty()) 5803 return error("Operand bundles found with no consumer"); 5804 5805 // Check the function list for unresolved values. 5806 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 5807 if (!A->getParent()) { 5808 // We found at least one unresolved value. Nuke them all to avoid leaks. 5809 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 5810 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 5811 A->replaceAllUsesWith(UndefValue::get(A->getType())); 5812 delete A; 5813 } 5814 } 5815 return error("Never resolved value found in function"); 5816 } 5817 } 5818 5819 // Unexpected unresolved metadata about to be dropped. 5820 if (MetadataList.hasFwdRefs()) 5821 return error("Invalid function metadata: outgoing forward refs"); 5822 5823 // Trim the value list down to the size it was before we parsed this function. 5824 ValueList.shrinkTo(ModuleValueListSize); 5825 MetadataList.shrinkTo(ModuleMetadataListSize); 5826 std::vector<BasicBlock*>().swap(FunctionBBs); 5827 return Error::success(); 5828 } 5829 5830 /// Find the function body in the bitcode stream 5831 Error BitcodeReader::findFunctionInStream( 5832 Function *F, 5833 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 5834 while (DeferredFunctionInfoIterator->second == 0) { 5835 // This is the fallback handling for the old format bitcode that 5836 // didn't contain the function index in the VST, or when we have 5837 // an anonymous function which would not have a VST entry. 5838 // Assert that we have one of those two cases. 5839 assert(VSTOffset == 0 || !F->hasName()); 5840 // Parse the next body in the stream and set its position in the 5841 // DeferredFunctionInfo map. 5842 if (Error Err = rememberAndSkipFunctionBodies()) 5843 return Err; 5844 } 5845 return Error::success(); 5846 } 5847 5848 //===----------------------------------------------------------------------===// 5849 // GVMaterializer implementation 5850 //===----------------------------------------------------------------------===// 5851 5852 Error BitcodeReader::materialize(GlobalValue *GV) { 5853 Function *F = dyn_cast<Function>(GV); 5854 // If it's not a function or is already material, ignore the request. 5855 if (!F || !F->isMaterializable()) 5856 return Error::success(); 5857 5858 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 5859 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 5860 // If its position is recorded as 0, its body is somewhere in the stream 5861 // but we haven't seen it yet. 5862 if (DFII->second == 0) 5863 if (Error Err = findFunctionInStream(F, DFII)) 5864 return Err; 5865 5866 // Materialize metadata before parsing any function bodies. 5867 if (Error Err = materializeMetadata()) 5868 return Err; 5869 5870 // Move the bit stream to the saved position of the deferred function body. 5871 Stream.JumpToBit(DFII->second); 5872 5873 if (Error Err = parseFunctionBody(F)) 5874 return Err; 5875 F->setIsMaterializable(false); 5876 5877 if (StripDebugInfo) 5878 stripDebugInfo(*F); 5879 5880 // Upgrade any old intrinsic calls in the function. 5881 for (auto &I : UpgradedIntrinsics) { 5882 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5883 UI != UE;) { 5884 User *U = *UI; 5885 ++UI; 5886 if (CallInst *CI = dyn_cast<CallInst>(U)) 5887 UpgradeIntrinsicCall(CI, I.second); 5888 } 5889 } 5890 5891 // Update calls to the remangled intrinsics 5892 for (auto &I : RemangledIntrinsics) 5893 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end(); 5894 UI != UE;) 5895 // Don't expect any other users than call sites 5896 CallSite(*UI++).setCalledFunction(I.second); 5897 5898 // Finish fn->subprogram upgrade for materialized functions. 5899 if (DISubprogram *SP = FunctionsWithSPs.lookup(F)) 5900 F->setSubprogram(SP); 5901 5902 // Bring in any functions that this function forward-referenced via 5903 // blockaddresses. 5904 return materializeForwardReferencedFunctions(); 5905 } 5906 5907 Error BitcodeReader::materializeModule() { 5908 if (Error Err = materializeMetadata()) 5909 return Err; 5910 5911 // Promise to materialize all forward references. 5912 WillMaterializeAllForwardRefs = true; 5913 5914 // Iterate over the module, deserializing any functions that are still on 5915 // disk. 5916 for (Function &F : *TheModule) { 5917 if (Error Err = materialize(&F)) 5918 return Err; 5919 } 5920 // At this point, if there are any function bodies, parse the rest of 5921 // the bits in the module past the last function block we have recorded 5922 // through either lazy scanning or the VST. 5923 if (LastFunctionBlockBit || NextUnreadBit) 5924 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit 5925 ? LastFunctionBlockBit 5926 : NextUnreadBit)) 5927 return Err; 5928 5929 // Check that all block address forward references got resolved (as we 5930 // promised above). 5931 if (!BasicBlockFwdRefs.empty()) 5932 return error("Never resolved function from blockaddress"); 5933 5934 // Upgrade any intrinsic calls that slipped through (should not happen!) and 5935 // delete the old functions to clean up. We can't do this unless the entire 5936 // module is materialized because there could always be another function body 5937 // with calls to the old function. 5938 for (auto &I : UpgradedIntrinsics) { 5939 for (auto *U : I.first->users()) { 5940 if (CallInst *CI = dyn_cast<CallInst>(U)) 5941 UpgradeIntrinsicCall(CI, I.second); 5942 } 5943 if (!I.first->use_empty()) 5944 I.first->replaceAllUsesWith(I.second); 5945 I.first->eraseFromParent(); 5946 } 5947 UpgradedIntrinsics.clear(); 5948 // Do the same for remangled intrinsics 5949 for (auto &I : RemangledIntrinsics) { 5950 I.first->replaceAllUsesWith(I.second); 5951 I.first->eraseFromParent(); 5952 } 5953 RemangledIntrinsics.clear(); 5954 5955 UpgradeDebugInfo(*TheModule); 5956 5957 UpgradeModuleFlags(*TheModule); 5958 return Error::success(); 5959 } 5960 5961 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 5962 return IdentifiedStructTypes; 5963 } 5964 5965 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader( 5966 MemoryBufferRef Buffer, bool CheckGlobalValSummaryPresenceOnly) 5967 : BitcodeReaderBase(Buffer), 5968 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {} 5969 5970 std::pair<GlobalValue::GUID, GlobalValue::GUID> 5971 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) { 5972 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId); 5973 assert(VGI != ValueIdToCallGraphGUIDMap.end()); 5974 return VGI->second; 5975 } 5976 5977 // Specialized value symbol table parser used when reading module index 5978 // blocks where we don't actually create global values. The parsed information 5979 // is saved in the bitcode reader for use when later parsing summaries. 5980 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable( 5981 uint64_t Offset, 5982 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) { 5983 assert(Offset > 0 && "Expected non-zero VST offset"); 5984 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream); 5985 5986 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 5987 return error("Invalid record"); 5988 5989 SmallVector<uint64_t, 64> Record; 5990 5991 // Read all the records for this value table. 5992 SmallString<128> ValueName; 5993 5994 while (true) { 5995 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 5996 5997 switch (Entry.Kind) { 5998 case BitstreamEntry::SubBlock: // Handled for us already. 5999 case BitstreamEntry::Error: 6000 return error("Malformed block"); 6001 case BitstreamEntry::EndBlock: 6002 // Done parsing VST, jump back to wherever we came from. 6003 Stream.JumpToBit(CurrentBit); 6004 return Error::success(); 6005 case BitstreamEntry::Record: 6006 // The interesting case. 6007 break; 6008 } 6009 6010 // Read a record. 6011 Record.clear(); 6012 switch (Stream.readRecord(Entry.ID, Record)) { 6013 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records). 6014 break; 6015 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] 6016 if (convertToString(Record, 1, ValueName)) 6017 return error("Invalid record"); 6018 unsigned ValueID = Record[0]; 6019 assert(!SourceFileName.empty()); 6020 auto VLI = ValueIdToLinkageMap.find(ValueID); 6021 assert(VLI != ValueIdToLinkageMap.end() && 6022 "No linkage found for VST entry?"); 6023 auto Linkage = VLI->second; 6024 std::string GlobalId = 6025 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName); 6026 auto ValueGUID = GlobalValue::getGUID(GlobalId); 6027 auto OriginalNameID = ValueGUID; 6028 if (GlobalValue::isLocalLinkage(Linkage)) 6029 OriginalNameID = GlobalValue::getGUID(ValueName); 6030 if (PrintSummaryGUIDs) 6031 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is " 6032 << ValueName << "\n"; 6033 ValueIdToCallGraphGUIDMap[ValueID] = 6034 std::make_pair(ValueGUID, OriginalNameID); 6035 ValueName.clear(); 6036 break; 6037 } 6038 case bitc::VST_CODE_FNENTRY: { 6039 // VST_CODE_FNENTRY: [valueid, offset, namechar x N] 6040 if (convertToString(Record, 2, ValueName)) 6041 return error("Invalid record"); 6042 unsigned ValueID = Record[0]; 6043 assert(!SourceFileName.empty()); 6044 auto VLI = ValueIdToLinkageMap.find(ValueID); 6045 assert(VLI != ValueIdToLinkageMap.end() && 6046 "No linkage found for VST entry?"); 6047 auto Linkage = VLI->second; 6048 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier( 6049 ValueName, VLI->second, SourceFileName); 6050 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId); 6051 auto OriginalNameID = FunctionGUID; 6052 if (GlobalValue::isLocalLinkage(Linkage)) 6053 OriginalNameID = GlobalValue::getGUID(ValueName); 6054 if (PrintSummaryGUIDs) 6055 dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is " 6056 << ValueName << "\n"; 6057 ValueIdToCallGraphGUIDMap[ValueID] = 6058 std::make_pair(FunctionGUID, OriginalNameID); 6059 6060 ValueName.clear(); 6061 break; 6062 } 6063 case bitc::VST_CODE_COMBINED_ENTRY: { 6064 // VST_CODE_COMBINED_ENTRY: [valueid, refguid] 6065 unsigned ValueID = Record[0]; 6066 GlobalValue::GUID RefGUID = Record[1]; 6067 // The "original name", which is the second value of the pair will be 6068 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index. 6069 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID); 6070 break; 6071 } 6072 } 6073 } 6074 } 6075 6076 // Parse just the blocks needed for building the index out of the module. 6077 // At the end of this routine the module Index is populated with a map 6078 // from global value id to GlobalValueSummary objects. 6079 Error ModuleSummaryIndexBitcodeReader::parseModule() { 6080 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 6081 return error("Invalid record"); 6082 6083 SmallVector<uint64_t, 64> Record; 6084 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap; 6085 unsigned ValueId = 0; 6086 6087 // Read the index for this module. 6088 while (true) { 6089 BitstreamEntry Entry = Stream.advance(); 6090 6091 switch (Entry.Kind) { 6092 case BitstreamEntry::Error: 6093 return error("Malformed block"); 6094 case BitstreamEntry::EndBlock: 6095 return Error::success(); 6096 6097 case BitstreamEntry::SubBlock: 6098 if (CheckGlobalValSummaryPresenceOnly) { 6099 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) { 6100 SeenGlobalValSummary = true; 6101 // No need to parse the rest since we found the summary. 6102 return Error::success(); 6103 } 6104 if (Stream.SkipBlock()) 6105 return error("Invalid record"); 6106 continue; 6107 } 6108 switch (Entry.ID) { 6109 default: // Skip unknown content. 6110 if (Stream.SkipBlock()) 6111 return error("Invalid record"); 6112 break; 6113 case bitc::BLOCKINFO_BLOCK_ID: 6114 // Need to parse these to get abbrev ids (e.g. for VST) 6115 if (readBlockInfo()) 6116 return error("Malformed block"); 6117 break; 6118 case bitc::VALUE_SYMTAB_BLOCK_ID: 6119 // Should have been parsed earlier via VSTOffset, unless there 6120 // is no summary section. 6121 assert(((SeenValueSymbolTable && VSTOffset > 0) || 6122 !SeenGlobalValSummary) && 6123 "Expected early VST parse via VSTOffset record"); 6124 if (Stream.SkipBlock()) 6125 return error("Invalid record"); 6126 break; 6127 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID: 6128 assert(!SeenValueSymbolTable && 6129 "Already read VST when parsing summary block?"); 6130 // We might not have a VST if there were no values in the 6131 // summary. An empty summary block generated when we are 6132 // performing ThinLTO compiles so we don't later invoke 6133 // the regular LTO process on them. 6134 if (VSTOffset > 0) { 6135 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap)) 6136 return Err; 6137 SeenValueSymbolTable = true; 6138 } 6139 SeenGlobalValSummary = true; 6140 if (Error Err = parseEntireSummary()) 6141 return Err; 6142 break; 6143 case bitc::MODULE_STRTAB_BLOCK_ID: 6144 if (Error Err = parseModuleStringTable()) 6145 return Err; 6146 break; 6147 } 6148 continue; 6149 6150 case BitstreamEntry::Record: { 6151 Record.clear(); 6152 auto BitCode = Stream.readRecord(Entry.ID, Record); 6153 switch (BitCode) { 6154 default: 6155 break; // Default behavior, ignore unknown content. 6156 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] 6157 case bitc::MODULE_CODE_SOURCE_FILENAME: { 6158 SmallString<128> ValueName; 6159 if (convertToString(Record, 0, ValueName)) 6160 return error("Invalid record"); 6161 SourceFileName = ValueName.c_str(); 6162 break; 6163 } 6164 /// MODULE_CODE_HASH: [5*i32] 6165 case bitc::MODULE_CODE_HASH: { 6166 if (Record.size() != 5) 6167 return error("Invalid hash length " + Twine(Record.size()).str()); 6168 if (!TheIndex) 6169 break; 6170 if (TheIndex->modulePaths().empty()) 6171 // We always seed the index with the module. 6172 TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0); 6173 if (TheIndex->modulePaths().size() != 1) 6174 return error("Don't expect multiple modules defined?"); 6175 auto &Hash = TheIndex->modulePaths().begin()->second.second; 6176 int Pos = 0; 6177 for (auto &Val : Record) { 6178 assert(!(Val >> 32) && "Unexpected high bits set"); 6179 Hash[Pos++] = Val; 6180 } 6181 break; 6182 } 6183 /// MODULE_CODE_VSTOFFSET: [offset] 6184 case bitc::MODULE_CODE_VSTOFFSET: 6185 if (Record.size() < 1) 6186 return error("Invalid record"); 6187 VSTOffset = Record[0]; 6188 break; 6189 // GLOBALVAR: [pointer type, isconst, initid, 6190 // linkage, alignment, section, visibility, threadlocal, 6191 // unnamed_addr, externally_initialized, dllstorageclass, 6192 // comdat] 6193 case bitc::MODULE_CODE_GLOBALVAR: { 6194 if (Record.size() < 6) 6195 return error("Invalid record"); 6196 uint64_t RawLinkage = Record[3]; 6197 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6198 ValueIdToLinkageMap[ValueId++] = Linkage; 6199 break; 6200 } 6201 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 6202 // alignment, section, visibility, gc, unnamed_addr, 6203 // prologuedata, dllstorageclass, comdat, prefixdata] 6204 case bitc::MODULE_CODE_FUNCTION: { 6205 if (Record.size() < 8) 6206 return error("Invalid record"); 6207 uint64_t RawLinkage = Record[3]; 6208 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6209 ValueIdToLinkageMap[ValueId++] = Linkage; 6210 break; 6211 } 6212 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, 6213 // dllstorageclass] 6214 case bitc::MODULE_CODE_ALIAS: { 6215 if (Record.size() < 6) 6216 return error("Invalid record"); 6217 uint64_t RawLinkage = Record[3]; 6218 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 6219 ValueIdToLinkageMap[ValueId++] = Linkage; 6220 break; 6221 } 6222 } 6223 } 6224 continue; 6225 } 6226 } 6227 } 6228 6229 // Eagerly parse the entire summary block. This populates the GlobalValueSummary 6230 // objects in the index. 6231 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary() { 6232 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID)) 6233 return error("Invalid record"); 6234 SmallVector<uint64_t, 64> Record; 6235 6236 // Parse version 6237 { 6238 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 6239 if (Entry.Kind != BitstreamEntry::Record) 6240 return error("Invalid Summary Block: record for version expected"); 6241 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION) 6242 return error("Invalid Summary Block: version expected"); 6243 } 6244 const uint64_t Version = Record[0]; 6245 const bool IsOldProfileFormat = Version == 1; 6246 if (!IsOldProfileFormat && Version != 2) 6247 return error("Invalid summary version " + Twine(Version) + 6248 ", 1 or 2 expected"); 6249 Record.clear(); 6250 6251 // Keep around the last seen summary to be used when we see an optional 6252 // "OriginalName" attachement. 6253 GlobalValueSummary *LastSeenSummary = nullptr; 6254 bool Combined = false; 6255 6256 while (true) { 6257 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 6258 6259 switch (Entry.Kind) { 6260 case BitstreamEntry::SubBlock: // Handled for us already. 6261 case BitstreamEntry::Error: 6262 return error("Malformed block"); 6263 case BitstreamEntry::EndBlock: 6264 // For a per-module index, remove any entries that still have empty 6265 // summaries. The VST parsing creates entries eagerly for all symbols, 6266 // but not all have associated summaries (e.g. it doesn't know how to 6267 // distinguish between VST_CODE_ENTRY for function declarations vs global 6268 // variables with initializers that end up with a summary). Remove those 6269 // entries now so that we don't need to rely on the combined index merger 6270 // to clean them up (especially since that may not run for the first 6271 // module's index if we merge into that). 6272 if (!Combined) 6273 TheIndex->removeEmptySummaryEntries(); 6274 return Error::success(); 6275 case BitstreamEntry::Record: 6276 // The interesting case. 6277 break; 6278 } 6279 6280 // Read a record. The record format depends on whether this 6281 // is a per-module index or a combined index file. In the per-module 6282 // case the records contain the associated value's ID for correlation 6283 // with VST entries. In the combined index the correlation is done 6284 // via the bitcode offset of the summary records (which were saved 6285 // in the combined index VST entries). The records also contain 6286 // information used for ThinLTO renaming and importing. 6287 Record.clear(); 6288 auto BitCode = Stream.readRecord(Entry.ID, Record); 6289 switch (BitCode) { 6290 default: // Default behavior: ignore. 6291 break; 6292 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid, 6293 // n x (valueid)] 6294 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs, 6295 // numrefs x valueid, 6296 // n x (valueid, hotness)] 6297 case bitc::FS_PERMODULE: 6298 case bitc::FS_PERMODULE_PROFILE: { 6299 unsigned ValueID = Record[0]; 6300 uint64_t RawFlags = Record[1]; 6301 unsigned InstCount = Record[2]; 6302 unsigned NumRefs = Record[3]; 6303 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6304 std::unique_ptr<FunctionSummary> FS = 6305 llvm::make_unique<FunctionSummary>(Flags, InstCount); 6306 // The module path string ref set in the summary must be owned by the 6307 // index's module string table. Since we don't have a module path 6308 // string table section in the per-module index, we create a single 6309 // module path string table entry with an empty (0) ID to take 6310 // ownership. 6311 FS->setModulePath( 6312 TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0)->first()); 6313 static int RefListStartIndex = 4; 6314 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6315 assert(Record.size() >= RefListStartIndex + NumRefs && 6316 "Record size inconsistent with number of references"); 6317 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) { 6318 unsigned RefValueId = Record[I]; 6319 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6320 FS->addRefEdge(RefGUID); 6321 } 6322 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE); 6323 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E; 6324 ++I) { 6325 CalleeInfo::HotnessType Hotness; 6326 GlobalValue::GUID CalleeGUID; 6327 std::tie(CalleeGUID, Hotness) = 6328 readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile); 6329 FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness)); 6330 } 6331 auto GUID = getGUIDFromValueId(ValueID); 6332 FS->setOriginalName(GUID.second); 6333 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS)); 6334 break; 6335 } 6336 // FS_ALIAS: [valueid, flags, valueid] 6337 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as 6338 // they expect all aliasee summaries to be available. 6339 case bitc::FS_ALIAS: { 6340 unsigned ValueID = Record[0]; 6341 uint64_t RawFlags = Record[1]; 6342 unsigned AliaseeID = Record[2]; 6343 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6344 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags); 6345 // The module path string ref set in the summary must be owned by the 6346 // index's module string table. Since we don't have a module path 6347 // string table section in the per-module index, we create a single 6348 // module path string table entry with an empty (0) ID to take 6349 // ownership. 6350 AS->setModulePath( 6351 TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0)->first()); 6352 6353 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first; 6354 auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID); 6355 if (!AliaseeSummary) 6356 return error("Alias expects aliasee summary to be parsed"); 6357 AS->setAliasee(AliaseeSummary); 6358 6359 auto GUID = getGUIDFromValueId(ValueID); 6360 AS->setOriginalName(GUID.second); 6361 TheIndex->addGlobalValueSummary(GUID.first, std::move(AS)); 6362 break; 6363 } 6364 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid] 6365 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: { 6366 unsigned ValueID = Record[0]; 6367 uint64_t RawFlags = Record[1]; 6368 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6369 std::unique_ptr<GlobalVarSummary> FS = 6370 llvm::make_unique<GlobalVarSummary>(Flags); 6371 FS->setModulePath( 6372 TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0)->first()); 6373 for (unsigned I = 2, E = Record.size(); I != E; ++I) { 6374 unsigned RefValueId = Record[I]; 6375 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6376 FS->addRefEdge(RefGUID); 6377 } 6378 auto GUID = getGUIDFromValueId(ValueID); 6379 FS->setOriginalName(GUID.second); 6380 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS)); 6381 break; 6382 } 6383 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs, 6384 // numrefs x valueid, n x (valueid)] 6385 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs, 6386 // numrefs x valueid, n x (valueid, hotness)] 6387 case bitc::FS_COMBINED: 6388 case bitc::FS_COMBINED_PROFILE: { 6389 unsigned ValueID = Record[0]; 6390 uint64_t ModuleId = Record[1]; 6391 uint64_t RawFlags = Record[2]; 6392 unsigned InstCount = Record[3]; 6393 unsigned NumRefs = Record[4]; 6394 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6395 std::unique_ptr<FunctionSummary> FS = 6396 llvm::make_unique<FunctionSummary>(Flags, InstCount); 6397 LastSeenSummary = FS.get(); 6398 FS->setModulePath(ModuleIdMap[ModuleId]); 6399 static int RefListStartIndex = 5; 6400 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs; 6401 assert(Record.size() >= RefListStartIndex + NumRefs && 6402 "Record size inconsistent with number of references"); 6403 for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E; 6404 ++I) { 6405 unsigned RefValueId = Record[I]; 6406 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6407 FS->addRefEdge(RefGUID); 6408 } 6409 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE); 6410 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E; 6411 ++I) { 6412 CalleeInfo::HotnessType Hotness; 6413 GlobalValue::GUID CalleeGUID; 6414 std::tie(CalleeGUID, Hotness) = 6415 readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile); 6416 FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness)); 6417 } 6418 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first; 6419 TheIndex->addGlobalValueSummary(GUID, std::move(FS)); 6420 Combined = true; 6421 break; 6422 } 6423 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid] 6424 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as 6425 // they expect all aliasee summaries to be available. 6426 case bitc::FS_COMBINED_ALIAS: { 6427 unsigned ValueID = Record[0]; 6428 uint64_t ModuleId = Record[1]; 6429 uint64_t RawFlags = Record[2]; 6430 unsigned AliaseeValueId = Record[3]; 6431 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6432 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags); 6433 LastSeenSummary = AS.get(); 6434 AS->setModulePath(ModuleIdMap[ModuleId]); 6435 6436 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first; 6437 auto AliaseeInModule = 6438 TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath()); 6439 if (!AliaseeInModule) 6440 return error("Alias expects aliasee summary to be parsed"); 6441 AS->setAliasee(AliaseeInModule); 6442 6443 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first; 6444 TheIndex->addGlobalValueSummary(GUID, std::move(AS)); 6445 Combined = true; 6446 break; 6447 } 6448 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid] 6449 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: { 6450 unsigned ValueID = Record[0]; 6451 uint64_t ModuleId = Record[1]; 6452 uint64_t RawFlags = Record[2]; 6453 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version); 6454 std::unique_ptr<GlobalVarSummary> FS = 6455 llvm::make_unique<GlobalVarSummary>(Flags); 6456 LastSeenSummary = FS.get(); 6457 FS->setModulePath(ModuleIdMap[ModuleId]); 6458 for (unsigned I = 3, E = Record.size(); I != E; ++I) { 6459 unsigned RefValueId = Record[I]; 6460 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first; 6461 FS->addRefEdge(RefGUID); 6462 } 6463 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first; 6464 TheIndex->addGlobalValueSummary(GUID, std::move(FS)); 6465 Combined = true; 6466 break; 6467 } 6468 // FS_COMBINED_ORIGINAL_NAME: [original_name] 6469 case bitc::FS_COMBINED_ORIGINAL_NAME: { 6470 uint64_t OriginalName = Record[0]; 6471 if (!LastSeenSummary) 6472 return error("Name attachment that does not follow a combined record"); 6473 LastSeenSummary->setOriginalName(OriginalName); 6474 // Reset the LastSeenSummary 6475 LastSeenSummary = nullptr; 6476 } 6477 } 6478 } 6479 llvm_unreachable("Exit infinite loop"); 6480 } 6481 6482 std::pair<GlobalValue::GUID, CalleeInfo::HotnessType> 6483 ModuleSummaryIndexBitcodeReader::readCallGraphEdge( 6484 const SmallVector<uint64_t, 64> &Record, unsigned int &I, 6485 const bool IsOldProfileFormat, const bool HasProfile) { 6486 6487 auto Hotness = CalleeInfo::HotnessType::Unknown; 6488 unsigned CalleeValueId = Record[I]; 6489 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first; 6490 if (IsOldProfileFormat) { 6491 I += 1; // Skip old callsitecount field 6492 if (HasProfile) 6493 I += 1; // Skip old profilecount field 6494 } else if (HasProfile) 6495 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]); 6496 return {CalleeGUID, Hotness}; 6497 } 6498 6499 // Parse the module string table block into the Index. 6500 // This populates the ModulePathStringTable map in the index. 6501 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() { 6502 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID)) 6503 return error("Invalid record"); 6504 6505 SmallVector<uint64_t, 64> Record; 6506 6507 SmallString<128> ModulePath; 6508 ModulePathStringTableTy::iterator LastSeenModulePath; 6509 6510 while (true) { 6511 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 6512 6513 switch (Entry.Kind) { 6514 case BitstreamEntry::SubBlock: // Handled for us already. 6515 case BitstreamEntry::Error: 6516 return error("Malformed block"); 6517 case BitstreamEntry::EndBlock: 6518 return Error::success(); 6519 case BitstreamEntry::Record: 6520 // The interesting case. 6521 break; 6522 } 6523 6524 Record.clear(); 6525 switch (Stream.readRecord(Entry.ID, Record)) { 6526 default: // Default behavior: ignore. 6527 break; 6528 case bitc::MST_CODE_ENTRY: { 6529 // MST_ENTRY: [modid, namechar x N] 6530 uint64_t ModuleId = Record[0]; 6531 6532 if (convertToString(Record, 1, ModulePath)) 6533 return error("Invalid record"); 6534 6535 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId); 6536 ModuleIdMap[ModuleId] = LastSeenModulePath->first(); 6537 6538 ModulePath.clear(); 6539 break; 6540 } 6541 /// MST_CODE_HASH: [5*i32] 6542 case bitc::MST_CODE_HASH: { 6543 if (Record.size() != 5) 6544 return error("Invalid hash length " + Twine(Record.size()).str()); 6545 if (LastSeenModulePath == TheIndex->modulePaths().end()) 6546 return error("Invalid hash that does not follow a module path"); 6547 int Pos = 0; 6548 for (auto &Val : Record) { 6549 assert(!(Val >> 32) && "Unexpected high bits set"); 6550 LastSeenModulePath->second.second[Pos++] = Val; 6551 } 6552 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly. 6553 LastSeenModulePath = TheIndex->modulePaths().end(); 6554 break; 6555 } 6556 } 6557 } 6558 llvm_unreachable("Exit infinite loop"); 6559 } 6560 6561 // Parse the function info index from the bitcode streamer into the given index. 6562 Error 6563 ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(ModuleSummaryIndex *I) { 6564 TheIndex = I; 6565 6566 if (Error Err = initStream()) 6567 return Err; 6568 6569 // Sniff for the signature. 6570 if (!hasValidBitcodeHeader(Stream)) 6571 return error("Invalid bitcode signature"); 6572 6573 // We expect a number of well-defined blocks, though we don't necessarily 6574 // need to understand them all. 6575 while (true) { 6576 if (Stream.AtEndOfStream()) { 6577 // We didn't really read a proper Module block. 6578 return error("Malformed block"); 6579 } 6580 6581 BitstreamEntry Entry = 6582 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 6583 6584 if (Entry.Kind != BitstreamEntry::SubBlock) 6585 return error("Malformed block"); 6586 6587 // If we see a MODULE_BLOCK, parse it to find the blocks needed for 6588 // building the function summary index. 6589 if (Entry.ID == bitc::MODULE_BLOCK_ID) 6590 return parseModule(); 6591 6592 if (Stream.SkipBlock()) 6593 return error("Invalid record"); 6594 } 6595 } 6596 6597 namespace { 6598 6599 // FIXME: This class is only here to support the transition to llvm::Error. It 6600 // will be removed once this transition is complete. Clients should prefer to 6601 // deal with the Error value directly, rather than converting to error_code. 6602 class BitcodeErrorCategoryType : public std::error_category { 6603 const char *name() const noexcept override { 6604 return "llvm.bitcode"; 6605 } 6606 std::string message(int IE) const override { 6607 BitcodeError E = static_cast<BitcodeError>(IE); 6608 switch (E) { 6609 case BitcodeError::CorruptedBitcode: 6610 return "Corrupted bitcode"; 6611 } 6612 llvm_unreachable("Unknown error type!"); 6613 } 6614 }; 6615 6616 } // end anonymous namespace 6617 6618 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 6619 6620 const std::error_category &llvm::BitcodeErrorCategory() { 6621 return *ErrorCategory; 6622 } 6623 6624 //===----------------------------------------------------------------------===// 6625 // External interface 6626 //===----------------------------------------------------------------------===// 6627 6628 /// \brief Get a lazy one-at-time loading module from bitcode. 6629 /// 6630 /// This isn't always used in a lazy context. In particular, it's also used by 6631 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull 6632 /// in forward-referenced functions from block address references. 6633 /// 6634 /// \param[in] MaterializeAll Set to \c true if we should materialize 6635 /// everything. 6636 static ErrorOr<std::unique_ptr<Module>> 6637 getLazyBitcodeModuleImpl(MemoryBufferRef Buffer, LLVMContext &Context, 6638 bool MaterializeAll, 6639 bool ShouldLazyLoadMetadata = false) { 6640 BitcodeReader *R = new BitcodeReader(Buffer, Context); 6641 6642 std::unique_ptr<Module> M = 6643 llvm::make_unique<Module>(Buffer.getBufferIdentifier(), Context); 6644 M->setMaterializer(R); 6645 6646 // Delay parsing Metadata if ShouldLazyLoadMetadata is true. 6647 if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata)) 6648 return errorToErrorCodeAndEmitErrors(Context, std::move(Err)); 6649 6650 if (MaterializeAll) { 6651 // Read in the entire module, and destroy the BitcodeReader. 6652 if (Error Err = M->materializeAll()) 6653 return errorToErrorCodeAndEmitErrors(Context, std::move(Err)); 6654 } else { 6655 // Resolve forward references from blockaddresses. 6656 if (Error Err = R->materializeForwardReferencedFunctions()) 6657 return errorToErrorCodeAndEmitErrors(Context, std::move(Err)); 6658 } 6659 return std::move(M); 6660 } 6661 6662 ErrorOr<std::unique_ptr<Module>> 6663 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, 6664 LLVMContext &Context, bool ShouldLazyLoadMetadata) { 6665 return getLazyBitcodeModuleImpl(Buffer, Context, false, 6666 ShouldLazyLoadMetadata); 6667 } 6668 6669 ErrorOr<std::unique_ptr<Module>> 6670 llvm::getOwningLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 6671 LLVMContext &Context, 6672 bool ShouldLazyLoadMetadata) { 6673 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata); 6674 if (MOrErr) 6675 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer)); 6676 return MOrErr; 6677 } 6678 6679 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer, 6680 LLVMContext &Context) { 6681 return getLazyBitcodeModuleImpl(Buffer, Context, true); 6682 // TODO: Restore the use-lists to the in-memory state when the bitcode was 6683 // written. We must defer until the Module has been fully materialized. 6684 } 6685 6686 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, 6687 LLVMContext &Context) { 6688 BitcodeReader R(Buffer, Context); 6689 ErrorOr<std::string> Triple = 6690 expectedToErrorOrAndEmitErrors(Context, R.parseTriple()); 6691 if (Triple.getError()) 6692 return ""; 6693 return Triple.get(); 6694 } 6695 6696 bool llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer, 6697 LLVMContext &Context) { 6698 BitcodeReader R(Buffer, Context); 6699 ErrorOr<bool> hasObjCCategory = 6700 expectedToErrorOrAndEmitErrors(Context, R.hasObjCCategory()); 6701 if (hasObjCCategory.getError()) 6702 return false; 6703 return hasObjCCategory.get(); 6704 } 6705 6706 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer, 6707 LLVMContext &Context) { 6708 BitcodeReader R(Buffer, Context); 6709 ErrorOr<std::string> ProducerString = 6710 expectedToErrorOrAndEmitErrors(Context, R.parseIdentificationBlock()); 6711 if (ProducerString.getError()) 6712 return ""; 6713 return ProducerString.get(); 6714 } 6715 6716 // Parse the specified bitcode buffer, returning the function info index. 6717 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex( 6718 MemoryBufferRef Buffer, 6719 const DiagnosticHandlerFunction &DiagnosticHandler) { 6720 ModuleSummaryIndexBitcodeReader R(Buffer); 6721 6722 auto Index = llvm::make_unique<ModuleSummaryIndex>(); 6723 6724 if (std::error_code EC = errorToErrorCodeAndEmitErrors( 6725 DiagnosticHandler, R.parseSummaryIndexInto(Index.get()))) 6726 return EC; 6727 6728 return std::move(Index); 6729 } 6730 6731 // Check if the given bitcode buffer contains a global value summary block. 6732 bool llvm::hasGlobalValueSummary( 6733 MemoryBufferRef Buffer, 6734 const DiagnosticHandlerFunction &DiagnosticHandler) { 6735 ModuleSummaryIndexBitcodeReader R(Buffer, true); 6736 6737 if (errorToErrorCodeAndEmitErrors(DiagnosticHandler, 6738 R.parseSummaryIndexInto(nullptr))) 6739 return false; 6740 6741 return R.foundGlobalValSummary(); 6742 } 6743