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