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