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