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