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