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/ManagedStatic.h" 27 #include "llvm/Support/MathExtras.h" 28 #include "llvm/Support/MemoryBuffer.h" 29 #include "llvm/Support/raw_ostream.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 *N = dyn_cast_or_null<UniquableMDNode>(MD)) 562 N->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_LOCATION: { 1271 if (Record.size() != 5) 1272 return Error("Invalid record"); 1273 1274 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get; 1275 unsigned Line = Record[1]; 1276 unsigned Column = Record[2]; 1277 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3])); 1278 Metadata *InlinedAt = 1279 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr; 1280 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt), 1281 NextMDValueNo++); 1282 break; 1283 } 1284 case bitc::METADATA_STRING: { 1285 std::string String(Record.begin(), Record.end()); 1286 llvm::UpgradeMDStringConstant(String); 1287 Metadata *MD = MDString::get(Context, String); 1288 MDValueList.AssignValue(MD, NextMDValueNo++); 1289 break; 1290 } 1291 case bitc::METADATA_KIND: { 1292 if (Record.size() < 2) 1293 return Error("Invalid record"); 1294 1295 unsigned Kind = Record[0]; 1296 SmallString<8> Name(Record.begin()+1, Record.end()); 1297 1298 unsigned NewKind = TheModule->getMDKindID(Name.str()); 1299 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1300 return Error("Conflicting METADATA_KIND records"); 1301 break; 1302 } 1303 } 1304 } 1305 } 1306 1307 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in 1308 /// the LSB for dense VBR encoding. 1309 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 1310 if ((V & 1) == 0) 1311 return V >> 1; 1312 if (V != 1) 1313 return -(V >> 1); 1314 // There is no such thing as -0 with integers. "-0" really means MININT. 1315 return 1ULL << 63; 1316 } 1317 1318 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 1319 /// values and aliases that we can. 1320 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() { 1321 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 1322 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 1323 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 1324 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist; 1325 1326 GlobalInitWorklist.swap(GlobalInits); 1327 AliasInitWorklist.swap(AliasInits); 1328 FunctionPrefixWorklist.swap(FunctionPrefixes); 1329 FunctionPrologueWorklist.swap(FunctionPrologues); 1330 1331 while (!GlobalInitWorklist.empty()) { 1332 unsigned ValID = GlobalInitWorklist.back().second; 1333 if (ValID >= ValueList.size()) { 1334 // Not ready to resolve this yet, it requires something later in the file. 1335 GlobalInits.push_back(GlobalInitWorklist.back()); 1336 } else { 1337 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1338 GlobalInitWorklist.back().first->setInitializer(C); 1339 else 1340 return Error("Expected a constant"); 1341 } 1342 GlobalInitWorklist.pop_back(); 1343 } 1344 1345 while (!AliasInitWorklist.empty()) { 1346 unsigned ValID = AliasInitWorklist.back().second; 1347 if (ValID >= ValueList.size()) { 1348 AliasInits.push_back(AliasInitWorklist.back()); 1349 } else { 1350 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1351 AliasInitWorklist.back().first->setAliasee(C); 1352 else 1353 return Error("Expected a constant"); 1354 } 1355 AliasInitWorklist.pop_back(); 1356 } 1357 1358 while (!FunctionPrefixWorklist.empty()) { 1359 unsigned ValID = FunctionPrefixWorklist.back().second; 1360 if (ValID >= ValueList.size()) { 1361 FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 1362 } else { 1363 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1364 FunctionPrefixWorklist.back().first->setPrefixData(C); 1365 else 1366 return Error("Expected a constant"); 1367 } 1368 FunctionPrefixWorklist.pop_back(); 1369 } 1370 1371 while (!FunctionPrologueWorklist.empty()) { 1372 unsigned ValID = FunctionPrologueWorklist.back().second; 1373 if (ValID >= ValueList.size()) { 1374 FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 1375 } else { 1376 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1377 FunctionPrologueWorklist.back().first->setPrologueData(C); 1378 else 1379 return Error("Expected a constant"); 1380 } 1381 FunctionPrologueWorklist.pop_back(); 1382 } 1383 1384 return std::error_code(); 1385 } 1386 1387 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 1388 SmallVector<uint64_t, 8> Words(Vals.size()); 1389 std::transform(Vals.begin(), Vals.end(), Words.begin(), 1390 BitcodeReader::decodeSignRotatedValue); 1391 1392 return APInt(TypeBits, Words); 1393 } 1394 1395 std::error_code BitcodeReader::ParseConstants() { 1396 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 1397 return Error("Invalid record"); 1398 1399 SmallVector<uint64_t, 64> Record; 1400 1401 // Read all the records for this value table. 1402 Type *CurTy = Type::getInt32Ty(Context); 1403 unsigned NextCstNo = ValueList.size(); 1404 while (1) { 1405 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1406 1407 switch (Entry.Kind) { 1408 case BitstreamEntry::SubBlock: // Handled for us already. 1409 case BitstreamEntry::Error: 1410 return Error("Malformed block"); 1411 case BitstreamEntry::EndBlock: 1412 if (NextCstNo != ValueList.size()) 1413 return Error("Invalid ronstant reference"); 1414 1415 // Once all the constants have been read, go through and resolve forward 1416 // references. 1417 ValueList.ResolveConstantForwardRefs(); 1418 return std::error_code(); 1419 case BitstreamEntry::Record: 1420 // The interesting case. 1421 break; 1422 } 1423 1424 // Read a record. 1425 Record.clear(); 1426 Value *V = nullptr; 1427 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 1428 switch (BitCode) { 1429 default: // Default behavior: unknown constant 1430 case bitc::CST_CODE_UNDEF: // UNDEF 1431 V = UndefValue::get(CurTy); 1432 break; 1433 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 1434 if (Record.empty()) 1435 return Error("Invalid record"); 1436 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 1437 return Error("Invalid record"); 1438 CurTy = TypeList[Record[0]]; 1439 continue; // Skip the ValueList manipulation. 1440 case bitc::CST_CODE_NULL: // NULL 1441 V = Constant::getNullValue(CurTy); 1442 break; 1443 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 1444 if (!CurTy->isIntegerTy() || Record.empty()) 1445 return Error("Invalid record"); 1446 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 1447 break; 1448 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 1449 if (!CurTy->isIntegerTy() || Record.empty()) 1450 return Error("Invalid record"); 1451 1452 APInt VInt = ReadWideAPInt(Record, 1453 cast<IntegerType>(CurTy)->getBitWidth()); 1454 V = ConstantInt::get(Context, VInt); 1455 1456 break; 1457 } 1458 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 1459 if (Record.empty()) 1460 return Error("Invalid record"); 1461 if (CurTy->isHalfTy()) 1462 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 1463 APInt(16, (uint16_t)Record[0]))); 1464 else if (CurTy->isFloatTy()) 1465 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 1466 APInt(32, (uint32_t)Record[0]))); 1467 else if (CurTy->isDoubleTy()) 1468 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 1469 APInt(64, Record[0]))); 1470 else if (CurTy->isX86_FP80Ty()) { 1471 // Bits are not stored the same way as a normal i80 APInt, compensate. 1472 uint64_t Rearrange[2]; 1473 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 1474 Rearrange[1] = Record[0] >> 48; 1475 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 1476 APInt(80, Rearrange))); 1477 } else if (CurTy->isFP128Ty()) 1478 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 1479 APInt(128, Record))); 1480 else if (CurTy->isPPC_FP128Ty()) 1481 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 1482 APInt(128, Record))); 1483 else 1484 V = UndefValue::get(CurTy); 1485 break; 1486 } 1487 1488 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 1489 if (Record.empty()) 1490 return Error("Invalid record"); 1491 1492 unsigned Size = Record.size(); 1493 SmallVector<Constant*, 16> Elts; 1494 1495 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 1496 for (unsigned i = 0; i != Size; ++i) 1497 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 1498 STy->getElementType(i))); 1499 V = ConstantStruct::get(STy, Elts); 1500 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 1501 Type *EltTy = ATy->getElementType(); 1502 for (unsigned i = 0; i != Size; ++i) 1503 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1504 V = ConstantArray::get(ATy, Elts); 1505 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 1506 Type *EltTy = VTy->getElementType(); 1507 for (unsigned i = 0; i != Size; ++i) 1508 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1509 V = ConstantVector::get(Elts); 1510 } else { 1511 V = UndefValue::get(CurTy); 1512 } 1513 break; 1514 } 1515 case bitc::CST_CODE_STRING: // STRING: [values] 1516 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 1517 if (Record.empty()) 1518 return Error("Invalid record"); 1519 1520 SmallString<16> Elts(Record.begin(), Record.end()); 1521 V = ConstantDataArray::getString(Context, Elts, 1522 BitCode == bitc::CST_CODE_CSTRING); 1523 break; 1524 } 1525 case bitc::CST_CODE_DATA: {// DATA: [n x value] 1526 if (Record.empty()) 1527 return Error("Invalid record"); 1528 1529 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 1530 unsigned Size = Record.size(); 1531 1532 if (EltTy->isIntegerTy(8)) { 1533 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 1534 if (isa<VectorType>(CurTy)) 1535 V = ConstantDataVector::get(Context, Elts); 1536 else 1537 V = ConstantDataArray::get(Context, Elts); 1538 } else if (EltTy->isIntegerTy(16)) { 1539 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 1540 if (isa<VectorType>(CurTy)) 1541 V = ConstantDataVector::get(Context, Elts); 1542 else 1543 V = ConstantDataArray::get(Context, Elts); 1544 } else if (EltTy->isIntegerTy(32)) { 1545 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 1546 if (isa<VectorType>(CurTy)) 1547 V = ConstantDataVector::get(Context, Elts); 1548 else 1549 V = ConstantDataArray::get(Context, Elts); 1550 } else if (EltTy->isIntegerTy(64)) { 1551 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 1552 if (isa<VectorType>(CurTy)) 1553 V = ConstantDataVector::get(Context, Elts); 1554 else 1555 V = ConstantDataArray::get(Context, Elts); 1556 } else if (EltTy->isFloatTy()) { 1557 SmallVector<float, 16> Elts(Size); 1558 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); 1559 if (isa<VectorType>(CurTy)) 1560 V = ConstantDataVector::get(Context, Elts); 1561 else 1562 V = ConstantDataArray::get(Context, Elts); 1563 } else if (EltTy->isDoubleTy()) { 1564 SmallVector<double, 16> Elts(Size); 1565 std::transform(Record.begin(), Record.end(), Elts.begin(), 1566 BitsToDouble); 1567 if (isa<VectorType>(CurTy)) 1568 V = ConstantDataVector::get(Context, Elts); 1569 else 1570 V = ConstantDataArray::get(Context, Elts); 1571 } else { 1572 return Error("Invalid type for value"); 1573 } 1574 break; 1575 } 1576 1577 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 1578 if (Record.size() < 3) 1579 return Error("Invalid record"); 1580 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 1581 if (Opc < 0) { 1582 V = UndefValue::get(CurTy); // Unknown binop. 1583 } else { 1584 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 1585 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 1586 unsigned Flags = 0; 1587 if (Record.size() >= 4) { 1588 if (Opc == Instruction::Add || 1589 Opc == Instruction::Sub || 1590 Opc == Instruction::Mul || 1591 Opc == Instruction::Shl) { 1592 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 1593 Flags |= OverflowingBinaryOperator::NoSignedWrap; 1594 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 1595 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 1596 } else if (Opc == Instruction::SDiv || 1597 Opc == Instruction::UDiv || 1598 Opc == Instruction::LShr || 1599 Opc == Instruction::AShr) { 1600 if (Record[3] & (1 << bitc::PEO_EXACT)) 1601 Flags |= SDivOperator::IsExact; 1602 } 1603 } 1604 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 1605 } 1606 break; 1607 } 1608 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 1609 if (Record.size() < 3) 1610 return Error("Invalid record"); 1611 int Opc = GetDecodedCastOpcode(Record[0]); 1612 if (Opc < 0) { 1613 V = UndefValue::get(CurTy); // Unknown cast. 1614 } else { 1615 Type *OpTy = getTypeByID(Record[1]); 1616 if (!OpTy) 1617 return Error("Invalid record"); 1618 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 1619 V = UpgradeBitCastExpr(Opc, Op, CurTy); 1620 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 1621 } 1622 break; 1623 } 1624 case bitc::CST_CODE_CE_INBOUNDS_GEP: 1625 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 1626 if (Record.size() & 1) 1627 return Error("Invalid record"); 1628 SmallVector<Constant*, 16> Elts; 1629 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1630 Type *ElTy = getTypeByID(Record[i]); 1631 if (!ElTy) 1632 return Error("Invalid record"); 1633 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 1634 } 1635 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 1636 V = ConstantExpr::getGetElementPtr(Elts[0], Indices, 1637 BitCode == 1638 bitc::CST_CODE_CE_INBOUNDS_GEP); 1639 break; 1640 } 1641 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 1642 if (Record.size() < 3) 1643 return Error("Invalid record"); 1644 1645 Type *SelectorTy = Type::getInt1Ty(Context); 1646 1647 // If CurTy is a vector of length n, then Record[0] must be a <n x i1> 1648 // vector. Otherwise, it must be a single bit. 1649 if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 1650 SelectorTy = VectorType::get(Type::getInt1Ty(Context), 1651 VTy->getNumElements()); 1652 1653 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 1654 SelectorTy), 1655 ValueList.getConstantFwdRef(Record[1],CurTy), 1656 ValueList.getConstantFwdRef(Record[2],CurTy)); 1657 break; 1658 } 1659 case bitc::CST_CODE_CE_EXTRACTELT 1660 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 1661 if (Record.size() < 3) 1662 return Error("Invalid record"); 1663 VectorType *OpTy = 1664 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1665 if (!OpTy) 1666 return Error("Invalid record"); 1667 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1668 Constant *Op1 = nullptr; 1669 if (Record.size() == 4) { 1670 Type *IdxTy = getTypeByID(Record[2]); 1671 if (!IdxTy) 1672 return Error("Invalid record"); 1673 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 1674 } else // TODO: Remove with llvm 4.0 1675 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1676 if (!Op1) 1677 return Error("Invalid record"); 1678 V = ConstantExpr::getExtractElement(Op0, Op1); 1679 break; 1680 } 1681 case bitc::CST_CODE_CE_INSERTELT 1682 : { // CE_INSERTELT: [opval, opval, opty, opval] 1683 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1684 if (Record.size() < 3 || !OpTy) 1685 return Error("Invalid record"); 1686 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1687 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 1688 OpTy->getElementType()); 1689 Constant *Op2 = nullptr; 1690 if (Record.size() == 4) { 1691 Type *IdxTy = getTypeByID(Record[2]); 1692 if (!IdxTy) 1693 return Error("Invalid record"); 1694 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 1695 } else // TODO: Remove with llvm 4.0 1696 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1697 if (!Op2) 1698 return Error("Invalid record"); 1699 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 1700 break; 1701 } 1702 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 1703 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1704 if (Record.size() < 3 || !OpTy) 1705 return Error("Invalid record"); 1706 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1707 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 1708 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1709 OpTy->getNumElements()); 1710 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 1711 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1712 break; 1713 } 1714 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 1715 VectorType *RTy = dyn_cast<VectorType>(CurTy); 1716 VectorType *OpTy = 1717 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1718 if (Record.size() < 4 || !RTy || !OpTy) 1719 return Error("Invalid record"); 1720 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1721 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1722 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1723 RTy->getNumElements()); 1724 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 1725 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1726 break; 1727 } 1728 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 1729 if (Record.size() < 4) 1730 return Error("Invalid record"); 1731 Type *OpTy = getTypeByID(Record[0]); 1732 if (!OpTy) 1733 return Error("Invalid record"); 1734 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1735 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1736 1737 if (OpTy->isFPOrFPVectorTy()) 1738 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 1739 else 1740 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 1741 break; 1742 } 1743 // This maintains backward compatibility, pre-asm dialect keywords. 1744 // FIXME: Remove with the 4.0 release. 1745 case bitc::CST_CODE_INLINEASM_OLD: { 1746 if (Record.size() < 2) 1747 return Error("Invalid record"); 1748 std::string AsmStr, ConstrStr; 1749 bool HasSideEffects = Record[0] & 1; 1750 bool IsAlignStack = Record[0] >> 1; 1751 unsigned AsmStrSize = Record[1]; 1752 if (2+AsmStrSize >= Record.size()) 1753 return Error("Invalid record"); 1754 unsigned ConstStrSize = Record[2+AsmStrSize]; 1755 if (3+AsmStrSize+ConstStrSize > Record.size()) 1756 return Error("Invalid record"); 1757 1758 for (unsigned i = 0; i != AsmStrSize; ++i) 1759 AsmStr += (char)Record[2+i]; 1760 for (unsigned i = 0; i != ConstStrSize; ++i) 1761 ConstrStr += (char)Record[3+AsmStrSize+i]; 1762 PointerType *PTy = cast<PointerType>(CurTy); 1763 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1764 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 1765 break; 1766 } 1767 // This version adds support for the asm dialect keywords (e.g., 1768 // inteldialect). 1769 case bitc::CST_CODE_INLINEASM: { 1770 if (Record.size() < 2) 1771 return Error("Invalid record"); 1772 std::string AsmStr, ConstrStr; 1773 bool HasSideEffects = Record[0] & 1; 1774 bool IsAlignStack = (Record[0] >> 1) & 1; 1775 unsigned AsmDialect = Record[0] >> 2; 1776 unsigned AsmStrSize = Record[1]; 1777 if (2+AsmStrSize >= Record.size()) 1778 return Error("Invalid record"); 1779 unsigned ConstStrSize = Record[2+AsmStrSize]; 1780 if (3+AsmStrSize+ConstStrSize > Record.size()) 1781 return Error("Invalid record"); 1782 1783 for (unsigned i = 0; i != AsmStrSize; ++i) 1784 AsmStr += (char)Record[2+i]; 1785 for (unsigned i = 0; i != ConstStrSize; ++i) 1786 ConstrStr += (char)Record[3+AsmStrSize+i]; 1787 PointerType *PTy = cast<PointerType>(CurTy); 1788 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1789 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 1790 InlineAsm::AsmDialect(AsmDialect)); 1791 break; 1792 } 1793 case bitc::CST_CODE_BLOCKADDRESS:{ 1794 if (Record.size() < 3) 1795 return Error("Invalid record"); 1796 Type *FnTy = getTypeByID(Record[0]); 1797 if (!FnTy) 1798 return Error("Invalid record"); 1799 Function *Fn = 1800 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 1801 if (!Fn) 1802 return Error("Invalid record"); 1803 1804 // Don't let Fn get dematerialized. 1805 BlockAddressesTaken.insert(Fn); 1806 1807 // If the function is already parsed we can insert the block address right 1808 // away. 1809 BasicBlock *BB; 1810 unsigned BBID = Record[2]; 1811 if (!BBID) 1812 // Invalid reference to entry block. 1813 return Error("Invalid ID"); 1814 if (!Fn->empty()) { 1815 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 1816 for (size_t I = 0, E = BBID; I != E; ++I) { 1817 if (BBI == BBE) 1818 return Error("Invalid ID"); 1819 ++BBI; 1820 } 1821 BB = BBI; 1822 } else { 1823 // Otherwise insert a placeholder and remember it so it can be inserted 1824 // when the function is parsed. 1825 auto &FwdBBs = BasicBlockFwdRefs[Fn]; 1826 if (FwdBBs.empty()) 1827 BasicBlockFwdRefQueue.push_back(Fn); 1828 if (FwdBBs.size() < BBID + 1) 1829 FwdBBs.resize(BBID + 1); 1830 if (!FwdBBs[BBID]) 1831 FwdBBs[BBID] = BasicBlock::Create(Context); 1832 BB = FwdBBs[BBID]; 1833 } 1834 V = BlockAddress::get(Fn, BB); 1835 break; 1836 } 1837 } 1838 1839 ValueList.AssignValue(V, NextCstNo); 1840 ++NextCstNo; 1841 } 1842 } 1843 1844 std::error_code BitcodeReader::ParseUseLists() { 1845 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 1846 return Error("Invalid record"); 1847 1848 // Read all the records. 1849 SmallVector<uint64_t, 64> Record; 1850 while (1) { 1851 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1852 1853 switch (Entry.Kind) { 1854 case BitstreamEntry::SubBlock: // Handled for us already. 1855 case BitstreamEntry::Error: 1856 return Error("Malformed block"); 1857 case BitstreamEntry::EndBlock: 1858 return std::error_code(); 1859 case BitstreamEntry::Record: 1860 // The interesting case. 1861 break; 1862 } 1863 1864 // Read a use list record. 1865 Record.clear(); 1866 bool IsBB = false; 1867 switch (Stream.readRecord(Entry.ID, Record)) { 1868 default: // Default behavior: unknown type. 1869 break; 1870 case bitc::USELIST_CODE_BB: 1871 IsBB = true; 1872 // fallthrough 1873 case bitc::USELIST_CODE_DEFAULT: { 1874 unsigned RecordLength = Record.size(); 1875 if (RecordLength < 3) 1876 // Records should have at least an ID and two indexes. 1877 return Error("Invalid record"); 1878 unsigned ID = Record.back(); 1879 Record.pop_back(); 1880 1881 Value *V; 1882 if (IsBB) { 1883 assert(ID < FunctionBBs.size() && "Basic block not found"); 1884 V = FunctionBBs[ID]; 1885 } else 1886 V = ValueList[ID]; 1887 unsigned NumUses = 0; 1888 SmallDenseMap<const Use *, unsigned, 16> Order; 1889 for (const Use &U : V->uses()) { 1890 if (++NumUses > Record.size()) 1891 break; 1892 Order[&U] = Record[NumUses - 1]; 1893 } 1894 if (Order.size() != Record.size() || NumUses > Record.size()) 1895 // Mismatches can happen if the functions are being materialized lazily 1896 // (out-of-order), or a value has been upgraded. 1897 break; 1898 1899 V->sortUseList([&](const Use &L, const Use &R) { 1900 return Order.lookup(&L) < Order.lookup(&R); 1901 }); 1902 break; 1903 } 1904 } 1905 } 1906 } 1907 1908 /// RememberAndSkipFunctionBody - When we see the block for a function body, 1909 /// remember where it is and then skip it. This lets us lazily deserialize the 1910 /// functions. 1911 std::error_code BitcodeReader::RememberAndSkipFunctionBody() { 1912 // Get the function we are talking about. 1913 if (FunctionsWithBodies.empty()) 1914 return Error("Insufficient function protos"); 1915 1916 Function *Fn = FunctionsWithBodies.back(); 1917 FunctionsWithBodies.pop_back(); 1918 1919 // Save the current stream state. 1920 uint64_t CurBit = Stream.GetCurrentBitNo(); 1921 DeferredFunctionInfo[Fn] = CurBit; 1922 1923 // Skip over the function block for now. 1924 if (Stream.SkipBlock()) 1925 return Error("Invalid record"); 1926 return std::error_code(); 1927 } 1928 1929 std::error_code BitcodeReader::GlobalCleanup() { 1930 // Patch the initializers for globals and aliases up. 1931 ResolveGlobalAndAliasInits(); 1932 if (!GlobalInits.empty() || !AliasInits.empty()) 1933 return Error("Malformed global initializer set"); 1934 1935 // Look for intrinsic functions which need to be upgraded at some point 1936 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 1937 FI != FE; ++FI) { 1938 Function *NewFn; 1939 if (UpgradeIntrinsicFunction(FI, NewFn)) 1940 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 1941 } 1942 1943 // Look for global variables which need to be renamed. 1944 for (Module::global_iterator 1945 GI = TheModule->global_begin(), GE = TheModule->global_end(); 1946 GI != GE;) { 1947 GlobalVariable *GV = GI++; 1948 UpgradeGlobalVariable(GV); 1949 } 1950 1951 // Force deallocation of memory for these vectors to favor the client that 1952 // want lazy deserialization. 1953 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 1954 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 1955 return std::error_code(); 1956 } 1957 1958 std::error_code BitcodeReader::ParseModule(bool Resume) { 1959 if (Resume) 1960 Stream.JumpToBit(NextUnreadBit); 1961 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 1962 return Error("Invalid record"); 1963 1964 SmallVector<uint64_t, 64> Record; 1965 std::vector<std::string> SectionTable; 1966 std::vector<std::string> GCTable; 1967 1968 // Read all the records for this module. 1969 while (1) { 1970 BitstreamEntry Entry = Stream.advance(); 1971 1972 switch (Entry.Kind) { 1973 case BitstreamEntry::Error: 1974 return Error("Malformed block"); 1975 case BitstreamEntry::EndBlock: 1976 return GlobalCleanup(); 1977 1978 case BitstreamEntry::SubBlock: 1979 switch (Entry.ID) { 1980 default: // Skip unknown content. 1981 if (Stream.SkipBlock()) 1982 return Error("Invalid record"); 1983 break; 1984 case bitc::BLOCKINFO_BLOCK_ID: 1985 if (Stream.ReadBlockInfoBlock()) 1986 return Error("Malformed block"); 1987 break; 1988 case bitc::PARAMATTR_BLOCK_ID: 1989 if (std::error_code EC = ParseAttributeBlock()) 1990 return EC; 1991 break; 1992 case bitc::PARAMATTR_GROUP_BLOCK_ID: 1993 if (std::error_code EC = ParseAttributeGroupBlock()) 1994 return EC; 1995 break; 1996 case bitc::TYPE_BLOCK_ID_NEW: 1997 if (std::error_code EC = ParseTypeTable()) 1998 return EC; 1999 break; 2000 case bitc::VALUE_SYMTAB_BLOCK_ID: 2001 if (std::error_code EC = ParseValueSymbolTable()) 2002 return EC; 2003 SeenValueSymbolTable = true; 2004 break; 2005 case bitc::CONSTANTS_BLOCK_ID: 2006 if (std::error_code EC = ParseConstants()) 2007 return EC; 2008 if (std::error_code EC = ResolveGlobalAndAliasInits()) 2009 return EC; 2010 break; 2011 case bitc::METADATA_BLOCK_ID: 2012 if (std::error_code EC = ParseMetadata()) 2013 return EC; 2014 break; 2015 case bitc::FUNCTION_BLOCK_ID: 2016 // If this is the first function body we've seen, reverse the 2017 // FunctionsWithBodies list. 2018 if (!SeenFirstFunctionBody) { 2019 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 2020 if (std::error_code EC = GlobalCleanup()) 2021 return EC; 2022 SeenFirstFunctionBody = true; 2023 } 2024 2025 if (std::error_code EC = RememberAndSkipFunctionBody()) 2026 return EC; 2027 // For streaming bitcode, suspend parsing when we reach the function 2028 // bodies. Subsequent materialization calls will resume it when 2029 // necessary. For streaming, the function bodies must be at the end of 2030 // the bitcode. If the bitcode file is old, the symbol table will be 2031 // at the end instead and will not have been seen yet. In this case, 2032 // just finish the parse now. 2033 if (LazyStreamer && SeenValueSymbolTable) { 2034 NextUnreadBit = Stream.GetCurrentBitNo(); 2035 return std::error_code(); 2036 } 2037 break; 2038 case bitc::USELIST_BLOCK_ID: 2039 if (std::error_code EC = ParseUseLists()) 2040 return EC; 2041 break; 2042 } 2043 continue; 2044 2045 case BitstreamEntry::Record: 2046 // The interesting case. 2047 break; 2048 } 2049 2050 2051 // Read a record. 2052 switch (Stream.readRecord(Entry.ID, Record)) { 2053 default: break; // Default behavior, ignore unknown content. 2054 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 2055 if (Record.size() < 1) 2056 return Error("Invalid record"); 2057 // Only version #0 and #1 are supported so far. 2058 unsigned module_version = Record[0]; 2059 switch (module_version) { 2060 default: 2061 return Error("Invalid value"); 2062 case 0: 2063 UseRelativeIDs = false; 2064 break; 2065 case 1: 2066 UseRelativeIDs = true; 2067 break; 2068 } 2069 break; 2070 } 2071 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2072 std::string S; 2073 if (ConvertToString(Record, 0, S)) 2074 return Error("Invalid record"); 2075 TheModule->setTargetTriple(S); 2076 break; 2077 } 2078 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 2079 std::string S; 2080 if (ConvertToString(Record, 0, S)) 2081 return Error("Invalid record"); 2082 TheModule->setDataLayout(S); 2083 break; 2084 } 2085 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 2086 std::string S; 2087 if (ConvertToString(Record, 0, S)) 2088 return Error("Invalid record"); 2089 TheModule->setModuleInlineAsm(S); 2090 break; 2091 } 2092 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 2093 // FIXME: Remove in 4.0. 2094 std::string S; 2095 if (ConvertToString(Record, 0, S)) 2096 return Error("Invalid record"); 2097 // Ignore value. 2098 break; 2099 } 2100 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 2101 std::string S; 2102 if (ConvertToString(Record, 0, S)) 2103 return Error("Invalid record"); 2104 SectionTable.push_back(S); 2105 break; 2106 } 2107 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 2108 std::string S; 2109 if (ConvertToString(Record, 0, S)) 2110 return Error("Invalid record"); 2111 GCTable.push_back(S); 2112 break; 2113 } 2114 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] 2115 if (Record.size() < 2) 2116 return Error("Invalid record"); 2117 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 2118 unsigned ComdatNameSize = Record[1]; 2119 std::string ComdatName; 2120 ComdatName.reserve(ComdatNameSize); 2121 for (unsigned i = 0; i != ComdatNameSize; ++i) 2122 ComdatName += (char)Record[2 + i]; 2123 Comdat *C = TheModule->getOrInsertComdat(ComdatName); 2124 C->setSelectionKind(SK); 2125 ComdatList.push_back(C); 2126 break; 2127 } 2128 // GLOBALVAR: [pointer type, isconst, initid, 2129 // linkage, alignment, section, visibility, threadlocal, 2130 // unnamed_addr, dllstorageclass] 2131 case bitc::MODULE_CODE_GLOBALVAR: { 2132 if (Record.size() < 6) 2133 return Error("Invalid record"); 2134 Type *Ty = getTypeByID(Record[0]); 2135 if (!Ty) 2136 return Error("Invalid record"); 2137 if (!Ty->isPointerTy()) 2138 return Error("Invalid type for value"); 2139 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 2140 Ty = cast<PointerType>(Ty)->getElementType(); 2141 2142 bool isConstant = Record[1]; 2143 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(Record[3]); 2144 unsigned Alignment = (1 << Record[4]) >> 1; 2145 std::string Section; 2146 if (Record[5]) { 2147 if (Record[5]-1 >= SectionTable.size()) 2148 return Error("Invalid ID"); 2149 Section = SectionTable[Record[5]-1]; 2150 } 2151 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 2152 // Local linkage must have default visibility. 2153 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 2154 // FIXME: Change to an error if non-default in 4.0. 2155 Visibility = GetDecodedVisibility(Record[6]); 2156 2157 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 2158 if (Record.size() > 7) 2159 TLM = GetDecodedThreadLocalMode(Record[7]); 2160 2161 bool UnnamedAddr = false; 2162 if (Record.size() > 8) 2163 UnnamedAddr = Record[8]; 2164 2165 bool ExternallyInitialized = false; 2166 if (Record.size() > 9) 2167 ExternallyInitialized = Record[9]; 2168 2169 GlobalVariable *NewGV = 2170 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 2171 TLM, AddressSpace, ExternallyInitialized); 2172 NewGV->setAlignment(Alignment); 2173 if (!Section.empty()) 2174 NewGV->setSection(Section); 2175 NewGV->setVisibility(Visibility); 2176 NewGV->setUnnamedAddr(UnnamedAddr); 2177 2178 if (Record.size() > 10) 2179 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10])); 2180 else 2181 UpgradeDLLImportExportLinkage(NewGV, Record[3]); 2182 2183 ValueList.push_back(NewGV); 2184 2185 // Remember which value to use for the global initializer. 2186 if (unsigned InitID = Record[2]) 2187 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 2188 2189 if (Record.size() > 11) 2190 if (unsigned ComdatID = Record[11]) { 2191 assert(ComdatID <= ComdatList.size()); 2192 NewGV->setComdat(ComdatList[ComdatID - 1]); 2193 } 2194 break; 2195 } 2196 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 2197 // alignment, section, visibility, gc, unnamed_addr, 2198 // prologuedata, dllstorageclass, comdat, prefixdata] 2199 case bitc::MODULE_CODE_FUNCTION: { 2200 if (Record.size() < 8) 2201 return Error("Invalid record"); 2202 Type *Ty = getTypeByID(Record[0]); 2203 if (!Ty) 2204 return Error("Invalid record"); 2205 if (!Ty->isPointerTy()) 2206 return Error("Invalid type for value"); 2207 FunctionType *FTy = 2208 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 2209 if (!FTy) 2210 return Error("Invalid type for value"); 2211 2212 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 2213 "", TheModule); 2214 2215 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 2216 bool isProto = Record[2]; 2217 Func->setLinkage(getDecodedLinkage(Record[3])); 2218 Func->setAttributes(getAttributes(Record[4])); 2219 2220 Func->setAlignment((1 << Record[5]) >> 1); 2221 if (Record[6]) { 2222 if (Record[6]-1 >= SectionTable.size()) 2223 return Error("Invalid ID"); 2224 Func->setSection(SectionTable[Record[6]-1]); 2225 } 2226 // Local linkage must have default visibility. 2227 if (!Func->hasLocalLinkage()) 2228 // FIXME: Change to an error if non-default in 4.0. 2229 Func->setVisibility(GetDecodedVisibility(Record[7])); 2230 if (Record.size() > 8 && Record[8]) { 2231 if (Record[8]-1 > GCTable.size()) 2232 return Error("Invalid ID"); 2233 Func->setGC(GCTable[Record[8]-1].c_str()); 2234 } 2235 bool UnnamedAddr = false; 2236 if (Record.size() > 9) 2237 UnnamedAddr = Record[9]; 2238 Func->setUnnamedAddr(UnnamedAddr); 2239 if (Record.size() > 10 && Record[10] != 0) 2240 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1)); 2241 2242 if (Record.size() > 11) 2243 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11])); 2244 else 2245 UpgradeDLLImportExportLinkage(Func, Record[3]); 2246 2247 if (Record.size() > 12) 2248 if (unsigned ComdatID = Record[12]) { 2249 assert(ComdatID <= ComdatList.size()); 2250 Func->setComdat(ComdatList[ComdatID - 1]); 2251 } 2252 2253 if (Record.size() > 13 && Record[13] != 0) 2254 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1)); 2255 2256 ValueList.push_back(Func); 2257 2258 // If this is a function with a body, remember the prototype we are 2259 // creating now, so that we can match up the body with them later. 2260 if (!isProto) { 2261 Func->setIsMaterializable(true); 2262 FunctionsWithBodies.push_back(Func); 2263 if (LazyStreamer) 2264 DeferredFunctionInfo[Func] = 0; 2265 } 2266 break; 2267 } 2268 // ALIAS: [alias type, aliasee val#, linkage] 2269 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass] 2270 case bitc::MODULE_CODE_ALIAS: { 2271 if (Record.size() < 3) 2272 return Error("Invalid record"); 2273 Type *Ty = getTypeByID(Record[0]); 2274 if (!Ty) 2275 return Error("Invalid record"); 2276 auto *PTy = dyn_cast<PointerType>(Ty); 2277 if (!PTy) 2278 return Error("Invalid type for value"); 2279 2280 auto *NewGA = 2281 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 2282 getDecodedLinkage(Record[2]), "", TheModule); 2283 // Old bitcode files didn't have visibility field. 2284 // Local linkage must have default visibility. 2285 if (Record.size() > 3 && !NewGA->hasLocalLinkage()) 2286 // FIXME: Change to an error if non-default in 4.0. 2287 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 2288 if (Record.size() > 4) 2289 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4])); 2290 else 2291 UpgradeDLLImportExportLinkage(NewGA, Record[2]); 2292 if (Record.size() > 5) 2293 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5])); 2294 if (Record.size() > 6) 2295 NewGA->setUnnamedAddr(Record[6]); 2296 ValueList.push_back(NewGA); 2297 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 2298 break; 2299 } 2300 /// MODULE_CODE_PURGEVALS: [numvals] 2301 case bitc::MODULE_CODE_PURGEVALS: 2302 // Trim down the value list to the specified size. 2303 if (Record.size() < 1 || Record[0] > ValueList.size()) 2304 return Error("Invalid record"); 2305 ValueList.shrinkTo(Record[0]); 2306 break; 2307 } 2308 Record.clear(); 2309 } 2310 } 2311 2312 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) { 2313 TheModule = nullptr; 2314 2315 if (std::error_code EC = InitStream()) 2316 return EC; 2317 2318 // Sniff for the signature. 2319 if (Stream.Read(8) != 'B' || 2320 Stream.Read(8) != 'C' || 2321 Stream.Read(4) != 0x0 || 2322 Stream.Read(4) != 0xC || 2323 Stream.Read(4) != 0xE || 2324 Stream.Read(4) != 0xD) 2325 return Error("Invalid bitcode signature"); 2326 2327 // We expect a number of well-defined blocks, though we don't necessarily 2328 // need to understand them all. 2329 while (1) { 2330 if (Stream.AtEndOfStream()) 2331 return std::error_code(); 2332 2333 BitstreamEntry Entry = 2334 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 2335 2336 switch (Entry.Kind) { 2337 case BitstreamEntry::Error: 2338 return Error("Malformed block"); 2339 case BitstreamEntry::EndBlock: 2340 return std::error_code(); 2341 2342 case BitstreamEntry::SubBlock: 2343 switch (Entry.ID) { 2344 case bitc::BLOCKINFO_BLOCK_ID: 2345 if (Stream.ReadBlockInfoBlock()) 2346 return Error("Malformed block"); 2347 break; 2348 case bitc::MODULE_BLOCK_ID: 2349 // Reject multiple MODULE_BLOCK's in a single bitstream. 2350 if (TheModule) 2351 return Error("Invalid multiple blocks"); 2352 TheModule = M; 2353 if (std::error_code EC = ParseModule(false)) 2354 return EC; 2355 if (LazyStreamer) 2356 return std::error_code(); 2357 break; 2358 default: 2359 if (Stream.SkipBlock()) 2360 return Error("Invalid record"); 2361 break; 2362 } 2363 continue; 2364 case BitstreamEntry::Record: 2365 // There should be no records in the top-level of blocks. 2366 2367 // The ranlib in Xcode 4 will align archive members by appending newlines 2368 // to the end of them. If this file size is a multiple of 4 but not 8, we 2369 // have to read and ignore these final 4 bytes :-( 2370 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 && 2371 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a && 2372 Stream.AtEndOfStream()) 2373 return std::error_code(); 2374 2375 return Error("Invalid record"); 2376 } 2377 } 2378 } 2379 2380 ErrorOr<std::string> BitcodeReader::parseModuleTriple() { 2381 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2382 return Error("Invalid record"); 2383 2384 SmallVector<uint64_t, 64> Record; 2385 2386 std::string Triple; 2387 // Read all the records for this module. 2388 while (1) { 2389 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2390 2391 switch (Entry.Kind) { 2392 case BitstreamEntry::SubBlock: // Handled for us already. 2393 case BitstreamEntry::Error: 2394 return Error("Malformed block"); 2395 case BitstreamEntry::EndBlock: 2396 return Triple; 2397 case BitstreamEntry::Record: 2398 // The interesting case. 2399 break; 2400 } 2401 2402 // Read a record. 2403 switch (Stream.readRecord(Entry.ID, Record)) { 2404 default: break; // Default behavior, ignore unknown content. 2405 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2406 std::string S; 2407 if (ConvertToString(Record, 0, S)) 2408 return Error("Invalid record"); 2409 Triple = S; 2410 break; 2411 } 2412 } 2413 Record.clear(); 2414 } 2415 llvm_unreachable("Exit infinite loop"); 2416 } 2417 2418 ErrorOr<std::string> BitcodeReader::parseTriple() { 2419 if (std::error_code EC = InitStream()) 2420 return EC; 2421 2422 // Sniff for the signature. 2423 if (Stream.Read(8) != 'B' || 2424 Stream.Read(8) != 'C' || 2425 Stream.Read(4) != 0x0 || 2426 Stream.Read(4) != 0xC || 2427 Stream.Read(4) != 0xE || 2428 Stream.Read(4) != 0xD) 2429 return Error("Invalid bitcode signature"); 2430 2431 // We expect a number of well-defined blocks, though we don't necessarily 2432 // need to understand them all. 2433 while (1) { 2434 BitstreamEntry Entry = Stream.advance(); 2435 2436 switch (Entry.Kind) { 2437 case BitstreamEntry::Error: 2438 return Error("Malformed block"); 2439 case BitstreamEntry::EndBlock: 2440 return std::error_code(); 2441 2442 case BitstreamEntry::SubBlock: 2443 if (Entry.ID == bitc::MODULE_BLOCK_ID) 2444 return parseModuleTriple(); 2445 2446 // Ignore other sub-blocks. 2447 if (Stream.SkipBlock()) 2448 return Error("Malformed block"); 2449 continue; 2450 2451 case BitstreamEntry::Record: 2452 Stream.skipRecord(Entry.ID); 2453 continue; 2454 } 2455 } 2456 } 2457 2458 /// ParseMetadataAttachment - Parse metadata attachments. 2459 std::error_code BitcodeReader::ParseMetadataAttachment() { 2460 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 2461 return Error("Invalid record"); 2462 2463 SmallVector<uint64_t, 64> Record; 2464 while (1) { 2465 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2466 2467 switch (Entry.Kind) { 2468 case BitstreamEntry::SubBlock: // Handled for us already. 2469 case BitstreamEntry::Error: 2470 return Error("Malformed block"); 2471 case BitstreamEntry::EndBlock: 2472 return std::error_code(); 2473 case BitstreamEntry::Record: 2474 // The interesting case. 2475 break; 2476 } 2477 2478 // Read a metadata attachment record. 2479 Record.clear(); 2480 switch (Stream.readRecord(Entry.ID, Record)) { 2481 default: // Default behavior: ignore. 2482 break; 2483 case bitc::METADATA_ATTACHMENT: { 2484 unsigned RecordLength = Record.size(); 2485 if (Record.empty() || (RecordLength - 1) % 2 == 1) 2486 return Error("Invalid record"); 2487 Instruction *Inst = InstructionList[Record[0]]; 2488 for (unsigned i = 1; i != RecordLength; i = i+2) { 2489 unsigned Kind = Record[i]; 2490 DenseMap<unsigned, unsigned>::iterator I = 2491 MDKindMap.find(Kind); 2492 if (I == MDKindMap.end()) 2493 return Error("Invalid ID"); 2494 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]); 2495 if (isa<LocalAsMetadata>(Node)) 2496 // Drop the attachment. This used to be legal, but there's no 2497 // upgrade path. 2498 break; 2499 Inst->setMetadata(I->second, cast<MDNode>(Node)); 2500 if (I->second == LLVMContext::MD_tbaa) 2501 InstsWithTBAATag.push_back(Inst); 2502 } 2503 break; 2504 } 2505 } 2506 } 2507 } 2508 2509 /// ParseFunctionBody - Lazily parse the specified function body block. 2510 std::error_code BitcodeReader::ParseFunctionBody(Function *F) { 2511 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 2512 return Error("Invalid record"); 2513 2514 InstructionList.clear(); 2515 unsigned ModuleValueListSize = ValueList.size(); 2516 unsigned ModuleMDValueListSize = MDValueList.size(); 2517 2518 // Add all the function arguments to the value table. 2519 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 2520 ValueList.push_back(I); 2521 2522 unsigned NextValueNo = ValueList.size(); 2523 BasicBlock *CurBB = nullptr; 2524 unsigned CurBBNo = 0; 2525 2526 DebugLoc LastLoc; 2527 auto getLastInstruction = [&]() -> Instruction * { 2528 if (CurBB && !CurBB->empty()) 2529 return &CurBB->back(); 2530 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 2531 !FunctionBBs[CurBBNo - 1]->empty()) 2532 return &FunctionBBs[CurBBNo - 1]->back(); 2533 return nullptr; 2534 }; 2535 2536 // Read all the records. 2537 SmallVector<uint64_t, 64> Record; 2538 while (1) { 2539 BitstreamEntry Entry = Stream.advance(); 2540 2541 switch (Entry.Kind) { 2542 case BitstreamEntry::Error: 2543 return Error("Malformed block"); 2544 case BitstreamEntry::EndBlock: 2545 goto OutOfRecordLoop; 2546 2547 case BitstreamEntry::SubBlock: 2548 switch (Entry.ID) { 2549 default: // Skip unknown content. 2550 if (Stream.SkipBlock()) 2551 return Error("Invalid record"); 2552 break; 2553 case bitc::CONSTANTS_BLOCK_ID: 2554 if (std::error_code EC = ParseConstants()) 2555 return EC; 2556 NextValueNo = ValueList.size(); 2557 break; 2558 case bitc::VALUE_SYMTAB_BLOCK_ID: 2559 if (std::error_code EC = ParseValueSymbolTable()) 2560 return EC; 2561 break; 2562 case bitc::METADATA_ATTACHMENT_ID: 2563 if (std::error_code EC = ParseMetadataAttachment()) 2564 return EC; 2565 break; 2566 case bitc::METADATA_BLOCK_ID: 2567 if (std::error_code EC = ParseMetadata()) 2568 return EC; 2569 break; 2570 case bitc::USELIST_BLOCK_ID: 2571 if (std::error_code EC = ParseUseLists()) 2572 return EC; 2573 break; 2574 } 2575 continue; 2576 2577 case BitstreamEntry::Record: 2578 // The interesting case. 2579 break; 2580 } 2581 2582 // Read a record. 2583 Record.clear(); 2584 Instruction *I = nullptr; 2585 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2586 switch (BitCode) { 2587 default: // Default behavior: reject 2588 return Error("Invalid value"); 2589 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 2590 if (Record.size() < 1 || Record[0] == 0) 2591 return Error("Invalid record"); 2592 // Create all the basic blocks for the function. 2593 FunctionBBs.resize(Record[0]); 2594 2595 // See if anything took the address of blocks in this function. 2596 auto BBFRI = BasicBlockFwdRefs.find(F); 2597 if (BBFRI == BasicBlockFwdRefs.end()) { 2598 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 2599 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 2600 } else { 2601 auto &BBRefs = BBFRI->second; 2602 // Check for invalid basic block references. 2603 if (BBRefs.size() > FunctionBBs.size()) 2604 return Error("Invalid ID"); 2605 assert(!BBRefs.empty() && "Unexpected empty array"); 2606 assert(!BBRefs.front() && "Invalid reference to entry block"); 2607 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 2608 ++I) 2609 if (I < RE && BBRefs[I]) { 2610 BBRefs[I]->insertInto(F); 2611 FunctionBBs[I] = BBRefs[I]; 2612 } else { 2613 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 2614 } 2615 2616 // Erase from the table. 2617 BasicBlockFwdRefs.erase(BBFRI); 2618 } 2619 2620 CurBB = FunctionBBs[0]; 2621 continue; 2622 } 2623 2624 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 2625 // This record indicates that the last instruction is at the same 2626 // location as the previous instruction with a location. 2627 I = getLastInstruction(); 2628 2629 if (!I) 2630 return Error("Invalid record"); 2631 I->setDebugLoc(LastLoc); 2632 I = nullptr; 2633 continue; 2634 2635 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 2636 I = getLastInstruction(); 2637 if (!I || Record.size() < 4) 2638 return Error("Invalid record"); 2639 2640 unsigned Line = Record[0], Col = Record[1]; 2641 unsigned ScopeID = Record[2], IAID = Record[3]; 2642 2643 MDNode *Scope = nullptr, *IA = nullptr; 2644 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1)); 2645 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1)); 2646 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 2647 I->setDebugLoc(LastLoc); 2648 I = nullptr; 2649 continue; 2650 } 2651 2652 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 2653 unsigned OpNum = 0; 2654 Value *LHS, *RHS; 2655 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2656 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2657 OpNum+1 > Record.size()) 2658 return Error("Invalid record"); 2659 2660 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 2661 if (Opc == -1) 2662 return Error("Invalid record"); 2663 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 2664 InstructionList.push_back(I); 2665 if (OpNum < Record.size()) { 2666 if (Opc == Instruction::Add || 2667 Opc == Instruction::Sub || 2668 Opc == Instruction::Mul || 2669 Opc == Instruction::Shl) { 2670 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2671 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 2672 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2673 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 2674 } else if (Opc == Instruction::SDiv || 2675 Opc == Instruction::UDiv || 2676 Opc == Instruction::LShr || 2677 Opc == Instruction::AShr) { 2678 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 2679 cast<BinaryOperator>(I)->setIsExact(true); 2680 } else if (isa<FPMathOperator>(I)) { 2681 FastMathFlags FMF; 2682 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra)) 2683 FMF.setUnsafeAlgebra(); 2684 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs)) 2685 FMF.setNoNaNs(); 2686 if (0 != (Record[OpNum] & FastMathFlags::NoInfs)) 2687 FMF.setNoInfs(); 2688 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros)) 2689 FMF.setNoSignedZeros(); 2690 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal)) 2691 FMF.setAllowReciprocal(); 2692 if (FMF.any()) 2693 I->setFastMathFlags(FMF); 2694 } 2695 2696 } 2697 break; 2698 } 2699 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 2700 unsigned OpNum = 0; 2701 Value *Op; 2702 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2703 OpNum+2 != Record.size()) 2704 return Error("Invalid record"); 2705 2706 Type *ResTy = getTypeByID(Record[OpNum]); 2707 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 2708 if (Opc == -1 || !ResTy) 2709 return Error("Invalid record"); 2710 Instruction *Temp = nullptr; 2711 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 2712 if (Temp) { 2713 InstructionList.push_back(Temp); 2714 CurBB->getInstList().push_back(Temp); 2715 } 2716 } else { 2717 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 2718 } 2719 InstructionList.push_back(I); 2720 break; 2721 } 2722 case bitc::FUNC_CODE_INST_INBOUNDS_GEP: 2723 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 2724 unsigned OpNum = 0; 2725 Value *BasePtr; 2726 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 2727 return Error("Invalid record"); 2728 2729 SmallVector<Value*, 16> GEPIdx; 2730 while (OpNum != Record.size()) { 2731 Value *Op; 2732 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2733 return Error("Invalid record"); 2734 GEPIdx.push_back(Op); 2735 } 2736 2737 I = GetElementPtrInst::Create(BasePtr, GEPIdx); 2738 InstructionList.push_back(I); 2739 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP) 2740 cast<GetElementPtrInst>(I)->setIsInBounds(true); 2741 break; 2742 } 2743 2744 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 2745 // EXTRACTVAL: [opty, opval, n x indices] 2746 unsigned OpNum = 0; 2747 Value *Agg; 2748 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2749 return Error("Invalid record"); 2750 2751 SmallVector<unsigned, 4> EXTRACTVALIdx; 2752 for (unsigned RecSize = Record.size(); 2753 OpNum != RecSize; ++OpNum) { 2754 uint64_t Index = Record[OpNum]; 2755 if ((unsigned)Index != Index) 2756 return Error("Invalid value"); 2757 EXTRACTVALIdx.push_back((unsigned)Index); 2758 } 2759 2760 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 2761 InstructionList.push_back(I); 2762 break; 2763 } 2764 2765 case bitc::FUNC_CODE_INST_INSERTVAL: { 2766 // INSERTVAL: [opty, opval, opty, opval, n x indices] 2767 unsigned OpNum = 0; 2768 Value *Agg; 2769 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2770 return Error("Invalid record"); 2771 Value *Val; 2772 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 2773 return Error("Invalid record"); 2774 2775 SmallVector<unsigned, 4> INSERTVALIdx; 2776 for (unsigned RecSize = Record.size(); 2777 OpNum != RecSize; ++OpNum) { 2778 uint64_t Index = Record[OpNum]; 2779 if ((unsigned)Index != Index) 2780 return Error("Invalid value"); 2781 INSERTVALIdx.push_back((unsigned)Index); 2782 } 2783 2784 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 2785 InstructionList.push_back(I); 2786 break; 2787 } 2788 2789 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 2790 // obsolete form of select 2791 // handles select i1 ... in old bitcode 2792 unsigned OpNum = 0; 2793 Value *TrueVal, *FalseVal, *Cond; 2794 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2795 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 2796 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 2797 return Error("Invalid record"); 2798 2799 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2800 InstructionList.push_back(I); 2801 break; 2802 } 2803 2804 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 2805 // new form of select 2806 // handles select i1 or select [N x i1] 2807 unsigned OpNum = 0; 2808 Value *TrueVal, *FalseVal, *Cond; 2809 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2810 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 2811 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 2812 return Error("Invalid record"); 2813 2814 // select condition can be either i1 or [N x i1] 2815 if (VectorType* vector_type = 2816 dyn_cast<VectorType>(Cond->getType())) { 2817 // expect <n x i1> 2818 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 2819 return Error("Invalid type for value"); 2820 } else { 2821 // expect i1 2822 if (Cond->getType() != Type::getInt1Ty(Context)) 2823 return Error("Invalid type for value"); 2824 } 2825 2826 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2827 InstructionList.push_back(I); 2828 break; 2829 } 2830 2831 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 2832 unsigned OpNum = 0; 2833 Value *Vec, *Idx; 2834 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2835 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 2836 return Error("Invalid record"); 2837 I = ExtractElementInst::Create(Vec, Idx); 2838 InstructionList.push_back(I); 2839 break; 2840 } 2841 2842 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 2843 unsigned OpNum = 0; 2844 Value *Vec, *Elt, *Idx; 2845 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2846 popValue(Record, OpNum, NextValueNo, 2847 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 2848 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 2849 return Error("Invalid record"); 2850 I = InsertElementInst::Create(Vec, Elt, Idx); 2851 InstructionList.push_back(I); 2852 break; 2853 } 2854 2855 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 2856 unsigned OpNum = 0; 2857 Value *Vec1, *Vec2, *Mask; 2858 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 2859 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 2860 return Error("Invalid record"); 2861 2862 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 2863 return Error("Invalid record"); 2864 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 2865 InstructionList.push_back(I); 2866 break; 2867 } 2868 2869 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 2870 // Old form of ICmp/FCmp returning bool 2871 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 2872 // both legal on vectors but had different behaviour. 2873 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 2874 // FCmp/ICmp returning bool or vector of bool 2875 2876 unsigned OpNum = 0; 2877 Value *LHS, *RHS; 2878 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2879 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2880 OpNum+1 != Record.size()) 2881 return Error("Invalid record"); 2882 2883 if (LHS->getType()->isFPOrFPVectorTy()) 2884 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 2885 else 2886 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 2887 InstructionList.push_back(I); 2888 break; 2889 } 2890 2891 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 2892 { 2893 unsigned Size = Record.size(); 2894 if (Size == 0) { 2895 I = ReturnInst::Create(Context); 2896 InstructionList.push_back(I); 2897 break; 2898 } 2899 2900 unsigned OpNum = 0; 2901 Value *Op = nullptr; 2902 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2903 return Error("Invalid record"); 2904 if (OpNum != Record.size()) 2905 return Error("Invalid record"); 2906 2907 I = ReturnInst::Create(Context, Op); 2908 InstructionList.push_back(I); 2909 break; 2910 } 2911 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 2912 if (Record.size() != 1 && Record.size() != 3) 2913 return Error("Invalid record"); 2914 BasicBlock *TrueDest = getBasicBlock(Record[0]); 2915 if (!TrueDest) 2916 return Error("Invalid record"); 2917 2918 if (Record.size() == 1) { 2919 I = BranchInst::Create(TrueDest); 2920 InstructionList.push_back(I); 2921 } 2922 else { 2923 BasicBlock *FalseDest = getBasicBlock(Record[1]); 2924 Value *Cond = getValue(Record, 2, NextValueNo, 2925 Type::getInt1Ty(Context)); 2926 if (!FalseDest || !Cond) 2927 return Error("Invalid record"); 2928 I = BranchInst::Create(TrueDest, FalseDest, Cond); 2929 InstructionList.push_back(I); 2930 } 2931 break; 2932 } 2933 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 2934 // Check magic 2935 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 2936 // "New" SwitchInst format with case ranges. The changes to write this 2937 // format were reverted but we still recognize bitcode that uses it. 2938 // Hopefully someday we will have support for case ranges and can use 2939 // this format again. 2940 2941 Type *OpTy = getTypeByID(Record[1]); 2942 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 2943 2944 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 2945 BasicBlock *Default = getBasicBlock(Record[3]); 2946 if (!OpTy || !Cond || !Default) 2947 return Error("Invalid record"); 2948 2949 unsigned NumCases = Record[4]; 2950 2951 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 2952 InstructionList.push_back(SI); 2953 2954 unsigned CurIdx = 5; 2955 for (unsigned i = 0; i != NumCases; ++i) { 2956 SmallVector<ConstantInt*, 1> CaseVals; 2957 unsigned NumItems = Record[CurIdx++]; 2958 for (unsigned ci = 0; ci != NumItems; ++ci) { 2959 bool isSingleNumber = Record[CurIdx++]; 2960 2961 APInt Low; 2962 unsigned ActiveWords = 1; 2963 if (ValueBitWidth > 64) 2964 ActiveWords = Record[CurIdx++]; 2965 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 2966 ValueBitWidth); 2967 CurIdx += ActiveWords; 2968 2969 if (!isSingleNumber) { 2970 ActiveWords = 1; 2971 if (ValueBitWidth > 64) 2972 ActiveWords = Record[CurIdx++]; 2973 APInt High = 2974 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 2975 ValueBitWidth); 2976 CurIdx += ActiveWords; 2977 2978 // FIXME: It is not clear whether values in the range should be 2979 // compared as signed or unsigned values. The partially 2980 // implemented changes that used this format in the past used 2981 // unsigned comparisons. 2982 for ( ; Low.ule(High); ++Low) 2983 CaseVals.push_back(ConstantInt::get(Context, Low)); 2984 } else 2985 CaseVals.push_back(ConstantInt::get(Context, Low)); 2986 } 2987 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 2988 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 2989 cve = CaseVals.end(); cvi != cve; ++cvi) 2990 SI->addCase(*cvi, DestBB); 2991 } 2992 I = SI; 2993 break; 2994 } 2995 2996 // Old SwitchInst format without case ranges. 2997 2998 if (Record.size() < 3 || (Record.size() & 1) == 0) 2999 return Error("Invalid record"); 3000 Type *OpTy = getTypeByID(Record[0]); 3001 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 3002 BasicBlock *Default = getBasicBlock(Record[2]); 3003 if (!OpTy || !Cond || !Default) 3004 return Error("Invalid record"); 3005 unsigned NumCases = (Record.size()-3)/2; 3006 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 3007 InstructionList.push_back(SI); 3008 for (unsigned i = 0, e = NumCases; i != e; ++i) { 3009 ConstantInt *CaseVal = 3010 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 3011 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 3012 if (!CaseVal || !DestBB) { 3013 delete SI; 3014 return Error("Invalid record"); 3015 } 3016 SI->addCase(CaseVal, DestBB); 3017 } 3018 I = SI; 3019 break; 3020 } 3021 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 3022 if (Record.size() < 2) 3023 return Error("Invalid record"); 3024 Type *OpTy = getTypeByID(Record[0]); 3025 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 3026 if (!OpTy || !Address) 3027 return Error("Invalid record"); 3028 unsigned NumDests = Record.size()-2; 3029 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 3030 InstructionList.push_back(IBI); 3031 for (unsigned i = 0, e = NumDests; i != e; ++i) { 3032 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 3033 IBI->addDestination(DestBB); 3034 } else { 3035 delete IBI; 3036 return Error("Invalid record"); 3037 } 3038 } 3039 I = IBI; 3040 break; 3041 } 3042 3043 case bitc::FUNC_CODE_INST_INVOKE: { 3044 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 3045 if (Record.size() < 4) 3046 return Error("Invalid record"); 3047 AttributeSet PAL = getAttributes(Record[0]); 3048 unsigned CCInfo = Record[1]; 3049 BasicBlock *NormalBB = getBasicBlock(Record[2]); 3050 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 3051 3052 unsigned OpNum = 4; 3053 Value *Callee; 3054 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 3055 return Error("Invalid record"); 3056 3057 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 3058 FunctionType *FTy = !CalleeTy ? nullptr : 3059 dyn_cast<FunctionType>(CalleeTy->getElementType()); 3060 3061 // Check that the right number of fixed parameters are here. 3062 if (!FTy || !NormalBB || !UnwindBB || 3063 Record.size() < OpNum+FTy->getNumParams()) 3064 return Error("Invalid record"); 3065 3066 SmallVector<Value*, 16> Ops; 3067 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 3068 Ops.push_back(getValue(Record, OpNum, NextValueNo, 3069 FTy->getParamType(i))); 3070 if (!Ops.back()) 3071 return Error("Invalid record"); 3072 } 3073 3074 if (!FTy->isVarArg()) { 3075 if (Record.size() != OpNum) 3076 return Error("Invalid record"); 3077 } else { 3078 // Read type/value pairs for varargs params. 3079 while (OpNum != Record.size()) { 3080 Value *Op; 3081 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3082 return Error("Invalid record"); 3083 Ops.push_back(Op); 3084 } 3085 } 3086 3087 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops); 3088 InstructionList.push_back(I); 3089 cast<InvokeInst>(I)->setCallingConv( 3090 static_cast<CallingConv::ID>(CCInfo)); 3091 cast<InvokeInst>(I)->setAttributes(PAL); 3092 break; 3093 } 3094 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 3095 unsigned Idx = 0; 3096 Value *Val = nullptr; 3097 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 3098 return Error("Invalid record"); 3099 I = ResumeInst::Create(Val); 3100 InstructionList.push_back(I); 3101 break; 3102 } 3103 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 3104 I = new UnreachableInst(Context); 3105 InstructionList.push_back(I); 3106 break; 3107 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 3108 if (Record.size() < 1 || ((Record.size()-1)&1)) 3109 return Error("Invalid record"); 3110 Type *Ty = getTypeByID(Record[0]); 3111 if (!Ty) 3112 return Error("Invalid record"); 3113 3114 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 3115 InstructionList.push_back(PN); 3116 3117 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 3118 Value *V; 3119 // With the new function encoding, it is possible that operands have 3120 // negative IDs (for forward references). Use a signed VBR 3121 // representation to keep the encoding small. 3122 if (UseRelativeIDs) 3123 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 3124 else 3125 V = getValue(Record, 1+i, NextValueNo, Ty); 3126 BasicBlock *BB = getBasicBlock(Record[2+i]); 3127 if (!V || !BB) 3128 return Error("Invalid record"); 3129 PN->addIncoming(V, BB); 3130 } 3131 I = PN; 3132 break; 3133 } 3134 3135 case bitc::FUNC_CODE_INST_LANDINGPAD: { 3136 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 3137 unsigned Idx = 0; 3138 if (Record.size() < 4) 3139 return Error("Invalid record"); 3140 Type *Ty = getTypeByID(Record[Idx++]); 3141 if (!Ty) 3142 return Error("Invalid record"); 3143 Value *PersFn = nullptr; 3144 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 3145 return Error("Invalid record"); 3146 3147 bool IsCleanup = !!Record[Idx++]; 3148 unsigned NumClauses = Record[Idx++]; 3149 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses); 3150 LP->setCleanup(IsCleanup); 3151 for (unsigned J = 0; J != NumClauses; ++J) { 3152 LandingPadInst::ClauseType CT = 3153 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 3154 Value *Val; 3155 3156 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 3157 delete LP; 3158 return Error("Invalid record"); 3159 } 3160 3161 assert((CT != LandingPadInst::Catch || 3162 !isa<ArrayType>(Val->getType())) && 3163 "Catch clause has a invalid type!"); 3164 assert((CT != LandingPadInst::Filter || 3165 isa<ArrayType>(Val->getType())) && 3166 "Filter clause has invalid type!"); 3167 LP->addClause(cast<Constant>(Val)); 3168 } 3169 3170 I = LP; 3171 InstructionList.push_back(I); 3172 break; 3173 } 3174 3175 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 3176 if (Record.size() != 4) 3177 return Error("Invalid record"); 3178 PointerType *Ty = 3179 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 3180 Type *OpTy = getTypeByID(Record[1]); 3181 Value *Size = getFnValueByID(Record[2], OpTy); 3182 unsigned AlignRecord = Record[3]; 3183 bool InAlloca = AlignRecord & (1 << 5); 3184 unsigned Align = AlignRecord & ((1 << 5) - 1); 3185 if (!Ty || !Size) 3186 return Error("Invalid record"); 3187 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 3188 AI->setUsedWithInAlloca(InAlloca); 3189 I = AI; 3190 InstructionList.push_back(I); 3191 break; 3192 } 3193 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 3194 unsigned OpNum = 0; 3195 Value *Op; 3196 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3197 OpNum+2 != Record.size()) 3198 return Error("Invalid record"); 3199 3200 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 3201 InstructionList.push_back(I); 3202 break; 3203 } 3204 case bitc::FUNC_CODE_INST_LOADATOMIC: { 3205 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 3206 unsigned OpNum = 0; 3207 Value *Op; 3208 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3209 OpNum+4 != Record.size()) 3210 return Error("Invalid record"); 3211 3212 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 3213 if (Ordering == NotAtomic || Ordering == Release || 3214 Ordering == AcquireRelease) 3215 return Error("Invalid record"); 3216 if (Ordering != NotAtomic && Record[OpNum] == 0) 3217 return Error("Invalid record"); 3218 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 3219 3220 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1, 3221 Ordering, SynchScope); 3222 InstructionList.push_back(I); 3223 break; 3224 } 3225 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol] 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+2 != Record.size()) 3232 return Error("Invalid record"); 3233 3234 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 3235 InstructionList.push_back(I); 3236 break; 3237 } 3238 case bitc::FUNC_CODE_INST_STOREATOMIC: { 3239 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 3240 unsigned OpNum = 0; 3241 Value *Val, *Ptr; 3242 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3243 popValue(Record, OpNum, NextValueNo, 3244 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 3245 OpNum+4 != Record.size()) 3246 return Error("Invalid record"); 3247 3248 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 3249 if (Ordering == NotAtomic || Ordering == Acquire || 3250 Ordering == AcquireRelease) 3251 return Error("Invalid record"); 3252 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 3253 if (Ordering != NotAtomic && Record[OpNum] == 0) 3254 return Error("Invalid record"); 3255 3256 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1, 3257 Ordering, SynchScope); 3258 InstructionList.push_back(I); 3259 break; 3260 } 3261 case bitc::FUNC_CODE_INST_CMPXCHG: { 3262 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 3263 // failureordering?, isweak?] 3264 unsigned OpNum = 0; 3265 Value *Ptr, *Cmp, *New; 3266 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3267 popValue(Record, OpNum, NextValueNo, 3268 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) || 3269 popValue(Record, OpNum, NextValueNo, 3270 cast<PointerType>(Ptr->getType())->getElementType(), New) || 3271 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5)) 3272 return Error("Invalid record"); 3273 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]); 3274 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered) 3275 return Error("Invalid record"); 3276 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]); 3277 3278 AtomicOrdering FailureOrdering; 3279 if (Record.size() < 7) 3280 FailureOrdering = 3281 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 3282 else 3283 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]); 3284 3285 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 3286 SynchScope); 3287 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 3288 3289 if (Record.size() < 8) { 3290 // Before weak cmpxchgs existed, the instruction simply returned the 3291 // value loaded from memory, so bitcode files from that era will be 3292 // expecting the first component of a modern cmpxchg. 3293 CurBB->getInstList().push_back(I); 3294 I = ExtractValueInst::Create(I, 0); 3295 } else { 3296 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 3297 } 3298 3299 InstructionList.push_back(I); 3300 break; 3301 } 3302 case bitc::FUNC_CODE_INST_ATOMICRMW: { 3303 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 3304 unsigned OpNum = 0; 3305 Value *Ptr, *Val; 3306 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3307 popValue(Record, OpNum, NextValueNo, 3308 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 3309 OpNum+4 != Record.size()) 3310 return Error("Invalid record"); 3311 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]); 3312 if (Operation < AtomicRMWInst::FIRST_BINOP || 3313 Operation > AtomicRMWInst::LAST_BINOP) 3314 return Error("Invalid record"); 3315 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 3316 if (Ordering == NotAtomic || Ordering == Unordered) 3317 return Error("Invalid record"); 3318 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 3319 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 3320 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 3321 InstructionList.push_back(I); 3322 break; 3323 } 3324 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 3325 if (2 != Record.size()) 3326 return Error("Invalid record"); 3327 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]); 3328 if (Ordering == NotAtomic || Ordering == Unordered || 3329 Ordering == Monotonic) 3330 return Error("Invalid record"); 3331 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]); 3332 I = new FenceInst(Context, Ordering, SynchScope); 3333 InstructionList.push_back(I); 3334 break; 3335 } 3336 case bitc::FUNC_CODE_INST_CALL: { 3337 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 3338 if (Record.size() < 3) 3339 return Error("Invalid record"); 3340 3341 AttributeSet PAL = getAttributes(Record[0]); 3342 unsigned CCInfo = Record[1]; 3343 3344 unsigned OpNum = 2; 3345 Value *Callee; 3346 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 3347 return Error("Invalid record"); 3348 3349 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 3350 FunctionType *FTy = nullptr; 3351 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 3352 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 3353 return Error("Invalid record"); 3354 3355 SmallVector<Value*, 16> Args; 3356 // Read the fixed params. 3357 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 3358 if (FTy->getParamType(i)->isLabelTy()) 3359 Args.push_back(getBasicBlock(Record[OpNum])); 3360 else 3361 Args.push_back(getValue(Record, OpNum, NextValueNo, 3362 FTy->getParamType(i))); 3363 if (!Args.back()) 3364 return Error("Invalid record"); 3365 } 3366 3367 // Read type/value pairs for varargs params. 3368 if (!FTy->isVarArg()) { 3369 if (OpNum != Record.size()) 3370 return Error("Invalid record"); 3371 } else { 3372 while (OpNum != Record.size()) { 3373 Value *Op; 3374 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3375 return Error("Invalid record"); 3376 Args.push_back(Op); 3377 } 3378 } 3379 3380 I = CallInst::Create(Callee, Args); 3381 InstructionList.push_back(I); 3382 cast<CallInst>(I)->setCallingConv( 3383 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1)); 3384 CallInst::TailCallKind TCK = CallInst::TCK_None; 3385 if (CCInfo & 1) 3386 TCK = CallInst::TCK_Tail; 3387 if (CCInfo & (1 << 14)) 3388 TCK = CallInst::TCK_MustTail; 3389 cast<CallInst>(I)->setTailCallKind(TCK); 3390 cast<CallInst>(I)->setAttributes(PAL); 3391 break; 3392 } 3393 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 3394 if (Record.size() < 3) 3395 return Error("Invalid record"); 3396 Type *OpTy = getTypeByID(Record[0]); 3397 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 3398 Type *ResTy = getTypeByID(Record[2]); 3399 if (!OpTy || !Op || !ResTy) 3400 return Error("Invalid record"); 3401 I = new VAArgInst(Op, ResTy); 3402 InstructionList.push_back(I); 3403 break; 3404 } 3405 } 3406 3407 // Add instruction to end of current BB. If there is no current BB, reject 3408 // this file. 3409 if (!CurBB) { 3410 delete I; 3411 return Error("Invalid instruction with no BB"); 3412 } 3413 CurBB->getInstList().push_back(I); 3414 3415 // If this was a terminator instruction, move to the next block. 3416 if (isa<TerminatorInst>(I)) { 3417 ++CurBBNo; 3418 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 3419 } 3420 3421 // Non-void values get registered in the value table for future use. 3422 if (I && !I->getType()->isVoidTy()) 3423 ValueList.AssignValue(I, NextValueNo++); 3424 } 3425 3426 OutOfRecordLoop: 3427 3428 // Check the function list for unresolved values. 3429 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 3430 if (!A->getParent()) { 3431 // We found at least one unresolved value. Nuke them all to avoid leaks. 3432 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 3433 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 3434 A->replaceAllUsesWith(UndefValue::get(A->getType())); 3435 delete A; 3436 } 3437 } 3438 return Error("Never resolved value found in function"); 3439 } 3440 } 3441 3442 // FIXME: Check for unresolved forward-declared metadata references 3443 // and clean up leaks. 3444 3445 // Trim the value list down to the size it was before we parsed this function. 3446 ValueList.shrinkTo(ModuleValueListSize); 3447 MDValueList.shrinkTo(ModuleMDValueListSize); 3448 std::vector<BasicBlock*>().swap(FunctionBBs); 3449 return std::error_code(); 3450 } 3451 3452 /// Find the function body in the bitcode stream 3453 std::error_code BitcodeReader::FindFunctionInStream( 3454 Function *F, 3455 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 3456 while (DeferredFunctionInfoIterator->second == 0) { 3457 if (Stream.AtEndOfStream()) 3458 return Error("Could not find function in stream"); 3459 // ParseModule will parse the next body in the stream and set its 3460 // position in the DeferredFunctionInfo map. 3461 if (std::error_code EC = ParseModule(true)) 3462 return EC; 3463 } 3464 return std::error_code(); 3465 } 3466 3467 //===----------------------------------------------------------------------===// 3468 // GVMaterializer implementation 3469 //===----------------------------------------------------------------------===// 3470 3471 void BitcodeReader::releaseBuffer() { Buffer.release(); } 3472 3473 std::error_code BitcodeReader::materialize(GlobalValue *GV) { 3474 Function *F = dyn_cast<Function>(GV); 3475 // If it's not a function or is already material, ignore the request. 3476 if (!F || !F->isMaterializable()) 3477 return std::error_code(); 3478 3479 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 3480 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 3481 // If its position is recorded as 0, its body is somewhere in the stream 3482 // but we haven't seen it yet. 3483 if (DFII->second == 0 && LazyStreamer) 3484 if (std::error_code EC = FindFunctionInStream(F, DFII)) 3485 return EC; 3486 3487 // Move the bit stream to the saved position of the deferred function body. 3488 Stream.JumpToBit(DFII->second); 3489 3490 if (std::error_code EC = ParseFunctionBody(F)) 3491 return EC; 3492 F->setIsMaterializable(false); 3493 3494 // Upgrade any old intrinsic calls in the function. 3495 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 3496 E = UpgradedIntrinsics.end(); I != E; ++I) { 3497 if (I->first != I->second) { 3498 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3499 UI != UE;) { 3500 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3501 UpgradeIntrinsicCall(CI, I->second); 3502 } 3503 } 3504 } 3505 3506 // Bring in any functions that this function forward-referenced via 3507 // blockaddresses. 3508 return materializeForwardReferencedFunctions(); 3509 } 3510 3511 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 3512 const Function *F = dyn_cast<Function>(GV); 3513 if (!F || F->isDeclaration()) 3514 return false; 3515 3516 // Dematerializing F would leave dangling references that wouldn't be 3517 // reconnected on re-materialization. 3518 if (BlockAddressesTaken.count(F)) 3519 return false; 3520 3521 return DeferredFunctionInfo.count(const_cast<Function*>(F)); 3522 } 3523 3524 void BitcodeReader::Dematerialize(GlobalValue *GV) { 3525 Function *F = dyn_cast<Function>(GV); 3526 // If this function isn't dematerializable, this is a noop. 3527 if (!F || !isDematerializable(F)) 3528 return; 3529 3530 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 3531 3532 // Just forget the function body, we can remat it later. 3533 F->dropAllReferences(); 3534 F->setIsMaterializable(true); 3535 } 3536 3537 std::error_code BitcodeReader::MaterializeModule(Module *M) { 3538 assert(M == TheModule && 3539 "Can only Materialize the Module this BitcodeReader is attached to."); 3540 3541 // Promise to materialize all forward references. 3542 WillMaterializeAllForwardRefs = true; 3543 3544 // Iterate over the module, deserializing any functions that are still on 3545 // disk. 3546 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 3547 F != E; ++F) { 3548 if (std::error_code EC = materialize(F)) 3549 return EC; 3550 } 3551 // At this point, if there are any function bodies, the current bit is 3552 // pointing to the END_BLOCK record after them. Now make sure the rest 3553 // of the bits in the module have been read. 3554 if (NextUnreadBit) 3555 ParseModule(true); 3556 3557 // Check that all block address forward references got resolved (as we 3558 // promised above). 3559 if (!BasicBlockFwdRefs.empty()) 3560 return Error("Never resolved function from blockaddress"); 3561 3562 // Upgrade any intrinsic calls that slipped through (should not happen!) and 3563 // delete the old functions to clean up. We can't do this unless the entire 3564 // module is materialized because there could always be another function body 3565 // with calls to the old function. 3566 for (std::vector<std::pair<Function*, Function*> >::iterator I = 3567 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 3568 if (I->first != I->second) { 3569 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3570 UI != UE;) { 3571 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3572 UpgradeIntrinsicCall(CI, I->second); 3573 } 3574 if (!I->first->use_empty()) 3575 I->first->replaceAllUsesWith(I->second); 3576 I->first->eraseFromParent(); 3577 } 3578 } 3579 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 3580 3581 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 3582 UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 3583 3584 UpgradeDebugInfo(*M); 3585 return std::error_code(); 3586 } 3587 3588 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 3589 return IdentifiedStructTypes; 3590 } 3591 3592 std::error_code BitcodeReader::InitStream() { 3593 if (LazyStreamer) 3594 return InitLazyStream(); 3595 return InitStreamFromBuffer(); 3596 } 3597 3598 std::error_code BitcodeReader::InitStreamFromBuffer() { 3599 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 3600 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 3601 3602 if (Buffer->getBufferSize() & 3) 3603 return Error("Invalid bitcode signature"); 3604 3605 // If we have a wrapper header, parse it and ignore the non-bc file contents. 3606 // The magic number is 0x0B17C0DE stored in little endian. 3607 if (isBitcodeWrapper(BufPtr, BufEnd)) 3608 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 3609 return Error("Invalid bitcode wrapper header"); 3610 3611 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 3612 Stream.init(&*StreamFile); 3613 3614 return std::error_code(); 3615 } 3616 3617 std::error_code BitcodeReader::InitLazyStream() { 3618 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 3619 // see it. 3620 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer); 3621 StreamingMemoryObject &Bytes = *OwnedBytes; 3622 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 3623 Stream.init(&*StreamFile); 3624 3625 unsigned char buf[16]; 3626 if (Bytes.readBytes(buf, 16, 0) != 16) 3627 return Error("Invalid bitcode signature"); 3628 3629 if (!isBitcode(buf, buf + 16)) 3630 return Error("Invalid bitcode signature"); 3631 3632 if (isBitcodeWrapper(buf, buf + 4)) { 3633 const unsigned char *bitcodeStart = buf; 3634 const unsigned char *bitcodeEnd = buf + 16; 3635 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 3636 Bytes.dropLeadingBytes(bitcodeStart - buf); 3637 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 3638 } 3639 return std::error_code(); 3640 } 3641 3642 namespace { 3643 class BitcodeErrorCategoryType : public std::error_category { 3644 const char *name() const LLVM_NOEXCEPT override { 3645 return "llvm.bitcode"; 3646 } 3647 std::string message(int IE) const override { 3648 BitcodeError E = static_cast<BitcodeError>(IE); 3649 switch (E) { 3650 case BitcodeError::InvalidBitcodeSignature: 3651 return "Invalid bitcode signature"; 3652 case BitcodeError::CorruptedBitcode: 3653 return "Corrupted bitcode"; 3654 } 3655 llvm_unreachable("Unknown error type!"); 3656 } 3657 }; 3658 } 3659 3660 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 3661 3662 const std::error_category &llvm::BitcodeErrorCategory() { 3663 return *ErrorCategory; 3664 } 3665 3666 //===----------------------------------------------------------------------===// 3667 // External interface 3668 //===----------------------------------------------------------------------===// 3669 3670 /// \brief Get a lazy one-at-time loading module from bitcode. 3671 /// 3672 /// This isn't always used in a lazy context. In particular, it's also used by 3673 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull 3674 /// in forward-referenced functions from block address references. 3675 /// 3676 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to 3677 /// materialize everything -- in particular, if this isn't truly lazy. 3678 static ErrorOr<Module *> 3679 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer, 3680 LLVMContext &Context, bool WillMaterializeAll, 3681 DiagnosticHandlerFunction DiagnosticHandler) { 3682 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 3683 BitcodeReader *R = 3684 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler); 3685 M->setMaterializer(R); 3686 3687 auto cleanupOnError = [&](std::error_code EC) { 3688 R->releaseBuffer(); // Never take ownership on error. 3689 delete M; // Also deletes R. 3690 return EC; 3691 }; 3692 3693 if (std::error_code EC = R->ParseBitcodeInto(M)) 3694 return cleanupOnError(EC); 3695 3696 if (!WillMaterializeAll) 3697 // Resolve forward references from blockaddresses. 3698 if (std::error_code EC = R->materializeForwardReferencedFunctions()) 3699 return cleanupOnError(EC); 3700 3701 Buffer.release(); // The BitcodeReader owns it now. 3702 return M; 3703 } 3704 3705 ErrorOr<Module *> 3706 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 3707 LLVMContext &Context, 3708 DiagnosticHandlerFunction DiagnosticHandler) { 3709 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false, 3710 DiagnosticHandler); 3711 } 3712 3713 ErrorOr<std::unique_ptr<Module>> 3714 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer, 3715 LLVMContext &Context, 3716 DiagnosticHandlerFunction DiagnosticHandler) { 3717 std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 3718 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler); 3719 M->setMaterializer(R); 3720 if (std::error_code EC = R->ParseBitcodeInto(M.get())) 3721 return EC; 3722 return std::move(M); 3723 } 3724 3725 ErrorOr<Module *> 3726 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 3727 DiagnosticHandlerFunction DiagnosticHandler) { 3728 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 3729 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl( 3730 std::move(Buf), Context, true, DiagnosticHandler); 3731 if (!ModuleOrErr) 3732 return ModuleOrErr; 3733 Module *M = ModuleOrErr.get(); 3734 // Read in the entire module, and destroy the BitcodeReader. 3735 if (std::error_code EC = M->materializeAllPermanently()) { 3736 delete M; 3737 return EC; 3738 } 3739 3740 // TODO: Restore the use-lists to the in-memory state when the bitcode was 3741 // written. We must defer until the Module has been fully materialized. 3742 3743 return M; 3744 } 3745 3746 std::string 3747 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context, 3748 DiagnosticHandlerFunction DiagnosticHandler) { 3749 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 3750 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context, 3751 DiagnosticHandler); 3752 ErrorOr<std::string> Triple = R->parseTriple(); 3753 if (Triple.getError()) 3754 return ""; 3755 return Triple.get(); 3756 } 3757