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