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