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