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