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