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