BitcodeReader.cpp revision 051a950000e21935165db56695e35bade668193b
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/Instructions.h" 20#include "llvm/Module.h" 21#include "llvm/AutoUpgrade.h" 22#include "llvm/ADT/SmallString.h" 23#include "llvm/ADT/SmallVector.h" 24#include "llvm/Support/MathExtras.h" 25#include "llvm/Support/MemoryBuffer.h" 26using namespace llvm; 27 28void BitcodeReader::FreeState() { 29 delete Buffer; 30 Buffer = 0; 31 std::vector<PATypeHolder>().swap(TypeList); 32 ValueList.clear(); 33 34 std::vector<PAListPtr>().swap(ParamAttrs); 35 std::vector<BasicBlock*>().swap(FunctionBBs); 36 std::vector<Function*>().swap(FunctionsWithBodies); 37 DeferredFunctionInfo.clear(); 38} 39 40//===----------------------------------------------------------------------===// 41// Helper functions to implement forward reference resolution, etc. 42//===----------------------------------------------------------------------===// 43 44/// ConvertToString - Convert a string from a record into an std::string, return 45/// true on failure. 46template<typename StrTy> 47static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx, 48 StrTy &Result) { 49 if (Idx > Record.size()) 50 return true; 51 52 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 53 Result += (char)Record[i]; 54 return false; 55} 56 57static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) { 58 switch (Val) { 59 default: // Map unknown/new linkages to external 60 case 0: return GlobalValue::ExternalLinkage; 61 case 1: return GlobalValue::WeakLinkage; 62 case 2: return GlobalValue::AppendingLinkage; 63 case 3: return GlobalValue::InternalLinkage; 64 case 4: return GlobalValue::LinkOnceLinkage; 65 case 5: return GlobalValue::DLLImportLinkage; 66 case 6: return GlobalValue::DLLExportLinkage; 67 case 7: return GlobalValue::ExternalWeakLinkage; 68 } 69} 70 71static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 72 switch (Val) { 73 default: // Map unknown visibilities to default. 74 case 0: return GlobalValue::DefaultVisibility; 75 case 1: return GlobalValue::HiddenVisibility; 76 case 2: return GlobalValue::ProtectedVisibility; 77 } 78} 79 80static int GetDecodedCastOpcode(unsigned Val) { 81 switch (Val) { 82 default: return -1; 83 case bitc::CAST_TRUNC : return Instruction::Trunc; 84 case bitc::CAST_ZEXT : return Instruction::ZExt; 85 case bitc::CAST_SEXT : return Instruction::SExt; 86 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 87 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 88 case bitc::CAST_UITOFP : return Instruction::UIToFP; 89 case bitc::CAST_SITOFP : return Instruction::SIToFP; 90 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 91 case bitc::CAST_FPEXT : return Instruction::FPExt; 92 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 93 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 94 case bitc::CAST_BITCAST : return Instruction::BitCast; 95 } 96} 97static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) { 98 switch (Val) { 99 default: return -1; 100 case bitc::BINOP_ADD: return Instruction::Add; 101 case bitc::BINOP_SUB: return Instruction::Sub; 102 case bitc::BINOP_MUL: return Instruction::Mul; 103 case bitc::BINOP_UDIV: return Instruction::UDiv; 104 case bitc::BINOP_SDIV: 105 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv; 106 case bitc::BINOP_UREM: return Instruction::URem; 107 case bitc::BINOP_SREM: 108 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem; 109 case bitc::BINOP_SHL: return Instruction::Shl; 110 case bitc::BINOP_LSHR: return Instruction::LShr; 111 case bitc::BINOP_ASHR: return Instruction::AShr; 112 case bitc::BINOP_AND: return Instruction::And; 113 case bitc::BINOP_OR: return Instruction::Or; 114 case bitc::BINOP_XOR: return Instruction::Xor; 115 } 116} 117 118 119namespace { 120 /// @brief A class for maintaining the slot number definition 121 /// as a placeholder for the actual definition for forward constants defs. 122 class ConstantPlaceHolder : public ConstantExpr { 123 ConstantPlaceHolder(); // DO NOT IMPLEMENT 124 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT 125 Use Op; 126 public: 127 // allocate space for exactly one operand 128 void *operator new(size_t s) { 129 return User::operator new(s, 1); 130 } 131 explicit ConstantPlaceHolder(const Type *Ty) 132 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1), 133 Op(UndefValue::get(Type::Int32Ty), this) { 134 } 135 }; 136} 137 138Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 139 const Type *Ty) { 140 if (Idx >= size()) { 141 // Insert a bunch of null values. 142 Uses.resize(Idx+1); 143 OperandList = &Uses[0]; 144 NumOperands = Idx+1; 145 } 146 147 if (Value *V = Uses[Idx]) { 148 assert(Ty == V->getType() && "Type mismatch in constant table!"); 149 return cast<Constant>(V); 150 } 151 152 // Create and return a placeholder, which will later be RAUW'd. 153 Constant *C = new ConstantPlaceHolder(Ty); 154 Uses[Idx].init(C, this); 155 return C; 156} 157 158Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) { 159 if (Idx >= size()) { 160 // Insert a bunch of null values. 161 Uses.resize(Idx+1); 162 OperandList = &Uses[0]; 163 NumOperands = Idx+1; 164 } 165 166 if (Value *V = Uses[Idx]) { 167 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!"); 168 return V; 169 } 170 171 // No type specified, must be invalid reference. 172 if (Ty == 0) return 0; 173 174 // Create and return a placeholder, which will later be RAUW'd. 175 Value *V = new Argument(Ty); 176 Uses[Idx].init(V, this); 177 return V; 178} 179 180 181const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) { 182 // If the TypeID is in range, return it. 183 if (ID < TypeList.size()) 184 return TypeList[ID].get(); 185 if (!isTypeTable) return 0; 186 187 // The type table allows forward references. Push as many Opaque types as 188 // needed to get up to ID. 189 while (TypeList.size() <= ID) 190 TypeList.push_back(OpaqueType::get()); 191 return TypeList.back().get(); 192} 193 194//===----------------------------------------------------------------------===// 195// Functions for parsing blocks from the bitcode file 196//===----------------------------------------------------------------------===// 197 198bool BitcodeReader::ParseParamAttrBlock() { 199 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 200 return Error("Malformed block record"); 201 202 if (!ParamAttrs.empty()) 203 return Error("Multiple PARAMATTR blocks found!"); 204 205 SmallVector<uint64_t, 64> Record; 206 207 SmallVector<ParamAttrsWithIndex, 8> Attrs; 208 209 // Read all the records. 210 while (1) { 211 unsigned Code = Stream.ReadCode(); 212 if (Code == bitc::END_BLOCK) { 213 if (Stream.ReadBlockEnd()) 214 return Error("Error at end of PARAMATTR block"); 215 return false; 216 } 217 218 if (Code == bitc::ENTER_SUBBLOCK) { 219 // No known subblocks, always skip them. 220 Stream.ReadSubBlockID(); 221 if (Stream.SkipBlock()) 222 return Error("Malformed block record"); 223 continue; 224 } 225 226 if (Code == bitc::DEFINE_ABBREV) { 227 Stream.ReadAbbrevRecord(); 228 continue; 229 } 230 231 // Read a record. 232 Record.clear(); 233 switch (Stream.ReadRecord(Code, Record)) { 234 default: // Default behavior: ignore. 235 break; 236 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...] 237 if (Record.size() & 1) 238 return Error("Invalid ENTRY record"); 239 240 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 241 if (Record[i+1] != ParamAttr::None) 242 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1])); 243 } 244 245 ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end())); 246 Attrs.clear(); 247 break; 248 } 249 } 250 } 251} 252 253 254bool BitcodeReader::ParseTypeTable() { 255 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID)) 256 return Error("Malformed block record"); 257 258 if (!TypeList.empty()) 259 return Error("Multiple TYPE_BLOCKs found!"); 260 261 SmallVector<uint64_t, 64> Record; 262 unsigned NumRecords = 0; 263 264 // Read all the records for this type table. 265 while (1) { 266 unsigned Code = Stream.ReadCode(); 267 if (Code == bitc::END_BLOCK) { 268 if (NumRecords != TypeList.size()) 269 return Error("Invalid type forward reference in TYPE_BLOCK"); 270 if (Stream.ReadBlockEnd()) 271 return Error("Error at end of type table block"); 272 return false; 273 } 274 275 if (Code == bitc::ENTER_SUBBLOCK) { 276 // No known subblocks, always skip them. 277 Stream.ReadSubBlockID(); 278 if (Stream.SkipBlock()) 279 return Error("Malformed block record"); 280 continue; 281 } 282 283 if (Code == bitc::DEFINE_ABBREV) { 284 Stream.ReadAbbrevRecord(); 285 continue; 286 } 287 288 // Read a record. 289 Record.clear(); 290 const Type *ResultTy = 0; 291 switch (Stream.ReadRecord(Code, Record)) { 292 default: // Default behavior: unknown type. 293 ResultTy = 0; 294 break; 295 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 296 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 297 // type list. This allows us to reserve space. 298 if (Record.size() < 1) 299 return Error("Invalid TYPE_CODE_NUMENTRY record"); 300 TypeList.reserve(Record[0]); 301 continue; 302 case bitc::TYPE_CODE_VOID: // VOID 303 ResultTy = Type::VoidTy; 304 break; 305 case bitc::TYPE_CODE_FLOAT: // FLOAT 306 ResultTy = Type::FloatTy; 307 break; 308 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 309 ResultTy = Type::DoubleTy; 310 break; 311 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 312 ResultTy = Type::X86_FP80Ty; 313 break; 314 case bitc::TYPE_CODE_FP128: // FP128 315 ResultTy = Type::FP128Ty; 316 break; 317 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 318 ResultTy = Type::PPC_FP128Ty; 319 break; 320 case bitc::TYPE_CODE_LABEL: // LABEL 321 ResultTy = Type::LabelTy; 322 break; 323 case bitc::TYPE_CODE_OPAQUE: // OPAQUE 324 ResultTy = 0; 325 break; 326 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 327 if (Record.size() < 1) 328 return Error("Invalid Integer type record"); 329 330 ResultTy = IntegerType::get(Record[0]); 331 break; 332 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 333 // [pointee type, address space] 334 if (Record.size() < 1) 335 return Error("Invalid POINTER type record"); 336 unsigned AddressSpace = 0; 337 if (Record.size() == 2) 338 AddressSpace = Record[1]; 339 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace); 340 break; 341 } 342 case bitc::TYPE_CODE_FUNCTION: { 343 // FIXME: attrid is dead, remove it in LLVM 3.0 344 // FUNCTION: [vararg, attrid, retty, paramty x N] 345 if (Record.size() < 3) 346 return Error("Invalid FUNCTION type record"); 347 std::vector<const Type*> ArgTys; 348 for (unsigned i = 3, e = Record.size(); i != e; ++i) 349 ArgTys.push_back(getTypeByID(Record[i], true)); 350 351 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys, 352 Record[0]); 353 break; 354 } 355 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N] 356 if (Record.size() < 1) 357 return Error("Invalid STRUCT type record"); 358 std::vector<const Type*> EltTys; 359 for (unsigned i = 1, e = Record.size(); i != e; ++i) 360 EltTys.push_back(getTypeByID(Record[i], true)); 361 ResultTy = StructType::get(EltTys, Record[0]); 362 break; 363 } 364 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 365 if (Record.size() < 2) 366 return Error("Invalid ARRAY type record"); 367 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]); 368 break; 369 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 370 if (Record.size() < 2) 371 return Error("Invalid VECTOR type record"); 372 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]); 373 break; 374 } 375 376 if (NumRecords == TypeList.size()) { 377 // If this is a new type slot, just append it. 378 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get()); 379 ++NumRecords; 380 } else if (ResultTy == 0) { 381 // Otherwise, this was forward referenced, so an opaque type was created, 382 // but the result type is actually just an opaque. Leave the one we 383 // created previously. 384 ++NumRecords; 385 } else { 386 // Otherwise, this was forward referenced, so an opaque type was created. 387 // Resolve the opaque type to the real type now. 388 assert(NumRecords < TypeList.size() && "Typelist imbalance"); 389 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get()); 390 391 // Don't directly push the new type on the Tab. Instead we want to replace 392 // the opaque type we previously inserted with the new concrete value. The 393 // refinement from the abstract (opaque) type to the new type causes all 394 // uses of the abstract type to use the concrete type (NewTy). This will 395 // also cause the opaque type to be deleted. 396 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy); 397 398 // This should have replaced the old opaque type with the new type in the 399 // value table... or with a preexisting type that was already in the 400 // system. Let's just make sure it did. 401 assert(TypeList[NumRecords-1].get() != OldTy && 402 "refineAbstractType didn't work!"); 403 } 404 } 405} 406 407 408bool BitcodeReader::ParseTypeSymbolTable() { 409 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID)) 410 return Error("Malformed block record"); 411 412 SmallVector<uint64_t, 64> Record; 413 414 // Read all the records for this type table. 415 std::string TypeName; 416 while (1) { 417 unsigned Code = Stream.ReadCode(); 418 if (Code == bitc::END_BLOCK) { 419 if (Stream.ReadBlockEnd()) 420 return Error("Error at end of type symbol table block"); 421 return false; 422 } 423 424 if (Code == bitc::ENTER_SUBBLOCK) { 425 // No known subblocks, always skip them. 426 Stream.ReadSubBlockID(); 427 if (Stream.SkipBlock()) 428 return Error("Malformed block record"); 429 continue; 430 } 431 432 if (Code == bitc::DEFINE_ABBREV) { 433 Stream.ReadAbbrevRecord(); 434 continue; 435 } 436 437 // Read a record. 438 Record.clear(); 439 switch (Stream.ReadRecord(Code, Record)) { 440 default: // Default behavior: unknown type. 441 break; 442 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N] 443 if (ConvertToString(Record, 1, TypeName)) 444 return Error("Invalid TST_ENTRY record"); 445 unsigned TypeID = Record[0]; 446 if (TypeID >= TypeList.size()) 447 return Error("Invalid Type ID in TST_ENTRY record"); 448 449 TheModule->addTypeName(TypeName, TypeList[TypeID].get()); 450 TypeName.clear(); 451 break; 452 } 453 } 454} 455 456bool BitcodeReader::ParseValueSymbolTable() { 457 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 458 return Error("Malformed block record"); 459 460 SmallVector<uint64_t, 64> Record; 461 462 // Read all the records for this value table. 463 SmallString<128> ValueName; 464 while (1) { 465 unsigned Code = Stream.ReadCode(); 466 if (Code == bitc::END_BLOCK) { 467 if (Stream.ReadBlockEnd()) 468 return Error("Error at end of value symbol table block"); 469 return false; 470 } 471 if (Code == bitc::ENTER_SUBBLOCK) { 472 // No known subblocks, always skip them. 473 Stream.ReadSubBlockID(); 474 if (Stream.SkipBlock()) 475 return Error("Malformed block record"); 476 continue; 477 } 478 479 if (Code == bitc::DEFINE_ABBREV) { 480 Stream.ReadAbbrevRecord(); 481 continue; 482 } 483 484 // Read a record. 485 Record.clear(); 486 switch (Stream.ReadRecord(Code, Record)) { 487 default: // Default behavior: unknown type. 488 break; 489 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 490 if (ConvertToString(Record, 1, ValueName)) 491 return Error("Invalid TST_ENTRY record"); 492 unsigned ValueID = Record[0]; 493 if (ValueID >= ValueList.size()) 494 return Error("Invalid Value ID in VST_ENTRY record"); 495 Value *V = ValueList[ValueID]; 496 497 V->setName(&ValueName[0], ValueName.size()); 498 ValueName.clear(); 499 break; 500 } 501 case bitc::VST_CODE_BBENTRY: { 502 if (ConvertToString(Record, 1, ValueName)) 503 return Error("Invalid VST_BBENTRY record"); 504 BasicBlock *BB = getBasicBlock(Record[0]); 505 if (BB == 0) 506 return Error("Invalid BB ID in VST_BBENTRY record"); 507 508 BB->setName(&ValueName[0], ValueName.size()); 509 ValueName.clear(); 510 break; 511 } 512 } 513 } 514} 515 516/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in 517/// the LSB for dense VBR encoding. 518static uint64_t DecodeSignRotatedValue(uint64_t V) { 519 if ((V & 1) == 0) 520 return V >> 1; 521 if (V != 1) 522 return -(V >> 1); 523 // There is no such thing as -0 with integers. "-0" really means MININT. 524 return 1ULL << 63; 525} 526 527/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 528/// values and aliases that we can. 529bool BitcodeReader::ResolveGlobalAndAliasInits() { 530 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 531 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 532 533 GlobalInitWorklist.swap(GlobalInits); 534 AliasInitWorklist.swap(AliasInits); 535 536 while (!GlobalInitWorklist.empty()) { 537 unsigned ValID = GlobalInitWorklist.back().second; 538 if (ValID >= ValueList.size()) { 539 // Not ready to resolve this yet, it requires something later in the file. 540 GlobalInits.push_back(GlobalInitWorklist.back()); 541 } else { 542 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 543 GlobalInitWorklist.back().first->setInitializer(C); 544 else 545 return Error("Global variable initializer is not a constant!"); 546 } 547 GlobalInitWorklist.pop_back(); 548 } 549 550 while (!AliasInitWorklist.empty()) { 551 unsigned ValID = AliasInitWorklist.back().second; 552 if (ValID >= ValueList.size()) { 553 AliasInits.push_back(AliasInitWorklist.back()); 554 } else { 555 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 556 AliasInitWorklist.back().first->setAliasee(C); 557 else 558 return Error("Alias initializer is not a constant!"); 559 } 560 AliasInitWorklist.pop_back(); 561 } 562 return false; 563} 564 565 566bool BitcodeReader::ParseConstants() { 567 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 568 return Error("Malformed block record"); 569 570 SmallVector<uint64_t, 64> Record; 571 572 // Read all the records for this value table. 573 const Type *CurTy = Type::Int32Ty; 574 unsigned NextCstNo = ValueList.size(); 575 while (1) { 576 unsigned Code = Stream.ReadCode(); 577 if (Code == bitc::END_BLOCK) { 578 if (NextCstNo != ValueList.size()) 579 return Error("Invalid constant reference!"); 580 581 if (Stream.ReadBlockEnd()) 582 return Error("Error at end of constants block"); 583 return false; 584 } 585 586 if (Code == bitc::ENTER_SUBBLOCK) { 587 // No known subblocks, always skip them. 588 Stream.ReadSubBlockID(); 589 if (Stream.SkipBlock()) 590 return Error("Malformed block record"); 591 continue; 592 } 593 594 if (Code == bitc::DEFINE_ABBREV) { 595 Stream.ReadAbbrevRecord(); 596 continue; 597 } 598 599 // Read a record. 600 Record.clear(); 601 Value *V = 0; 602 switch (Stream.ReadRecord(Code, Record)) { 603 default: // Default behavior: unknown constant 604 case bitc::CST_CODE_UNDEF: // UNDEF 605 V = UndefValue::get(CurTy); 606 break; 607 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 608 if (Record.empty()) 609 return Error("Malformed CST_SETTYPE record"); 610 if (Record[0] >= TypeList.size()) 611 return Error("Invalid Type ID in CST_SETTYPE record"); 612 CurTy = TypeList[Record[0]]; 613 continue; // Skip the ValueList manipulation. 614 case bitc::CST_CODE_NULL: // NULL 615 V = Constant::getNullValue(CurTy); 616 break; 617 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 618 if (!isa<IntegerType>(CurTy) || Record.empty()) 619 return Error("Invalid CST_INTEGER record"); 620 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0])); 621 break; 622 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 623 if (!isa<IntegerType>(CurTy) || Record.empty()) 624 return Error("Invalid WIDE_INTEGER record"); 625 626 unsigned NumWords = Record.size(); 627 SmallVector<uint64_t, 8> Words; 628 Words.resize(NumWords); 629 for (unsigned i = 0; i != NumWords; ++i) 630 Words[i] = DecodeSignRotatedValue(Record[i]); 631 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(), 632 NumWords, &Words[0])); 633 break; 634 } 635 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 636 if (Record.empty()) 637 return Error("Invalid FLOAT record"); 638 if (CurTy == Type::FloatTy) 639 V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0]))); 640 else if (CurTy == Type::DoubleTy) 641 V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0]))); 642 else if (CurTy == Type::X86_FP80Ty) 643 V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0]))); 644 else if (CurTy == Type::FP128Ty) 645 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]), true)); 646 else if (CurTy == Type::PPC_FP128Ty) 647 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]))); 648 else 649 V = UndefValue::get(CurTy); 650 break; 651 } 652 653 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 654 if (Record.empty()) 655 return Error("Invalid CST_AGGREGATE record"); 656 657 unsigned Size = Record.size(); 658 std::vector<Constant*> Elts; 659 660 if (const StructType *STy = dyn_cast<StructType>(CurTy)) { 661 for (unsigned i = 0; i != Size; ++i) 662 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 663 STy->getElementType(i))); 664 V = ConstantStruct::get(STy, Elts); 665 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 666 const Type *EltTy = ATy->getElementType(); 667 for (unsigned i = 0; i != Size; ++i) 668 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 669 V = ConstantArray::get(ATy, Elts); 670 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 671 const Type *EltTy = VTy->getElementType(); 672 for (unsigned i = 0; i != Size; ++i) 673 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 674 V = ConstantVector::get(Elts); 675 } else { 676 V = UndefValue::get(CurTy); 677 } 678 break; 679 } 680 case bitc::CST_CODE_STRING: { // STRING: [values] 681 if (Record.empty()) 682 return Error("Invalid CST_AGGREGATE record"); 683 684 const ArrayType *ATy = cast<ArrayType>(CurTy); 685 const Type *EltTy = ATy->getElementType(); 686 687 unsigned Size = Record.size(); 688 std::vector<Constant*> Elts; 689 for (unsigned i = 0; i != Size; ++i) 690 Elts.push_back(ConstantInt::get(EltTy, Record[i])); 691 V = ConstantArray::get(ATy, Elts); 692 break; 693 } 694 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 695 if (Record.empty()) 696 return Error("Invalid CST_AGGREGATE record"); 697 698 const ArrayType *ATy = cast<ArrayType>(CurTy); 699 const Type *EltTy = ATy->getElementType(); 700 701 unsigned Size = Record.size(); 702 std::vector<Constant*> Elts; 703 for (unsigned i = 0; i != Size; ++i) 704 Elts.push_back(ConstantInt::get(EltTy, Record[i])); 705 Elts.push_back(Constant::getNullValue(EltTy)); 706 V = ConstantArray::get(ATy, Elts); 707 break; 708 } 709 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 710 if (Record.size() < 3) return Error("Invalid CE_BINOP record"); 711 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 712 if (Opc < 0) { 713 V = UndefValue::get(CurTy); // Unknown binop. 714 } else { 715 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 716 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 717 V = ConstantExpr::get(Opc, LHS, RHS); 718 } 719 break; 720 } 721 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 722 if (Record.size() < 3) return Error("Invalid CE_CAST record"); 723 int Opc = GetDecodedCastOpcode(Record[0]); 724 if (Opc < 0) { 725 V = UndefValue::get(CurTy); // Unknown cast. 726 } else { 727 const Type *OpTy = getTypeByID(Record[1]); 728 if (!OpTy) return Error("Invalid CE_CAST record"); 729 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 730 V = ConstantExpr::getCast(Opc, Op, CurTy); 731 } 732 break; 733 } 734 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 735 if (Record.size() & 1) return Error("Invalid CE_GEP record"); 736 SmallVector<Constant*, 16> Elts; 737 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 738 const Type *ElTy = getTypeByID(Record[i]); 739 if (!ElTy) return Error("Invalid CE_GEP record"); 740 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 741 } 742 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1); 743 break; 744 } 745 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#] 746 if (Record.size() < 3) return Error("Invalid CE_SELECT record"); 747 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 748 Type::Int1Ty), 749 ValueList.getConstantFwdRef(Record[1],CurTy), 750 ValueList.getConstantFwdRef(Record[2],CurTy)); 751 break; 752 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] 753 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record"); 754 const VectorType *OpTy = 755 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 756 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record"); 757 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 758 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], 759 OpTy->getElementType()); 760 V = ConstantExpr::getExtractElement(Op0, Op1); 761 break; 762 } 763 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval] 764 const VectorType *OpTy = dyn_cast<VectorType>(CurTy); 765 if (Record.size() < 3 || OpTy == 0) 766 return Error("Invalid CE_INSERTELT record"); 767 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 768 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 769 OpTy->getElementType()); 770 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty); 771 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 772 break; 773 } 774 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 775 const VectorType *OpTy = dyn_cast<VectorType>(CurTy); 776 if (Record.size() < 3 || OpTy == 0) 777 return Error("Invalid CE_INSERTELT record"); 778 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 779 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 780 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements()); 781 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 782 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 783 break; 784 } 785 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 786 if (Record.size() < 4) return Error("Invalid CE_CMP record"); 787 const Type *OpTy = getTypeByID(Record[0]); 788 if (OpTy == 0) return Error("Invalid CE_CMP record"); 789 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 790 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 791 792 if (OpTy->isFloatingPoint()) 793 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 794 else 795 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 796 break; 797 } 798 case bitc::CST_CODE_INLINEASM: { 799 if (Record.size() < 2) return Error("Invalid INLINEASM record"); 800 std::string AsmStr, ConstrStr; 801 bool HasSideEffects = Record[0]; 802 unsigned AsmStrSize = Record[1]; 803 if (2+AsmStrSize >= Record.size()) 804 return Error("Invalid INLINEASM record"); 805 unsigned ConstStrSize = Record[2+AsmStrSize]; 806 if (3+AsmStrSize+ConstStrSize > Record.size()) 807 return Error("Invalid INLINEASM record"); 808 809 for (unsigned i = 0; i != AsmStrSize; ++i) 810 AsmStr += (char)Record[2+i]; 811 for (unsigned i = 0; i != ConstStrSize; ++i) 812 ConstrStr += (char)Record[3+AsmStrSize+i]; 813 const PointerType *PTy = cast<PointerType>(CurTy); 814 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 815 AsmStr, ConstrStr, HasSideEffects); 816 break; 817 } 818 } 819 820 ValueList.AssignValue(V, NextCstNo); 821 ++NextCstNo; 822 } 823} 824 825/// RememberAndSkipFunctionBody - When we see the block for a function body, 826/// remember where it is and then skip it. This lets us lazily deserialize the 827/// functions. 828bool BitcodeReader::RememberAndSkipFunctionBody() { 829 // Get the function we are talking about. 830 if (FunctionsWithBodies.empty()) 831 return Error("Insufficient function protos"); 832 833 Function *Fn = FunctionsWithBodies.back(); 834 FunctionsWithBodies.pop_back(); 835 836 // Save the current stream state. 837 uint64_t CurBit = Stream.GetCurrentBitNo(); 838 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage()); 839 840 // Set the functions linkage to GhostLinkage so we know it is lazily 841 // deserialized. 842 Fn->setLinkage(GlobalValue::GhostLinkage); 843 844 // Skip over the function block for now. 845 if (Stream.SkipBlock()) 846 return Error("Malformed block record"); 847 return false; 848} 849 850bool BitcodeReader::ParseModule(const std::string &ModuleID) { 851 // Reject multiple MODULE_BLOCK's in a single bitstream. 852 if (TheModule) 853 return Error("Multiple MODULE_BLOCKs in same stream"); 854 855 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 856 return Error("Malformed block record"); 857 858 // Otherwise, create the module. 859 TheModule = new Module(ModuleID); 860 861 SmallVector<uint64_t, 64> Record; 862 std::vector<std::string> SectionTable; 863 std::vector<std::string> CollectorTable; 864 865 // Read all the records for this module. 866 while (!Stream.AtEndOfStream()) { 867 unsigned Code = Stream.ReadCode(); 868 if (Code == bitc::END_BLOCK) { 869 if (Stream.ReadBlockEnd()) 870 return Error("Error at end of module block"); 871 872 // Patch the initializers for globals and aliases up. 873 ResolveGlobalAndAliasInits(); 874 if (!GlobalInits.empty() || !AliasInits.empty()) 875 return Error("Malformed global initializer set"); 876 if (!FunctionsWithBodies.empty()) 877 return Error("Too few function bodies found"); 878 879 // Look for intrinsic functions which need to be upgraded at some point 880 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 881 FI != FE; ++FI) { 882 Function* NewFn; 883 if (UpgradeIntrinsicFunction(FI, NewFn)) 884 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 885 } 886 887 // Force deallocation of memory for these vectors to favor the client that 888 // want lazy deserialization. 889 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 890 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 891 std::vector<Function*>().swap(FunctionsWithBodies); 892 return false; 893 } 894 895 if (Code == bitc::ENTER_SUBBLOCK) { 896 switch (Stream.ReadSubBlockID()) { 897 default: // Skip unknown content. 898 if (Stream.SkipBlock()) 899 return Error("Malformed block record"); 900 break; 901 case bitc::BLOCKINFO_BLOCK_ID: 902 if (Stream.ReadBlockInfoBlock()) 903 return Error("Malformed BlockInfoBlock"); 904 break; 905 case bitc::PARAMATTR_BLOCK_ID: 906 if (ParseParamAttrBlock()) 907 return true; 908 break; 909 case bitc::TYPE_BLOCK_ID: 910 if (ParseTypeTable()) 911 return true; 912 break; 913 case bitc::TYPE_SYMTAB_BLOCK_ID: 914 if (ParseTypeSymbolTable()) 915 return true; 916 break; 917 case bitc::VALUE_SYMTAB_BLOCK_ID: 918 if (ParseValueSymbolTable()) 919 return true; 920 break; 921 case bitc::CONSTANTS_BLOCK_ID: 922 if (ParseConstants() || ResolveGlobalAndAliasInits()) 923 return true; 924 break; 925 case bitc::FUNCTION_BLOCK_ID: 926 // If this is the first function body we've seen, reverse the 927 // FunctionsWithBodies list. 928 if (!HasReversedFunctionsWithBodies) { 929 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 930 HasReversedFunctionsWithBodies = true; 931 } 932 933 if (RememberAndSkipFunctionBody()) 934 return true; 935 break; 936 } 937 continue; 938 } 939 940 if (Code == bitc::DEFINE_ABBREV) { 941 Stream.ReadAbbrevRecord(); 942 continue; 943 } 944 945 // Read a record. 946 switch (Stream.ReadRecord(Code, Record)) { 947 default: break; // Default behavior, ignore unknown content. 948 case bitc::MODULE_CODE_VERSION: // VERSION: [version#] 949 if (Record.size() < 1) 950 return Error("Malformed MODULE_CODE_VERSION"); 951 // Only version #0 is supported so far. 952 if (Record[0] != 0) 953 return Error("Unknown bitstream version!"); 954 break; 955 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 956 std::string S; 957 if (ConvertToString(Record, 0, S)) 958 return Error("Invalid MODULE_CODE_TRIPLE record"); 959 TheModule->setTargetTriple(S); 960 break; 961 } 962 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 963 std::string S; 964 if (ConvertToString(Record, 0, S)) 965 return Error("Invalid MODULE_CODE_DATALAYOUT record"); 966 TheModule->setDataLayout(S); 967 break; 968 } 969 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 970 std::string S; 971 if (ConvertToString(Record, 0, S)) 972 return Error("Invalid MODULE_CODE_ASM record"); 973 TheModule->setModuleInlineAsm(S); 974 break; 975 } 976 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 977 std::string S; 978 if (ConvertToString(Record, 0, S)) 979 return Error("Invalid MODULE_CODE_DEPLIB record"); 980 TheModule->addLibrary(S); 981 break; 982 } 983 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 984 std::string S; 985 if (ConvertToString(Record, 0, S)) 986 return Error("Invalid MODULE_CODE_SECTIONNAME record"); 987 SectionTable.push_back(S); 988 break; 989 } 990 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N] 991 std::string S; 992 if (ConvertToString(Record, 0, S)) 993 return Error("Invalid MODULE_CODE_COLLECTORNAME record"); 994 CollectorTable.push_back(S); 995 break; 996 } 997 // GLOBALVAR: [pointer type, isconst, initid, 998 // linkage, alignment, section, visibility, threadlocal] 999 case bitc::MODULE_CODE_GLOBALVAR: { 1000 if (Record.size() < 6) 1001 return Error("Invalid MODULE_CODE_GLOBALVAR record"); 1002 const Type *Ty = getTypeByID(Record[0]); 1003 if (!isa<PointerType>(Ty)) 1004 return Error("Global not a pointer type!"); 1005 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 1006 Ty = cast<PointerType>(Ty)->getElementType(); 1007 1008 bool isConstant = Record[1]; 1009 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 1010 unsigned Alignment = (1 << Record[4]) >> 1; 1011 std::string Section; 1012 if (Record[5]) { 1013 if (Record[5]-1 >= SectionTable.size()) 1014 return Error("Invalid section ID"); 1015 Section = SectionTable[Record[5]-1]; 1016 } 1017 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 1018 if (Record.size() > 6) 1019 Visibility = GetDecodedVisibility(Record[6]); 1020 bool isThreadLocal = false; 1021 if (Record.size() > 7) 1022 isThreadLocal = Record[7]; 1023 1024 GlobalVariable *NewGV = 1025 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule, 1026 isThreadLocal, AddressSpace); 1027 NewGV->setAlignment(Alignment); 1028 if (!Section.empty()) 1029 NewGV->setSection(Section); 1030 NewGV->setVisibility(Visibility); 1031 NewGV->setThreadLocal(isThreadLocal); 1032 1033 ValueList.push_back(NewGV); 1034 1035 // Remember which value to use for the global initializer. 1036 if (unsigned InitID = Record[2]) 1037 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 1038 break; 1039 } 1040 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 1041 // alignment, section, visibility, collector] 1042 case bitc::MODULE_CODE_FUNCTION: { 1043 if (Record.size() < 8) 1044 return Error("Invalid MODULE_CODE_FUNCTION record"); 1045 const Type *Ty = getTypeByID(Record[0]); 1046 if (!isa<PointerType>(Ty)) 1047 return Error("Function not a pointer type!"); 1048 const FunctionType *FTy = 1049 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 1050 if (!FTy) 1051 return Error("Function not a pointer to function type!"); 1052 1053 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 1054 "", TheModule); 1055 1056 Func->setCallingConv(Record[1]); 1057 bool isProto = Record[2]; 1058 Func->setLinkage(GetDecodedLinkage(Record[3])); 1059 Func->setParamAttrs(getParamAttrs(Record[4])); 1060 1061 Func->setAlignment((1 << Record[5]) >> 1); 1062 if (Record[6]) { 1063 if (Record[6]-1 >= SectionTable.size()) 1064 return Error("Invalid section ID"); 1065 Func->setSection(SectionTable[Record[6]-1]); 1066 } 1067 Func->setVisibility(GetDecodedVisibility(Record[7])); 1068 if (Record.size() > 8 && Record[8]) { 1069 if (Record[8]-1 > CollectorTable.size()) 1070 return Error("Invalid collector ID"); 1071 Func->setCollector(CollectorTable[Record[8]-1].c_str()); 1072 } 1073 1074 ValueList.push_back(Func); 1075 1076 // If this is a function with a body, remember the prototype we are 1077 // creating now, so that we can match up the body with them later. 1078 if (!isProto) 1079 FunctionsWithBodies.push_back(Func); 1080 break; 1081 } 1082 // ALIAS: [alias type, aliasee val#, linkage] 1083 // ALIAS: [alias type, aliasee val#, linkage, visibility] 1084 case bitc::MODULE_CODE_ALIAS: { 1085 if (Record.size() < 3) 1086 return Error("Invalid MODULE_ALIAS record"); 1087 const Type *Ty = getTypeByID(Record[0]); 1088 if (!isa<PointerType>(Ty)) 1089 return Error("Function not a pointer type!"); 1090 1091 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]), 1092 "", 0, TheModule); 1093 // Old bitcode files didn't have visibility field. 1094 if (Record.size() > 3) 1095 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 1096 ValueList.push_back(NewGA); 1097 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 1098 break; 1099 } 1100 /// MODULE_CODE_PURGEVALS: [numvals] 1101 case bitc::MODULE_CODE_PURGEVALS: 1102 // Trim down the value list to the specified size. 1103 if (Record.size() < 1 || Record[0] > ValueList.size()) 1104 return Error("Invalid MODULE_PURGEVALS record"); 1105 ValueList.shrinkTo(Record[0]); 1106 break; 1107 } 1108 Record.clear(); 1109 } 1110 1111 return Error("Premature end of bitstream"); 1112} 1113 1114 1115bool BitcodeReader::ParseBitcode() { 1116 TheModule = 0; 1117 1118 if (Buffer->getBufferSize() & 3) 1119 return Error("Bitcode stream should be a multiple of 4 bytes in length"); 1120 1121 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart(); 1122 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize()); 1123 1124 // Sniff for the signature. 1125 if (Stream.Read(8) != 'B' || 1126 Stream.Read(8) != 'C' || 1127 Stream.Read(4) != 0x0 || 1128 Stream.Read(4) != 0xC || 1129 Stream.Read(4) != 0xE || 1130 Stream.Read(4) != 0xD) 1131 return Error("Invalid bitcode signature"); 1132 1133 // We expect a number of well-defined blocks, though we don't necessarily 1134 // need to understand them all. 1135 while (!Stream.AtEndOfStream()) { 1136 unsigned Code = Stream.ReadCode(); 1137 1138 if (Code != bitc::ENTER_SUBBLOCK) 1139 return Error("Invalid record at top-level"); 1140 1141 unsigned BlockID = Stream.ReadSubBlockID(); 1142 1143 // We only know the MODULE subblock ID. 1144 switch (BlockID) { 1145 case bitc::BLOCKINFO_BLOCK_ID: 1146 if (Stream.ReadBlockInfoBlock()) 1147 return Error("Malformed BlockInfoBlock"); 1148 break; 1149 case bitc::MODULE_BLOCK_ID: 1150 if (ParseModule(Buffer->getBufferIdentifier())) 1151 return true; 1152 break; 1153 default: 1154 if (Stream.SkipBlock()) 1155 return Error("Malformed block record"); 1156 break; 1157 } 1158 } 1159 1160 return false; 1161} 1162 1163 1164/// ParseFunctionBody - Lazily parse the specified function body block. 1165bool BitcodeReader::ParseFunctionBody(Function *F) { 1166 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 1167 return Error("Malformed block record"); 1168 1169 unsigned ModuleValueListSize = ValueList.size(); 1170 1171 // Add all the function arguments to the value table. 1172 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 1173 ValueList.push_back(I); 1174 1175 unsigned NextValueNo = ValueList.size(); 1176 BasicBlock *CurBB = 0; 1177 unsigned CurBBNo = 0; 1178 1179 // Read all the records. 1180 SmallVector<uint64_t, 64> Record; 1181 while (1) { 1182 unsigned Code = Stream.ReadCode(); 1183 if (Code == bitc::END_BLOCK) { 1184 if (Stream.ReadBlockEnd()) 1185 return Error("Error at end of function block"); 1186 break; 1187 } 1188 1189 if (Code == bitc::ENTER_SUBBLOCK) { 1190 switch (Stream.ReadSubBlockID()) { 1191 default: // Skip unknown content. 1192 if (Stream.SkipBlock()) 1193 return Error("Malformed block record"); 1194 break; 1195 case bitc::CONSTANTS_BLOCK_ID: 1196 if (ParseConstants()) return true; 1197 NextValueNo = ValueList.size(); 1198 break; 1199 case bitc::VALUE_SYMTAB_BLOCK_ID: 1200 if (ParseValueSymbolTable()) return true; 1201 break; 1202 } 1203 continue; 1204 } 1205 1206 if (Code == bitc::DEFINE_ABBREV) { 1207 Stream.ReadAbbrevRecord(); 1208 continue; 1209 } 1210 1211 // Read a record. 1212 Record.clear(); 1213 Instruction *I = 0; 1214 switch (Stream.ReadRecord(Code, Record)) { 1215 default: // Default behavior: reject 1216 return Error("Unknown instruction"); 1217 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 1218 if (Record.size() < 1 || Record[0] == 0) 1219 return Error("Invalid DECLAREBLOCKS record"); 1220 // Create all the basic blocks for the function. 1221 FunctionBBs.resize(Record[0]); 1222 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 1223 FunctionBBs[i] = BasicBlock::Create("", F); 1224 CurBB = FunctionBBs[0]; 1225 continue; 1226 1227 case bitc::FUNC_CODE_INST_BB_UNWINDDEST: // BB_UNWINDDEST: [bb#] 1228 if (CurBB->getUnwindDest()) 1229 return Error("Only permit one BB_UNWINDDEST per BB"); 1230 if (Record.size() != 1) 1231 return Error("Invalid BB_UNWINDDEST record"); 1232 1233 CurBB->setUnwindDest(getBasicBlock(Record[0])); 1234 continue; 1235 1236 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 1237 unsigned OpNum = 0; 1238 Value *LHS, *RHS; 1239 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 1240 getValue(Record, OpNum, LHS->getType(), RHS) || 1241 OpNum+1 != Record.size()) 1242 return Error("Invalid BINOP record"); 1243 1244 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType()); 1245 if (Opc == -1) return Error("Invalid BINOP record"); 1246 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS); 1247 break; 1248 } 1249 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 1250 unsigned OpNum = 0; 1251 Value *Op; 1252 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 1253 OpNum+2 != Record.size()) 1254 return Error("Invalid CAST record"); 1255 1256 const Type *ResTy = getTypeByID(Record[OpNum]); 1257 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 1258 if (Opc == -1 || ResTy == 0) 1259 return Error("Invalid CAST record"); 1260 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy); 1261 break; 1262 } 1263 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 1264 unsigned OpNum = 0; 1265 Value *BasePtr; 1266 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 1267 return Error("Invalid GEP record"); 1268 1269 SmallVector<Value*, 16> GEPIdx; 1270 while (OpNum != Record.size()) { 1271 Value *Op; 1272 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1273 return Error("Invalid GEP record"); 1274 GEPIdx.push_back(Op); 1275 } 1276 1277 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end()); 1278 break; 1279 } 1280 1281 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 1282 unsigned OpNum = 0; 1283 Value *TrueVal, *FalseVal, *Cond; 1284 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 1285 getValue(Record, OpNum, TrueVal->getType(), FalseVal) || 1286 getValue(Record, OpNum, Type::Int1Ty, Cond)) 1287 return Error("Invalid SELECT record"); 1288 1289 I = SelectInst::Create(Cond, TrueVal, FalseVal); 1290 break; 1291 } 1292 1293 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 1294 unsigned OpNum = 0; 1295 Value *Vec, *Idx; 1296 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 1297 getValue(Record, OpNum, Type::Int32Ty, Idx)) 1298 return Error("Invalid EXTRACTELT record"); 1299 I = new ExtractElementInst(Vec, Idx); 1300 break; 1301 } 1302 1303 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 1304 unsigned OpNum = 0; 1305 Value *Vec, *Elt, *Idx; 1306 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 1307 getValue(Record, OpNum, 1308 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 1309 getValue(Record, OpNum, Type::Int32Ty, Idx)) 1310 return Error("Invalid INSERTELT record"); 1311 I = InsertElementInst::Create(Vec, Elt, Idx); 1312 break; 1313 } 1314 1315 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 1316 unsigned OpNum = 0; 1317 Value *Vec1, *Vec2, *Mask; 1318 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 1319 getValue(Record, OpNum, Vec1->getType(), Vec2)) 1320 return Error("Invalid SHUFFLEVEC record"); 1321 1322 const Type *MaskTy = 1323 VectorType::get(Type::Int32Ty, 1324 cast<VectorType>(Vec1->getType())->getNumElements()); 1325 1326 if (getValue(Record, OpNum, MaskTy, Mask)) 1327 return Error("Invalid SHUFFLEVEC record"); 1328 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 1329 break; 1330 } 1331 1332 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred] 1333 unsigned OpNum = 0; 1334 Value *LHS, *RHS; 1335 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 1336 getValue(Record, OpNum, LHS->getType(), RHS) || 1337 OpNum+1 != Record.size()) 1338 return Error("Invalid CMP record"); 1339 1340 if (LHS->getType()->isFPOrFPVector()) 1341 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 1342 else 1343 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 1344 break; 1345 } 1346 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n] 1347 if (Record.size() != 2) 1348 return Error("Invalid GETRESULT record"); 1349 unsigned OpNum = 0; 1350 Value *Op; 1351 getValueTypePair(Record, OpNum, NextValueNo, Op); 1352 unsigned Index = Record[1]; 1353 I = new GetResultInst(Op, Index); 1354 break; 1355 } 1356 1357 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 1358 { 1359 unsigned Size = Record.size(); 1360 if (Size == 0) { 1361 I = ReturnInst::Create(); 1362 break; 1363 } else { 1364 unsigned OpNum = 0; 1365 SmallVector<Value *,4> Vs; 1366 do { 1367 Value *Op = NULL; 1368 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1369 return Error("Invalid RET record"); 1370 Vs.push_back(Op); 1371 } while(OpNum != Record.size()); 1372 1373 // SmallVector Vs has at least one element. 1374 I = ReturnInst::Create(&Vs[0], Vs.size()); 1375 break; 1376 } 1377 } 1378 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 1379 if (Record.size() != 1 && Record.size() != 3) 1380 return Error("Invalid BR record"); 1381 BasicBlock *TrueDest = getBasicBlock(Record[0]); 1382 if (TrueDest == 0) 1383 return Error("Invalid BR record"); 1384 1385 if (Record.size() == 1) 1386 I = BranchInst::Create(TrueDest); 1387 else { 1388 BasicBlock *FalseDest = getBasicBlock(Record[1]); 1389 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty); 1390 if (FalseDest == 0 || Cond == 0) 1391 return Error("Invalid BR record"); 1392 I = BranchInst::Create(TrueDest, FalseDest, Cond); 1393 } 1394 break; 1395 } 1396 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops] 1397 if (Record.size() < 3 || (Record.size() & 1) == 0) 1398 return Error("Invalid SWITCH record"); 1399 const Type *OpTy = getTypeByID(Record[0]); 1400 Value *Cond = getFnValueByID(Record[1], OpTy); 1401 BasicBlock *Default = getBasicBlock(Record[2]); 1402 if (OpTy == 0 || Cond == 0 || Default == 0) 1403 return Error("Invalid SWITCH record"); 1404 unsigned NumCases = (Record.size()-3)/2; 1405 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 1406 for (unsigned i = 0, e = NumCases; i != e; ++i) { 1407 ConstantInt *CaseVal = 1408 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 1409 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 1410 if (CaseVal == 0 || DestBB == 0) { 1411 delete SI; 1412 return Error("Invalid SWITCH record!"); 1413 } 1414 SI->addCase(CaseVal, DestBB); 1415 } 1416 I = SI; 1417 break; 1418 } 1419 1420 case bitc::FUNC_CODE_INST_INVOKE: { 1421 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 1422 if (Record.size() < 4) return Error("Invalid INVOKE record"); 1423 PAListPtr PAL = getParamAttrs(Record[0]); 1424 unsigned CCInfo = Record[1]; 1425 BasicBlock *NormalBB = getBasicBlock(Record[2]); 1426 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 1427 1428 unsigned OpNum = 4; 1429 Value *Callee; 1430 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 1431 return Error("Invalid INVOKE record"); 1432 1433 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 1434 const FunctionType *FTy = !CalleeTy ? 0 : 1435 dyn_cast<FunctionType>(CalleeTy->getElementType()); 1436 1437 // Check that the right number of fixed parameters are here. 1438 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 || 1439 Record.size() < OpNum+FTy->getNumParams()) 1440 return Error("Invalid INVOKE record"); 1441 1442 SmallVector<Value*, 16> Ops; 1443 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 1444 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 1445 if (Ops.back() == 0) return Error("Invalid INVOKE record"); 1446 } 1447 1448 if (!FTy->isVarArg()) { 1449 if (Record.size() != OpNum) 1450 return Error("Invalid INVOKE record"); 1451 } else { 1452 // Read type/value pairs for varargs params. 1453 while (OpNum != Record.size()) { 1454 Value *Op; 1455 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1456 return Error("Invalid INVOKE record"); 1457 Ops.push_back(Op); 1458 } 1459 } 1460 1461 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end()); 1462 cast<InvokeInst>(I)->setCallingConv(CCInfo); 1463 cast<InvokeInst>(I)->setParamAttrs(PAL); 1464 break; 1465 } 1466 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND 1467 I = new UnwindInst(); 1468 break; 1469 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 1470 I = new UnreachableInst(); 1471 break; 1472 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 1473 if (Record.size() < 1 || ((Record.size()-1)&1)) 1474 return Error("Invalid PHI record"); 1475 const Type *Ty = getTypeByID(Record[0]); 1476 if (!Ty) return Error("Invalid PHI record"); 1477 1478 PHINode *PN = PHINode::Create(Ty); 1479 PN->reserveOperandSpace(Record.size()-1); 1480 1481 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 1482 Value *V = getFnValueByID(Record[1+i], Ty); 1483 BasicBlock *BB = getBasicBlock(Record[2+i]); 1484 if (!V || !BB) return Error("Invalid PHI record"); 1485 PN->addIncoming(V, BB); 1486 } 1487 I = PN; 1488 break; 1489 } 1490 1491 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align] 1492 if (Record.size() < 3) 1493 return Error("Invalid MALLOC record"); 1494 const PointerType *Ty = 1495 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 1496 Value *Size = getFnValueByID(Record[1], Type::Int32Ty); 1497 unsigned Align = Record[2]; 1498 if (!Ty || !Size) return Error("Invalid MALLOC record"); 1499 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1); 1500 break; 1501 } 1502 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty] 1503 unsigned OpNum = 0; 1504 Value *Op; 1505 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 1506 OpNum != Record.size()) 1507 return Error("Invalid FREE record"); 1508 I = new FreeInst(Op); 1509 break; 1510 } 1511 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align] 1512 if (Record.size() < 3) 1513 return Error("Invalid ALLOCA record"); 1514 const PointerType *Ty = 1515 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 1516 Value *Size = getFnValueByID(Record[1], Type::Int32Ty); 1517 unsigned Align = Record[2]; 1518 if (!Ty || !Size) return Error("Invalid ALLOCA record"); 1519 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 1520 break; 1521 } 1522 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 1523 unsigned OpNum = 0; 1524 Value *Op; 1525 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 1526 OpNum+2 != Record.size()) 1527 return Error("Invalid LOAD record"); 1528 1529 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 1530 break; 1531 } 1532 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol] 1533 unsigned OpNum = 0; 1534 Value *Val, *Ptr; 1535 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 1536 getValue(Record, OpNum, 1537 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 1538 OpNum+2 != Record.size()) 1539 return Error("Invalid STORE record"); 1540 1541 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 1542 break; 1543 } 1544 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol] 1545 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0. 1546 unsigned OpNum = 0; 1547 Value *Val, *Ptr; 1548 if (getValueTypePair(Record, OpNum, NextValueNo, Val) || 1549 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)|| 1550 OpNum+2 != Record.size()) 1551 return Error("Invalid STORE record"); 1552 1553 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 1554 break; 1555 } 1556 case bitc::FUNC_CODE_INST_CALL: { 1557 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 1558 if (Record.size() < 3) 1559 return Error("Invalid CALL record"); 1560 1561 PAListPtr PAL = getParamAttrs(Record[0]); 1562 unsigned CCInfo = Record[1]; 1563 1564 unsigned OpNum = 2; 1565 Value *Callee; 1566 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 1567 return Error("Invalid CALL record"); 1568 1569 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 1570 const FunctionType *FTy = 0; 1571 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 1572 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 1573 return Error("Invalid CALL record"); 1574 1575 SmallVector<Value*, 16> Args; 1576 // Read the fixed params. 1577 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 1578 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID) 1579 Args.push_back(getBasicBlock(Record[OpNum])); 1580 else 1581 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 1582 if (Args.back() == 0) return Error("Invalid CALL record"); 1583 } 1584 1585 // Read type/value pairs for varargs params. 1586 if (!FTy->isVarArg()) { 1587 if (OpNum != Record.size()) 1588 return Error("Invalid CALL record"); 1589 } else { 1590 while (OpNum != Record.size()) { 1591 Value *Op; 1592 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 1593 return Error("Invalid CALL record"); 1594 Args.push_back(Op); 1595 } 1596 } 1597 1598 I = CallInst::Create(Callee, Args.begin(), Args.end()); 1599 cast<CallInst>(I)->setCallingConv(CCInfo>>1); 1600 cast<CallInst>(I)->setTailCall(CCInfo & 1); 1601 cast<CallInst>(I)->setParamAttrs(PAL); 1602 break; 1603 } 1604 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 1605 if (Record.size() < 3) 1606 return Error("Invalid VAARG record"); 1607 const Type *OpTy = getTypeByID(Record[0]); 1608 Value *Op = getFnValueByID(Record[1], OpTy); 1609 const Type *ResTy = getTypeByID(Record[2]); 1610 if (!OpTy || !Op || !ResTy) 1611 return Error("Invalid VAARG record"); 1612 I = new VAArgInst(Op, ResTy); 1613 break; 1614 } 1615 } 1616 1617 // Add instruction to end of current BB. If there is no current BB, reject 1618 // this file. 1619 if (CurBB == 0) { 1620 delete I; 1621 return Error("Invalid instruction with no BB"); 1622 } 1623 CurBB->getInstList().push_back(I); 1624 1625 // If this was a terminator instruction, move to the next block. 1626 if (isa<TerminatorInst>(I)) { 1627 ++CurBBNo; 1628 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0; 1629 } 1630 1631 // Non-void values get registered in the value table for future use. 1632 if (I && I->getType() != Type::VoidTy) 1633 ValueList.AssignValue(I, NextValueNo++); 1634 } 1635 1636 // Check the function list for unresolved values. 1637 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 1638 if (A->getParent() == 0) { 1639 // We found at least one unresolved value. Nuke them all to avoid leaks. 1640 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 1641 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) { 1642 A->replaceAllUsesWith(UndefValue::get(A->getType())); 1643 delete A; 1644 } 1645 } 1646 return Error("Never resolved value found in function!"); 1647 } 1648 } 1649 1650 // Trim the value list down to the size it was before we parsed this function. 1651 ValueList.shrinkTo(ModuleValueListSize); 1652 std::vector<BasicBlock*>().swap(FunctionBBs); 1653 1654 return false; 1655} 1656 1657//===----------------------------------------------------------------------===// 1658// ModuleProvider implementation 1659//===----------------------------------------------------------------------===// 1660 1661 1662bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) { 1663 // If it already is material, ignore the request. 1664 if (!F->hasNotBeenReadFromBitcode()) return false; 1665 1666 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII = 1667 DeferredFunctionInfo.find(F); 1668 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 1669 1670 // Move the bit stream to the saved position of the deferred function body and 1671 // restore the real linkage type for the function. 1672 Stream.JumpToBit(DFII->second.first); 1673 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second); 1674 1675 if (ParseFunctionBody(F)) { 1676 if (ErrInfo) *ErrInfo = ErrorString; 1677 return true; 1678 } 1679 1680 // Upgrade any old intrinsic calls in the function. 1681 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 1682 E = UpgradedIntrinsics.end(); I != E; ++I) { 1683 if (I->first != I->second) { 1684 for (Value::use_iterator UI = I->first->use_begin(), 1685 UE = I->first->use_end(); UI != UE; ) { 1686 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 1687 UpgradeIntrinsicCall(CI, I->second); 1688 } 1689 } 1690 } 1691 1692 return false; 1693} 1694 1695void BitcodeReader::dematerializeFunction(Function *F) { 1696 // If this function isn't materialized, or if it is a proto, this is a noop. 1697 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration()) 1698 return; 1699 1700 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 1701 1702 // Just forget the function body, we can remat it later. 1703 F->deleteBody(); 1704 F->setLinkage(GlobalValue::GhostLinkage); 1705} 1706 1707 1708Module *BitcodeReader::materializeModule(std::string *ErrInfo) { 1709 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I = 1710 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E; 1711 ++I) { 1712 Function *F = I->first; 1713 if (F->hasNotBeenReadFromBitcode() && 1714 materializeFunction(F, ErrInfo)) 1715 return 0; 1716 } 1717 1718 // Upgrade any intrinsic calls that slipped through (should not happen!) and 1719 // delete the old functions to clean up. We can't do this unless the entire 1720 // module is materialized because there could always be another function body 1721 // with calls to the old function. 1722 for (std::vector<std::pair<Function*, Function*> >::iterator I = 1723 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 1724 if (I->first != I->second) { 1725 for (Value::use_iterator UI = I->first->use_begin(), 1726 UE = I->first->use_end(); UI != UE; ) { 1727 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 1728 UpgradeIntrinsicCall(CI, I->second); 1729 } 1730 ValueList.replaceUsesOfWith(I->first, I->second); 1731 I->first->eraseFromParent(); 1732 } 1733 } 1734 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 1735 1736 return TheModule; 1737} 1738 1739 1740/// This method is provided by the parent ModuleProvde class and overriden 1741/// here. It simply releases the module from its provided and frees up our 1742/// state. 1743/// @brief Release our hold on the generated module 1744Module *BitcodeReader::releaseModule(std::string *ErrInfo) { 1745 // Since we're losing control of this Module, we must hand it back complete 1746 Module *M = ModuleProvider::releaseModule(ErrInfo); 1747 FreeState(); 1748 return M; 1749} 1750 1751 1752//===----------------------------------------------------------------------===// 1753// External interface 1754//===----------------------------------------------------------------------===// 1755 1756/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file. 1757/// 1758ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer, 1759 std::string *ErrMsg) { 1760 BitcodeReader *R = new BitcodeReader(Buffer); 1761 if (R->ParseBitcode()) { 1762 if (ErrMsg) 1763 *ErrMsg = R->getErrorString(); 1764 1765 // Don't let the BitcodeReader dtor delete 'Buffer'. 1766 R->releaseMemoryBuffer(); 1767 delete R; 1768 return 0; 1769 } 1770 return R; 1771} 1772 1773/// ParseBitcodeFile - Read the specified bitcode file, returning the module. 1774/// If an error occurs, return null and fill in *ErrMsg if non-null. 1775Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){ 1776 BitcodeReader *R; 1777 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg)); 1778 if (!R) return 0; 1779 1780 // Read in the entire module. 1781 Module *M = R->materializeModule(ErrMsg); 1782 1783 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether 1784 // there was an error. 1785 R->releaseMemoryBuffer(); 1786 1787 // If there was no error, tell ModuleProvider not to delete it when its dtor 1788 // is run. 1789 if (M) 1790 M = R->releaseModule(ErrMsg); 1791 1792 delete R; 1793 return M; 1794} 1795