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