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