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