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