1 //===- MachineFunction.cpp ------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Collect native machine code information for a function. This allows 10 // target-specific information about the generated code to be stored with each 11 // function. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/MachineFunction.h" 16 #include "llvm/ADT/BitVector.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/DenseSet.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallString.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/Analysis/ConstantFolding.h" 25 #include "llvm/Analysis/EHPersonalities.h" 26 #include "llvm/CodeGen/MachineBasicBlock.h" 27 #include "llvm/CodeGen/MachineConstantPool.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineInstr.h" 30 #include "llvm/CodeGen/MachineJumpTableInfo.h" 31 #include "llvm/CodeGen/MachineMemOperand.h" 32 #include "llvm/CodeGen/MachineModuleInfo.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/PseudoSourceValue.h" 35 #include "llvm/CodeGen/TargetFrameLowering.h" 36 #include "llvm/CodeGen/TargetLowering.h" 37 #include "llvm/CodeGen/TargetRegisterInfo.h" 38 #include "llvm/CodeGen/TargetSubtargetInfo.h" 39 #include "llvm/CodeGen/WasmEHFuncInfo.h" 40 #include "llvm/CodeGen/WinEHFuncInfo.h" 41 #include "llvm/Config/llvm-config.h" 42 #include "llvm/IR/Attributes.h" 43 #include "llvm/IR/BasicBlock.h" 44 #include "llvm/IR/Constant.h" 45 #include "llvm/IR/DataLayout.h" 46 #include "llvm/IR/DebugInfoMetadata.h" 47 #include "llvm/IR/DerivedTypes.h" 48 #include "llvm/IR/Function.h" 49 #include "llvm/IR/GlobalValue.h" 50 #include "llvm/IR/Instruction.h" 51 #include "llvm/IR/Instructions.h" 52 #include "llvm/IR/Metadata.h" 53 #include "llvm/IR/Module.h" 54 #include "llvm/IR/ModuleSlotTracker.h" 55 #include "llvm/IR/Value.h" 56 #include "llvm/MC/MCContext.h" 57 #include "llvm/MC/MCSymbol.h" 58 #include "llvm/MC/SectionKind.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CommandLine.h" 61 #include "llvm/Support/Compiler.h" 62 #include "llvm/Support/DOTGraphTraits.h" 63 #include "llvm/Support/Debug.h" 64 #include "llvm/Support/ErrorHandling.h" 65 #include "llvm/Support/GraphWriter.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include <algorithm> 69 #include <cassert> 70 #include <cstddef> 71 #include <cstdint> 72 #include <iterator> 73 #include <string> 74 #include <utility> 75 #include <vector> 76 77 using namespace llvm; 78 79 #define DEBUG_TYPE "codegen" 80 81 static cl::opt<unsigned> 82 AlignAllFunctions("align-all-functions", 83 cl::desc("Force the alignment of all functions."), 84 cl::init(0), cl::Hidden); 85 86 static const char *getPropertyName(MachineFunctionProperties::Property Prop) { 87 using P = MachineFunctionProperties::Property; 88 89 switch(Prop) { 90 case P::FailedISel: return "FailedISel"; 91 case P::IsSSA: return "IsSSA"; 92 case P::Legalized: return "Legalized"; 93 case P::NoPHIs: return "NoPHIs"; 94 case P::NoVRegs: return "NoVRegs"; 95 case P::RegBankSelected: return "RegBankSelected"; 96 case P::Selected: return "Selected"; 97 case P::TracksLiveness: return "TracksLiveness"; 98 } 99 llvm_unreachable("Invalid machine function property"); 100 } 101 102 // Pin the vtable to this file. 103 void MachineFunction::Delegate::anchor() {} 104 105 void MachineFunctionProperties::print(raw_ostream &OS) const { 106 const char *Separator = ""; 107 for (BitVector::size_type I = 0; I < Properties.size(); ++I) { 108 if (!Properties[I]) 109 continue; 110 OS << Separator << getPropertyName(static_cast<Property>(I)); 111 Separator = ", "; 112 } 113 } 114 115 //===----------------------------------------------------------------------===// 116 // MachineFunction implementation 117 //===----------------------------------------------------------------------===// 118 119 // Out-of-line virtual method. 120 MachineFunctionInfo::~MachineFunctionInfo() = default; 121 122 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) { 123 MBB->getParent()->DeleteMachineBasicBlock(MBB); 124 } 125 126 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI, 127 const Function &F) { 128 if (F.hasFnAttribute(Attribute::StackAlignment)) 129 return F.getFnStackAlignment(); 130 return STI->getFrameLowering()->getStackAlignment(); 131 } 132 133 MachineFunction::MachineFunction(const Function &F, 134 const LLVMTargetMachine &Target, 135 const TargetSubtargetInfo &STI, 136 unsigned FunctionNum, MachineModuleInfo &mmi) 137 : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) { 138 FunctionNumber = FunctionNum; 139 init(); 140 } 141 142 void MachineFunction::handleInsertion(MachineInstr &MI) { 143 if (TheDelegate) 144 TheDelegate->MF_HandleInsertion(MI); 145 } 146 147 void MachineFunction::handleRemoval(MachineInstr &MI) { 148 if (TheDelegate) 149 TheDelegate->MF_HandleRemoval(MI); 150 } 151 152 void MachineFunction::init() { 153 // Assume the function starts in SSA form with correct liveness. 154 Properties.set(MachineFunctionProperties::Property::IsSSA); 155 Properties.set(MachineFunctionProperties::Property::TracksLiveness); 156 if (STI->getRegisterInfo()) 157 RegInfo = new (Allocator) MachineRegisterInfo(this); 158 else 159 RegInfo = nullptr; 160 161 MFInfo = nullptr; 162 // We can realign the stack if the target supports it and the user hasn't 163 // explicitly asked us not to. 164 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() && 165 !F.hasFnAttribute("no-realign-stack"); 166 FrameInfo = new (Allocator) MachineFrameInfo( 167 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP, 168 /*ForceRealign=*/CanRealignSP && 169 F.hasFnAttribute(Attribute::StackAlignment)); 170 171 if (F.hasFnAttribute(Attribute::StackAlignment)) 172 FrameInfo->ensureMaxAlignment(F.getFnStackAlignment()); 173 174 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout()); 175 Alignment = STI->getTargetLowering()->getMinFunctionAlignment(); 176 177 // FIXME: Shouldn't use pref alignment if explicit alignment is set on F. 178 // FIXME: Use Function::hasOptSize(). 179 if (!F.hasFnAttribute(Attribute::OptimizeForSize)) 180 Alignment = std::max(Alignment, 181 STI->getTargetLowering()->getPrefFunctionAlignment()); 182 183 if (AlignAllFunctions) 184 Alignment = AlignAllFunctions; 185 186 JumpTableInfo = nullptr; 187 188 if (isFuncletEHPersonality(classifyEHPersonality( 189 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) { 190 WinEHInfo = new (Allocator) WinEHFuncInfo(); 191 } 192 193 if (isScopedEHPersonality(classifyEHPersonality( 194 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) { 195 WasmEHInfo = new (Allocator) WasmEHFuncInfo(); 196 } 197 198 assert(Target.isCompatibleDataLayout(getDataLayout()) && 199 "Can't create a MachineFunction using a Module with a " 200 "Target-incompatible DataLayout attached\n"); 201 202 PSVManager = 203 llvm::make_unique<PseudoSourceValueManager>(*(getSubtarget(). 204 getInstrInfo())); 205 } 206 207 MachineFunction::~MachineFunction() { 208 clear(); 209 } 210 211 void MachineFunction::clear() { 212 Properties.reset(); 213 // Don't call destructors on MachineInstr and MachineOperand. All of their 214 // memory comes from the BumpPtrAllocator which is about to be purged. 215 // 216 // Do call MachineBasicBlock destructors, it contains std::vectors. 217 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I)) 218 I->Insts.clearAndLeakNodesUnsafely(); 219 MBBNumbering.clear(); 220 221 InstructionRecycler.clear(Allocator); 222 OperandRecycler.clear(Allocator); 223 BasicBlockRecycler.clear(Allocator); 224 CodeViewAnnotations.clear(); 225 VariableDbgInfos.clear(); 226 if (RegInfo) { 227 RegInfo->~MachineRegisterInfo(); 228 Allocator.Deallocate(RegInfo); 229 } 230 if (MFInfo) { 231 MFInfo->~MachineFunctionInfo(); 232 Allocator.Deallocate(MFInfo); 233 } 234 235 FrameInfo->~MachineFrameInfo(); 236 Allocator.Deallocate(FrameInfo); 237 238 ConstantPool->~MachineConstantPool(); 239 Allocator.Deallocate(ConstantPool); 240 241 if (JumpTableInfo) { 242 JumpTableInfo->~MachineJumpTableInfo(); 243 Allocator.Deallocate(JumpTableInfo); 244 } 245 246 if (WinEHInfo) { 247 WinEHInfo->~WinEHFuncInfo(); 248 Allocator.Deallocate(WinEHInfo); 249 } 250 251 if (WasmEHInfo) { 252 WasmEHInfo->~WasmEHFuncInfo(); 253 Allocator.Deallocate(WasmEHInfo); 254 } 255 } 256 257 const DataLayout &MachineFunction::getDataLayout() const { 258 return F.getParent()->getDataLayout(); 259 } 260 261 /// Get the JumpTableInfo for this function. 262 /// If it does not already exist, allocate one. 263 MachineJumpTableInfo *MachineFunction:: 264 getOrCreateJumpTableInfo(unsigned EntryKind) { 265 if (JumpTableInfo) return JumpTableInfo; 266 267 JumpTableInfo = new (Allocator) 268 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind); 269 return JumpTableInfo; 270 } 271 272 /// Should we be emitting segmented stack stuff for the function 273 bool MachineFunction::shouldSplitStack() const { 274 return getFunction().hasFnAttribute("split-stack"); 275 } 276 277 LLVM_NODISCARD unsigned 278 MachineFunction::addFrameInst(const MCCFIInstruction &Inst) { 279 FrameInstructions.push_back(Inst); 280 return FrameInstructions.size() - 1; 281 } 282 283 /// This discards all of the MachineBasicBlock numbers and recomputes them. 284 /// This guarantees that the MBB numbers are sequential, dense, and match the 285 /// ordering of the blocks within the function. If a specific MachineBasicBlock 286 /// is specified, only that block and those after it are renumbered. 287 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) { 288 if (empty()) { MBBNumbering.clear(); return; } 289 MachineFunction::iterator MBBI, E = end(); 290 if (MBB == nullptr) 291 MBBI = begin(); 292 else 293 MBBI = MBB->getIterator(); 294 295 // Figure out the block number this should have. 296 unsigned BlockNo = 0; 297 if (MBBI != begin()) 298 BlockNo = std::prev(MBBI)->getNumber() + 1; 299 300 for (; MBBI != E; ++MBBI, ++BlockNo) { 301 if (MBBI->getNumber() != (int)BlockNo) { 302 // Remove use of the old number. 303 if (MBBI->getNumber() != -1) { 304 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI && 305 "MBB number mismatch!"); 306 MBBNumbering[MBBI->getNumber()] = nullptr; 307 } 308 309 // If BlockNo is already taken, set that block's number to -1. 310 if (MBBNumbering[BlockNo]) 311 MBBNumbering[BlockNo]->setNumber(-1); 312 313 MBBNumbering[BlockNo] = &*MBBI; 314 MBBI->setNumber(BlockNo); 315 } 316 } 317 318 // Okay, all the blocks are renumbered. If we have compactified the block 319 // numbering, shrink MBBNumbering now. 320 assert(BlockNo <= MBBNumbering.size() && "Mismatch!"); 321 MBBNumbering.resize(BlockNo); 322 } 323 324 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'. 325 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID, 326 const DebugLoc &DL, 327 bool NoImp) { 328 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 329 MachineInstr(*this, MCID, DL, NoImp); 330 } 331 332 /// Create a new MachineInstr which is a copy of the 'Orig' instruction, 333 /// identical in all ways except the instruction has no parent, prev, or next. 334 MachineInstr * 335 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { 336 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 337 MachineInstr(*this, *Orig); 338 } 339 340 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB, 341 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) { 342 MachineInstr *FirstClone = nullptr; 343 MachineBasicBlock::const_instr_iterator I = Orig.getIterator(); 344 while (true) { 345 MachineInstr *Cloned = CloneMachineInstr(&*I); 346 MBB.insert(InsertBefore, Cloned); 347 if (FirstClone == nullptr) { 348 FirstClone = Cloned; 349 } else { 350 Cloned->bundleWithPred(); 351 } 352 353 if (!I->isBundledWithSucc()) 354 break; 355 ++I; 356 } 357 return *FirstClone; 358 } 359 360 /// Delete the given MachineInstr. 361 /// 362 /// This function also serves as the MachineInstr destructor - the real 363 /// ~MachineInstr() destructor must be empty. 364 void 365 MachineFunction::DeleteMachineInstr(MachineInstr *MI) { 366 // Strip it for parts. The operand array and the MI object itself are 367 // independently recyclable. 368 if (MI->Operands) 369 deallocateOperandArray(MI->CapOperands, MI->Operands); 370 // Don't call ~MachineInstr() which must be trivial anyway because 371 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their 372 // destructors. 373 InstructionRecycler.Deallocate(Allocator, MI); 374 } 375 376 /// Allocate a new MachineBasicBlock. Use this instead of 377 /// `new MachineBasicBlock'. 378 MachineBasicBlock * 379 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 380 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 381 MachineBasicBlock(*this, bb); 382 } 383 384 /// Delete the given MachineBasicBlock. 385 void 386 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) { 387 assert(MBB->getParent() == this && "MBB parent mismatch!"); 388 MBB->~MachineBasicBlock(); 389 BasicBlockRecycler.Deallocate(Allocator, MBB); 390 } 391 392 MachineMemOperand *MachineFunction::getMachineMemOperand( 393 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, 394 unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges, 395 SyncScope::ID SSID, AtomicOrdering Ordering, 396 AtomicOrdering FailureOrdering) { 397 return new (Allocator) 398 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges, 399 SSID, Ordering, FailureOrdering); 400 } 401 402 MachineMemOperand * 403 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 404 int64_t Offset, uint64_t Size) { 405 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo(); 406 407 // If there is no pointer value, the offset isn't tracked so we need to adjust 408 // the base alignment. 409 unsigned Align = PtrInfo.V.isNull() 410 ? MinAlign(MMO->getBaseAlignment(), Offset) 411 : MMO->getBaseAlignment(); 412 413 return new (Allocator) 414 MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size, 415 Align, AAMDNodes(), nullptr, MMO->getSyncScopeID(), 416 MMO->getOrdering(), MMO->getFailureOrdering()); 417 } 418 419 MachineMemOperand * 420 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 421 const AAMDNodes &AAInfo) { 422 MachinePointerInfo MPI = MMO->getValue() ? 423 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) : 424 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset()); 425 426 return new (Allocator) 427 MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(), 428 MMO->getBaseAlignment(), AAInfo, 429 MMO->getRanges(), MMO->getSyncScopeID(), 430 MMO->getOrdering(), MMO->getFailureOrdering()); 431 } 432 433 MachineMemOperand * 434 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 435 MachineMemOperand::Flags Flags) { 436 return new (Allocator) MachineMemOperand( 437 MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlignment(), 438 MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(), 439 MMO->getOrdering(), MMO->getFailureOrdering()); 440 } 441 442 MachineInstr::ExtraInfo * 443 MachineFunction::createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs, 444 MCSymbol *PreInstrSymbol, 445 MCSymbol *PostInstrSymbol) { 446 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol, 447 PostInstrSymbol); 448 } 449 450 const char *MachineFunction::createExternalSymbolName(StringRef Name) { 451 char *Dest = Allocator.Allocate<char>(Name.size() + 1); 452 llvm::copy(Name, Dest); 453 Dest[Name.size()] = 0; 454 return Dest; 455 } 456 457 uint32_t *MachineFunction::allocateRegMask() { 458 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs(); 459 unsigned Size = MachineOperand::getRegMaskSize(NumRegs); 460 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size); 461 memset(Mask, 0, Size * sizeof(Mask[0])); 462 return Mask; 463 } 464 465 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 466 LLVM_DUMP_METHOD void MachineFunction::dump() const { 467 print(dbgs()); 468 } 469 #endif 470 471 StringRef MachineFunction::getName() const { 472 return getFunction().getName(); 473 } 474 475 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const { 476 OS << "# Machine code for function " << getName() << ": "; 477 getProperties().print(OS); 478 OS << '\n'; 479 480 // Print Frame Information 481 FrameInfo->print(*this, OS); 482 483 // Print JumpTable Information 484 if (JumpTableInfo) 485 JumpTableInfo->print(OS); 486 487 // Print Constant Pool 488 ConstantPool->print(OS); 489 490 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); 491 492 if (RegInfo && !RegInfo->livein_empty()) { 493 OS << "Function Live Ins: "; 494 for (MachineRegisterInfo::livein_iterator 495 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 496 OS << printReg(I->first, TRI); 497 if (I->second) 498 OS << " in " << printReg(I->second, TRI); 499 if (std::next(I) != E) 500 OS << ", "; 501 } 502 OS << '\n'; 503 } 504 505 ModuleSlotTracker MST(getFunction().getParent()); 506 MST.incorporateFunction(getFunction()); 507 for (const auto &BB : *this) { 508 OS << '\n'; 509 // If we print the whole function, print it at its most verbose level. 510 BB.print(OS, MST, Indexes, /*IsStandalone=*/true); 511 } 512 513 OS << "\n# End machine code for function " << getName() << ".\n\n"; 514 } 515 516 namespace llvm { 517 518 template<> 519 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 520 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 521 522 static std::string getGraphName(const MachineFunction *F) { 523 return ("CFG for '" + F->getName() + "' function").str(); 524 } 525 526 std::string getNodeLabel(const MachineBasicBlock *Node, 527 const MachineFunction *Graph) { 528 std::string OutStr; 529 { 530 raw_string_ostream OSS(OutStr); 531 532 if (isSimple()) { 533 OSS << printMBBReference(*Node); 534 if (const BasicBlock *BB = Node->getBasicBlock()) 535 OSS << ": " << BB->getName(); 536 } else 537 Node->print(OSS); 538 } 539 540 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 541 542 // Process string output to make it nicer... 543 for (unsigned i = 0; i != OutStr.length(); ++i) 544 if (OutStr[i] == '\n') { // Left justify 545 OutStr[i] = '\\'; 546 OutStr.insert(OutStr.begin()+i+1, 'l'); 547 } 548 return OutStr; 549 } 550 }; 551 552 } // end namespace llvm 553 554 void MachineFunction::viewCFG() const 555 { 556 #ifndef NDEBUG 557 ViewGraph(this, "mf" + getName()); 558 #else 559 errs() << "MachineFunction::viewCFG is only available in debug builds on " 560 << "systems with Graphviz or gv!\n"; 561 #endif // NDEBUG 562 } 563 564 void MachineFunction::viewCFGOnly() const 565 { 566 #ifndef NDEBUG 567 ViewGraph(this, "mf" + getName(), true); 568 #else 569 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " 570 << "systems with Graphviz or gv!\n"; 571 #endif // NDEBUG 572 } 573 574 /// Add the specified physical register as a live-in value and 575 /// create a corresponding virtual register for it. 576 unsigned MachineFunction::addLiveIn(unsigned PReg, 577 const TargetRegisterClass *RC) { 578 MachineRegisterInfo &MRI = getRegInfo(); 579 unsigned VReg = MRI.getLiveInVirtReg(PReg); 580 if (VReg) { 581 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); 582 (void)VRegRC; 583 // A physical register can be added several times. 584 // Between two calls, the register class of the related virtual register 585 // may have been constrained to match some operation constraints. 586 // In that case, check that the current register class includes the 587 // physical register and is a sub class of the specified RC. 588 assert((VRegRC == RC || (VRegRC->contains(PReg) && 589 RC->hasSubClassEq(VRegRC))) && 590 "Register class mismatch!"); 591 return VReg; 592 } 593 VReg = MRI.createVirtualRegister(RC); 594 MRI.addLiveIn(PReg, VReg); 595 return VReg; 596 } 597 598 /// Return the MCSymbol for the specified non-empty jump table. 599 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 600 /// normal 'L' label is returned. 601 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 602 bool isLinkerPrivate) const { 603 const DataLayout &DL = getDataLayout(); 604 assert(JumpTableInfo && "No jump tables"); 605 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); 606 607 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() 608 : DL.getPrivateGlobalPrefix(); 609 SmallString<60> Name; 610 raw_svector_ostream(Name) 611 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; 612 return Ctx.getOrCreateSymbol(Name); 613 } 614 615 /// Return a function-local symbol to represent the PIC base. 616 MCSymbol *MachineFunction::getPICBaseSymbol() const { 617 const DataLayout &DL = getDataLayout(); 618 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 619 Twine(getFunctionNumber()) + "$pb"); 620 } 621 622 /// \name Exception Handling 623 /// \{ 624 625 LandingPadInfo & 626 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) { 627 unsigned N = LandingPads.size(); 628 for (unsigned i = 0; i < N; ++i) { 629 LandingPadInfo &LP = LandingPads[i]; 630 if (LP.LandingPadBlock == LandingPad) 631 return LP; 632 } 633 634 LandingPads.push_back(LandingPadInfo(LandingPad)); 635 return LandingPads[N]; 636 } 637 638 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad, 639 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 640 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 641 LP.BeginLabels.push_back(BeginLabel); 642 LP.EndLabels.push_back(EndLabel); 643 } 644 645 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) { 646 MCSymbol *LandingPadLabel = Ctx.createTempSymbol(); 647 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 648 LP.LandingPadLabel = LandingPadLabel; 649 650 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI(); 651 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) { 652 if (const auto *PF = 653 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts())) 654 getMMI().addPersonality(PF); 655 656 if (LPI->isCleanup()) 657 addCleanup(LandingPad); 658 659 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% 660 // correct, but we need to do it this way because of how the DWARF EH 661 // emitter processes the clauses. 662 for (unsigned I = LPI->getNumClauses(); I != 0; --I) { 663 Value *Val = LPI->getClause(I - 1); 664 if (LPI->isCatch(I - 1)) { 665 addCatchTypeInfo(LandingPad, 666 dyn_cast<GlobalValue>(Val->stripPointerCasts())); 667 } else { 668 // Add filters in a list. 669 auto *CVal = cast<Constant>(Val); 670 SmallVector<const GlobalValue *, 4> FilterList; 671 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end(); 672 II != IE; ++II) 673 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts())); 674 675 addFilterTypeInfo(LandingPad, FilterList); 676 } 677 } 678 679 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) { 680 for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) { 681 Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts(); 682 addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo)); 683 } 684 685 } else { 686 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!"); 687 } 688 689 return LandingPadLabel; 690 } 691 692 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad, 693 ArrayRef<const GlobalValue *> TyInfo) { 694 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 695 for (unsigned N = TyInfo.size(); N; --N) 696 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 697 } 698 699 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad, 700 ArrayRef<const GlobalValue *> TyInfo) { 701 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 702 std::vector<unsigned> IdsInFilter(TyInfo.size()); 703 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 704 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 705 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 706 } 707 708 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap, 709 bool TidyIfNoBeginLabels) { 710 for (unsigned i = 0; i != LandingPads.size(); ) { 711 LandingPadInfo &LandingPad = LandingPads[i]; 712 if (LandingPad.LandingPadLabel && 713 !LandingPad.LandingPadLabel->isDefined() && 714 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 715 LandingPad.LandingPadLabel = nullptr; 716 717 // Special case: we *should* emit LPs with null LP MBB. This indicates 718 // "nounwind" case. 719 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 720 LandingPads.erase(LandingPads.begin() + i); 721 continue; 722 } 723 724 if (TidyIfNoBeginLabels) { 725 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 726 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 727 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 728 if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) && 729 (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0))) 730 continue; 731 732 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 733 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 734 --j; 735 --e; 736 } 737 738 // Remove landing pads with no try-ranges. 739 if (LandingPads[i].BeginLabels.empty()) { 740 LandingPads.erase(LandingPads.begin() + i); 741 continue; 742 } 743 } 744 745 // If there is no landing pad, ensure that the list of typeids is empty. 746 // If the only typeid is a cleanup, this is the same as having no typeids. 747 if (!LandingPad.LandingPadBlock || 748 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 749 LandingPad.TypeIds.clear(); 750 ++i; 751 } 752 } 753 754 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) { 755 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 756 LP.TypeIds.push_back(0); 757 } 758 759 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad, 760 const Function *Filter, 761 const BlockAddress *RecoverBA) { 762 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 763 SEHHandler Handler; 764 Handler.FilterOrFinally = Filter; 765 Handler.RecoverBA = RecoverBA; 766 LP.SEHHandlers.push_back(Handler); 767 } 768 769 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 770 const Function *Cleanup) { 771 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 772 SEHHandler Handler; 773 Handler.FilterOrFinally = Cleanup; 774 Handler.RecoverBA = nullptr; 775 LP.SEHHandlers.push_back(Handler); 776 } 777 778 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym, 779 ArrayRef<unsigned> Sites) { 780 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 781 } 782 783 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) { 784 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 785 if (TypeInfos[i] == TI) return i + 1; 786 787 TypeInfos.push_back(TI); 788 return TypeInfos.size(); 789 } 790 791 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) { 792 // If the new filter coincides with the tail of an existing filter, then 793 // re-use the existing filter. Folding filters more than this requires 794 // re-ordering filters and/or their elements - probably not worth it. 795 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 796 E = FilterEnds.end(); I != E; ++I) { 797 unsigned i = *I, j = TyIds.size(); 798 799 while (i && j) 800 if (FilterIds[--i] != TyIds[--j]) 801 goto try_next; 802 803 if (!j) 804 // The new filter coincides with range [i, end) of the existing filter. 805 return -(1 + i); 806 807 try_next:; 808 } 809 810 // Add the new filter. 811 int FilterID = -(1 + FilterIds.size()); 812 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 813 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end()); 814 FilterEnds.push_back(FilterIds.size()); 815 FilterIds.push_back(0); // terminator 816 return FilterID; 817 } 818 819 void MachineFunction::addCodeViewHeapAllocSite(MachineInstr *I, MDNode *MD) { 820 MCSymbol *BeginLabel = Ctx.createTempSymbol("heapallocsite", true); 821 MCSymbol *EndLabel = Ctx.createTempSymbol("heapallocsite", true); 822 I->setPreInstrSymbol(*this, BeginLabel); 823 I->setPostInstrSymbol(*this, EndLabel); 824 825 DIType *DI = dyn_cast<DIType>(MD); 826 CodeViewHeapAllocSites.push_back(std::make_tuple(BeginLabel, EndLabel, DI)); 827 } 828 829 /// \} 830 831 //===----------------------------------------------------------------------===// 832 // MachineJumpTableInfo implementation 833 //===----------------------------------------------------------------------===// 834 835 /// Return the size of each entry in the jump table. 836 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { 837 // The size of a jump table entry is 4 bytes unless the entry is just the 838 // address of a block, in which case it is the pointer size. 839 switch (getEntryKind()) { 840 case MachineJumpTableInfo::EK_BlockAddress: 841 return TD.getPointerSize(); 842 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 843 return 8; 844 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 845 case MachineJumpTableInfo::EK_LabelDifference32: 846 case MachineJumpTableInfo::EK_Custom32: 847 return 4; 848 case MachineJumpTableInfo::EK_Inline: 849 return 0; 850 } 851 llvm_unreachable("Unknown jump table encoding!"); 852 } 853 854 /// Return the alignment of each entry in the jump table. 855 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { 856 // The alignment of a jump table entry is the alignment of int32 unless the 857 // entry is just the address of a block, in which case it is the pointer 858 // alignment. 859 switch (getEntryKind()) { 860 case MachineJumpTableInfo::EK_BlockAddress: 861 return TD.getPointerABIAlignment(0); 862 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 863 return TD.getABIIntegerTypeAlignment(64); 864 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 865 case MachineJumpTableInfo::EK_LabelDifference32: 866 case MachineJumpTableInfo::EK_Custom32: 867 return TD.getABIIntegerTypeAlignment(32); 868 case MachineJumpTableInfo::EK_Inline: 869 return 1; 870 } 871 llvm_unreachable("Unknown jump table encoding!"); 872 } 873 874 /// Create a new jump table entry in the jump table info. 875 unsigned MachineJumpTableInfo::createJumpTableIndex( 876 const std::vector<MachineBasicBlock*> &DestBBs) { 877 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 878 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 879 return JumpTables.size()-1; 880 } 881 882 /// If Old is the target of any jump tables, update the jump tables to branch 883 /// to New instead. 884 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 885 MachineBasicBlock *New) { 886 assert(Old != New && "Not making a change?"); 887 bool MadeChange = false; 888 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) 889 ReplaceMBBInJumpTable(i, Old, New); 890 return MadeChange; 891 } 892 893 /// If Old is a target of the jump tables, update the jump table to branch to 894 /// New instead. 895 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, 896 MachineBasicBlock *Old, 897 MachineBasicBlock *New) { 898 assert(Old != New && "Not making a change?"); 899 bool MadeChange = false; 900 MachineJumpTableEntry &JTE = JumpTables[Idx]; 901 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j) 902 if (JTE.MBBs[j] == Old) { 903 JTE.MBBs[j] = New; 904 MadeChange = true; 905 } 906 return MadeChange; 907 } 908 909 void MachineJumpTableInfo::print(raw_ostream &OS) const { 910 if (JumpTables.empty()) return; 911 912 OS << "Jump Tables:\n"; 913 914 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 915 OS << printJumpTableEntryReference(i) << ": "; 916 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j) 917 OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]); 918 } 919 920 OS << '\n'; 921 } 922 923 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 924 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); } 925 #endif 926 927 Printable llvm::printJumpTableEntryReference(unsigned Idx) { 928 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; }); 929 } 930 931 //===----------------------------------------------------------------------===// 932 // MachineConstantPool implementation 933 //===----------------------------------------------------------------------===// 934 935 void MachineConstantPoolValue::anchor() {} 936 937 Type *MachineConstantPoolEntry::getType() const { 938 if (isMachineConstantPoolEntry()) 939 return Val.MachineCPVal->getType(); 940 return Val.ConstVal->getType(); 941 } 942 943 bool MachineConstantPoolEntry::needsRelocation() const { 944 if (isMachineConstantPoolEntry()) 945 return true; 946 return Val.ConstVal->needsRelocation(); 947 } 948 949 SectionKind 950 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { 951 if (needsRelocation()) 952 return SectionKind::getReadOnlyWithRel(); 953 switch (DL->getTypeAllocSize(getType())) { 954 case 4: 955 return SectionKind::getMergeableConst4(); 956 case 8: 957 return SectionKind::getMergeableConst8(); 958 case 16: 959 return SectionKind::getMergeableConst16(); 960 case 32: 961 return SectionKind::getMergeableConst32(); 962 default: 963 return SectionKind::getReadOnly(); 964 } 965 } 966 967 MachineConstantPool::~MachineConstantPool() { 968 // A constant may be a member of both Constants and MachineCPVsSharingEntries, 969 // so keep track of which we've deleted to avoid double deletions. 970 DenseSet<MachineConstantPoolValue*> Deleted; 971 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 972 if (Constants[i].isMachineConstantPoolEntry()) { 973 Deleted.insert(Constants[i].Val.MachineCPVal); 974 delete Constants[i].Val.MachineCPVal; 975 } 976 for (DenseSet<MachineConstantPoolValue*>::iterator I = 977 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end(); 978 I != E; ++I) { 979 if (Deleted.count(*I) == 0) 980 delete *I; 981 } 982 } 983 984 /// Test whether the given two constants can be allocated the same constant pool 985 /// entry. 986 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, 987 const DataLayout &DL) { 988 // Handle the trivial case quickly. 989 if (A == B) return true; 990 991 // If they have the same type but weren't the same constant, quickly 992 // reject them. 993 if (A->getType() == B->getType()) return false; 994 995 // We can't handle structs or arrays. 996 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || 997 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) 998 return false; 999 1000 // For now, only support constants with the same size. 1001 uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); 1002 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) 1003 return false; 1004 1005 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); 1006 1007 // Try constant folding a bitcast of both instructions to an integer. If we 1008 // get two identical ConstantInt's, then we are good to share them. We use 1009 // the constant folding APIs to do this so that we get the benefit of 1010 // DataLayout. 1011 if (isa<PointerType>(A->getType())) 1012 A = ConstantFoldCastOperand(Instruction::PtrToInt, 1013 const_cast<Constant *>(A), IntTy, DL); 1014 else if (A->getType() != IntTy) 1015 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A), 1016 IntTy, DL); 1017 if (isa<PointerType>(B->getType())) 1018 B = ConstantFoldCastOperand(Instruction::PtrToInt, 1019 const_cast<Constant *>(B), IntTy, DL); 1020 else if (B->getType() != IntTy) 1021 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B), 1022 IntTy, DL); 1023 1024 return A == B; 1025 } 1026 1027 /// Create a new entry in the constant pool or return an existing one. 1028 /// User must specify the log2 of the minimum required alignment for the object. 1029 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 1030 unsigned Alignment) { 1031 assert(Alignment && "Alignment must be specified!"); 1032 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1033 1034 // Check to see if we already have this constant. 1035 // 1036 // FIXME, this could be made much more efficient for large constant pools. 1037 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1038 if (!Constants[i].isMachineConstantPoolEntry() && 1039 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { 1040 if ((unsigned)Constants[i].getAlignment() < Alignment) 1041 Constants[i].Alignment = Alignment; 1042 return i; 1043 } 1044 1045 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 1046 return Constants.size()-1; 1047 } 1048 1049 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 1050 unsigned Alignment) { 1051 assert(Alignment && "Alignment must be specified!"); 1052 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1053 1054 // Check to see if we already have this constant. 1055 // 1056 // FIXME, this could be made much more efficient for large constant pools. 1057 int Idx = V->getExistingMachineCPValue(this, Alignment); 1058 if (Idx != -1) { 1059 MachineCPVsSharingEntries.insert(V); 1060 return (unsigned)Idx; 1061 } 1062 1063 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 1064 return Constants.size()-1; 1065 } 1066 1067 void MachineConstantPool::print(raw_ostream &OS) const { 1068 if (Constants.empty()) return; 1069 1070 OS << "Constant Pool:\n"; 1071 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 1072 OS << " cp#" << i << ": "; 1073 if (Constants[i].isMachineConstantPoolEntry()) 1074 Constants[i].Val.MachineCPVal->print(OS); 1075 else 1076 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); 1077 OS << ", align=" << Constants[i].getAlignment(); 1078 OS << "\n"; 1079 } 1080 } 1081 1082 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1083 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); } 1084 #endif 1085