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