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