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