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