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