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