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