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 if (BufferOwned) 43 delete Buffer; 44 Buffer = nullptr; 45 std::vector<Type*>().swap(TypeList); 46 ValueList.clear(); 47 MDValueList.clear(); 48 49 std::vector<AttributeSet>().swap(MAttributes); 50 std::vector<BasicBlock*>().swap(FunctionBBs); 51 std::vector<Function*>().swap(FunctionsWithBodies); 52 DeferredFunctionInfo.clear(); 53 MDKindMap.clear(); 54 55 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references"); 56 } 57 58 //===----------------------------------------------------------------------===// 59 // Helper functions to implement forward reference resolution, etc. 60 //===----------------------------------------------------------------------===// 61 62 /// ConvertToString - Convert a string from a record into an std::string, return 63 /// true on failure. 64 template<typename StrTy> 65 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx, 66 StrTy &Result) { 67 if (Idx > Record.size()) 68 return true; 69 70 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 71 Result += (char)Record[i]; 72 return false; 73 } 74 75 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) { 76 switch (Val) { 77 default: // Map unknown/new linkages to external 78 case 0: return GlobalValue::ExternalLinkage; 79 case 1: return GlobalValue::WeakAnyLinkage; 80 case 2: return GlobalValue::AppendingLinkage; 81 case 3: return GlobalValue::InternalLinkage; 82 case 4: return GlobalValue::LinkOnceAnyLinkage; 83 case 5: return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 84 case 6: return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 85 case 7: return GlobalValue::ExternalWeakLinkage; 86 case 8: return GlobalValue::CommonLinkage; 87 case 9: return GlobalValue::PrivateLinkage; 88 case 10: return GlobalValue::WeakODRLinkage; 89 case 11: return GlobalValue::LinkOnceODRLinkage; 90 case 12: return GlobalValue::AvailableExternallyLinkage; 91 case 13: 92 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 93 case 14: 94 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 95 } 96 } 97 98 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 99 switch (Val) { 100 default: // Map unknown visibilities to default. 101 case 0: return GlobalValue::DefaultVisibility; 102 case 1: return GlobalValue::HiddenVisibility; 103 case 2: return GlobalValue::ProtectedVisibility; 104 } 105 } 106 107 static GlobalValue::DLLStorageClassTypes 108 GetDecodedDLLStorageClass(unsigned Val) { 109 switch (Val) { 110 default: // Map unknown values to default. 111 case 0: return GlobalValue::DefaultStorageClass; 112 case 1: return GlobalValue::DLLImportStorageClass; 113 case 2: return GlobalValue::DLLExportStorageClass; 114 } 115 } 116 117 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) { 118 switch (Val) { 119 case 0: return GlobalVariable::NotThreadLocal; 120 default: // Map unknown non-zero value to general dynamic. 121 case 1: return GlobalVariable::GeneralDynamicTLSModel; 122 case 2: return GlobalVariable::LocalDynamicTLSModel; 123 case 3: return GlobalVariable::InitialExecTLSModel; 124 case 4: return GlobalVariable::LocalExecTLSModel; 125 } 126 } 127 128 static int GetDecodedCastOpcode(unsigned Val) { 129 switch (Val) { 130 default: return -1; 131 case bitc::CAST_TRUNC : return Instruction::Trunc; 132 case bitc::CAST_ZEXT : return Instruction::ZExt; 133 case bitc::CAST_SEXT : return Instruction::SExt; 134 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 135 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 136 case bitc::CAST_UITOFP : return Instruction::UIToFP; 137 case bitc::CAST_SITOFP : return Instruction::SIToFP; 138 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 139 case bitc::CAST_FPEXT : return Instruction::FPExt; 140 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 141 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 142 case bitc::CAST_BITCAST : return Instruction::BitCast; 143 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 144 } 145 } 146 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) { 147 switch (Val) { 148 default: return -1; 149 case bitc::BINOP_ADD: 150 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add; 151 case bitc::BINOP_SUB: 152 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub; 153 case bitc::BINOP_MUL: 154 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul; 155 case bitc::BINOP_UDIV: return Instruction::UDiv; 156 case bitc::BINOP_SDIV: 157 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv; 158 case bitc::BINOP_UREM: return Instruction::URem; 159 case bitc::BINOP_SREM: 160 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem; 161 case bitc::BINOP_SHL: return Instruction::Shl; 162 case bitc::BINOP_LSHR: return Instruction::LShr; 163 case bitc::BINOP_ASHR: return Instruction::AShr; 164 case bitc::BINOP_AND: return Instruction::And; 165 case bitc::BINOP_OR: return Instruction::Or; 166 case bitc::BINOP_XOR: return Instruction::Xor; 167 } 168 } 169 170 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) { 171 switch (Val) { 172 default: return AtomicRMWInst::BAD_BINOP; 173 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 174 case bitc::RMW_ADD: return AtomicRMWInst::Add; 175 case bitc::RMW_SUB: return AtomicRMWInst::Sub; 176 case bitc::RMW_AND: return AtomicRMWInst::And; 177 case bitc::RMW_NAND: return AtomicRMWInst::Nand; 178 case bitc::RMW_OR: return AtomicRMWInst::Or; 179 case bitc::RMW_XOR: return AtomicRMWInst::Xor; 180 case bitc::RMW_MAX: return AtomicRMWInst::Max; 181 case bitc::RMW_MIN: return AtomicRMWInst::Min; 182 case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 183 case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 184 } 185 } 186 187 static AtomicOrdering GetDecodedOrdering(unsigned Val) { 188 switch (Val) { 189 case bitc::ORDERING_NOTATOMIC: return NotAtomic; 190 case bitc::ORDERING_UNORDERED: return Unordered; 191 case bitc::ORDERING_MONOTONIC: return Monotonic; 192 case bitc::ORDERING_ACQUIRE: return Acquire; 193 case bitc::ORDERING_RELEASE: return Release; 194 case bitc::ORDERING_ACQREL: return AcquireRelease; 195 default: // Map unknown orderings to sequentially-consistent. 196 case bitc::ORDERING_SEQCST: return SequentiallyConsistent; 197 } 198 } 199 200 static SynchronizationScope GetDecodedSynchScope(unsigned Val) { 201 switch (Val) { 202 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread; 203 default: // Map unknown scopes to cross-thread. 204 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread; 205 } 206 } 207 208 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) { 209 switch (Val) { 210 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 211 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 212 } 213 } 214 215 namespace llvm { 216 namespace { 217 /// @brief A class for maintaining the slot number definition 218 /// as a placeholder for the actual definition for forward constants defs. 219 class ConstantPlaceHolder : public ConstantExpr { 220 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION; 221 public: 222 // allocate space for exactly one operand 223 void *operator new(size_t s) { 224 return User::operator new(s, 1); 225 } 226 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context) 227 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 228 Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 229 } 230 231 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast. 232 static bool classof(const Value *V) { 233 return isa<ConstantExpr>(V) && 234 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 235 } 236 237 238 /// Provide fast operand accessors 239 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 240 }; 241 } 242 243 // FIXME: can we inherit this from ConstantExpr? 244 template <> 245 struct OperandTraits<ConstantPlaceHolder> : 246 public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 247 }; 248 } 249 250 251 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { 252 if (Idx == size()) { 253 push_back(V); 254 return; 255 } 256 257 if (Idx >= size()) 258 resize(Idx+1); 259 260 WeakVH &OldV = ValuePtrs[Idx]; 261 if (!OldV) { 262 OldV = V; 263 return; 264 } 265 266 // Handle constants and non-constants (e.g. instrs) differently for 267 // efficiency. 268 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 269 ResolveConstants.push_back(std::make_pair(PHC, Idx)); 270 OldV = V; 271 } else { 272 // If there was a forward reference to this value, replace it. 273 Value *PrevVal = OldV; 274 OldV->replaceAllUsesWith(V); 275 delete PrevVal; 276 } 277 } 278 279 280 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 281 Type *Ty) { 282 if (Idx >= size()) 283 resize(Idx + 1); 284 285 if (Value *V = ValuePtrs[Idx]) { 286 assert(Ty == V->getType() && "Type mismatch in constant table!"); 287 return cast<Constant>(V); 288 } 289 290 // Create and return a placeholder, which will later be RAUW'd. 291 Constant *C = new ConstantPlaceHolder(Ty, Context); 292 ValuePtrs[Idx] = C; 293 return C; 294 } 295 296 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 297 if (Idx >= size()) 298 resize(Idx + 1); 299 300 if (Value *V = ValuePtrs[Idx]) { 301 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!"); 302 return V; 303 } 304 305 // No type specified, must be invalid reference. 306 if (!Ty) return nullptr; 307 308 // Create and return a placeholder, which will later be RAUW'd. 309 Value *V = new Argument(Ty); 310 ValuePtrs[Idx] = V; 311 return V; 312 } 313 314 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk 315 /// resolves any forward references. The idea behind this is that we sometimes 316 /// get constants (such as large arrays) which reference *many* forward ref 317 /// constants. Replacing each of these causes a lot of thrashing when 318 /// building/reuniquing the constant. Instead of doing this, we look at all the 319 /// uses and rewrite all the place holders at once for any constant that uses 320 /// a placeholder. 321 void BitcodeReaderValueList::ResolveConstantForwardRefs() { 322 // Sort the values by-pointer so that they are efficient to look up with a 323 // binary search. 324 std::sort(ResolveConstants.begin(), ResolveConstants.end()); 325 326 SmallVector<Constant*, 64> NewOps; 327 328 while (!ResolveConstants.empty()) { 329 Value *RealVal = operator[](ResolveConstants.back().second); 330 Constant *Placeholder = ResolveConstants.back().first; 331 ResolveConstants.pop_back(); 332 333 // Loop over all users of the placeholder, updating them to reference the 334 // new value. If they reference more than one placeholder, update them all 335 // at once. 336 while (!Placeholder->use_empty()) { 337 auto UI = Placeholder->user_begin(); 338 User *U = *UI; 339 340 // If the using object isn't uniqued, just update the operands. This 341 // handles instructions and initializers for global variables. 342 if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 343 UI.getUse().set(RealVal); 344 continue; 345 } 346 347 // Otherwise, we have a constant that uses the placeholder. Replace that 348 // constant with a new constant that has *all* placeholder uses updated. 349 Constant *UserC = cast<Constant>(U); 350 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 351 I != E; ++I) { 352 Value *NewOp; 353 if (!isa<ConstantPlaceHolder>(*I)) { 354 // Not a placeholder reference. 355 NewOp = *I; 356 } else if (*I == Placeholder) { 357 // Common case is that it just references this one placeholder. 358 NewOp = RealVal; 359 } else { 360 // Otherwise, look up the placeholder in ResolveConstants. 361 ResolveConstantsTy::iterator It = 362 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 363 std::pair<Constant*, unsigned>(cast<Constant>(*I), 364 0)); 365 assert(It != ResolveConstants.end() && It->first == *I); 366 NewOp = operator[](It->second); 367 } 368 369 NewOps.push_back(cast<Constant>(NewOp)); 370 } 371 372 // Make the new constant. 373 Constant *NewC; 374 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 375 NewC = ConstantArray::get(UserCA->getType(), NewOps); 376 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 377 NewC = ConstantStruct::get(UserCS->getType(), NewOps); 378 } else if (isa<ConstantVector>(UserC)) { 379 NewC = ConstantVector::get(NewOps); 380 } else { 381 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 382 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 383 } 384 385 UserC->replaceAllUsesWith(NewC); 386 UserC->destroyConstant(); 387 NewOps.clear(); 388 } 389 390 // Update all ValueHandles, they should be the only users at this point. 391 Placeholder->replaceAllUsesWith(RealVal); 392 delete Placeholder; 393 } 394 } 395 396 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) { 397 if (Idx == size()) { 398 push_back(V); 399 return; 400 } 401 402 if (Idx >= size()) 403 resize(Idx+1); 404 405 WeakVH &OldV = MDValuePtrs[Idx]; 406 if (!OldV) { 407 OldV = V; 408 return; 409 } 410 411 // If there was a forward reference to this value, replace it. 412 MDNode *PrevVal = cast<MDNode>(OldV); 413 OldV->replaceAllUsesWith(V); 414 MDNode::deleteTemporary(PrevVal); 415 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new 416 // value for Idx. 417 MDValuePtrs[Idx] = V; 418 } 419 420 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) { 421 if (Idx >= size()) 422 resize(Idx + 1); 423 424 if (Value *V = MDValuePtrs[Idx]) { 425 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!"); 426 return V; 427 } 428 429 // Create and return a placeholder, which will later be RAUW'd. 430 Value *V = MDNode::getTemporary(Context, None); 431 MDValuePtrs[Idx] = V; 432 return V; 433 } 434 435 Type *BitcodeReader::getTypeByID(unsigned ID) { 436 // The type table size is always specified correctly. 437 if (ID >= TypeList.size()) 438 return nullptr; 439 440 if (Type *Ty = TypeList[ID]) 441 return Ty; 442 443 // If we have a forward reference, the only possible case is when it is to a 444 // named struct. Just create a placeholder for now. 445 return TypeList[ID] = StructType::create(Context); 446 } 447 448 449 //===----------------------------------------------------------------------===// 450 // Functions for parsing blocks from the bitcode file 451 //===----------------------------------------------------------------------===// 452 453 454 /// \brief This fills an AttrBuilder object with the LLVM attributes that have 455 /// been decoded from the given integer. This function must stay in sync with 456 /// 'encodeLLVMAttributesForBitcode'. 457 static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 458 uint64_t EncodedAttrs) { 459 // FIXME: Remove in 4.0. 460 461 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 462 // the bits above 31 down by 11 bits. 463 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 464 assert((!Alignment || isPowerOf2_32(Alignment)) && 465 "Alignment must be a power of two."); 466 467 if (Alignment) 468 B.addAlignmentAttr(Alignment); 469 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 470 (EncodedAttrs & 0xffff)); 471 } 472 473 error_code BitcodeReader::ParseAttributeBlock() { 474 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 475 return Error(InvalidRecord); 476 477 if (!MAttributes.empty()) 478 return Error(InvalidMultipleBlocks); 479 480 SmallVector<uint64_t, 64> Record; 481 482 SmallVector<AttributeSet, 8> Attrs; 483 484 // Read all the records. 485 while (1) { 486 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 487 488 switch (Entry.Kind) { 489 case BitstreamEntry::SubBlock: // Handled for us already. 490 case BitstreamEntry::Error: 491 return Error(MalformedBlock); 492 case BitstreamEntry::EndBlock: 493 return error_code(); 494 case BitstreamEntry::Record: 495 // The interesting case. 496 break; 497 } 498 499 // Read a record. 500 Record.clear(); 501 switch (Stream.readRecord(Entry.ID, Record)) { 502 default: // Default behavior: ignore. 503 break; 504 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 505 // FIXME: Remove in 4.0. 506 if (Record.size() & 1) 507 return Error(InvalidRecord); 508 509 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 510 AttrBuilder B; 511 decodeLLVMAttributesForBitcode(B, Record[i+1]); 512 Attrs.push_back(AttributeSet::get(Context, Record[i], B)); 513 } 514 515 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 516 Attrs.clear(); 517 break; 518 } 519 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 520 for (unsigned i = 0, e = Record.size(); i != e; ++i) 521 Attrs.push_back(MAttributeGroups[Record[i]]); 522 523 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 524 Attrs.clear(); 525 break; 526 } 527 } 528 } 529 } 530 531 // Returns Attribute::None on unrecognized codes. 532 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) { 533 switch (Code) { 534 default: 535 return Attribute::None; 536 case bitc::ATTR_KIND_ALIGNMENT: 537 return Attribute::Alignment; 538 case bitc::ATTR_KIND_ALWAYS_INLINE: 539 return Attribute::AlwaysInline; 540 case bitc::ATTR_KIND_BUILTIN: 541 return Attribute::Builtin; 542 case bitc::ATTR_KIND_BY_VAL: 543 return Attribute::ByVal; 544 case bitc::ATTR_KIND_IN_ALLOCA: 545 return Attribute::InAlloca; 546 case bitc::ATTR_KIND_COLD: 547 return Attribute::Cold; 548 case bitc::ATTR_KIND_INLINE_HINT: 549 return Attribute::InlineHint; 550 case bitc::ATTR_KIND_IN_REG: 551 return Attribute::InReg; 552 case bitc::ATTR_KIND_JUMP_TABLE: 553 return Attribute::JumpTable; 554 case bitc::ATTR_KIND_MIN_SIZE: 555 return Attribute::MinSize; 556 case bitc::ATTR_KIND_NAKED: 557 return Attribute::Naked; 558 case bitc::ATTR_KIND_NEST: 559 return Attribute::Nest; 560 case bitc::ATTR_KIND_NO_ALIAS: 561 return Attribute::NoAlias; 562 case bitc::ATTR_KIND_NO_BUILTIN: 563 return Attribute::NoBuiltin; 564 case bitc::ATTR_KIND_NO_CAPTURE: 565 return Attribute::NoCapture; 566 case bitc::ATTR_KIND_NO_DUPLICATE: 567 return Attribute::NoDuplicate; 568 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 569 return Attribute::NoImplicitFloat; 570 case bitc::ATTR_KIND_NO_INLINE: 571 return Attribute::NoInline; 572 case bitc::ATTR_KIND_NON_LAZY_BIND: 573 return Attribute::NonLazyBind; 574 case bitc::ATTR_KIND_NON_NULL: 575 return Attribute::NonNull; 576 case bitc::ATTR_KIND_NO_RED_ZONE: 577 return Attribute::NoRedZone; 578 case bitc::ATTR_KIND_NO_RETURN: 579 return Attribute::NoReturn; 580 case bitc::ATTR_KIND_NO_UNWIND: 581 return Attribute::NoUnwind; 582 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 583 return Attribute::OptimizeForSize; 584 case bitc::ATTR_KIND_OPTIMIZE_NONE: 585 return Attribute::OptimizeNone; 586 case bitc::ATTR_KIND_READ_NONE: 587 return Attribute::ReadNone; 588 case bitc::ATTR_KIND_READ_ONLY: 589 return Attribute::ReadOnly; 590 case bitc::ATTR_KIND_RETURNED: 591 return Attribute::Returned; 592 case bitc::ATTR_KIND_RETURNS_TWICE: 593 return Attribute::ReturnsTwice; 594 case bitc::ATTR_KIND_S_EXT: 595 return Attribute::SExt; 596 case bitc::ATTR_KIND_STACK_ALIGNMENT: 597 return Attribute::StackAlignment; 598 case bitc::ATTR_KIND_STACK_PROTECT: 599 return Attribute::StackProtect; 600 case bitc::ATTR_KIND_STACK_PROTECT_REQ: 601 return Attribute::StackProtectReq; 602 case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 603 return Attribute::StackProtectStrong; 604 case bitc::ATTR_KIND_STRUCT_RET: 605 return Attribute::StructRet; 606 case bitc::ATTR_KIND_SANITIZE_ADDRESS: 607 return Attribute::SanitizeAddress; 608 case bitc::ATTR_KIND_SANITIZE_THREAD: 609 return Attribute::SanitizeThread; 610 case bitc::ATTR_KIND_SANITIZE_MEMORY: 611 return Attribute::SanitizeMemory; 612 case bitc::ATTR_KIND_UW_TABLE: 613 return Attribute::UWTable; 614 case bitc::ATTR_KIND_Z_EXT: 615 return Attribute::ZExt; 616 } 617 } 618 619 error_code BitcodeReader::ParseAttrKind(uint64_t Code, 620 Attribute::AttrKind *Kind) { 621 *Kind = GetAttrFromCode(Code); 622 if (*Kind == Attribute::None) 623 return Error(InvalidValue); 624 return error_code(); 625 } 626 627 error_code BitcodeReader::ParseAttributeGroupBlock() { 628 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 629 return Error(InvalidRecord); 630 631 if (!MAttributeGroups.empty()) 632 return Error(InvalidMultipleBlocks); 633 634 SmallVector<uint64_t, 64> Record; 635 636 // Read all the records. 637 while (1) { 638 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 639 640 switch (Entry.Kind) { 641 case BitstreamEntry::SubBlock: // Handled for us already. 642 case BitstreamEntry::Error: 643 return Error(MalformedBlock); 644 case BitstreamEntry::EndBlock: 645 return error_code(); 646 case BitstreamEntry::Record: 647 // The interesting case. 648 break; 649 } 650 651 // Read a record. 652 Record.clear(); 653 switch (Stream.readRecord(Entry.ID, Record)) { 654 default: // Default behavior: ignore. 655 break; 656 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 657 if (Record.size() < 3) 658 return Error(InvalidRecord); 659 660 uint64_t GrpID = Record[0]; 661 uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 662 663 AttrBuilder B; 664 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 665 if (Record[i] == 0) { // Enum attribute 666 Attribute::AttrKind Kind; 667 if (error_code EC = ParseAttrKind(Record[++i], &Kind)) 668 return EC; 669 670 B.addAttribute(Kind); 671 } else if (Record[i] == 1) { // Align attribute 672 Attribute::AttrKind Kind; 673 if (error_code EC = ParseAttrKind(Record[++i], &Kind)) 674 return EC; 675 if (Kind == Attribute::Alignment) 676 B.addAlignmentAttr(Record[++i]); 677 else 678 B.addStackAlignmentAttr(Record[++i]); 679 } else { // String attribute 680 assert((Record[i] == 3 || Record[i] == 4) && 681 "Invalid attribute group entry"); 682 bool HasValue = (Record[i++] == 4); 683 SmallString<64> KindStr; 684 SmallString<64> ValStr; 685 686 while (Record[i] != 0 && i != e) 687 KindStr += Record[i++]; 688 assert(Record[i] == 0 && "Kind string not null terminated"); 689 690 if (HasValue) { 691 // Has a value associated with it. 692 ++i; // Skip the '0' that terminates the "kind" string. 693 while (Record[i] != 0 && i != e) 694 ValStr += Record[i++]; 695 assert(Record[i] == 0 && "Value string not null terminated"); 696 } 697 698 B.addAttribute(KindStr.str(), ValStr.str()); 699 } 700 } 701 702 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B); 703 break; 704 } 705 } 706 } 707 } 708 709 error_code BitcodeReader::ParseTypeTable() { 710 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 711 return Error(InvalidRecord); 712 713 return ParseTypeTableBody(); 714 } 715 716 error_code BitcodeReader::ParseTypeTableBody() { 717 if (!TypeList.empty()) 718 return Error(InvalidMultipleBlocks); 719 720 SmallVector<uint64_t, 64> Record; 721 unsigned NumRecords = 0; 722 723 SmallString<64> TypeName; 724 725 // Read all the records for this type table. 726 while (1) { 727 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 728 729 switch (Entry.Kind) { 730 case BitstreamEntry::SubBlock: // Handled for us already. 731 case BitstreamEntry::Error: 732 return Error(MalformedBlock); 733 case BitstreamEntry::EndBlock: 734 if (NumRecords != TypeList.size()) 735 return Error(MalformedBlock); 736 return error_code(); 737 case BitstreamEntry::Record: 738 // The interesting case. 739 break; 740 } 741 742 // Read a record. 743 Record.clear(); 744 Type *ResultTy = nullptr; 745 switch (Stream.readRecord(Entry.ID, Record)) { 746 default: 747 return Error(InvalidValue); 748 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 749 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 750 // type list. This allows us to reserve space. 751 if (Record.size() < 1) 752 return Error(InvalidRecord); 753 TypeList.resize(Record[0]); 754 continue; 755 case bitc::TYPE_CODE_VOID: // VOID 756 ResultTy = Type::getVoidTy(Context); 757 break; 758 case bitc::TYPE_CODE_HALF: // HALF 759 ResultTy = Type::getHalfTy(Context); 760 break; 761 case bitc::TYPE_CODE_FLOAT: // FLOAT 762 ResultTy = Type::getFloatTy(Context); 763 break; 764 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 765 ResultTy = Type::getDoubleTy(Context); 766 break; 767 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 768 ResultTy = Type::getX86_FP80Ty(Context); 769 break; 770 case bitc::TYPE_CODE_FP128: // FP128 771 ResultTy = Type::getFP128Ty(Context); 772 break; 773 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 774 ResultTy = Type::getPPC_FP128Ty(Context); 775 break; 776 case bitc::TYPE_CODE_LABEL: // LABEL 777 ResultTy = Type::getLabelTy(Context); 778 break; 779 case bitc::TYPE_CODE_METADATA: // METADATA 780 ResultTy = Type::getMetadataTy(Context); 781 break; 782 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 783 ResultTy = Type::getX86_MMXTy(Context); 784 break; 785 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 786 if (Record.size() < 1) 787 return Error(InvalidRecord); 788 789 ResultTy = IntegerType::get(Context, Record[0]); 790 break; 791 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 792 // [pointee type, address space] 793 if (Record.size() < 1) 794 return Error(InvalidRecord); 795 unsigned AddressSpace = 0; 796 if (Record.size() == 2) 797 AddressSpace = Record[1]; 798 ResultTy = getTypeByID(Record[0]); 799 if (!ResultTy) 800 return Error(InvalidType); 801 ResultTy = PointerType::get(ResultTy, AddressSpace); 802 break; 803 } 804 case bitc::TYPE_CODE_FUNCTION_OLD: { 805 // FIXME: attrid is dead, remove it in LLVM 4.0 806 // FUNCTION: [vararg, attrid, retty, paramty x N] 807 if (Record.size() < 3) 808 return Error(InvalidRecord); 809 SmallVector<Type*, 8> ArgTys; 810 for (unsigned i = 3, e = Record.size(); i != e; ++i) { 811 if (Type *T = getTypeByID(Record[i])) 812 ArgTys.push_back(T); 813 else 814 break; 815 } 816 817 ResultTy = getTypeByID(Record[2]); 818 if (!ResultTy || ArgTys.size() < Record.size()-3) 819 return Error(InvalidType); 820 821 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 822 break; 823 } 824 case bitc::TYPE_CODE_FUNCTION: { 825 // FUNCTION: [vararg, retty, paramty x N] 826 if (Record.size() < 2) 827 return Error(InvalidRecord); 828 SmallVector<Type*, 8> ArgTys; 829 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 830 if (Type *T = getTypeByID(Record[i])) 831 ArgTys.push_back(T); 832 else 833 break; 834 } 835 836 ResultTy = getTypeByID(Record[1]); 837 if (!ResultTy || ArgTys.size() < Record.size()-2) 838 return Error(InvalidType); 839 840 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 841 break; 842 } 843 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 844 if (Record.size() < 1) 845 return Error(InvalidRecord); 846 SmallVector<Type*, 8> EltTys; 847 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 848 if (Type *T = getTypeByID(Record[i])) 849 EltTys.push_back(T); 850 else 851 break; 852 } 853 if (EltTys.size() != Record.size()-1) 854 return Error(InvalidType); 855 ResultTy = StructType::get(Context, EltTys, Record[0]); 856 break; 857 } 858 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 859 if (ConvertToString(Record, 0, TypeName)) 860 return Error(InvalidRecord); 861 continue; 862 863 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 864 if (Record.size() < 1) 865 return Error(InvalidRecord); 866 867 if (NumRecords >= TypeList.size()) 868 return Error(InvalidTYPETable); 869 870 // Check to see if this was forward referenced, if so fill in the temp. 871 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 872 if (Res) { 873 Res->setName(TypeName); 874 TypeList[NumRecords] = nullptr; 875 } else // Otherwise, create a new struct. 876 Res = StructType::create(Context, TypeName); 877 TypeName.clear(); 878 879 SmallVector<Type*, 8> EltTys; 880 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 881 if (Type *T = getTypeByID(Record[i])) 882 EltTys.push_back(T); 883 else 884 break; 885 } 886 if (EltTys.size() != Record.size()-1) 887 return Error(InvalidRecord); 888 Res->setBody(EltTys, Record[0]); 889 ResultTy = Res; 890 break; 891 } 892 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 893 if (Record.size() != 1) 894 return Error(InvalidRecord); 895 896 if (NumRecords >= TypeList.size()) 897 return Error(InvalidTYPETable); 898 899 // Check to see if this was forward referenced, if so fill in the temp. 900 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 901 if (Res) { 902 Res->setName(TypeName); 903 TypeList[NumRecords] = nullptr; 904 } else // Otherwise, create a new struct with no body. 905 Res = StructType::create(Context, TypeName); 906 TypeName.clear(); 907 ResultTy = Res; 908 break; 909 } 910 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 911 if (Record.size() < 2) 912 return Error(InvalidRecord); 913 if ((ResultTy = getTypeByID(Record[1]))) 914 ResultTy = ArrayType::get(ResultTy, Record[0]); 915 else 916 return Error(InvalidType); 917 break; 918 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 919 if (Record.size() < 2) 920 return Error(InvalidRecord); 921 if ((ResultTy = getTypeByID(Record[1]))) 922 ResultTy = VectorType::get(ResultTy, Record[0]); 923 else 924 return Error(InvalidType); 925 break; 926 } 927 928 if (NumRecords >= TypeList.size()) 929 return Error(InvalidTYPETable); 930 assert(ResultTy && "Didn't read a type?"); 931 assert(!TypeList[NumRecords] && "Already read type?"); 932 TypeList[NumRecords++] = ResultTy; 933 } 934 } 935 936 error_code BitcodeReader::ParseValueSymbolTable() { 937 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 938 return Error(InvalidRecord); 939 940 SmallVector<uint64_t, 64> Record; 941 942 // Read all the records for this value table. 943 SmallString<128> ValueName; 944 while (1) { 945 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 946 947 switch (Entry.Kind) { 948 case BitstreamEntry::SubBlock: // Handled for us already. 949 case BitstreamEntry::Error: 950 return Error(MalformedBlock); 951 case BitstreamEntry::EndBlock: 952 return error_code(); 953 case BitstreamEntry::Record: 954 // The interesting case. 955 break; 956 } 957 958 // Read a record. 959 Record.clear(); 960 switch (Stream.readRecord(Entry.ID, Record)) { 961 default: // Default behavior: unknown type. 962 break; 963 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 964 if (ConvertToString(Record, 1, ValueName)) 965 return Error(InvalidRecord); 966 unsigned ValueID = Record[0]; 967 if (ValueID >= ValueList.size() || !ValueList[ValueID]) 968 return Error(InvalidRecord); 969 Value *V = ValueList[ValueID]; 970 971 V->setName(StringRef(ValueName.data(), ValueName.size())); 972 ValueName.clear(); 973 break; 974 } 975 case bitc::VST_CODE_BBENTRY: { 976 if (ConvertToString(Record, 1, ValueName)) 977 return Error(InvalidRecord); 978 BasicBlock *BB = getBasicBlock(Record[0]); 979 if (!BB) 980 return Error(InvalidRecord); 981 982 BB->setName(StringRef(ValueName.data(), ValueName.size())); 983 ValueName.clear(); 984 break; 985 } 986 } 987 } 988 } 989 990 error_code BitcodeReader::ParseMetadata() { 991 unsigned NextMDValueNo = MDValueList.size(); 992 993 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 994 return Error(InvalidRecord); 995 996 SmallVector<uint64_t, 64> Record; 997 998 // Read all the records. 999 while (1) { 1000 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1001 1002 switch (Entry.Kind) { 1003 case BitstreamEntry::SubBlock: // Handled for us already. 1004 case BitstreamEntry::Error: 1005 return Error(MalformedBlock); 1006 case BitstreamEntry::EndBlock: 1007 return error_code(); 1008 case BitstreamEntry::Record: 1009 // The interesting case. 1010 break; 1011 } 1012 1013 bool IsFunctionLocal = false; 1014 // Read a record. 1015 Record.clear(); 1016 unsigned Code = Stream.readRecord(Entry.ID, Record); 1017 switch (Code) { 1018 default: // Default behavior: ignore. 1019 break; 1020 case bitc::METADATA_NAME: { 1021 // Read name of the named metadata. 1022 SmallString<8> Name(Record.begin(), Record.end()); 1023 Record.clear(); 1024 Code = Stream.ReadCode(); 1025 1026 // METADATA_NAME is always followed by METADATA_NAMED_NODE. 1027 unsigned NextBitCode = Stream.readRecord(Code, Record); 1028 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode; 1029 1030 // Read named metadata elements. 1031 unsigned Size = Record.size(); 1032 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 1033 for (unsigned i = 0; i != Size; ++i) { 1034 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i])); 1035 if (!MD) 1036 return Error(InvalidRecord); 1037 NMD->addOperand(MD); 1038 } 1039 break; 1040 } 1041 case bitc::METADATA_FN_NODE: 1042 IsFunctionLocal = true; 1043 // fall-through 1044 case bitc::METADATA_NODE: { 1045 if (Record.size() % 2 == 1) 1046 return Error(InvalidRecord); 1047 1048 unsigned Size = Record.size(); 1049 SmallVector<Value*, 8> Elts; 1050 for (unsigned i = 0; i != Size; i += 2) { 1051 Type *Ty = getTypeByID(Record[i]); 1052 if (!Ty) 1053 return Error(InvalidRecord); 1054 if (Ty->isMetadataTy()) 1055 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1])); 1056 else if (!Ty->isVoidTy()) 1057 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty)); 1058 else 1059 Elts.push_back(nullptr); 1060 } 1061 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal); 1062 IsFunctionLocal = false; 1063 MDValueList.AssignValue(V, NextMDValueNo++); 1064 break; 1065 } 1066 case bitc::METADATA_STRING: { 1067 SmallString<8> String(Record.begin(), Record.end()); 1068 Value *V = MDString::get(Context, String); 1069 MDValueList.AssignValue(V, NextMDValueNo++); 1070 break; 1071 } 1072 case bitc::METADATA_KIND: { 1073 if (Record.size() < 2) 1074 return Error(InvalidRecord); 1075 1076 unsigned Kind = Record[0]; 1077 SmallString<8> Name(Record.begin()+1, Record.end()); 1078 1079 unsigned NewKind = TheModule->getMDKindID(Name.str()); 1080 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1081 return Error(ConflictingMETADATA_KINDRecords); 1082 break; 1083 } 1084 } 1085 } 1086 } 1087 1088 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in 1089 /// the LSB for dense VBR encoding. 1090 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 1091 if ((V & 1) == 0) 1092 return V >> 1; 1093 if (V != 1) 1094 return -(V >> 1); 1095 // There is no such thing as -0 with integers. "-0" really means MININT. 1096 return 1ULL << 63; 1097 } 1098 1099 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 1100 /// values and aliases that we can. 1101 error_code BitcodeReader::ResolveGlobalAndAliasInits() { 1102 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 1103 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 1104 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 1105 1106 GlobalInitWorklist.swap(GlobalInits); 1107 AliasInitWorklist.swap(AliasInits); 1108 FunctionPrefixWorklist.swap(FunctionPrefixes); 1109 1110 while (!GlobalInitWorklist.empty()) { 1111 unsigned ValID = GlobalInitWorklist.back().second; 1112 if (ValID >= ValueList.size()) { 1113 // Not ready to resolve this yet, it requires something later in the file. 1114 GlobalInits.push_back(GlobalInitWorklist.back()); 1115 } else { 1116 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1117 GlobalInitWorklist.back().first->setInitializer(C); 1118 else 1119 return Error(ExpectedConstant); 1120 } 1121 GlobalInitWorklist.pop_back(); 1122 } 1123 1124 while (!AliasInitWorklist.empty()) { 1125 unsigned ValID = AliasInitWorklist.back().second; 1126 if (ValID >= ValueList.size()) { 1127 AliasInits.push_back(AliasInitWorklist.back()); 1128 } else { 1129 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1130 AliasInitWorklist.back().first->setAliasee(C); 1131 else 1132 return Error(ExpectedConstant); 1133 } 1134 AliasInitWorklist.pop_back(); 1135 } 1136 1137 while (!FunctionPrefixWorklist.empty()) { 1138 unsigned ValID = FunctionPrefixWorklist.back().second; 1139 if (ValID >= ValueList.size()) { 1140 FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 1141 } else { 1142 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1143 FunctionPrefixWorklist.back().first->setPrefixData(C); 1144 else 1145 return Error(ExpectedConstant); 1146 } 1147 FunctionPrefixWorklist.pop_back(); 1148 } 1149 1150 return error_code(); 1151 } 1152 1153 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 1154 SmallVector<uint64_t, 8> Words(Vals.size()); 1155 std::transform(Vals.begin(), Vals.end(), Words.begin(), 1156 BitcodeReader::decodeSignRotatedValue); 1157 1158 return APInt(TypeBits, Words); 1159 } 1160 1161 error_code BitcodeReader::ParseConstants() { 1162 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 1163 return Error(InvalidRecord); 1164 1165 SmallVector<uint64_t, 64> Record; 1166 1167 // Read all the records for this value table. 1168 Type *CurTy = Type::getInt32Ty(Context); 1169 unsigned NextCstNo = ValueList.size(); 1170 while (1) { 1171 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1172 1173 switch (Entry.Kind) { 1174 case BitstreamEntry::SubBlock: // Handled for us already. 1175 case BitstreamEntry::Error: 1176 return Error(MalformedBlock); 1177 case BitstreamEntry::EndBlock: 1178 if (NextCstNo != ValueList.size()) 1179 return Error(InvalidConstantReference); 1180 1181 // Once all the constants have been read, go through and resolve forward 1182 // references. 1183 ValueList.ResolveConstantForwardRefs(); 1184 return error_code(); 1185 case BitstreamEntry::Record: 1186 // The interesting case. 1187 break; 1188 } 1189 1190 // Read a record. 1191 Record.clear(); 1192 Value *V = nullptr; 1193 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 1194 switch (BitCode) { 1195 default: // Default behavior: unknown constant 1196 case bitc::CST_CODE_UNDEF: // UNDEF 1197 V = UndefValue::get(CurTy); 1198 break; 1199 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 1200 if (Record.empty()) 1201 return Error(InvalidRecord); 1202 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 1203 return Error(InvalidRecord); 1204 CurTy = TypeList[Record[0]]; 1205 continue; // Skip the ValueList manipulation. 1206 case bitc::CST_CODE_NULL: // NULL 1207 V = Constant::getNullValue(CurTy); 1208 break; 1209 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 1210 if (!CurTy->isIntegerTy() || Record.empty()) 1211 return Error(InvalidRecord); 1212 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 1213 break; 1214 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 1215 if (!CurTy->isIntegerTy() || Record.empty()) 1216 return Error(InvalidRecord); 1217 1218 APInt VInt = ReadWideAPInt(Record, 1219 cast<IntegerType>(CurTy)->getBitWidth()); 1220 V = ConstantInt::get(Context, VInt); 1221 1222 break; 1223 } 1224 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 1225 if (Record.empty()) 1226 return Error(InvalidRecord); 1227 if (CurTy->isHalfTy()) 1228 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 1229 APInt(16, (uint16_t)Record[0]))); 1230 else if (CurTy->isFloatTy()) 1231 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 1232 APInt(32, (uint32_t)Record[0]))); 1233 else if (CurTy->isDoubleTy()) 1234 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 1235 APInt(64, Record[0]))); 1236 else if (CurTy->isX86_FP80Ty()) { 1237 // Bits are not stored the same way as a normal i80 APInt, compensate. 1238 uint64_t Rearrange[2]; 1239 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 1240 Rearrange[1] = Record[0] >> 48; 1241 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 1242 APInt(80, Rearrange))); 1243 } else if (CurTy->isFP128Ty()) 1244 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 1245 APInt(128, Record))); 1246 else if (CurTy->isPPC_FP128Ty()) 1247 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 1248 APInt(128, Record))); 1249 else 1250 V = UndefValue::get(CurTy); 1251 break; 1252 } 1253 1254 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 1255 if (Record.empty()) 1256 return Error(InvalidRecord); 1257 1258 unsigned Size = Record.size(); 1259 SmallVector<Constant*, 16> Elts; 1260 1261 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 1262 for (unsigned i = 0; i != Size; ++i) 1263 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 1264 STy->getElementType(i))); 1265 V = ConstantStruct::get(STy, Elts); 1266 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 1267 Type *EltTy = ATy->getElementType(); 1268 for (unsigned i = 0; i != Size; ++i) 1269 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1270 V = ConstantArray::get(ATy, Elts); 1271 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 1272 Type *EltTy = VTy->getElementType(); 1273 for (unsigned i = 0; i != Size; ++i) 1274 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1275 V = ConstantVector::get(Elts); 1276 } else { 1277 V = UndefValue::get(CurTy); 1278 } 1279 break; 1280 } 1281 case bitc::CST_CODE_STRING: // STRING: [values] 1282 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 1283 if (Record.empty()) 1284 return Error(InvalidRecord); 1285 1286 SmallString<16> Elts(Record.begin(), Record.end()); 1287 V = ConstantDataArray::getString(Context, Elts, 1288 BitCode == bitc::CST_CODE_CSTRING); 1289 break; 1290 } 1291 case bitc::CST_CODE_DATA: {// DATA: [n x value] 1292 if (Record.empty()) 1293 return Error(InvalidRecord); 1294 1295 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 1296 unsigned Size = Record.size(); 1297 1298 if (EltTy->isIntegerTy(8)) { 1299 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 1300 if (isa<VectorType>(CurTy)) 1301 V = ConstantDataVector::get(Context, Elts); 1302 else 1303 V = ConstantDataArray::get(Context, Elts); 1304 } else if (EltTy->isIntegerTy(16)) { 1305 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 1306 if (isa<VectorType>(CurTy)) 1307 V = ConstantDataVector::get(Context, Elts); 1308 else 1309 V = ConstantDataArray::get(Context, Elts); 1310 } else if (EltTy->isIntegerTy(32)) { 1311 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 1312 if (isa<VectorType>(CurTy)) 1313 V = ConstantDataVector::get(Context, Elts); 1314 else 1315 V = ConstantDataArray::get(Context, Elts); 1316 } else if (EltTy->isIntegerTy(64)) { 1317 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 1318 if (isa<VectorType>(CurTy)) 1319 V = ConstantDataVector::get(Context, Elts); 1320 else 1321 V = ConstantDataArray::get(Context, Elts); 1322 } else if (EltTy->isFloatTy()) { 1323 SmallVector<float, 16> Elts(Size); 1324 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); 1325 if (isa<VectorType>(CurTy)) 1326 V = ConstantDataVector::get(Context, Elts); 1327 else 1328 V = ConstantDataArray::get(Context, Elts); 1329 } else if (EltTy->isDoubleTy()) { 1330 SmallVector<double, 16> Elts(Size); 1331 std::transform(Record.begin(), Record.end(), Elts.begin(), 1332 BitsToDouble); 1333 if (isa<VectorType>(CurTy)) 1334 V = ConstantDataVector::get(Context, Elts); 1335 else 1336 V = ConstantDataArray::get(Context, Elts); 1337 } else { 1338 return Error(InvalidTypeForValue); 1339 } 1340 break; 1341 } 1342 1343 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 1344 if (Record.size() < 3) 1345 return Error(InvalidRecord); 1346 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 1347 if (Opc < 0) { 1348 V = UndefValue::get(CurTy); // Unknown binop. 1349 } else { 1350 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 1351 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 1352 unsigned Flags = 0; 1353 if (Record.size() >= 4) { 1354 if (Opc == Instruction::Add || 1355 Opc == Instruction::Sub || 1356 Opc == Instruction::Mul || 1357 Opc == Instruction::Shl) { 1358 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 1359 Flags |= OverflowingBinaryOperator::NoSignedWrap; 1360 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 1361 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 1362 } else if (Opc == Instruction::SDiv || 1363 Opc == Instruction::UDiv || 1364 Opc == Instruction::LShr || 1365 Opc == Instruction::AShr) { 1366 if (Record[3] & (1 << bitc::PEO_EXACT)) 1367 Flags |= SDivOperator::IsExact; 1368 } 1369 } 1370 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 1371 } 1372 break; 1373 } 1374 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 1375 if (Record.size() < 3) 1376 return Error(InvalidRecord); 1377 int Opc = GetDecodedCastOpcode(Record[0]); 1378 if (Opc < 0) { 1379 V = UndefValue::get(CurTy); // Unknown cast. 1380 } else { 1381 Type *OpTy = getTypeByID(Record[1]); 1382 if (!OpTy) 1383 return Error(InvalidRecord); 1384 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 1385 V = UpgradeBitCastExpr(Opc, Op, CurTy); 1386 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 1387 } 1388 break; 1389 } 1390 case bitc::CST_CODE_CE_INBOUNDS_GEP: 1391 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 1392 if (Record.size() & 1) 1393 return Error(InvalidRecord); 1394 SmallVector<Constant*, 16> Elts; 1395 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1396 Type *ElTy = getTypeByID(Record[i]); 1397 if (!ElTy) 1398 return Error(InvalidRecord); 1399 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 1400 } 1401 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 1402 V = ConstantExpr::getGetElementPtr(Elts[0], Indices, 1403 BitCode == 1404 bitc::CST_CODE_CE_INBOUNDS_GEP); 1405 break; 1406 } 1407 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 1408 if (Record.size() < 3) 1409 return Error(InvalidRecord); 1410 1411 Type *SelectorTy = Type::getInt1Ty(Context); 1412 1413 // If CurTy is a vector of length n, then Record[0] must be a <n x i1> 1414 // vector. Otherwise, it must be a single bit. 1415 if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 1416 SelectorTy = VectorType::get(Type::getInt1Ty(Context), 1417 VTy->getNumElements()); 1418 1419 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 1420 SelectorTy), 1421 ValueList.getConstantFwdRef(Record[1],CurTy), 1422 ValueList.getConstantFwdRef(Record[2],CurTy)); 1423 break; 1424 } 1425 case bitc::CST_CODE_CE_EXTRACTELT 1426 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 1427 if (Record.size() < 3) 1428 return Error(InvalidRecord); 1429 VectorType *OpTy = 1430 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1431 if (!OpTy) 1432 return Error(InvalidRecord); 1433 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1434 Constant *Op1 = nullptr; 1435 if (Record.size() == 4) { 1436 Type *IdxTy = getTypeByID(Record[2]); 1437 if (!IdxTy) 1438 return Error(InvalidRecord); 1439 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 1440 } else // TODO: Remove with llvm 4.0 1441 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1442 if (!Op1) 1443 return Error(InvalidRecord); 1444 V = ConstantExpr::getExtractElement(Op0, Op1); 1445 break; 1446 } 1447 case bitc::CST_CODE_CE_INSERTELT 1448 : { // CE_INSERTELT: [opval, opval, opty, opval] 1449 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1450 if (Record.size() < 3 || !OpTy) 1451 return Error(InvalidRecord); 1452 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1453 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 1454 OpTy->getElementType()); 1455 Constant *Op2 = nullptr; 1456 if (Record.size() == 4) { 1457 Type *IdxTy = getTypeByID(Record[2]); 1458 if (!IdxTy) 1459 return Error(InvalidRecord); 1460 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 1461 } else // TODO: Remove with llvm 4.0 1462 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1463 if (!Op2) 1464 return Error(InvalidRecord); 1465 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 1466 break; 1467 } 1468 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 1469 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1470 if (Record.size() < 3 || !OpTy) 1471 return Error(InvalidRecord); 1472 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1473 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 1474 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1475 OpTy->getNumElements()); 1476 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 1477 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1478 break; 1479 } 1480 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 1481 VectorType *RTy = dyn_cast<VectorType>(CurTy); 1482 VectorType *OpTy = 1483 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1484 if (Record.size() < 4 || !RTy || !OpTy) 1485 return Error(InvalidRecord); 1486 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1487 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1488 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1489 RTy->getNumElements()); 1490 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 1491 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1492 break; 1493 } 1494 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 1495 if (Record.size() < 4) 1496 return Error(InvalidRecord); 1497 Type *OpTy = getTypeByID(Record[0]); 1498 if (!OpTy) 1499 return Error(InvalidRecord); 1500 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1501 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1502 1503 if (OpTy->isFPOrFPVectorTy()) 1504 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 1505 else 1506 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 1507 break; 1508 } 1509 // This maintains backward compatibility, pre-asm dialect keywords. 1510 // FIXME: Remove with the 4.0 release. 1511 case bitc::CST_CODE_INLINEASM_OLD: { 1512 if (Record.size() < 2) 1513 return Error(InvalidRecord); 1514 std::string AsmStr, ConstrStr; 1515 bool HasSideEffects = Record[0] & 1; 1516 bool IsAlignStack = Record[0] >> 1; 1517 unsigned AsmStrSize = Record[1]; 1518 if (2+AsmStrSize >= Record.size()) 1519 return Error(InvalidRecord); 1520 unsigned ConstStrSize = Record[2+AsmStrSize]; 1521 if (3+AsmStrSize+ConstStrSize > Record.size()) 1522 return Error(InvalidRecord); 1523 1524 for (unsigned i = 0; i != AsmStrSize; ++i) 1525 AsmStr += (char)Record[2+i]; 1526 for (unsigned i = 0; i != ConstStrSize; ++i) 1527 ConstrStr += (char)Record[3+AsmStrSize+i]; 1528 PointerType *PTy = cast<PointerType>(CurTy); 1529 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1530 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 1531 break; 1532 } 1533 // This version adds support for the asm dialect keywords (e.g., 1534 // inteldialect). 1535 case bitc::CST_CODE_INLINEASM: { 1536 if (Record.size() < 2) 1537 return Error(InvalidRecord); 1538 std::string AsmStr, ConstrStr; 1539 bool HasSideEffects = Record[0] & 1; 1540 bool IsAlignStack = (Record[0] >> 1) & 1; 1541 unsigned AsmDialect = Record[0] >> 2; 1542 unsigned AsmStrSize = Record[1]; 1543 if (2+AsmStrSize >= Record.size()) 1544 return Error(InvalidRecord); 1545 unsigned ConstStrSize = Record[2+AsmStrSize]; 1546 if (3+AsmStrSize+ConstStrSize > Record.size()) 1547 return Error(InvalidRecord); 1548 1549 for (unsigned i = 0; i != AsmStrSize; ++i) 1550 AsmStr += (char)Record[2+i]; 1551 for (unsigned i = 0; i != ConstStrSize; ++i) 1552 ConstrStr += (char)Record[3+AsmStrSize+i]; 1553 PointerType *PTy = cast<PointerType>(CurTy); 1554 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1555 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 1556 InlineAsm::AsmDialect(AsmDialect)); 1557 break; 1558 } 1559 case bitc::CST_CODE_BLOCKADDRESS:{ 1560 if (Record.size() < 3) 1561 return Error(InvalidRecord); 1562 Type *FnTy = getTypeByID(Record[0]); 1563 if (!FnTy) 1564 return Error(InvalidRecord); 1565 Function *Fn = 1566 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 1567 if (!Fn) 1568 return Error(InvalidRecord); 1569 1570 // If the function is already parsed we can insert the block address right 1571 // away. 1572 if (!Fn->empty()) { 1573 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 1574 for (size_t I = 0, E = Record[2]; I != E; ++I) { 1575 if (BBI == BBE) 1576 return Error(InvalidID); 1577 ++BBI; 1578 } 1579 V = BlockAddress::get(Fn, BBI); 1580 } else { 1581 // Otherwise insert a placeholder and remember it so it can be inserted 1582 // when the function is parsed. 1583 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(), 1584 Type::getInt8Ty(Context), 1585 false, GlobalValue::InternalLinkage, 1586 nullptr, ""); 1587 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef)); 1588 V = FwdRef; 1589 } 1590 break; 1591 } 1592 } 1593 1594 ValueList.AssignValue(V, NextCstNo); 1595 ++NextCstNo; 1596 } 1597 } 1598 1599 error_code BitcodeReader::ParseUseLists() { 1600 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 1601 return Error(InvalidRecord); 1602 1603 SmallVector<uint64_t, 64> Record; 1604 1605 // Read all the records. 1606 while (1) { 1607 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1608 1609 switch (Entry.Kind) { 1610 case BitstreamEntry::SubBlock: // Handled for us already. 1611 case BitstreamEntry::Error: 1612 return Error(MalformedBlock); 1613 case BitstreamEntry::EndBlock: 1614 return error_code(); 1615 case BitstreamEntry::Record: 1616 // The interesting case. 1617 break; 1618 } 1619 1620 // Read a use list record. 1621 Record.clear(); 1622 switch (Stream.readRecord(Entry.ID, Record)) { 1623 default: // Default behavior: unknown type. 1624 break; 1625 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD. 1626 unsigned RecordLength = Record.size(); 1627 if (RecordLength < 1) 1628 return Error(InvalidRecord); 1629 UseListRecords.push_back(Record); 1630 break; 1631 } 1632 } 1633 } 1634 } 1635 1636 /// RememberAndSkipFunctionBody - When we see the block for a function body, 1637 /// remember where it is and then skip it. This lets us lazily deserialize the 1638 /// functions. 1639 error_code BitcodeReader::RememberAndSkipFunctionBody() { 1640 // Get the function we are talking about. 1641 if (FunctionsWithBodies.empty()) 1642 return Error(InsufficientFunctionProtos); 1643 1644 Function *Fn = FunctionsWithBodies.back(); 1645 FunctionsWithBodies.pop_back(); 1646 1647 // Save the current stream state. 1648 uint64_t CurBit = Stream.GetCurrentBitNo(); 1649 DeferredFunctionInfo[Fn] = CurBit; 1650 1651 // Skip over the function block for now. 1652 if (Stream.SkipBlock()) 1653 return Error(InvalidRecord); 1654 return error_code(); 1655 } 1656 1657 error_code BitcodeReader::GlobalCleanup() { 1658 // Patch the initializers for globals and aliases up. 1659 ResolveGlobalAndAliasInits(); 1660 if (!GlobalInits.empty() || !AliasInits.empty()) 1661 return Error(MalformedGlobalInitializerSet); 1662 1663 // Look for intrinsic functions which need to be upgraded at some point 1664 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 1665 FI != FE; ++FI) { 1666 Function *NewFn; 1667 if (UpgradeIntrinsicFunction(FI, NewFn)) 1668 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 1669 } 1670 1671 // Look for global variables which need to be renamed. 1672 for (Module::global_iterator 1673 GI = TheModule->global_begin(), GE = TheModule->global_end(); 1674 GI != GE;) { 1675 GlobalVariable *GV = GI++; 1676 UpgradeGlobalVariable(GV); 1677 } 1678 1679 // Force deallocation of memory for these vectors to favor the client that 1680 // want lazy deserialization. 1681 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 1682 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 1683 return error_code(); 1684 } 1685 1686 error_code BitcodeReader::ParseModule(bool Resume) { 1687 if (Resume) 1688 Stream.JumpToBit(NextUnreadBit); 1689 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 1690 return Error(InvalidRecord); 1691 1692 SmallVector<uint64_t, 64> Record; 1693 std::vector<std::string> SectionTable; 1694 std::vector<std::string> GCTable; 1695 1696 // Read all the records for this module. 1697 while (1) { 1698 BitstreamEntry Entry = Stream.advance(); 1699 1700 switch (Entry.Kind) { 1701 case BitstreamEntry::Error: 1702 return Error(MalformedBlock); 1703 case BitstreamEntry::EndBlock: 1704 return GlobalCleanup(); 1705 1706 case BitstreamEntry::SubBlock: 1707 switch (Entry.ID) { 1708 default: // Skip unknown content. 1709 if (Stream.SkipBlock()) 1710 return Error(InvalidRecord); 1711 break; 1712 case bitc::BLOCKINFO_BLOCK_ID: 1713 if (Stream.ReadBlockInfoBlock()) 1714 return Error(MalformedBlock); 1715 break; 1716 case bitc::PARAMATTR_BLOCK_ID: 1717 if (error_code EC = ParseAttributeBlock()) 1718 return EC; 1719 break; 1720 case bitc::PARAMATTR_GROUP_BLOCK_ID: 1721 if (error_code EC = ParseAttributeGroupBlock()) 1722 return EC; 1723 break; 1724 case bitc::TYPE_BLOCK_ID_NEW: 1725 if (error_code EC = ParseTypeTable()) 1726 return EC; 1727 break; 1728 case bitc::VALUE_SYMTAB_BLOCK_ID: 1729 if (error_code EC = ParseValueSymbolTable()) 1730 return EC; 1731 SeenValueSymbolTable = true; 1732 break; 1733 case bitc::CONSTANTS_BLOCK_ID: 1734 if (error_code EC = ParseConstants()) 1735 return EC; 1736 if (error_code EC = ResolveGlobalAndAliasInits()) 1737 return EC; 1738 break; 1739 case bitc::METADATA_BLOCK_ID: 1740 if (error_code EC = ParseMetadata()) 1741 return EC; 1742 break; 1743 case bitc::FUNCTION_BLOCK_ID: 1744 // If this is the first function body we've seen, reverse the 1745 // FunctionsWithBodies list. 1746 if (!SeenFirstFunctionBody) { 1747 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 1748 if (error_code EC = GlobalCleanup()) 1749 return EC; 1750 SeenFirstFunctionBody = true; 1751 } 1752 1753 if (error_code EC = RememberAndSkipFunctionBody()) 1754 return EC; 1755 // For streaming bitcode, suspend parsing when we reach the function 1756 // bodies. Subsequent materialization calls will resume it when 1757 // necessary. For streaming, the function bodies must be at the end of 1758 // the bitcode. If the bitcode file is old, the symbol table will be 1759 // at the end instead and will not have been seen yet. In this case, 1760 // just finish the parse now. 1761 if (LazyStreamer && SeenValueSymbolTable) { 1762 NextUnreadBit = Stream.GetCurrentBitNo(); 1763 return error_code(); 1764 } 1765 break; 1766 case bitc::USELIST_BLOCK_ID: 1767 if (error_code EC = ParseUseLists()) 1768 return EC; 1769 break; 1770 } 1771 continue; 1772 1773 case BitstreamEntry::Record: 1774 // The interesting case. 1775 break; 1776 } 1777 1778 1779 // Read a record. 1780 switch (Stream.readRecord(Entry.ID, Record)) { 1781 default: break; // Default behavior, ignore unknown content. 1782 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 1783 if (Record.size() < 1) 1784 return Error(InvalidRecord); 1785 // Only version #0 and #1 are supported so far. 1786 unsigned module_version = Record[0]; 1787 switch (module_version) { 1788 default: 1789 return Error(InvalidValue); 1790 case 0: 1791 UseRelativeIDs = false; 1792 break; 1793 case 1: 1794 UseRelativeIDs = true; 1795 break; 1796 } 1797 break; 1798 } 1799 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 1800 std::string S; 1801 if (ConvertToString(Record, 0, S)) 1802 return Error(InvalidRecord); 1803 TheModule->setTargetTriple(S); 1804 break; 1805 } 1806 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 1807 std::string S; 1808 if (ConvertToString(Record, 0, S)) 1809 return Error(InvalidRecord); 1810 TheModule->setDataLayout(S); 1811 break; 1812 } 1813 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 1814 std::string S; 1815 if (ConvertToString(Record, 0, S)) 1816 return Error(InvalidRecord); 1817 TheModule->setModuleInlineAsm(S); 1818 break; 1819 } 1820 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 1821 // FIXME: Remove in 4.0. 1822 std::string S; 1823 if (ConvertToString(Record, 0, S)) 1824 return Error(InvalidRecord); 1825 // Ignore value. 1826 break; 1827 } 1828 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 1829 std::string S; 1830 if (ConvertToString(Record, 0, S)) 1831 return Error(InvalidRecord); 1832 SectionTable.push_back(S); 1833 break; 1834 } 1835 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 1836 std::string S; 1837 if (ConvertToString(Record, 0, S)) 1838 return Error(InvalidRecord); 1839 GCTable.push_back(S); 1840 break; 1841 } 1842 // GLOBALVAR: [pointer type, isconst, initid, 1843 // linkage, alignment, section, visibility, threadlocal, 1844 // unnamed_addr, dllstorageclass] 1845 case bitc::MODULE_CODE_GLOBALVAR: { 1846 if (Record.size() < 6) 1847 return Error(InvalidRecord); 1848 Type *Ty = getTypeByID(Record[0]); 1849 if (!Ty) 1850 return Error(InvalidRecord); 1851 if (!Ty->isPointerTy()) 1852 return Error(InvalidTypeForValue); 1853 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 1854 Ty = cast<PointerType>(Ty)->getElementType(); 1855 1856 bool isConstant = Record[1]; 1857 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 1858 unsigned Alignment = (1 << Record[4]) >> 1; 1859 std::string Section; 1860 if (Record[5]) { 1861 if (Record[5]-1 >= SectionTable.size()) 1862 return Error(InvalidID); 1863 Section = SectionTable[Record[5]-1]; 1864 } 1865 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 1866 // Local linkage must have default visibility. 1867 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 1868 // FIXME: Change to an error if non-default in 4.0. 1869 Visibility = GetDecodedVisibility(Record[6]); 1870 1871 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 1872 if (Record.size() > 7) 1873 TLM = GetDecodedThreadLocalMode(Record[7]); 1874 1875 bool UnnamedAddr = false; 1876 if (Record.size() > 8) 1877 UnnamedAddr = Record[8]; 1878 1879 bool ExternallyInitialized = false; 1880 if (Record.size() > 9) 1881 ExternallyInitialized = Record[9]; 1882 1883 GlobalVariable *NewGV = 1884 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 1885 TLM, AddressSpace, ExternallyInitialized); 1886 NewGV->setAlignment(Alignment); 1887 if (!Section.empty()) 1888 NewGV->setSection(Section); 1889 NewGV->setVisibility(Visibility); 1890 NewGV->setUnnamedAddr(UnnamedAddr); 1891 1892 if (Record.size() > 10) 1893 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10])); 1894 else 1895 UpgradeDLLImportExportLinkage(NewGV, Record[3]); 1896 1897 ValueList.push_back(NewGV); 1898 1899 // Remember which value to use for the global initializer. 1900 if (unsigned InitID = Record[2]) 1901 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 1902 break; 1903 } 1904 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 1905 // alignment, section, visibility, gc, unnamed_addr, 1906 // dllstorageclass] 1907 case bitc::MODULE_CODE_FUNCTION: { 1908 if (Record.size() < 8) 1909 return Error(InvalidRecord); 1910 Type *Ty = getTypeByID(Record[0]); 1911 if (!Ty) 1912 return Error(InvalidRecord); 1913 if (!Ty->isPointerTy()) 1914 return Error(InvalidTypeForValue); 1915 FunctionType *FTy = 1916 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 1917 if (!FTy) 1918 return Error(InvalidTypeForValue); 1919 1920 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 1921 "", TheModule); 1922 1923 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 1924 bool isProto = Record[2]; 1925 Func->setLinkage(GetDecodedLinkage(Record[3])); 1926 Func->setAttributes(getAttributes(Record[4])); 1927 1928 Func->setAlignment((1 << Record[5]) >> 1); 1929 if (Record[6]) { 1930 if (Record[6]-1 >= SectionTable.size()) 1931 return Error(InvalidID); 1932 Func->setSection(SectionTable[Record[6]-1]); 1933 } 1934 // Local linkage must have default visibility. 1935 if (!Func->hasLocalLinkage()) 1936 // FIXME: Change to an error if non-default in 4.0. 1937 Func->setVisibility(GetDecodedVisibility(Record[7])); 1938 if (Record.size() > 8 && Record[8]) { 1939 if (Record[8]-1 > GCTable.size()) 1940 return Error(InvalidID); 1941 Func->setGC(GCTable[Record[8]-1].c_str()); 1942 } 1943 bool UnnamedAddr = false; 1944 if (Record.size() > 9) 1945 UnnamedAddr = Record[9]; 1946 Func->setUnnamedAddr(UnnamedAddr); 1947 if (Record.size() > 10 && Record[10] != 0) 1948 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1)); 1949 1950 if (Record.size() > 11) 1951 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11])); 1952 else 1953 UpgradeDLLImportExportLinkage(Func, Record[3]); 1954 1955 ValueList.push_back(Func); 1956 1957 // If this is a function with a body, remember the prototype we are 1958 // creating now, so that we can match up the body with them later. 1959 if (!isProto) { 1960 FunctionsWithBodies.push_back(Func); 1961 if (LazyStreamer) DeferredFunctionInfo[Func] = 0; 1962 } 1963 break; 1964 } 1965 // ALIAS: [alias type, aliasee val#, linkage] 1966 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass] 1967 case bitc::MODULE_CODE_ALIAS: { 1968 if (Record.size() < 3) 1969 return Error(InvalidRecord); 1970 Type *Ty = getTypeByID(Record[0]); 1971 if (!Ty) 1972 return Error(InvalidRecord); 1973 auto *PTy = dyn_cast<PointerType>(Ty); 1974 if (!PTy) 1975 return Error(InvalidTypeForValue); 1976 1977 auto *NewGA = 1978 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 1979 GetDecodedLinkage(Record[2]), "", TheModule); 1980 // Old bitcode files didn't have visibility field. 1981 // Local linkage must have default visibility. 1982 if (Record.size() > 3 && !NewGA->hasLocalLinkage()) 1983 // FIXME: Change to an error if non-default in 4.0. 1984 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 1985 if (Record.size() > 4) 1986 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4])); 1987 else 1988 UpgradeDLLImportExportLinkage(NewGA, Record[2]); 1989 if (Record.size() > 5) 1990 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5])); 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 error_code BitcodeReader::ParseBitcodeInto(Module *M) { 2008 TheModule = nullptr; 2009 2010 if (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 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 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 (error_code EC = ParseModule(false)) 2049 return EC; 2050 if (LazyStreamer) 2051 return 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 error_code(); 2069 2070 return Error(InvalidRecord); 2071 } 2072 } 2073 } 2074 2075 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 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 error_code BitcodeReader::ParseTriple(std::string &Triple) { 2112 if (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 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 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 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 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 (error_code EC = ParseConstants()) 2236 return EC; 2237 NextValueNo = ValueList.size(); 2238 break; 2239 case bitc::VALUE_SYMTAB_BLOCK_ID: 2240 if (error_code EC = ParseValueSymbolTable()) 2241 return EC; 2242 break; 2243 case bitc::METADATA_ATTACHMENT_ID: 2244 if (error_code EC = ParseMetadataAttachment()) 2245 return EC; 2246 break; 2247 case bitc::METADATA_BLOCK_ID: 2248 if (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] 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 (OpNum + 3 != Record.size() && OpNum + 4 != Record.size())) 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 InstructionList.push_back(I); 2950 break; 2951 } 2952 case bitc::FUNC_CODE_INST_ATOMICRMW: { 2953 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 2954 unsigned OpNum = 0; 2955 Value *Ptr, *Val; 2956 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2957 popValue(Record, OpNum, NextValueNo, 2958 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2959 OpNum+4 != Record.size()) 2960 return Error(InvalidRecord); 2961 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]); 2962 if (Operation < AtomicRMWInst::FIRST_BINOP || 2963 Operation > AtomicRMWInst::LAST_BINOP) 2964 return Error(InvalidRecord); 2965 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2966 if (Ordering == NotAtomic || Ordering == Unordered) 2967 return Error(InvalidRecord); 2968 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2969 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 2970 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 2971 InstructionList.push_back(I); 2972 break; 2973 } 2974 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 2975 if (2 != Record.size()) 2976 return Error(InvalidRecord); 2977 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]); 2978 if (Ordering == NotAtomic || Ordering == Unordered || 2979 Ordering == Monotonic) 2980 return Error(InvalidRecord); 2981 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]); 2982 I = new FenceInst(Context, Ordering, SynchScope); 2983 InstructionList.push_back(I); 2984 break; 2985 } 2986 case bitc::FUNC_CODE_INST_CALL: { 2987 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 2988 if (Record.size() < 3) 2989 return Error(InvalidRecord); 2990 2991 AttributeSet PAL = getAttributes(Record[0]); 2992 unsigned CCInfo = Record[1]; 2993 2994 unsigned OpNum = 2; 2995 Value *Callee; 2996 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 2997 return Error(InvalidRecord); 2998 2999 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 3000 FunctionType *FTy = nullptr; 3001 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 3002 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 3003 return Error(InvalidRecord); 3004 3005 SmallVector<Value*, 16> Args; 3006 // Read the fixed params. 3007 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 3008 if (FTy->getParamType(i)->isLabelTy()) 3009 Args.push_back(getBasicBlock(Record[OpNum])); 3010 else 3011 Args.push_back(getValue(Record, OpNum, NextValueNo, 3012 FTy->getParamType(i))); 3013 if (!Args.back()) 3014 return Error(InvalidRecord); 3015 } 3016 3017 // Read type/value pairs for varargs params. 3018 if (!FTy->isVarArg()) { 3019 if (OpNum != Record.size()) 3020 return Error(InvalidRecord); 3021 } else { 3022 while (OpNum != Record.size()) { 3023 Value *Op; 3024 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3025 return Error(InvalidRecord); 3026 Args.push_back(Op); 3027 } 3028 } 3029 3030 I = CallInst::Create(Callee, Args); 3031 InstructionList.push_back(I); 3032 cast<CallInst>(I)->setCallingConv( 3033 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1)); 3034 CallInst::TailCallKind TCK = CallInst::TCK_None; 3035 if (CCInfo & 1) 3036 TCK = CallInst::TCK_Tail; 3037 if (CCInfo & (1 << 14)) 3038 TCK = CallInst::TCK_MustTail; 3039 cast<CallInst>(I)->setTailCallKind(TCK); 3040 cast<CallInst>(I)->setAttributes(PAL); 3041 break; 3042 } 3043 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 3044 if (Record.size() < 3) 3045 return Error(InvalidRecord); 3046 Type *OpTy = getTypeByID(Record[0]); 3047 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 3048 Type *ResTy = getTypeByID(Record[2]); 3049 if (!OpTy || !Op || !ResTy) 3050 return Error(InvalidRecord); 3051 I = new VAArgInst(Op, ResTy); 3052 InstructionList.push_back(I); 3053 break; 3054 } 3055 } 3056 3057 // Add instruction to end of current BB. If there is no current BB, reject 3058 // this file. 3059 if (!CurBB) { 3060 delete I; 3061 return Error(InvalidInstructionWithNoBB); 3062 } 3063 CurBB->getInstList().push_back(I); 3064 3065 // If this was a terminator instruction, move to the next block. 3066 if (isa<TerminatorInst>(I)) { 3067 ++CurBBNo; 3068 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 3069 } 3070 3071 // Non-void values get registered in the value table for future use. 3072 if (I && !I->getType()->isVoidTy()) 3073 ValueList.AssignValue(I, NextValueNo++); 3074 } 3075 3076 OutOfRecordLoop: 3077 3078 // Check the function list for unresolved values. 3079 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 3080 if (!A->getParent()) { 3081 // We found at least one unresolved value. Nuke them all to avoid leaks. 3082 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 3083 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 3084 A->replaceAllUsesWith(UndefValue::get(A->getType())); 3085 delete A; 3086 } 3087 } 3088 return Error(NeverResolvedValueFoundInFunction); 3089 } 3090 } 3091 3092 // FIXME: Check for unresolved forward-declared metadata references 3093 // and clean up leaks. 3094 3095 // See if anything took the address of blocks in this function. If so, 3096 // resolve them now. 3097 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI = 3098 BlockAddrFwdRefs.find(F); 3099 if (BAFRI != BlockAddrFwdRefs.end()) { 3100 std::vector<BlockAddrRefTy> &RefList = BAFRI->second; 3101 for (unsigned i = 0, e = RefList.size(); i != e; ++i) { 3102 unsigned BlockIdx = RefList[i].first; 3103 if (BlockIdx >= FunctionBBs.size()) 3104 return Error(InvalidID); 3105 3106 GlobalVariable *FwdRef = RefList[i].second; 3107 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx])); 3108 FwdRef->eraseFromParent(); 3109 } 3110 3111 BlockAddrFwdRefs.erase(BAFRI); 3112 } 3113 3114 // Trim the value list down to the size it was before we parsed this function. 3115 ValueList.shrinkTo(ModuleValueListSize); 3116 MDValueList.shrinkTo(ModuleMDValueListSize); 3117 std::vector<BasicBlock*>().swap(FunctionBBs); 3118 return error_code(); 3119 } 3120 3121 /// Find the function body in the bitcode stream 3122 error_code BitcodeReader::FindFunctionInStream(Function *F, 3123 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) { 3124 while (DeferredFunctionInfoIterator->second == 0) { 3125 if (Stream.AtEndOfStream()) 3126 return Error(CouldNotFindFunctionInStream); 3127 // ParseModule will parse the next body in the stream and set its 3128 // position in the DeferredFunctionInfo map. 3129 if (error_code EC = ParseModule(true)) 3130 return EC; 3131 } 3132 return error_code(); 3133 } 3134 3135 //===----------------------------------------------------------------------===// 3136 // GVMaterializer implementation 3137 //===----------------------------------------------------------------------===// 3138 3139 3140 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const { 3141 if (const Function *F = dyn_cast<Function>(GV)) { 3142 return F->isDeclaration() && 3143 DeferredFunctionInfo.count(const_cast<Function*>(F)); 3144 } 3145 return false; 3146 } 3147 3148 error_code BitcodeReader::Materialize(GlobalValue *GV) { 3149 Function *F = dyn_cast<Function>(GV); 3150 // If it's not a function or is already material, ignore the request. 3151 if (!F || !F->isMaterializable()) 3152 return error_code(); 3153 3154 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 3155 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 3156 // If its position is recorded as 0, its body is somewhere in the stream 3157 // but we haven't seen it yet. 3158 if (DFII->second == 0 && LazyStreamer) 3159 if (error_code EC = FindFunctionInStream(F, DFII)) 3160 return EC; 3161 3162 // Move the bit stream to the saved position of the deferred function body. 3163 Stream.JumpToBit(DFII->second); 3164 3165 if (error_code EC = ParseFunctionBody(F)) 3166 return EC; 3167 3168 // Upgrade any old intrinsic calls in the function. 3169 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 3170 E = UpgradedIntrinsics.end(); I != E; ++I) { 3171 if (I->first != I->second) { 3172 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3173 UI != UE;) { 3174 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3175 UpgradeIntrinsicCall(CI, I->second); 3176 } 3177 } 3178 } 3179 3180 return error_code(); 3181 } 3182 3183 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 3184 const Function *F = dyn_cast<Function>(GV); 3185 if (!F || F->isDeclaration()) 3186 return false; 3187 return DeferredFunctionInfo.count(const_cast<Function*>(F)); 3188 } 3189 3190 void BitcodeReader::Dematerialize(GlobalValue *GV) { 3191 Function *F = dyn_cast<Function>(GV); 3192 // If this function isn't dematerializable, this is a noop. 3193 if (!F || !isDematerializable(F)) 3194 return; 3195 3196 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 3197 3198 // Just forget the function body, we can remat it later. 3199 F->deleteBody(); 3200 } 3201 3202 3203 error_code BitcodeReader::MaterializeModule(Module *M) { 3204 assert(M == TheModule && 3205 "Can only Materialize the Module this BitcodeReader is attached to."); 3206 // Iterate over the module, deserializing any functions that are still on 3207 // disk. 3208 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 3209 F != E; ++F) { 3210 if (F->isMaterializable()) { 3211 if (error_code EC = Materialize(F)) 3212 return EC; 3213 } 3214 } 3215 // At this point, if there are any function bodies, the current bit is 3216 // pointing to the END_BLOCK record after them. Now make sure the rest 3217 // of the bits in the module have been read. 3218 if (NextUnreadBit) 3219 ParseModule(true); 3220 3221 // Upgrade any intrinsic calls that slipped through (should not happen!) and 3222 // delete the old functions to clean up. We can't do this unless the entire 3223 // module is materialized because there could always be another function body 3224 // with calls to the old function. 3225 for (std::vector<std::pair<Function*, Function*> >::iterator I = 3226 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 3227 if (I->first != I->second) { 3228 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3229 UI != UE;) { 3230 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3231 UpgradeIntrinsicCall(CI, I->second); 3232 } 3233 if (!I->first->use_empty()) 3234 I->first->replaceAllUsesWith(I->second); 3235 I->first->eraseFromParent(); 3236 } 3237 } 3238 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 3239 3240 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 3241 UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 3242 3243 UpgradeDebugInfo(*M); 3244 return error_code(); 3245 } 3246 3247 error_code BitcodeReader::InitStream() { 3248 if (LazyStreamer) 3249 return InitLazyStream(); 3250 return InitStreamFromBuffer(); 3251 } 3252 3253 error_code BitcodeReader::InitStreamFromBuffer() { 3254 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 3255 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 3256 3257 if (Buffer->getBufferSize() & 3) { 3258 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd)) 3259 return Error(InvalidBitcodeSignature); 3260 else 3261 return Error(BitcodeStreamInvalidSize); 3262 } 3263 3264 // If we have a wrapper header, parse it and ignore the non-bc file contents. 3265 // The magic number is 0x0B17C0DE stored in little endian. 3266 if (isBitcodeWrapper(BufPtr, BufEnd)) 3267 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 3268 return Error(InvalidBitcodeWrapperHeader); 3269 3270 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 3271 Stream.init(*StreamFile); 3272 3273 return error_code(); 3274 } 3275 3276 error_code BitcodeReader::InitLazyStream() { 3277 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 3278 // see it. 3279 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer); 3280 StreamFile.reset(new BitstreamReader(Bytes)); 3281 Stream.init(*StreamFile); 3282 3283 unsigned char buf[16]; 3284 if (Bytes->readBytes(0, 16, buf) == -1) 3285 return Error(BitcodeStreamInvalidSize); 3286 3287 if (!isBitcode(buf, buf + 16)) 3288 return Error(InvalidBitcodeSignature); 3289 3290 if (isBitcodeWrapper(buf, buf + 4)) { 3291 const unsigned char *bitcodeStart = buf; 3292 const unsigned char *bitcodeEnd = buf + 16; 3293 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 3294 Bytes->dropLeadingBytes(bitcodeStart - buf); 3295 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart); 3296 } 3297 return error_code(); 3298 } 3299 3300 namespace { 3301 class BitcodeErrorCategoryType : public error_category { 3302 const char *name() const override { 3303 return "llvm.bitcode"; 3304 } 3305 std::string message(int IE) const override { 3306 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE); 3307 switch (E) { 3308 case BitcodeReader::BitcodeStreamInvalidSize: 3309 return "Bitcode stream length should be >= 16 bytes and a multiple of 4"; 3310 case BitcodeReader::ConflictingMETADATA_KINDRecords: 3311 return "Conflicting METADATA_KIND records"; 3312 case BitcodeReader::CouldNotFindFunctionInStream: 3313 return "Could not find function in stream"; 3314 case BitcodeReader::ExpectedConstant: 3315 return "Expected a constant"; 3316 case BitcodeReader::InsufficientFunctionProtos: 3317 return "Insufficient function protos"; 3318 case BitcodeReader::InvalidBitcodeSignature: 3319 return "Invalid bitcode signature"; 3320 case BitcodeReader::InvalidBitcodeWrapperHeader: 3321 return "Invalid bitcode wrapper header"; 3322 case BitcodeReader::InvalidConstantReference: 3323 return "Invalid ronstant reference"; 3324 case BitcodeReader::InvalidID: 3325 return "Invalid ID"; 3326 case BitcodeReader::InvalidInstructionWithNoBB: 3327 return "Invalid instruction with no BB"; 3328 case BitcodeReader::InvalidRecord: 3329 return "Invalid record"; 3330 case BitcodeReader::InvalidTypeForValue: 3331 return "Invalid type for value"; 3332 case BitcodeReader::InvalidTYPETable: 3333 return "Invalid TYPE table"; 3334 case BitcodeReader::InvalidType: 3335 return "Invalid type"; 3336 case BitcodeReader::MalformedBlock: 3337 return "Malformed block"; 3338 case BitcodeReader::MalformedGlobalInitializerSet: 3339 return "Malformed global initializer set"; 3340 case BitcodeReader::InvalidMultipleBlocks: 3341 return "Invalid multiple blocks"; 3342 case BitcodeReader::NeverResolvedValueFoundInFunction: 3343 return "Never resolved value found in function"; 3344 case BitcodeReader::InvalidValue: 3345 return "Invalid value"; 3346 } 3347 llvm_unreachable("Unknown error type!"); 3348 } 3349 }; 3350 } 3351 3352 const error_category &BitcodeReader::BitcodeErrorCategory() { 3353 static BitcodeErrorCategoryType O; 3354 return O; 3355 } 3356 3357 //===----------------------------------------------------------------------===// 3358 // External interface 3359 //===----------------------------------------------------------------------===// 3360 3361 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file. 3362 /// 3363 ErrorOr<Module *> llvm::getLazyBitcodeModule(MemoryBuffer *Buffer, 3364 LLVMContext &Context) { 3365 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 3366 BitcodeReader *R = new BitcodeReader(Buffer, Context); 3367 M->setMaterializer(R); 3368 if (error_code EC = R->ParseBitcodeInto(M)) { 3369 delete M; // Also deletes R. 3370 return EC; 3371 } 3372 // Have the BitcodeReader dtor delete 'Buffer'. 3373 R->setBufferOwned(true); 3374 3375 R->materializeForwardReferencedFunctions(); 3376 3377 return M; 3378 } 3379 3380 3381 Module *llvm::getStreamedBitcodeModule(const std::string &name, 3382 DataStreamer *streamer, 3383 LLVMContext &Context, 3384 std::string *ErrMsg) { 3385 Module *M = new Module(name, Context); 3386 BitcodeReader *R = new BitcodeReader(streamer, Context); 3387 M->setMaterializer(R); 3388 if (error_code EC = R->ParseBitcodeInto(M)) { 3389 if (ErrMsg) 3390 *ErrMsg = EC.message(); 3391 delete M; // Also deletes R. 3392 return nullptr; 3393 } 3394 R->setBufferOwned(false); // no buffer to delete 3395 return M; 3396 } 3397 3398 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBuffer *Buffer, 3399 LLVMContext &Context) { 3400 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModule(Buffer, Context); 3401 if (!ModuleOrErr) 3402 return ModuleOrErr; 3403 Module *M = ModuleOrErr.get(); 3404 3405 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether 3406 // there was an error. 3407 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false); 3408 3409 // Read in the entire module, and destroy the BitcodeReader. 3410 if (error_code EC = M->materializeAllPermanently()) { 3411 delete M; 3412 return EC; 3413 } 3414 3415 // TODO: Restore the use-lists to the in-memory state when the bitcode was 3416 // written. We must defer until the Module has been fully materialized. 3417 3418 return M; 3419 } 3420 3421 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer, 3422 LLVMContext& Context, 3423 std::string *ErrMsg) { 3424 BitcodeReader *R = new BitcodeReader(Buffer, Context); 3425 // Don't let the BitcodeReader dtor delete 'Buffer'. 3426 R->setBufferOwned(false); 3427 3428 std::string Triple(""); 3429 if (error_code EC = R->ParseTriple(Triple)) 3430 if (ErrMsg) 3431 *ErrMsg = EC.message(); 3432 3433 delete R; 3434 return Triple; 3435 } 3436