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