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 SmallString<8> String(Record.begin(), Record.end()); 1066 Value *V = MDString::get(Context, String); 1067 MDValueList.AssignValue(V, NextMDValueNo++); 1068 break; 1069 } 1070 case bitc::METADATA_KIND: { 1071 if (Record.size() < 2) 1072 return Error(InvalidRecord); 1073 1074 unsigned Kind = Record[0]; 1075 SmallString<8> Name(Record.begin()+1, Record.end()); 1076 1077 unsigned NewKind = TheModule->getMDKindID(Name.str()); 1078 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1079 return Error(ConflictingMETADATA_KINDRecords); 1080 break; 1081 } 1082 } 1083 } 1084 } 1085 1086 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in 1087 /// the LSB for dense VBR encoding. 1088 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 1089 if ((V & 1) == 0) 1090 return V >> 1; 1091 if (V != 1) 1092 return -(V >> 1); 1093 // There is no such thing as -0 with integers. "-0" really means MININT. 1094 return 1ULL << 63; 1095 } 1096 1097 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 1098 /// values and aliases that we can. 1099 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() { 1100 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 1101 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 1102 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 1103 1104 GlobalInitWorklist.swap(GlobalInits); 1105 AliasInitWorklist.swap(AliasInits); 1106 FunctionPrefixWorklist.swap(FunctionPrefixes); 1107 1108 while (!GlobalInitWorklist.empty()) { 1109 unsigned ValID = GlobalInitWorklist.back().second; 1110 if (ValID >= ValueList.size()) { 1111 // Not ready to resolve this yet, it requires something later in the file. 1112 GlobalInits.push_back(GlobalInitWorklist.back()); 1113 } else { 1114 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1115 GlobalInitWorklist.back().first->setInitializer(C); 1116 else 1117 return Error(ExpectedConstant); 1118 } 1119 GlobalInitWorklist.pop_back(); 1120 } 1121 1122 while (!AliasInitWorklist.empty()) { 1123 unsigned ValID = AliasInitWorklist.back().second; 1124 if (ValID >= ValueList.size()) { 1125 AliasInits.push_back(AliasInitWorklist.back()); 1126 } else { 1127 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1128 AliasInitWorklist.back().first->setAliasee(C); 1129 else 1130 return Error(ExpectedConstant); 1131 } 1132 AliasInitWorklist.pop_back(); 1133 } 1134 1135 while (!FunctionPrefixWorklist.empty()) { 1136 unsigned ValID = FunctionPrefixWorklist.back().second; 1137 if (ValID >= ValueList.size()) { 1138 FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 1139 } else { 1140 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1141 FunctionPrefixWorklist.back().first->setPrefixData(C); 1142 else 1143 return Error(ExpectedConstant); 1144 } 1145 FunctionPrefixWorklist.pop_back(); 1146 } 1147 1148 return std::error_code(); 1149 } 1150 1151 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 1152 SmallVector<uint64_t, 8> Words(Vals.size()); 1153 std::transform(Vals.begin(), Vals.end(), Words.begin(), 1154 BitcodeReader::decodeSignRotatedValue); 1155 1156 return APInt(TypeBits, Words); 1157 } 1158 1159 std::error_code BitcodeReader::ParseConstants() { 1160 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 1161 return Error(InvalidRecord); 1162 1163 SmallVector<uint64_t, 64> Record; 1164 1165 // Read all the records for this value table. 1166 Type *CurTy = Type::getInt32Ty(Context); 1167 unsigned NextCstNo = ValueList.size(); 1168 while (1) { 1169 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1170 1171 switch (Entry.Kind) { 1172 case BitstreamEntry::SubBlock: // Handled for us already. 1173 case BitstreamEntry::Error: 1174 return Error(MalformedBlock); 1175 case BitstreamEntry::EndBlock: 1176 if (NextCstNo != ValueList.size()) 1177 return Error(InvalidConstantReference); 1178 1179 // Once all the constants have been read, go through and resolve forward 1180 // references. 1181 ValueList.ResolveConstantForwardRefs(); 1182 return std::error_code(); 1183 case BitstreamEntry::Record: 1184 // The interesting case. 1185 break; 1186 } 1187 1188 // Read a record. 1189 Record.clear(); 1190 Value *V = nullptr; 1191 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 1192 switch (BitCode) { 1193 default: // Default behavior: unknown constant 1194 case bitc::CST_CODE_UNDEF: // UNDEF 1195 V = UndefValue::get(CurTy); 1196 break; 1197 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 1198 if (Record.empty()) 1199 return Error(InvalidRecord); 1200 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 1201 return Error(InvalidRecord); 1202 CurTy = TypeList[Record[0]]; 1203 continue; // Skip the ValueList manipulation. 1204 case bitc::CST_CODE_NULL: // NULL 1205 V = Constant::getNullValue(CurTy); 1206 break; 1207 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 1208 if (!CurTy->isIntegerTy() || Record.empty()) 1209 return Error(InvalidRecord); 1210 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 1211 break; 1212 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 1213 if (!CurTy->isIntegerTy() || Record.empty()) 1214 return Error(InvalidRecord); 1215 1216 APInt VInt = ReadWideAPInt(Record, 1217 cast<IntegerType>(CurTy)->getBitWidth()); 1218 V = ConstantInt::get(Context, VInt); 1219 1220 break; 1221 } 1222 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 1223 if (Record.empty()) 1224 return Error(InvalidRecord); 1225 if (CurTy->isHalfTy()) 1226 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 1227 APInt(16, (uint16_t)Record[0]))); 1228 else if (CurTy->isFloatTy()) 1229 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 1230 APInt(32, (uint32_t)Record[0]))); 1231 else if (CurTy->isDoubleTy()) 1232 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 1233 APInt(64, Record[0]))); 1234 else if (CurTy->isX86_FP80Ty()) { 1235 // Bits are not stored the same way as a normal i80 APInt, compensate. 1236 uint64_t Rearrange[2]; 1237 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 1238 Rearrange[1] = Record[0] >> 48; 1239 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 1240 APInt(80, Rearrange))); 1241 } else if (CurTy->isFP128Ty()) 1242 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 1243 APInt(128, Record))); 1244 else if (CurTy->isPPC_FP128Ty()) 1245 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 1246 APInt(128, Record))); 1247 else 1248 V = UndefValue::get(CurTy); 1249 break; 1250 } 1251 1252 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 1253 if (Record.empty()) 1254 return Error(InvalidRecord); 1255 1256 unsigned Size = Record.size(); 1257 SmallVector<Constant*, 16> Elts; 1258 1259 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 1260 for (unsigned i = 0; i != Size; ++i) 1261 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 1262 STy->getElementType(i))); 1263 V = ConstantStruct::get(STy, Elts); 1264 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 1265 Type *EltTy = ATy->getElementType(); 1266 for (unsigned i = 0; i != Size; ++i) 1267 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1268 V = ConstantArray::get(ATy, Elts); 1269 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 1270 Type *EltTy = VTy->getElementType(); 1271 for (unsigned i = 0; i != Size; ++i) 1272 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1273 V = ConstantVector::get(Elts); 1274 } else { 1275 V = UndefValue::get(CurTy); 1276 } 1277 break; 1278 } 1279 case bitc::CST_CODE_STRING: // STRING: [values] 1280 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 1281 if (Record.empty()) 1282 return Error(InvalidRecord); 1283 1284 SmallString<16> Elts(Record.begin(), Record.end()); 1285 V = ConstantDataArray::getString(Context, Elts, 1286 BitCode == bitc::CST_CODE_CSTRING); 1287 break; 1288 } 1289 case bitc::CST_CODE_DATA: {// DATA: [n x value] 1290 if (Record.empty()) 1291 return Error(InvalidRecord); 1292 1293 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 1294 unsigned Size = Record.size(); 1295 1296 if (EltTy->isIntegerTy(8)) { 1297 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 1298 if (isa<VectorType>(CurTy)) 1299 V = ConstantDataVector::get(Context, Elts); 1300 else 1301 V = ConstantDataArray::get(Context, Elts); 1302 } else if (EltTy->isIntegerTy(16)) { 1303 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 1304 if (isa<VectorType>(CurTy)) 1305 V = ConstantDataVector::get(Context, Elts); 1306 else 1307 V = ConstantDataArray::get(Context, Elts); 1308 } else if (EltTy->isIntegerTy(32)) { 1309 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 1310 if (isa<VectorType>(CurTy)) 1311 V = ConstantDataVector::get(Context, Elts); 1312 else 1313 V = ConstantDataArray::get(Context, Elts); 1314 } else if (EltTy->isIntegerTy(64)) { 1315 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 1316 if (isa<VectorType>(CurTy)) 1317 V = ConstantDataVector::get(Context, Elts); 1318 else 1319 V = ConstantDataArray::get(Context, Elts); 1320 } else if (EltTy->isFloatTy()) { 1321 SmallVector<float, 16> Elts(Size); 1322 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); 1323 if (isa<VectorType>(CurTy)) 1324 V = ConstantDataVector::get(Context, Elts); 1325 else 1326 V = ConstantDataArray::get(Context, Elts); 1327 } else if (EltTy->isDoubleTy()) { 1328 SmallVector<double, 16> Elts(Size); 1329 std::transform(Record.begin(), Record.end(), Elts.begin(), 1330 BitsToDouble); 1331 if (isa<VectorType>(CurTy)) 1332 V = ConstantDataVector::get(Context, Elts); 1333 else 1334 V = ConstantDataArray::get(Context, Elts); 1335 } else { 1336 return Error(InvalidTypeForValue); 1337 } 1338 break; 1339 } 1340 1341 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 1342 if (Record.size() < 3) 1343 return Error(InvalidRecord); 1344 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 1345 if (Opc < 0) { 1346 V = UndefValue::get(CurTy); // Unknown binop. 1347 } else { 1348 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 1349 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 1350 unsigned Flags = 0; 1351 if (Record.size() >= 4) { 1352 if (Opc == Instruction::Add || 1353 Opc == Instruction::Sub || 1354 Opc == Instruction::Mul || 1355 Opc == Instruction::Shl) { 1356 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 1357 Flags |= OverflowingBinaryOperator::NoSignedWrap; 1358 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 1359 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 1360 } else if (Opc == Instruction::SDiv || 1361 Opc == Instruction::UDiv || 1362 Opc == Instruction::LShr || 1363 Opc == Instruction::AShr) { 1364 if (Record[3] & (1 << bitc::PEO_EXACT)) 1365 Flags |= SDivOperator::IsExact; 1366 } 1367 } 1368 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 1369 } 1370 break; 1371 } 1372 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 1373 if (Record.size() < 3) 1374 return Error(InvalidRecord); 1375 int Opc = GetDecodedCastOpcode(Record[0]); 1376 if (Opc < 0) { 1377 V = UndefValue::get(CurTy); // Unknown cast. 1378 } else { 1379 Type *OpTy = getTypeByID(Record[1]); 1380 if (!OpTy) 1381 return Error(InvalidRecord); 1382 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 1383 V = UpgradeBitCastExpr(Opc, Op, CurTy); 1384 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 1385 } 1386 break; 1387 } 1388 case bitc::CST_CODE_CE_INBOUNDS_GEP: 1389 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 1390 if (Record.size() & 1) 1391 return Error(InvalidRecord); 1392 SmallVector<Constant*, 16> Elts; 1393 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1394 Type *ElTy = getTypeByID(Record[i]); 1395 if (!ElTy) 1396 return Error(InvalidRecord); 1397 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 1398 } 1399 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 1400 V = ConstantExpr::getGetElementPtr(Elts[0], Indices, 1401 BitCode == 1402 bitc::CST_CODE_CE_INBOUNDS_GEP); 1403 break; 1404 } 1405 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 1406 if (Record.size() < 3) 1407 return Error(InvalidRecord); 1408 1409 Type *SelectorTy = Type::getInt1Ty(Context); 1410 1411 // If CurTy is a vector of length n, then Record[0] must be a <n x i1> 1412 // vector. Otherwise, it must be a single bit. 1413 if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 1414 SelectorTy = VectorType::get(Type::getInt1Ty(Context), 1415 VTy->getNumElements()); 1416 1417 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 1418 SelectorTy), 1419 ValueList.getConstantFwdRef(Record[1],CurTy), 1420 ValueList.getConstantFwdRef(Record[2],CurTy)); 1421 break; 1422 } 1423 case bitc::CST_CODE_CE_EXTRACTELT 1424 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 1425 if (Record.size() < 3) 1426 return Error(InvalidRecord); 1427 VectorType *OpTy = 1428 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1429 if (!OpTy) 1430 return Error(InvalidRecord); 1431 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1432 Constant *Op1 = nullptr; 1433 if (Record.size() == 4) { 1434 Type *IdxTy = getTypeByID(Record[2]); 1435 if (!IdxTy) 1436 return Error(InvalidRecord); 1437 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 1438 } else // TODO: Remove with llvm 4.0 1439 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1440 if (!Op1) 1441 return Error(InvalidRecord); 1442 V = ConstantExpr::getExtractElement(Op0, Op1); 1443 break; 1444 } 1445 case bitc::CST_CODE_CE_INSERTELT 1446 : { // CE_INSERTELT: [opval, opval, opty, opval] 1447 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1448 if (Record.size() < 3 || !OpTy) 1449 return Error(InvalidRecord); 1450 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1451 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 1452 OpTy->getElementType()); 1453 Constant *Op2 = nullptr; 1454 if (Record.size() == 4) { 1455 Type *IdxTy = getTypeByID(Record[2]); 1456 if (!IdxTy) 1457 return Error(InvalidRecord); 1458 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 1459 } else // TODO: Remove with llvm 4.0 1460 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1461 if (!Op2) 1462 return Error(InvalidRecord); 1463 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 1464 break; 1465 } 1466 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 1467 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1468 if (Record.size() < 3 || !OpTy) 1469 return Error(InvalidRecord); 1470 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1471 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 1472 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1473 OpTy->getNumElements()); 1474 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 1475 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1476 break; 1477 } 1478 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 1479 VectorType *RTy = dyn_cast<VectorType>(CurTy); 1480 VectorType *OpTy = 1481 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1482 if (Record.size() < 4 || !RTy || !OpTy) 1483 return Error(InvalidRecord); 1484 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1485 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1486 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1487 RTy->getNumElements()); 1488 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 1489 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1490 break; 1491 } 1492 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 1493 if (Record.size() < 4) 1494 return Error(InvalidRecord); 1495 Type *OpTy = getTypeByID(Record[0]); 1496 if (!OpTy) 1497 return Error(InvalidRecord); 1498 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1499 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1500 1501 if (OpTy->isFPOrFPVectorTy()) 1502 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 1503 else 1504 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 1505 break; 1506 } 1507 // This maintains backward compatibility, pre-asm dialect keywords. 1508 // FIXME: Remove with the 4.0 release. 1509 case bitc::CST_CODE_INLINEASM_OLD: { 1510 if (Record.size() < 2) 1511 return Error(InvalidRecord); 1512 std::string AsmStr, ConstrStr; 1513 bool HasSideEffects = Record[0] & 1; 1514 bool IsAlignStack = Record[0] >> 1; 1515 unsigned AsmStrSize = Record[1]; 1516 if (2+AsmStrSize >= Record.size()) 1517 return Error(InvalidRecord); 1518 unsigned ConstStrSize = Record[2+AsmStrSize]; 1519 if (3+AsmStrSize+ConstStrSize > Record.size()) 1520 return Error(InvalidRecord); 1521 1522 for (unsigned i = 0; i != AsmStrSize; ++i) 1523 AsmStr += (char)Record[2+i]; 1524 for (unsigned i = 0; i != ConstStrSize; ++i) 1525 ConstrStr += (char)Record[3+AsmStrSize+i]; 1526 PointerType *PTy = cast<PointerType>(CurTy); 1527 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1528 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 1529 break; 1530 } 1531 // This version adds support for the asm dialect keywords (e.g., 1532 // inteldialect). 1533 case bitc::CST_CODE_INLINEASM: { 1534 if (Record.size() < 2) 1535 return Error(InvalidRecord); 1536 std::string AsmStr, ConstrStr; 1537 bool HasSideEffects = Record[0] & 1; 1538 bool IsAlignStack = (Record[0] >> 1) & 1; 1539 unsigned AsmDialect = Record[0] >> 2; 1540 unsigned AsmStrSize = Record[1]; 1541 if (2+AsmStrSize >= Record.size()) 1542 return Error(InvalidRecord); 1543 unsigned ConstStrSize = Record[2+AsmStrSize]; 1544 if (3+AsmStrSize+ConstStrSize > Record.size()) 1545 return Error(InvalidRecord); 1546 1547 for (unsigned i = 0; i != AsmStrSize; ++i) 1548 AsmStr += (char)Record[2+i]; 1549 for (unsigned i = 0; i != ConstStrSize; ++i) 1550 ConstrStr += (char)Record[3+AsmStrSize+i]; 1551 PointerType *PTy = cast<PointerType>(CurTy); 1552 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1553 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 1554 InlineAsm::AsmDialect(AsmDialect)); 1555 break; 1556 } 1557 case bitc::CST_CODE_BLOCKADDRESS:{ 1558 if (Record.size() < 3) 1559 return Error(InvalidRecord); 1560 Type *FnTy = getTypeByID(Record[0]); 1561 if (!FnTy) 1562 return Error(InvalidRecord); 1563 Function *Fn = 1564 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 1565 if (!Fn) 1566 return Error(InvalidRecord); 1567 1568 // If the function is already parsed we can insert the block address right 1569 // away. 1570 if (!Fn->empty()) { 1571 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 1572 for (size_t I = 0, E = Record[2]; I != E; ++I) { 1573 if (BBI == BBE) 1574 return Error(InvalidID); 1575 ++BBI; 1576 } 1577 V = BlockAddress::get(Fn, BBI); 1578 } else { 1579 // Otherwise insert a placeholder and remember it so it can be inserted 1580 // when the function is parsed. 1581 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(), 1582 Type::getInt8Ty(Context), 1583 false, GlobalValue::InternalLinkage, 1584 nullptr, ""); 1585 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef)); 1586 V = FwdRef; 1587 } 1588 break; 1589 } 1590 } 1591 1592 ValueList.AssignValue(V, NextCstNo); 1593 ++NextCstNo; 1594 } 1595 } 1596 1597 std::error_code BitcodeReader::ParseUseLists() { 1598 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 1599 return Error(InvalidRecord); 1600 1601 SmallVector<uint64_t, 64> Record; 1602 1603 // Read all the records. 1604 while (1) { 1605 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1606 1607 switch (Entry.Kind) { 1608 case BitstreamEntry::SubBlock: // Handled for us already. 1609 case BitstreamEntry::Error: 1610 return Error(MalformedBlock); 1611 case BitstreamEntry::EndBlock: 1612 return std::error_code(); 1613 case BitstreamEntry::Record: 1614 // The interesting case. 1615 break; 1616 } 1617 1618 // Read a use list record. 1619 Record.clear(); 1620 switch (Stream.readRecord(Entry.ID, Record)) { 1621 default: // Default behavior: unknown type. 1622 break; 1623 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD. 1624 unsigned RecordLength = Record.size(); 1625 if (RecordLength < 1) 1626 return Error(InvalidRecord); 1627 UseListRecords.push_back(Record); 1628 break; 1629 } 1630 } 1631 } 1632 } 1633 1634 /// RememberAndSkipFunctionBody - When we see the block for a function body, 1635 /// remember where it is and then skip it. This lets us lazily deserialize the 1636 /// functions. 1637 std::error_code BitcodeReader::RememberAndSkipFunctionBody() { 1638 // Get the function we are talking about. 1639 if (FunctionsWithBodies.empty()) 1640 return Error(InsufficientFunctionProtos); 1641 1642 Function *Fn = FunctionsWithBodies.back(); 1643 FunctionsWithBodies.pop_back(); 1644 1645 // Save the current stream state. 1646 uint64_t CurBit = Stream.GetCurrentBitNo(); 1647 DeferredFunctionInfo[Fn] = CurBit; 1648 1649 // Skip over the function block for now. 1650 if (Stream.SkipBlock()) 1651 return Error(InvalidRecord); 1652 return std::error_code(); 1653 } 1654 1655 std::error_code BitcodeReader::GlobalCleanup() { 1656 // Patch the initializers for globals and aliases up. 1657 ResolveGlobalAndAliasInits(); 1658 if (!GlobalInits.empty() || !AliasInits.empty()) 1659 return Error(MalformedGlobalInitializerSet); 1660 1661 // Look for intrinsic functions which need to be upgraded at some point 1662 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 1663 FI != FE; ++FI) { 1664 Function *NewFn; 1665 if (UpgradeIntrinsicFunction(FI, NewFn)) 1666 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 1667 } 1668 1669 // Look for global variables which need to be renamed. 1670 for (Module::global_iterator 1671 GI = TheModule->global_begin(), GE = TheModule->global_end(); 1672 GI != GE;) { 1673 GlobalVariable *GV = GI++; 1674 UpgradeGlobalVariable(GV); 1675 } 1676 1677 // Force deallocation of memory for these vectors to favor the client that 1678 // want lazy deserialization. 1679 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 1680 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 1681 return std::error_code(); 1682 } 1683 1684 std::error_code BitcodeReader::ParseModule(bool Resume) { 1685 if (Resume) 1686 Stream.JumpToBit(NextUnreadBit); 1687 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 1688 return Error(InvalidRecord); 1689 1690 SmallVector<uint64_t, 64> Record; 1691 std::vector<std::string> SectionTable; 1692 std::vector<std::string> GCTable; 1693 1694 // Read all the records for this module. 1695 while (1) { 1696 BitstreamEntry Entry = Stream.advance(); 1697 1698 switch (Entry.Kind) { 1699 case BitstreamEntry::Error: 1700 return Error(MalformedBlock); 1701 case BitstreamEntry::EndBlock: 1702 return GlobalCleanup(); 1703 1704 case BitstreamEntry::SubBlock: 1705 switch (Entry.ID) { 1706 default: // Skip unknown content. 1707 if (Stream.SkipBlock()) 1708 return Error(InvalidRecord); 1709 break; 1710 case bitc::BLOCKINFO_BLOCK_ID: 1711 if (Stream.ReadBlockInfoBlock()) 1712 return Error(MalformedBlock); 1713 break; 1714 case bitc::PARAMATTR_BLOCK_ID: 1715 if (std::error_code EC = ParseAttributeBlock()) 1716 return EC; 1717 break; 1718 case bitc::PARAMATTR_GROUP_BLOCK_ID: 1719 if (std::error_code EC = ParseAttributeGroupBlock()) 1720 return EC; 1721 break; 1722 case bitc::TYPE_BLOCK_ID_NEW: 1723 if (std::error_code EC = ParseTypeTable()) 1724 return EC; 1725 break; 1726 case bitc::VALUE_SYMTAB_BLOCK_ID: 1727 if (std::error_code EC = ParseValueSymbolTable()) 1728 return EC; 1729 SeenValueSymbolTable = true; 1730 break; 1731 case bitc::CONSTANTS_BLOCK_ID: 1732 if (std::error_code EC = ParseConstants()) 1733 return EC; 1734 if (std::error_code EC = ResolveGlobalAndAliasInits()) 1735 return EC; 1736 break; 1737 case bitc::METADATA_BLOCK_ID: 1738 if (std::error_code EC = ParseMetadata()) 1739 return EC; 1740 break; 1741 case bitc::FUNCTION_BLOCK_ID: 1742 // If this is the first function body we've seen, reverse the 1743 // FunctionsWithBodies list. 1744 if (!SeenFirstFunctionBody) { 1745 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 1746 if (std::error_code EC = GlobalCleanup()) 1747 return EC; 1748 SeenFirstFunctionBody = true; 1749 } 1750 1751 if (std::error_code EC = RememberAndSkipFunctionBody()) 1752 return EC; 1753 // For streaming bitcode, suspend parsing when we reach the function 1754 // bodies. Subsequent materialization calls will resume it when 1755 // necessary. For streaming, the function bodies must be at the end of 1756 // the bitcode. If the bitcode file is old, the symbol table will be 1757 // at the end instead and will not have been seen yet. In this case, 1758 // just finish the parse now. 1759 if (LazyStreamer && SeenValueSymbolTable) { 1760 NextUnreadBit = Stream.GetCurrentBitNo(); 1761 return std::error_code(); 1762 } 1763 break; 1764 case bitc::USELIST_BLOCK_ID: 1765 if (std::error_code EC = ParseUseLists()) 1766 return EC; 1767 break; 1768 } 1769 continue; 1770 1771 case BitstreamEntry::Record: 1772 // The interesting case. 1773 break; 1774 } 1775 1776 1777 // Read a record. 1778 switch (Stream.readRecord(Entry.ID, Record)) { 1779 default: break; // Default behavior, ignore unknown content. 1780 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 1781 if (Record.size() < 1) 1782 return Error(InvalidRecord); 1783 // Only version #0 and #1 are supported so far. 1784 unsigned module_version = Record[0]; 1785 switch (module_version) { 1786 default: 1787 return Error(InvalidValue); 1788 case 0: 1789 UseRelativeIDs = false; 1790 break; 1791 case 1: 1792 UseRelativeIDs = true; 1793 break; 1794 } 1795 break; 1796 } 1797 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 1798 std::string S; 1799 if (ConvertToString(Record, 0, S)) 1800 return Error(InvalidRecord); 1801 TheModule->setTargetTriple(S); 1802 break; 1803 } 1804 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 1805 std::string S; 1806 if (ConvertToString(Record, 0, S)) 1807 return Error(InvalidRecord); 1808 TheModule->setDataLayout(S); 1809 break; 1810 } 1811 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 1812 std::string S; 1813 if (ConvertToString(Record, 0, S)) 1814 return Error(InvalidRecord); 1815 TheModule->setModuleInlineAsm(S); 1816 break; 1817 } 1818 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 1819 // FIXME: Remove in 4.0. 1820 std::string S; 1821 if (ConvertToString(Record, 0, S)) 1822 return Error(InvalidRecord); 1823 // Ignore value. 1824 break; 1825 } 1826 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 1827 std::string S; 1828 if (ConvertToString(Record, 0, S)) 1829 return Error(InvalidRecord); 1830 SectionTable.push_back(S); 1831 break; 1832 } 1833 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 1834 std::string S; 1835 if (ConvertToString(Record, 0, S)) 1836 return Error(InvalidRecord); 1837 GCTable.push_back(S); 1838 break; 1839 } 1840 // GLOBALVAR: [pointer type, isconst, initid, 1841 // linkage, alignment, section, visibility, threadlocal, 1842 // unnamed_addr, dllstorageclass] 1843 case bitc::MODULE_CODE_GLOBALVAR: { 1844 if (Record.size() < 6) 1845 return Error(InvalidRecord); 1846 Type *Ty = getTypeByID(Record[0]); 1847 if (!Ty) 1848 return Error(InvalidRecord); 1849 if (!Ty->isPointerTy()) 1850 return Error(InvalidTypeForValue); 1851 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 1852 Ty = cast<PointerType>(Ty)->getElementType(); 1853 1854 bool isConstant = Record[1]; 1855 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 1856 unsigned Alignment = (1 << Record[4]) >> 1; 1857 std::string Section; 1858 if (Record[5]) { 1859 if (Record[5]-1 >= SectionTable.size()) 1860 return Error(InvalidID); 1861 Section = SectionTable[Record[5]-1]; 1862 } 1863 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 1864 // Local linkage must have default visibility. 1865 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 1866 // FIXME: Change to an error if non-default in 4.0. 1867 Visibility = GetDecodedVisibility(Record[6]); 1868 1869 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 1870 if (Record.size() > 7) 1871 TLM = GetDecodedThreadLocalMode(Record[7]); 1872 1873 bool UnnamedAddr = false; 1874 if (Record.size() > 8) 1875 UnnamedAddr = Record[8]; 1876 1877 bool ExternallyInitialized = false; 1878 if (Record.size() > 9) 1879 ExternallyInitialized = Record[9]; 1880 1881 GlobalVariable *NewGV = 1882 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 1883 TLM, AddressSpace, ExternallyInitialized); 1884 NewGV->setAlignment(Alignment); 1885 if (!Section.empty()) 1886 NewGV->setSection(Section); 1887 NewGV->setVisibility(Visibility); 1888 NewGV->setUnnamedAddr(UnnamedAddr); 1889 1890 if (Record.size() > 10) 1891 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10])); 1892 else 1893 UpgradeDLLImportExportLinkage(NewGV, Record[3]); 1894 1895 ValueList.push_back(NewGV); 1896 1897 // Remember which value to use for the global initializer. 1898 if (unsigned InitID = Record[2]) 1899 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 1900 break; 1901 } 1902 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 1903 // alignment, section, visibility, gc, unnamed_addr, 1904 // dllstorageclass] 1905 case bitc::MODULE_CODE_FUNCTION: { 1906 if (Record.size() < 8) 1907 return Error(InvalidRecord); 1908 Type *Ty = getTypeByID(Record[0]); 1909 if (!Ty) 1910 return Error(InvalidRecord); 1911 if (!Ty->isPointerTy()) 1912 return Error(InvalidTypeForValue); 1913 FunctionType *FTy = 1914 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 1915 if (!FTy) 1916 return Error(InvalidTypeForValue); 1917 1918 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 1919 "", TheModule); 1920 1921 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 1922 bool isProto = Record[2]; 1923 Func->setLinkage(GetDecodedLinkage(Record[3])); 1924 Func->setAttributes(getAttributes(Record[4])); 1925 1926 Func->setAlignment((1 << Record[5]) >> 1); 1927 if (Record[6]) { 1928 if (Record[6]-1 >= SectionTable.size()) 1929 return Error(InvalidID); 1930 Func->setSection(SectionTable[Record[6]-1]); 1931 } 1932 // Local linkage must have default visibility. 1933 if (!Func->hasLocalLinkage()) 1934 // FIXME: Change to an error if non-default in 4.0. 1935 Func->setVisibility(GetDecodedVisibility(Record[7])); 1936 if (Record.size() > 8 && Record[8]) { 1937 if (Record[8]-1 > GCTable.size()) 1938 return Error(InvalidID); 1939 Func->setGC(GCTable[Record[8]-1].c_str()); 1940 } 1941 bool UnnamedAddr = false; 1942 if (Record.size() > 9) 1943 UnnamedAddr = Record[9]; 1944 Func->setUnnamedAddr(UnnamedAddr); 1945 if (Record.size() > 10 && Record[10] != 0) 1946 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1)); 1947 1948 if (Record.size() > 11) 1949 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11])); 1950 else 1951 UpgradeDLLImportExportLinkage(Func, Record[3]); 1952 1953 ValueList.push_back(Func); 1954 1955 // If this is a function with a body, remember the prototype we are 1956 // creating now, so that we can match up the body with them later. 1957 if (!isProto) { 1958 FunctionsWithBodies.push_back(Func); 1959 if (LazyStreamer) DeferredFunctionInfo[Func] = 0; 1960 } 1961 break; 1962 } 1963 // ALIAS: [alias type, aliasee val#, linkage] 1964 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass] 1965 case bitc::MODULE_CODE_ALIAS: { 1966 if (Record.size() < 3) 1967 return Error(InvalidRecord); 1968 Type *Ty = getTypeByID(Record[0]); 1969 if (!Ty) 1970 return Error(InvalidRecord); 1971 auto *PTy = dyn_cast<PointerType>(Ty); 1972 if (!PTy) 1973 return Error(InvalidTypeForValue); 1974 1975 auto *NewGA = 1976 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 1977 GetDecodedLinkage(Record[2]), "", TheModule); 1978 // Old bitcode files didn't have visibility field. 1979 // Local linkage must have default visibility. 1980 if (Record.size() > 3 && !NewGA->hasLocalLinkage()) 1981 // FIXME: Change to an error if non-default in 4.0. 1982 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 1983 if (Record.size() > 4) 1984 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4])); 1985 else 1986 UpgradeDLLImportExportLinkage(NewGA, Record[2]); 1987 if (Record.size() > 5) 1988 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5])); 1989 if (Record.size() > 6) 1990 NewGA->setUnnamedAddr(Record[6]); 1991 ValueList.push_back(NewGA); 1992 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 1993 break; 1994 } 1995 /// MODULE_CODE_PURGEVALS: [numvals] 1996 case bitc::MODULE_CODE_PURGEVALS: 1997 // Trim down the value list to the specified size. 1998 if (Record.size() < 1 || Record[0] > ValueList.size()) 1999 return Error(InvalidRecord); 2000 ValueList.shrinkTo(Record[0]); 2001 break; 2002 } 2003 Record.clear(); 2004 } 2005 } 2006 2007 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) { 2008 TheModule = nullptr; 2009 2010 if (std::error_code EC = InitStream()) 2011 return EC; 2012 2013 // Sniff for the signature. 2014 if (Stream.Read(8) != 'B' || 2015 Stream.Read(8) != 'C' || 2016 Stream.Read(4) != 0x0 || 2017 Stream.Read(4) != 0xC || 2018 Stream.Read(4) != 0xE || 2019 Stream.Read(4) != 0xD) 2020 return Error(InvalidBitcodeSignature); 2021 2022 // We expect a number of well-defined blocks, though we don't necessarily 2023 // need to understand them all. 2024 while (1) { 2025 if (Stream.AtEndOfStream()) 2026 return std::error_code(); 2027 2028 BitstreamEntry Entry = 2029 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 2030 2031 switch (Entry.Kind) { 2032 case BitstreamEntry::Error: 2033 return Error(MalformedBlock); 2034 case BitstreamEntry::EndBlock: 2035 return std::error_code(); 2036 2037 case BitstreamEntry::SubBlock: 2038 switch (Entry.ID) { 2039 case bitc::BLOCKINFO_BLOCK_ID: 2040 if (Stream.ReadBlockInfoBlock()) 2041 return Error(MalformedBlock); 2042 break; 2043 case bitc::MODULE_BLOCK_ID: 2044 // Reject multiple MODULE_BLOCK's in a single bitstream. 2045 if (TheModule) 2046 return Error(InvalidMultipleBlocks); 2047 TheModule = M; 2048 if (std::error_code EC = ParseModule(false)) 2049 return EC; 2050 if (LazyStreamer) 2051 return std::error_code(); 2052 break; 2053 default: 2054 if (Stream.SkipBlock()) 2055 return Error(InvalidRecord); 2056 break; 2057 } 2058 continue; 2059 case BitstreamEntry::Record: 2060 // There should be no records in the top-level of blocks. 2061 2062 // The ranlib in Xcode 4 will align archive members by appending newlines 2063 // to the end of them. If this file size is a multiple of 4 but not 8, we 2064 // have to read and ignore these final 4 bytes :-( 2065 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 && 2066 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a && 2067 Stream.AtEndOfStream()) 2068 return std::error_code(); 2069 2070 return Error(InvalidRecord); 2071 } 2072 } 2073 } 2074 2075 std::error_code BitcodeReader::ParseModuleTriple(std::string &Triple) { 2076 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2077 return Error(InvalidRecord); 2078 2079 SmallVector<uint64_t, 64> Record; 2080 2081 // Read all the records for this module. 2082 while (1) { 2083 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2084 2085 switch (Entry.Kind) { 2086 case BitstreamEntry::SubBlock: // Handled for us already. 2087 case BitstreamEntry::Error: 2088 return Error(MalformedBlock); 2089 case BitstreamEntry::EndBlock: 2090 return std::error_code(); 2091 case BitstreamEntry::Record: 2092 // The interesting case. 2093 break; 2094 } 2095 2096 // Read a record. 2097 switch (Stream.readRecord(Entry.ID, Record)) { 2098 default: break; // Default behavior, ignore unknown content. 2099 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2100 std::string S; 2101 if (ConvertToString(Record, 0, S)) 2102 return Error(InvalidRecord); 2103 Triple = S; 2104 break; 2105 } 2106 } 2107 Record.clear(); 2108 } 2109 } 2110 2111 std::error_code BitcodeReader::ParseTriple(std::string &Triple) { 2112 if (std::error_code EC = InitStream()) 2113 return EC; 2114 2115 // Sniff for the signature. 2116 if (Stream.Read(8) != 'B' || 2117 Stream.Read(8) != 'C' || 2118 Stream.Read(4) != 0x0 || 2119 Stream.Read(4) != 0xC || 2120 Stream.Read(4) != 0xE || 2121 Stream.Read(4) != 0xD) 2122 return Error(InvalidBitcodeSignature); 2123 2124 // We expect a number of well-defined blocks, though we don't necessarily 2125 // need to understand them all. 2126 while (1) { 2127 BitstreamEntry Entry = Stream.advance(); 2128 2129 switch (Entry.Kind) { 2130 case BitstreamEntry::Error: 2131 return Error(MalformedBlock); 2132 case BitstreamEntry::EndBlock: 2133 return std::error_code(); 2134 2135 case BitstreamEntry::SubBlock: 2136 if (Entry.ID == bitc::MODULE_BLOCK_ID) 2137 return ParseModuleTriple(Triple); 2138 2139 // Ignore other sub-blocks. 2140 if (Stream.SkipBlock()) 2141 return Error(MalformedBlock); 2142 continue; 2143 2144 case BitstreamEntry::Record: 2145 Stream.skipRecord(Entry.ID); 2146 continue; 2147 } 2148 } 2149 } 2150 2151 /// ParseMetadataAttachment - Parse metadata attachments. 2152 std::error_code BitcodeReader::ParseMetadataAttachment() { 2153 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 2154 return Error(InvalidRecord); 2155 2156 SmallVector<uint64_t, 64> Record; 2157 while (1) { 2158 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2159 2160 switch (Entry.Kind) { 2161 case BitstreamEntry::SubBlock: // Handled for us already. 2162 case BitstreamEntry::Error: 2163 return Error(MalformedBlock); 2164 case BitstreamEntry::EndBlock: 2165 return std::error_code(); 2166 case BitstreamEntry::Record: 2167 // The interesting case. 2168 break; 2169 } 2170 2171 // Read a metadata attachment record. 2172 Record.clear(); 2173 switch (Stream.readRecord(Entry.ID, Record)) { 2174 default: // Default behavior: ignore. 2175 break; 2176 case bitc::METADATA_ATTACHMENT: { 2177 unsigned RecordLength = Record.size(); 2178 if (Record.empty() || (RecordLength - 1) % 2 == 1) 2179 return Error(InvalidRecord); 2180 Instruction *Inst = InstructionList[Record[0]]; 2181 for (unsigned i = 1; i != RecordLength; i = i+2) { 2182 unsigned Kind = Record[i]; 2183 DenseMap<unsigned, unsigned>::iterator I = 2184 MDKindMap.find(Kind); 2185 if (I == MDKindMap.end()) 2186 return Error(InvalidID); 2187 Value *Node = MDValueList.getValueFwdRef(Record[i+1]); 2188 Inst->setMetadata(I->second, cast<MDNode>(Node)); 2189 if (I->second == LLVMContext::MD_tbaa) 2190 InstsWithTBAATag.push_back(Inst); 2191 } 2192 break; 2193 } 2194 } 2195 } 2196 } 2197 2198 /// ParseFunctionBody - Lazily parse the specified function body block. 2199 std::error_code BitcodeReader::ParseFunctionBody(Function *F) { 2200 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 2201 return Error(InvalidRecord); 2202 2203 InstructionList.clear(); 2204 unsigned ModuleValueListSize = ValueList.size(); 2205 unsigned ModuleMDValueListSize = MDValueList.size(); 2206 2207 // Add all the function arguments to the value table. 2208 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 2209 ValueList.push_back(I); 2210 2211 unsigned NextValueNo = ValueList.size(); 2212 BasicBlock *CurBB = nullptr; 2213 unsigned CurBBNo = 0; 2214 2215 DebugLoc LastLoc; 2216 2217 // Read all the records. 2218 SmallVector<uint64_t, 64> Record; 2219 while (1) { 2220 BitstreamEntry Entry = Stream.advance(); 2221 2222 switch (Entry.Kind) { 2223 case BitstreamEntry::Error: 2224 return Error(MalformedBlock); 2225 case BitstreamEntry::EndBlock: 2226 goto OutOfRecordLoop; 2227 2228 case BitstreamEntry::SubBlock: 2229 switch (Entry.ID) { 2230 default: // Skip unknown content. 2231 if (Stream.SkipBlock()) 2232 return Error(InvalidRecord); 2233 break; 2234 case bitc::CONSTANTS_BLOCK_ID: 2235 if (std::error_code EC = ParseConstants()) 2236 return EC; 2237 NextValueNo = ValueList.size(); 2238 break; 2239 case bitc::VALUE_SYMTAB_BLOCK_ID: 2240 if (std::error_code EC = ParseValueSymbolTable()) 2241 return EC; 2242 break; 2243 case bitc::METADATA_ATTACHMENT_ID: 2244 if (std::error_code EC = ParseMetadataAttachment()) 2245 return EC; 2246 break; 2247 case bitc::METADATA_BLOCK_ID: 2248 if (std::error_code EC = ParseMetadata()) 2249 return EC; 2250 break; 2251 } 2252 continue; 2253 2254 case BitstreamEntry::Record: 2255 // The interesting case. 2256 break; 2257 } 2258 2259 // Read a record. 2260 Record.clear(); 2261 Instruction *I = nullptr; 2262 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2263 switch (BitCode) { 2264 default: // Default behavior: reject 2265 return Error(InvalidValue); 2266 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 2267 if (Record.size() < 1 || Record[0] == 0) 2268 return Error(InvalidRecord); 2269 // Create all the basic blocks for the function. 2270 FunctionBBs.resize(Record[0]); 2271 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 2272 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 2273 CurBB = FunctionBBs[0]; 2274 continue; 2275 2276 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 2277 // This record indicates that the last instruction is at the same 2278 // location as the previous instruction with a location. 2279 I = nullptr; 2280 2281 // Get the last instruction emitted. 2282 if (CurBB && !CurBB->empty()) 2283 I = &CurBB->back(); 2284 else if (CurBBNo && FunctionBBs[CurBBNo-1] && 2285 !FunctionBBs[CurBBNo-1]->empty()) 2286 I = &FunctionBBs[CurBBNo-1]->back(); 2287 2288 if (!I) 2289 return Error(InvalidRecord); 2290 I->setDebugLoc(LastLoc); 2291 I = nullptr; 2292 continue; 2293 2294 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 2295 I = nullptr; // Get the last instruction emitted. 2296 if (CurBB && !CurBB->empty()) 2297 I = &CurBB->back(); 2298 else if (CurBBNo && FunctionBBs[CurBBNo-1] && 2299 !FunctionBBs[CurBBNo-1]->empty()) 2300 I = &FunctionBBs[CurBBNo-1]->back(); 2301 if (!I || Record.size() < 4) 2302 return Error(InvalidRecord); 2303 2304 unsigned Line = Record[0], Col = Record[1]; 2305 unsigned ScopeID = Record[2], IAID = Record[3]; 2306 2307 MDNode *Scope = nullptr, *IA = nullptr; 2308 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1)); 2309 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1)); 2310 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 2311 I->setDebugLoc(LastLoc); 2312 I = nullptr; 2313 continue; 2314 } 2315 2316 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 2317 unsigned OpNum = 0; 2318 Value *LHS, *RHS; 2319 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2320 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2321 OpNum+1 > Record.size()) 2322 return Error(InvalidRecord); 2323 2324 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 2325 if (Opc == -1) 2326 return Error(InvalidRecord); 2327 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 2328 InstructionList.push_back(I); 2329 if (OpNum < Record.size()) { 2330 if (Opc == Instruction::Add || 2331 Opc == Instruction::Sub || 2332 Opc == Instruction::Mul || 2333 Opc == Instruction::Shl) { 2334 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2335 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 2336 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2337 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 2338 } else if (Opc == Instruction::SDiv || 2339 Opc == Instruction::UDiv || 2340 Opc == Instruction::LShr || 2341 Opc == Instruction::AShr) { 2342 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 2343 cast<BinaryOperator>(I)->setIsExact(true); 2344 } else if (isa<FPMathOperator>(I)) { 2345 FastMathFlags FMF; 2346 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra)) 2347 FMF.setUnsafeAlgebra(); 2348 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs)) 2349 FMF.setNoNaNs(); 2350 if (0 != (Record[OpNum] & FastMathFlags::NoInfs)) 2351 FMF.setNoInfs(); 2352 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros)) 2353 FMF.setNoSignedZeros(); 2354 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal)) 2355 FMF.setAllowReciprocal(); 2356 if (FMF.any()) 2357 I->setFastMathFlags(FMF); 2358 } 2359 2360 } 2361 break; 2362 } 2363 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 2364 unsigned OpNum = 0; 2365 Value *Op; 2366 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2367 OpNum+2 != Record.size()) 2368 return Error(InvalidRecord); 2369 2370 Type *ResTy = getTypeByID(Record[OpNum]); 2371 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 2372 if (Opc == -1 || !ResTy) 2373 return Error(InvalidRecord); 2374 Instruction *Temp = nullptr; 2375 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 2376 if (Temp) { 2377 InstructionList.push_back(Temp); 2378 CurBB->getInstList().push_back(Temp); 2379 } 2380 } else { 2381 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 2382 } 2383 InstructionList.push_back(I); 2384 break; 2385 } 2386 case bitc::FUNC_CODE_INST_INBOUNDS_GEP: 2387 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 2388 unsigned OpNum = 0; 2389 Value *BasePtr; 2390 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 2391 return Error(InvalidRecord); 2392 2393 SmallVector<Value*, 16> GEPIdx; 2394 while (OpNum != Record.size()) { 2395 Value *Op; 2396 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2397 return Error(InvalidRecord); 2398 GEPIdx.push_back(Op); 2399 } 2400 2401 I = GetElementPtrInst::Create(BasePtr, GEPIdx); 2402 InstructionList.push_back(I); 2403 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP) 2404 cast<GetElementPtrInst>(I)->setIsInBounds(true); 2405 break; 2406 } 2407 2408 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 2409 // EXTRACTVAL: [opty, opval, n x indices] 2410 unsigned OpNum = 0; 2411 Value *Agg; 2412 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2413 return Error(InvalidRecord); 2414 2415 SmallVector<unsigned, 4> EXTRACTVALIdx; 2416 for (unsigned RecSize = Record.size(); 2417 OpNum != RecSize; ++OpNum) { 2418 uint64_t Index = Record[OpNum]; 2419 if ((unsigned)Index != Index) 2420 return Error(InvalidValue); 2421 EXTRACTVALIdx.push_back((unsigned)Index); 2422 } 2423 2424 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 2425 InstructionList.push_back(I); 2426 break; 2427 } 2428 2429 case bitc::FUNC_CODE_INST_INSERTVAL: { 2430 // INSERTVAL: [opty, opval, opty, opval, n x indices] 2431 unsigned OpNum = 0; 2432 Value *Agg; 2433 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2434 return Error(InvalidRecord); 2435 Value *Val; 2436 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 2437 return Error(InvalidRecord); 2438 2439 SmallVector<unsigned, 4> INSERTVALIdx; 2440 for (unsigned RecSize = Record.size(); 2441 OpNum != RecSize; ++OpNum) { 2442 uint64_t Index = Record[OpNum]; 2443 if ((unsigned)Index != Index) 2444 return Error(InvalidValue); 2445 INSERTVALIdx.push_back((unsigned)Index); 2446 } 2447 2448 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 2449 InstructionList.push_back(I); 2450 break; 2451 } 2452 2453 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 2454 // obsolete form of select 2455 // handles select i1 ... in old bitcode 2456 unsigned OpNum = 0; 2457 Value *TrueVal, *FalseVal, *Cond; 2458 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2459 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 2460 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 2461 return Error(InvalidRecord); 2462 2463 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2464 InstructionList.push_back(I); 2465 break; 2466 } 2467 2468 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 2469 // new form of select 2470 // handles select i1 or select [N x i1] 2471 unsigned OpNum = 0; 2472 Value *TrueVal, *FalseVal, *Cond; 2473 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2474 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 2475 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 2476 return Error(InvalidRecord); 2477 2478 // select condition can be either i1 or [N x i1] 2479 if (VectorType* vector_type = 2480 dyn_cast<VectorType>(Cond->getType())) { 2481 // expect <n x i1> 2482 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 2483 return Error(InvalidTypeForValue); 2484 } else { 2485 // expect i1 2486 if (Cond->getType() != Type::getInt1Ty(Context)) 2487 return Error(InvalidTypeForValue); 2488 } 2489 2490 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2491 InstructionList.push_back(I); 2492 break; 2493 } 2494 2495 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 2496 unsigned OpNum = 0; 2497 Value *Vec, *Idx; 2498 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2499 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 2500 return Error(InvalidRecord); 2501 I = ExtractElementInst::Create(Vec, Idx); 2502 InstructionList.push_back(I); 2503 break; 2504 } 2505 2506 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 2507 unsigned OpNum = 0; 2508 Value *Vec, *Elt, *Idx; 2509 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2510 popValue(Record, OpNum, NextValueNo, 2511 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 2512 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 2513 return Error(InvalidRecord); 2514 I = InsertElementInst::Create(Vec, Elt, Idx); 2515 InstructionList.push_back(I); 2516 break; 2517 } 2518 2519 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 2520 unsigned OpNum = 0; 2521 Value *Vec1, *Vec2, *Mask; 2522 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 2523 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 2524 return Error(InvalidRecord); 2525 2526 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 2527 return Error(InvalidRecord); 2528 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 2529 InstructionList.push_back(I); 2530 break; 2531 } 2532 2533 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 2534 // Old form of ICmp/FCmp returning bool 2535 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 2536 // both legal on vectors but had different behaviour. 2537 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 2538 // FCmp/ICmp returning bool or vector of bool 2539 2540 unsigned OpNum = 0; 2541 Value *LHS, *RHS; 2542 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2543 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2544 OpNum+1 != Record.size()) 2545 return Error(InvalidRecord); 2546 2547 if (LHS->getType()->isFPOrFPVectorTy()) 2548 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 2549 else 2550 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 2551 InstructionList.push_back(I); 2552 break; 2553 } 2554 2555 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 2556 { 2557 unsigned Size = Record.size(); 2558 if (Size == 0) { 2559 I = ReturnInst::Create(Context); 2560 InstructionList.push_back(I); 2561 break; 2562 } 2563 2564 unsigned OpNum = 0; 2565 Value *Op = nullptr; 2566 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2567 return Error(InvalidRecord); 2568 if (OpNum != Record.size()) 2569 return Error(InvalidRecord); 2570 2571 I = ReturnInst::Create(Context, Op); 2572 InstructionList.push_back(I); 2573 break; 2574 } 2575 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 2576 if (Record.size() != 1 && Record.size() != 3) 2577 return Error(InvalidRecord); 2578 BasicBlock *TrueDest = getBasicBlock(Record[0]); 2579 if (!TrueDest) 2580 return Error(InvalidRecord); 2581 2582 if (Record.size() == 1) { 2583 I = BranchInst::Create(TrueDest); 2584 InstructionList.push_back(I); 2585 } 2586 else { 2587 BasicBlock *FalseDest = getBasicBlock(Record[1]); 2588 Value *Cond = getValue(Record, 2, NextValueNo, 2589 Type::getInt1Ty(Context)); 2590 if (!FalseDest || !Cond) 2591 return Error(InvalidRecord); 2592 I = BranchInst::Create(TrueDest, FalseDest, Cond); 2593 InstructionList.push_back(I); 2594 } 2595 break; 2596 } 2597 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 2598 // Check magic 2599 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 2600 // "New" SwitchInst format with case ranges. The changes to write this 2601 // format were reverted but we still recognize bitcode that uses it. 2602 // Hopefully someday we will have support for case ranges and can use 2603 // this format again. 2604 2605 Type *OpTy = getTypeByID(Record[1]); 2606 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 2607 2608 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 2609 BasicBlock *Default = getBasicBlock(Record[3]); 2610 if (!OpTy || !Cond || !Default) 2611 return Error(InvalidRecord); 2612 2613 unsigned NumCases = Record[4]; 2614 2615 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 2616 InstructionList.push_back(SI); 2617 2618 unsigned CurIdx = 5; 2619 for (unsigned i = 0; i != NumCases; ++i) { 2620 SmallVector<ConstantInt*, 1> CaseVals; 2621 unsigned NumItems = Record[CurIdx++]; 2622 for (unsigned ci = 0; ci != NumItems; ++ci) { 2623 bool isSingleNumber = Record[CurIdx++]; 2624 2625 APInt Low; 2626 unsigned ActiveWords = 1; 2627 if (ValueBitWidth > 64) 2628 ActiveWords = Record[CurIdx++]; 2629 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 2630 ValueBitWidth); 2631 CurIdx += ActiveWords; 2632 2633 if (!isSingleNumber) { 2634 ActiveWords = 1; 2635 if (ValueBitWidth > 64) 2636 ActiveWords = Record[CurIdx++]; 2637 APInt High = 2638 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 2639 ValueBitWidth); 2640 CurIdx += ActiveWords; 2641 2642 // FIXME: It is not clear whether values in the range should be 2643 // compared as signed or unsigned values. The partially 2644 // implemented changes that used this format in the past used 2645 // unsigned comparisons. 2646 for ( ; Low.ule(High); ++Low) 2647 CaseVals.push_back(ConstantInt::get(Context, Low)); 2648 } else 2649 CaseVals.push_back(ConstantInt::get(Context, Low)); 2650 } 2651 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 2652 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 2653 cve = CaseVals.end(); cvi != cve; ++cvi) 2654 SI->addCase(*cvi, DestBB); 2655 } 2656 I = SI; 2657 break; 2658 } 2659 2660 // Old SwitchInst format without case ranges. 2661 2662 if (Record.size() < 3 || (Record.size() & 1) == 0) 2663 return Error(InvalidRecord); 2664 Type *OpTy = getTypeByID(Record[0]); 2665 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 2666 BasicBlock *Default = getBasicBlock(Record[2]); 2667 if (!OpTy || !Cond || !Default) 2668 return Error(InvalidRecord); 2669 unsigned NumCases = (Record.size()-3)/2; 2670 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 2671 InstructionList.push_back(SI); 2672 for (unsigned i = 0, e = NumCases; i != e; ++i) { 2673 ConstantInt *CaseVal = 2674 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 2675 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 2676 if (!CaseVal || !DestBB) { 2677 delete SI; 2678 return Error(InvalidRecord); 2679 } 2680 SI->addCase(CaseVal, DestBB); 2681 } 2682 I = SI; 2683 break; 2684 } 2685 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 2686 if (Record.size() < 2) 2687 return Error(InvalidRecord); 2688 Type *OpTy = getTypeByID(Record[0]); 2689 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 2690 if (!OpTy || !Address) 2691 return Error(InvalidRecord); 2692 unsigned NumDests = Record.size()-2; 2693 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 2694 InstructionList.push_back(IBI); 2695 for (unsigned i = 0, e = NumDests; i != e; ++i) { 2696 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 2697 IBI->addDestination(DestBB); 2698 } else { 2699 delete IBI; 2700 return Error(InvalidRecord); 2701 } 2702 } 2703 I = IBI; 2704 break; 2705 } 2706 2707 case bitc::FUNC_CODE_INST_INVOKE: { 2708 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 2709 if (Record.size() < 4) 2710 return Error(InvalidRecord); 2711 AttributeSet PAL = getAttributes(Record[0]); 2712 unsigned CCInfo = Record[1]; 2713 BasicBlock *NormalBB = getBasicBlock(Record[2]); 2714 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 2715 2716 unsigned OpNum = 4; 2717 Value *Callee; 2718 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 2719 return Error(InvalidRecord); 2720 2721 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 2722 FunctionType *FTy = !CalleeTy ? nullptr : 2723 dyn_cast<FunctionType>(CalleeTy->getElementType()); 2724 2725 // Check that the right number of fixed parameters are here. 2726 if (!FTy || !NormalBB || !UnwindBB || 2727 Record.size() < OpNum+FTy->getNumParams()) 2728 return Error(InvalidRecord); 2729 2730 SmallVector<Value*, 16> Ops; 2731 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 2732 Ops.push_back(getValue(Record, OpNum, NextValueNo, 2733 FTy->getParamType(i))); 2734 if (!Ops.back()) 2735 return Error(InvalidRecord); 2736 } 2737 2738 if (!FTy->isVarArg()) { 2739 if (Record.size() != OpNum) 2740 return Error(InvalidRecord); 2741 } else { 2742 // Read type/value pairs for varargs params. 2743 while (OpNum != Record.size()) { 2744 Value *Op; 2745 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2746 return Error(InvalidRecord); 2747 Ops.push_back(Op); 2748 } 2749 } 2750 2751 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops); 2752 InstructionList.push_back(I); 2753 cast<InvokeInst>(I)->setCallingConv( 2754 static_cast<CallingConv::ID>(CCInfo)); 2755 cast<InvokeInst>(I)->setAttributes(PAL); 2756 break; 2757 } 2758 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 2759 unsigned Idx = 0; 2760 Value *Val = nullptr; 2761 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 2762 return Error(InvalidRecord); 2763 I = ResumeInst::Create(Val); 2764 InstructionList.push_back(I); 2765 break; 2766 } 2767 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 2768 I = new UnreachableInst(Context); 2769 InstructionList.push_back(I); 2770 break; 2771 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 2772 if (Record.size() < 1 || ((Record.size()-1)&1)) 2773 return Error(InvalidRecord); 2774 Type *Ty = getTypeByID(Record[0]); 2775 if (!Ty) 2776 return Error(InvalidRecord); 2777 2778 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 2779 InstructionList.push_back(PN); 2780 2781 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 2782 Value *V; 2783 // With the new function encoding, it is possible that operands have 2784 // negative IDs (for forward references). Use a signed VBR 2785 // representation to keep the encoding small. 2786 if (UseRelativeIDs) 2787 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 2788 else 2789 V = getValue(Record, 1+i, NextValueNo, Ty); 2790 BasicBlock *BB = getBasicBlock(Record[2+i]); 2791 if (!V || !BB) 2792 return Error(InvalidRecord); 2793 PN->addIncoming(V, BB); 2794 } 2795 I = PN; 2796 break; 2797 } 2798 2799 case bitc::FUNC_CODE_INST_LANDINGPAD: { 2800 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 2801 unsigned Idx = 0; 2802 if (Record.size() < 4) 2803 return Error(InvalidRecord); 2804 Type *Ty = getTypeByID(Record[Idx++]); 2805 if (!Ty) 2806 return Error(InvalidRecord); 2807 Value *PersFn = nullptr; 2808 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 2809 return Error(InvalidRecord); 2810 2811 bool IsCleanup = !!Record[Idx++]; 2812 unsigned NumClauses = Record[Idx++]; 2813 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses); 2814 LP->setCleanup(IsCleanup); 2815 for (unsigned J = 0; J != NumClauses; ++J) { 2816 LandingPadInst::ClauseType CT = 2817 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 2818 Value *Val; 2819 2820 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 2821 delete LP; 2822 return Error(InvalidRecord); 2823 } 2824 2825 assert((CT != LandingPadInst::Catch || 2826 !isa<ArrayType>(Val->getType())) && 2827 "Catch clause has a invalid type!"); 2828 assert((CT != LandingPadInst::Filter || 2829 isa<ArrayType>(Val->getType())) && 2830 "Filter clause has invalid type!"); 2831 LP->addClause(cast<Constant>(Val)); 2832 } 2833 2834 I = LP; 2835 InstructionList.push_back(I); 2836 break; 2837 } 2838 2839 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 2840 if (Record.size() != 4) 2841 return Error(InvalidRecord); 2842 PointerType *Ty = 2843 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 2844 Type *OpTy = getTypeByID(Record[1]); 2845 Value *Size = getFnValueByID(Record[2], OpTy); 2846 unsigned Align = Record[3]; 2847 if (!Ty || !Size) 2848 return Error(InvalidRecord); 2849 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 2850 InstructionList.push_back(I); 2851 break; 2852 } 2853 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 2854 unsigned OpNum = 0; 2855 Value *Op; 2856 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2857 OpNum+2 != Record.size()) 2858 return Error(InvalidRecord); 2859 2860 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 2861 InstructionList.push_back(I); 2862 break; 2863 } 2864 case bitc::FUNC_CODE_INST_LOADATOMIC: { 2865 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 2866 unsigned OpNum = 0; 2867 Value *Op; 2868 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2869 OpNum+4 != Record.size()) 2870 return Error(InvalidRecord); 2871 2872 2873 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2874 if (Ordering == NotAtomic || Ordering == Release || 2875 Ordering == AcquireRelease) 2876 return Error(InvalidRecord); 2877 if (Ordering != NotAtomic && Record[OpNum] == 0) 2878 return Error(InvalidRecord); 2879 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2880 2881 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1, 2882 Ordering, SynchScope); 2883 InstructionList.push_back(I); 2884 break; 2885 } 2886 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol] 2887 unsigned OpNum = 0; 2888 Value *Val, *Ptr; 2889 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2890 popValue(Record, OpNum, NextValueNo, 2891 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2892 OpNum+2 != Record.size()) 2893 return Error(InvalidRecord); 2894 2895 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 2896 InstructionList.push_back(I); 2897 break; 2898 } 2899 case bitc::FUNC_CODE_INST_STOREATOMIC: { 2900 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 2901 unsigned OpNum = 0; 2902 Value *Val, *Ptr; 2903 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2904 popValue(Record, OpNum, NextValueNo, 2905 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2906 OpNum+4 != Record.size()) 2907 return Error(InvalidRecord); 2908 2909 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2910 if (Ordering == NotAtomic || Ordering == Acquire || 2911 Ordering == AcquireRelease) 2912 return Error(InvalidRecord); 2913 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2914 if (Ordering != NotAtomic && Record[OpNum] == 0) 2915 return Error(InvalidRecord); 2916 2917 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1, 2918 Ordering, SynchScope); 2919 InstructionList.push_back(I); 2920 break; 2921 } 2922 case bitc::FUNC_CODE_INST_CMPXCHG: { 2923 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 2924 // failureordering?, isweak?] 2925 unsigned OpNum = 0; 2926 Value *Ptr, *Cmp, *New; 2927 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2928 popValue(Record, OpNum, NextValueNo, 2929 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) || 2930 popValue(Record, OpNum, NextValueNo, 2931 cast<PointerType>(Ptr->getType())->getElementType(), New) || 2932 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5)) 2933 return Error(InvalidRecord); 2934 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]); 2935 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered) 2936 return Error(InvalidRecord); 2937 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]); 2938 2939 AtomicOrdering FailureOrdering; 2940 if (Record.size() < 7) 2941 FailureOrdering = 2942 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 2943 else 2944 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]); 2945 2946 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 2947 SynchScope); 2948 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 2949 2950 if (Record.size() < 8) { 2951 // Before weak cmpxchgs existed, the instruction simply returned the 2952 // value loaded from memory, so bitcode files from that era will be 2953 // expecting the first component of a modern cmpxchg. 2954 CurBB->getInstList().push_back(I); 2955 I = ExtractValueInst::Create(I, 0); 2956 } else { 2957 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 2958 } 2959 2960 InstructionList.push_back(I); 2961 break; 2962 } 2963 case bitc::FUNC_CODE_INST_ATOMICRMW: { 2964 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 2965 unsigned OpNum = 0; 2966 Value *Ptr, *Val; 2967 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2968 popValue(Record, OpNum, NextValueNo, 2969 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2970 OpNum+4 != Record.size()) 2971 return Error(InvalidRecord); 2972 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]); 2973 if (Operation < AtomicRMWInst::FIRST_BINOP || 2974 Operation > AtomicRMWInst::LAST_BINOP) 2975 return Error(InvalidRecord); 2976 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2977 if (Ordering == NotAtomic || Ordering == Unordered) 2978 return Error(InvalidRecord); 2979 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2980 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 2981 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 2982 InstructionList.push_back(I); 2983 break; 2984 } 2985 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 2986 if (2 != Record.size()) 2987 return Error(InvalidRecord); 2988 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]); 2989 if (Ordering == NotAtomic || Ordering == Unordered || 2990 Ordering == Monotonic) 2991 return Error(InvalidRecord); 2992 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]); 2993 I = new FenceInst(Context, Ordering, SynchScope); 2994 InstructionList.push_back(I); 2995 break; 2996 } 2997 case bitc::FUNC_CODE_INST_CALL: { 2998 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 2999 if (Record.size() < 3) 3000 return Error(InvalidRecord); 3001 3002 AttributeSet PAL = getAttributes(Record[0]); 3003 unsigned CCInfo = Record[1]; 3004 3005 unsigned OpNum = 2; 3006 Value *Callee; 3007 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 3008 return Error(InvalidRecord); 3009 3010 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 3011 FunctionType *FTy = nullptr; 3012 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 3013 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 3014 return Error(InvalidRecord); 3015 3016 SmallVector<Value*, 16> Args; 3017 // Read the fixed params. 3018 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 3019 if (FTy->getParamType(i)->isLabelTy()) 3020 Args.push_back(getBasicBlock(Record[OpNum])); 3021 else 3022 Args.push_back(getValue(Record, OpNum, NextValueNo, 3023 FTy->getParamType(i))); 3024 if (!Args.back()) 3025 return Error(InvalidRecord); 3026 } 3027 3028 // Read type/value pairs for varargs params. 3029 if (!FTy->isVarArg()) { 3030 if (OpNum != Record.size()) 3031 return Error(InvalidRecord); 3032 } else { 3033 while (OpNum != Record.size()) { 3034 Value *Op; 3035 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3036 return Error(InvalidRecord); 3037 Args.push_back(Op); 3038 } 3039 } 3040 3041 I = CallInst::Create(Callee, Args); 3042 InstructionList.push_back(I); 3043 cast<CallInst>(I)->setCallingConv( 3044 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1)); 3045 CallInst::TailCallKind TCK = CallInst::TCK_None; 3046 if (CCInfo & 1) 3047 TCK = CallInst::TCK_Tail; 3048 if (CCInfo & (1 << 14)) 3049 TCK = CallInst::TCK_MustTail; 3050 cast<CallInst>(I)->setTailCallKind(TCK); 3051 cast<CallInst>(I)->setAttributes(PAL); 3052 break; 3053 } 3054 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 3055 if (Record.size() < 3) 3056 return Error(InvalidRecord); 3057 Type *OpTy = getTypeByID(Record[0]); 3058 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 3059 Type *ResTy = getTypeByID(Record[2]); 3060 if (!OpTy || !Op || !ResTy) 3061 return Error(InvalidRecord); 3062 I = new VAArgInst(Op, ResTy); 3063 InstructionList.push_back(I); 3064 break; 3065 } 3066 } 3067 3068 // Add instruction to end of current BB. If there is no current BB, reject 3069 // this file. 3070 if (!CurBB) { 3071 delete I; 3072 return Error(InvalidInstructionWithNoBB); 3073 } 3074 CurBB->getInstList().push_back(I); 3075 3076 // If this was a terminator instruction, move to the next block. 3077 if (isa<TerminatorInst>(I)) { 3078 ++CurBBNo; 3079 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 3080 } 3081 3082 // Non-void values get registered in the value table for future use. 3083 if (I && !I->getType()->isVoidTy()) 3084 ValueList.AssignValue(I, NextValueNo++); 3085 } 3086 3087 OutOfRecordLoop: 3088 3089 // Check the function list for unresolved values. 3090 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 3091 if (!A->getParent()) { 3092 // We found at least one unresolved value. Nuke them all to avoid leaks. 3093 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 3094 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 3095 A->replaceAllUsesWith(UndefValue::get(A->getType())); 3096 delete A; 3097 } 3098 } 3099 return Error(NeverResolvedValueFoundInFunction); 3100 } 3101 } 3102 3103 // FIXME: Check for unresolved forward-declared metadata references 3104 // and clean up leaks. 3105 3106 // See if anything took the address of blocks in this function. If so, 3107 // resolve them now. 3108 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI = 3109 BlockAddrFwdRefs.find(F); 3110 if (BAFRI != BlockAddrFwdRefs.end()) { 3111 std::vector<BlockAddrRefTy> &RefList = BAFRI->second; 3112 for (unsigned i = 0, e = RefList.size(); i != e; ++i) { 3113 unsigned BlockIdx = RefList[i].first; 3114 if (BlockIdx >= FunctionBBs.size()) 3115 return Error(InvalidID); 3116 3117 GlobalVariable *FwdRef = RefList[i].second; 3118 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx])); 3119 FwdRef->eraseFromParent(); 3120 } 3121 3122 BlockAddrFwdRefs.erase(BAFRI); 3123 } 3124 3125 // Trim the value list down to the size it was before we parsed this function. 3126 ValueList.shrinkTo(ModuleValueListSize); 3127 MDValueList.shrinkTo(ModuleMDValueListSize); 3128 std::vector<BasicBlock*>().swap(FunctionBBs); 3129 return std::error_code(); 3130 } 3131 3132 /// Find the function body in the bitcode stream 3133 std::error_code BitcodeReader::FindFunctionInStream( 3134 Function *F, 3135 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 3136 while (DeferredFunctionInfoIterator->second == 0) { 3137 if (Stream.AtEndOfStream()) 3138 return Error(CouldNotFindFunctionInStream); 3139 // ParseModule will parse the next body in the stream and set its 3140 // position in the DeferredFunctionInfo map. 3141 if (std::error_code EC = ParseModule(true)) 3142 return EC; 3143 } 3144 return std::error_code(); 3145 } 3146 3147 //===----------------------------------------------------------------------===// 3148 // GVMaterializer implementation 3149 //===----------------------------------------------------------------------===// 3150 3151 void BitcodeReader::releaseBuffer() { Buffer.release(); } 3152 3153 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const { 3154 if (const Function *F = dyn_cast<Function>(GV)) { 3155 return F->isDeclaration() && 3156 DeferredFunctionInfo.count(const_cast<Function*>(F)); 3157 } 3158 return false; 3159 } 3160 3161 std::error_code BitcodeReader::Materialize(GlobalValue *GV) { 3162 Function *F = dyn_cast<Function>(GV); 3163 // If it's not a function or is already material, ignore the request. 3164 if (!F || !F->isMaterializable()) 3165 return std::error_code(); 3166 3167 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 3168 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 3169 // If its position is recorded as 0, its body is somewhere in the stream 3170 // but we haven't seen it yet. 3171 if (DFII->second == 0 && LazyStreamer) 3172 if (std::error_code EC = FindFunctionInStream(F, DFII)) 3173 return EC; 3174 3175 // Move the bit stream to the saved position of the deferred function body. 3176 Stream.JumpToBit(DFII->second); 3177 3178 if (std::error_code EC = ParseFunctionBody(F)) 3179 return EC; 3180 3181 // Upgrade any old intrinsic calls in the function. 3182 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 3183 E = UpgradedIntrinsics.end(); I != E; ++I) { 3184 if (I->first != I->second) { 3185 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3186 UI != UE;) { 3187 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3188 UpgradeIntrinsicCall(CI, I->second); 3189 } 3190 } 3191 } 3192 3193 return std::error_code(); 3194 } 3195 3196 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 3197 const Function *F = dyn_cast<Function>(GV); 3198 if (!F || F->isDeclaration()) 3199 return false; 3200 return DeferredFunctionInfo.count(const_cast<Function*>(F)); 3201 } 3202 3203 void BitcodeReader::Dematerialize(GlobalValue *GV) { 3204 Function *F = dyn_cast<Function>(GV); 3205 // If this function isn't dematerializable, this is a noop. 3206 if (!F || !isDematerializable(F)) 3207 return; 3208 3209 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 3210 3211 // Just forget the function body, we can remat it later. 3212 F->deleteBody(); 3213 } 3214 3215 std::error_code BitcodeReader::MaterializeModule(Module *M) { 3216 assert(M == TheModule && 3217 "Can only Materialize the Module this BitcodeReader is attached to."); 3218 // Iterate over the module, deserializing any functions that are still on 3219 // disk. 3220 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 3221 F != E; ++F) { 3222 if (F->isMaterializable()) { 3223 if (std::error_code EC = Materialize(F)) 3224 return EC; 3225 } 3226 } 3227 // At this point, if there are any function bodies, the current bit is 3228 // pointing to the END_BLOCK record after them. Now make sure the rest 3229 // of the bits in the module have been read. 3230 if (NextUnreadBit) 3231 ParseModule(true); 3232 3233 // Upgrade any intrinsic calls that slipped through (should not happen!) and 3234 // delete the old functions to clean up. We can't do this unless the entire 3235 // module is materialized because there could always be another function body 3236 // with calls to the old function. 3237 for (std::vector<std::pair<Function*, Function*> >::iterator I = 3238 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 3239 if (I->first != I->second) { 3240 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3241 UI != UE;) { 3242 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3243 UpgradeIntrinsicCall(CI, I->second); 3244 } 3245 if (!I->first->use_empty()) 3246 I->first->replaceAllUsesWith(I->second); 3247 I->first->eraseFromParent(); 3248 } 3249 } 3250 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 3251 3252 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 3253 UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 3254 3255 UpgradeDebugInfo(*M); 3256 return std::error_code(); 3257 } 3258 3259 std::error_code BitcodeReader::InitStream() { 3260 if (LazyStreamer) 3261 return InitLazyStream(); 3262 return InitStreamFromBuffer(); 3263 } 3264 3265 std::error_code BitcodeReader::InitStreamFromBuffer() { 3266 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 3267 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 3268 3269 if (Buffer->getBufferSize() & 3) { 3270 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd)) 3271 return Error(InvalidBitcodeSignature); 3272 else 3273 return Error(BitcodeStreamInvalidSize); 3274 } 3275 3276 // If we have a wrapper header, parse it and ignore the non-bc file contents. 3277 // The magic number is 0x0B17C0DE stored in little endian. 3278 if (isBitcodeWrapper(BufPtr, BufEnd)) 3279 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 3280 return Error(InvalidBitcodeWrapperHeader); 3281 3282 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 3283 Stream.init(*StreamFile); 3284 3285 return std::error_code(); 3286 } 3287 3288 std::error_code BitcodeReader::InitLazyStream() { 3289 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 3290 // see it. 3291 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer); 3292 StreamFile.reset(new BitstreamReader(Bytes)); 3293 Stream.init(*StreamFile); 3294 3295 unsigned char buf[16]; 3296 if (Bytes->readBytes(0, 16, buf) == -1) 3297 return Error(BitcodeStreamInvalidSize); 3298 3299 if (!isBitcode(buf, buf + 16)) 3300 return Error(InvalidBitcodeSignature); 3301 3302 if (isBitcodeWrapper(buf, buf + 4)) { 3303 const unsigned char *bitcodeStart = buf; 3304 const unsigned char *bitcodeEnd = buf + 16; 3305 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 3306 Bytes->dropLeadingBytes(bitcodeStart - buf); 3307 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart); 3308 } 3309 return std::error_code(); 3310 } 3311 3312 namespace { 3313 class BitcodeErrorCategoryType : public std::error_category { 3314 const char *name() const LLVM_NOEXCEPT override { 3315 return "llvm.bitcode"; 3316 } 3317 std::string message(int IE) const override { 3318 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE); 3319 switch (E) { 3320 case BitcodeReader::BitcodeStreamInvalidSize: 3321 return "Bitcode stream length should be >= 16 bytes and a multiple of 4"; 3322 case BitcodeReader::ConflictingMETADATA_KINDRecords: 3323 return "Conflicting METADATA_KIND records"; 3324 case BitcodeReader::CouldNotFindFunctionInStream: 3325 return "Could not find function in stream"; 3326 case BitcodeReader::ExpectedConstant: 3327 return "Expected a constant"; 3328 case BitcodeReader::InsufficientFunctionProtos: 3329 return "Insufficient function protos"; 3330 case BitcodeReader::InvalidBitcodeSignature: 3331 return "Invalid bitcode signature"; 3332 case BitcodeReader::InvalidBitcodeWrapperHeader: 3333 return "Invalid bitcode wrapper header"; 3334 case BitcodeReader::InvalidConstantReference: 3335 return "Invalid ronstant reference"; 3336 case BitcodeReader::InvalidID: 3337 return "Invalid ID"; 3338 case BitcodeReader::InvalidInstructionWithNoBB: 3339 return "Invalid instruction with no BB"; 3340 case BitcodeReader::InvalidRecord: 3341 return "Invalid record"; 3342 case BitcodeReader::InvalidTypeForValue: 3343 return "Invalid type for value"; 3344 case BitcodeReader::InvalidTYPETable: 3345 return "Invalid TYPE table"; 3346 case BitcodeReader::InvalidType: 3347 return "Invalid type"; 3348 case BitcodeReader::MalformedBlock: 3349 return "Malformed block"; 3350 case BitcodeReader::MalformedGlobalInitializerSet: 3351 return "Malformed global initializer set"; 3352 case BitcodeReader::InvalidMultipleBlocks: 3353 return "Invalid multiple blocks"; 3354 case BitcodeReader::NeverResolvedValueFoundInFunction: 3355 return "Never resolved value found in function"; 3356 case BitcodeReader::InvalidValue: 3357 return "Invalid value"; 3358 } 3359 llvm_unreachable("Unknown error type!"); 3360 } 3361 }; 3362 } 3363 3364 const std::error_category &BitcodeReader::BitcodeErrorCategory() { 3365 static BitcodeErrorCategoryType O; 3366 return O; 3367 } 3368 3369 //===----------------------------------------------------------------------===// 3370 // External interface 3371 //===----------------------------------------------------------------------===// 3372 3373 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file. 3374 /// 3375 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer, 3376 LLVMContext &Context) { 3377 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 3378 BitcodeReader *R = new BitcodeReader(Buffer, Context); 3379 M->setMaterializer(R); 3380 if (std::error_code EC = R->ParseBitcodeInto(M)) { 3381 R->releaseBuffer(); // Never take ownership on error. 3382 delete M; // Also deletes R. 3383 return EC; 3384 } 3385 3386 R->materializeForwardReferencedFunctions(); 3387 3388 return M; 3389 } 3390 3391 3392 Module *llvm::getStreamedBitcodeModule(const std::string &name, 3393 DataStreamer *streamer, 3394 LLVMContext &Context, 3395 std::string *ErrMsg) { 3396 Module *M = new Module(name, Context); 3397 BitcodeReader *R = new BitcodeReader(streamer, Context); 3398 M->setMaterializer(R); 3399 if (std::error_code EC = R->ParseBitcodeInto(M)) { 3400 if (ErrMsg) 3401 *ErrMsg = EC.message(); 3402 delete M; // Also deletes R. 3403 return nullptr; 3404 } 3405 return M; 3406 } 3407 3408 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer, 3409 LLVMContext &Context) { 3410 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context); 3411 if (!ModuleOrErr) 3412 return ModuleOrErr; 3413 Module *M = ModuleOrErr.get(); 3414 // Read in the entire module, and destroy the BitcodeReader. 3415 if (std::error_code EC = M->materializeAllPermanently(true)) { 3416 delete M; 3417 return EC; 3418 } 3419 3420 // TODO: Restore the use-lists to the in-memory state when the bitcode was 3421 // written. We must defer until the Module has been fully materialized. 3422 3423 return M; 3424 } 3425 3426 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer, 3427 LLVMContext& Context, 3428 std::string *ErrMsg) { 3429 BitcodeReader *R = new BitcodeReader(Buffer, Context); 3430 3431 std::string Triple(""); 3432 if (std::error_code EC = R->ParseTriple(Triple)) 3433 if (ErrMsg) 3434 *ErrMsg = EC.message(); 3435 3436 R->releaseBuffer(); 3437 delete R; 3438 return Triple; 3439 } 3440