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