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