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