LLVM 23.0.0git
SILowerSGPRSpills.cpp
Go to the documentation of this file.
1//===-- SILowerSGPRSPills.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// Handle SGPR spills. This pass takes the place of PrologEpilogInserter for all
10// SGPR spills, so must insert CSR SGPR spills as well as expand them.
11//
12// This pass must never create new SGPR virtual registers.
13//
14// FIXME: Must stop RegScavenger spills in later passes.
15//
16//===----------------------------------------------------------------------===//
17
18#include "SILowerSGPRSpills.h"
19#include "AMDGPU.h"
20#include "GCNSubtarget.h"
23#include "SISpillUtils.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "si-lower-sgpr-spills"
34
36
37namespace {
38
39/// Insertion point for IMPLICIT_DEF: iterator may be MBB::end() and can't be
40/// dereferenced so the parent block is stored explicitly.
41struct LaneVGPRInsertPt {
44};
45
46static LaneVGPRInsertPt insertPt(MachineBasicBlock *MBB,
48 return {MBB, It};
49}
50
51static cl::opt<unsigned> MaxNumVGPRsForWwmAllocation(
52 "amdgpu-num-vgprs-for-wwm-alloc",
53 cl::desc("Max num VGPRs for whole-wave register allocation."),
55
56class SILowerSGPRSpills {
57private:
58 const SIRegisterInfo *TRI = nullptr;
59 const SIInstrInfo *TII = nullptr;
60 LiveIntervals *LIS = nullptr;
61 SlotIndexes *Indexes = nullptr;
62 MachineDominatorTree *MDT = nullptr;
63 MachineCycleInfo *MCI = nullptr;
64
65 // Save and Restore blocks of the current function. Typically there is a
66 // single save block, unless Windows EH funclets are involved.
67 MBBVector SaveBlocks;
68 MBBVector RestoreBlocks;
69
70 MachineBasicBlock *getCycleDomBB(MachineCycle *C);
71
72public:
73 SILowerSGPRSpills(LiveIntervals *LIS, SlotIndexes *Indexes,
75 : LIS(LIS), Indexes(Indexes), MDT(MDT), MCI(MCI) {}
76 bool run(MachineFunction &MF);
77 void calculateSaveRestoreBlocks(MachineFunction &MF);
78 bool spillCalleeSavedRegs(MachineFunction &MF,
79 SmallVectorImpl<int> &CalleeSavedFIs);
80 void updateLaneVGPRDomInstr(
82 DenseMap<Register, LaneVGPRInsertPt> &LaneVGPRDomInstr);
83 void determineRegsForWWMAllocation(MachineFunction &MF, BitVector &RegMask);
84};
85
86class SILowerSGPRSpillsLegacy : public MachineFunctionPass {
87public:
88 static char ID;
89
90 SILowerSGPRSpillsLegacy() : MachineFunctionPass(ID) {}
91
92 bool runOnMachineFunction(MachineFunction &MF) override;
93
94 void getAnalysisUsage(AnalysisUsage &AU) const override {
97 AU.setPreservesAll();
99 }
100
101 MachineFunctionProperties getClearedProperties() const override {
102 // SILowerSGPRSpills introduces new Virtual VGPRs for spilling SGPRs.
103 return MachineFunctionProperties().setIsSSA().setNoVRegs();
104 }
105};
106
107} // end anonymous namespace
108
109char SILowerSGPRSpillsLegacy::ID = 0;
110
111INITIALIZE_PASS_BEGIN(SILowerSGPRSpillsLegacy, DEBUG_TYPE,
112 "SI lower SGPR spill instructions", false, false)
117INITIALIZE_PASS_END(SILowerSGPRSpillsLegacy, DEBUG_TYPE,
118 "SI lower SGPR spill instructions", false, false)
119
120char &llvm::SILowerSGPRSpillsLegacyID = SILowerSGPRSpillsLegacy::ID;
121
122/// Insert spill code for the callee-saved registers used in the function.
124 ArrayRef<CalleeSavedInfo> CSI, SlotIndexes *Indexes,
125 LiveIntervals *LIS) {
126 const TargetFrameLowering *TFI = ST.getFrameLowering();
127 const TargetRegisterInfo *TRI = ST.getRegisterInfo();
128 MachineBasicBlock::iterator I = SaveBlock.begin();
129 MachineInstrSpan MIS(I, &SaveBlock);
130 bool Success = TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI);
131 assert(Success && "spillCalleeSavedRegisters should always succeed");
132 (void)Success;
133
134 // TFI doesn't update Indexes and LIS, so we have to do it separately.
135 if (Indexes)
136 Indexes->repairIndexesInRange(&SaveBlock, SaveBlock.begin(), I);
137
138 if (LIS)
139 for (const CalleeSavedInfo &CS : CSI)
140 LIS->removeAllRegUnitsForPhysReg(CS.getReg());
141}
142
143/// Insert restore code for the callee-saved registers used in the function.
144static void insertCSRRestores(MachineBasicBlock &RestoreBlock,
146 SlotIndexes *Indexes, LiveIntervals *LIS) {
147 MachineFunction &MF = *RestoreBlock.getParent();
151 // Restore all registers immediately before the return and any
152 // terminators that precede it.
154 const MachineBasicBlock::iterator BeforeRestoresI =
155 I == RestoreBlock.begin() ? I : std::prev(I);
156
157 // FIXME: Just emit the readlane/writelane directly
158 if (!TFI->restoreCalleeSavedRegisters(RestoreBlock, I, CSI, TRI)) {
159 for (const CalleeSavedInfo &CI : reverse(CSI)) {
160 // Insert in reverse order. loadRegFromStackSlot can insert
161 // multiple instructions.
162 TFI->restoreCalleeSavedRegister(RestoreBlock, I, CI, &TII, TRI);
163
164 if (Indexes) {
165 MachineInstr &Inst = *std::prev(I);
166 Indexes->insertMachineInstrInMaps(Inst);
167 }
168
169 if (LIS)
170 LIS->removeAllRegUnitsForPhysReg(CI.getReg());
171 }
172 } else {
173 // TFI doesn't update Indexes and LIS, so we have to do it separately.
174 if (Indexes)
175 Indexes->repairIndexesInRange(&RestoreBlock, BeforeRestoresI,
176 RestoreBlock.getFirstTerminator());
177
178 if (LIS)
179 for (const CalleeSavedInfo &CS : CSI)
180 LIS->removeAllRegUnitsForPhysReg(CS.getReg());
181 }
182}
183
184/// Compute the sets of entry and return blocks for saving and restoring
185/// callee-saved registers, and placing prolog and epilog code.
186void SILowerSGPRSpills::calculateSaveRestoreBlocks(MachineFunction &MF) {
187 const MachineFrameInfo &MFI = MF.getFrameInfo();
188
189 // Even when we do not change any CSR, we still want to insert the
190 // prologue and epilogue of the function.
191 // So set the save points for those.
192
193 // Use the points found by shrink-wrapping, if any.
194 if (!MFI.getSavePoints().empty()) {
195 assert(MFI.getSavePoints().size() == 1 &&
196 "Multiple save points not yet supported!");
197 const auto &SavePoint = *MFI.getSavePoints().begin();
198 SaveBlocks.push_back(SavePoint.first);
199 assert(MFI.getRestorePoints().size() == 1 &&
200 "Multiple restore points not yet supported!");
201 const auto &RestorePoint = *MFI.getRestorePoints().begin();
202 MachineBasicBlock *RestoreBlock = RestorePoint.first;
203 // If RestoreBlock does not have any successor and is not a return block
204 // then the end point is unreachable and we do not need to insert any
205 // epilogue.
206 if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
207 RestoreBlocks.push_back(RestoreBlock);
208 return;
209 }
210
211 // Save refs to entry and return blocks.
212 SaveBlocks.push_back(&MF.front());
213 for (MachineBasicBlock &MBB : MF) {
214 if (MBB.isEHFuncletEntry())
215 SaveBlocks.push_back(&MBB);
216 if (MBB.isReturnBlock())
217 RestoreBlocks.push_back(&MBB);
218 }
219}
220
221// TODO: To support shrink wrapping, this would need to copy
222// PrologEpilogInserter's updateLiveness.
224 MachineBasicBlock &EntryBB = MF.front();
225
226 for (const CalleeSavedInfo &CSIReg : CSI)
227 EntryBB.addLiveIn(CSIReg.getReg());
228 EntryBB.sortUniqueLiveIns();
229}
230
231bool SILowerSGPRSpills::spillCalleeSavedRegs(
232 MachineFunction &MF, SmallVectorImpl<int> &CalleeSavedFIs) {
233 MachineRegisterInfo &MRI = MF.getRegInfo();
234 const Function &F = MF.getFunction();
235 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
236 const SIFrameLowering *TFI = ST.getFrameLowering();
237 MachineFrameInfo &MFI = MF.getFrameInfo();
238 RegScavenger *RS = nullptr;
239
240 // Determine which of the registers in the callee save list should be saved.
241 BitVector SavedRegs;
242 TFI->determineCalleeSavesSGPR(MF, SavedRegs, RS);
243
244 // Add the code to save and restore the callee saved registers.
245 if (!F.hasFnAttribute(Attribute::Naked)) {
246 // FIXME: This is a lie. The CalleeSavedInfo is incomplete, but this is
247 // necessary for verifier liveness checks.
248 MFI.setCalleeSavedInfoValid(true);
249
250 std::vector<CalleeSavedInfo> CSI;
251 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
252 MCRegister RetAddrReg = TRI->getReturnAddressReg(MF);
253 MCRegister RetAddrRegSub0 = TRI->getSubReg(RetAddrReg, AMDGPU::sub0);
254 MCRegister RetAddrRegSub1 = TRI->getSubReg(RetAddrReg, AMDGPU::sub1);
255 bool SpillRetAddrReg = false;
256
257 for (unsigned I = 0; CSRegs[I]; ++I) {
258 MCRegister Reg = CSRegs[I];
259
260 if (SavedRegs.test(Reg)) {
261 if (Reg == RetAddrRegSub0 || Reg == RetAddrRegSub1) {
262 SpillRetAddrReg = true;
263 continue;
264 }
265
266 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
267 int JunkFI = MFI.CreateStackObject(TRI->getSpillSize(*RC),
268 TRI->getSpillAlign(*RC), true);
269
270 CSI.emplace_back(Reg, JunkFI);
271 CalleeSavedFIs.push_back(JunkFI);
272 }
273 }
274
275 // Return address uses a register pair. Add the super register to the
276 // CSI list so that it's easier to identify the entire spill and CFI
277 // can be emitted appropriately.
278 if (SpillRetAddrReg) {
279 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(RetAddrReg);
280 int JunkFI = MFI.CreateStackObject(TRI->getSpillSize(*RC),
281 TRI->getSpillAlign(*RC), true);
282 CSI.push_back(CalleeSavedInfo(RetAddrReg, JunkFI));
283 CalleeSavedFIs.push_back(JunkFI);
284 }
285
286 if (!CSI.empty()) {
287 for (MachineBasicBlock *SaveBlock : SaveBlocks)
288 insertCSRSaves(ST, *SaveBlock, CSI, Indexes, LIS);
289
290 // Add live ins to save blocks.
291 assert(SaveBlocks.size() == 1 && "shrink wrapping not fully implemented");
292 updateLiveness(MF, CSI);
293
294 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
295 insertCSRRestores(*RestoreBlock, CSI, Indexes, LIS);
296 return true;
297 }
298 }
299
300 return false;
301}
302
303MachineBasicBlock *SILowerSGPRSpills::getCycleDomBB(MachineCycle *C) {
304 // If the insertion point lands on a cycle entry, move it to a block that
305 // dominates all entries.
306 if (C->isReducible()) {
307 if (auto *IDom = MDT->getNode(C->getHeader())->getIDom())
308 return IDom->getBlock();
309 llvm_unreachable("Expected cycle to have an IDom.");
310 return nullptr;
311 }
312
313 const SmallVectorImpl<MachineBasicBlock *> &Entries = C->getEntries();
314 assert(!Entries.empty() && "Expected cycle to have at least one entry.");
315 MachineBasicBlock *EntryBB = Entries[0];
316 for (unsigned I = 1; I < Entries.size(); ++I)
317 EntryBB = MDT->findNearestCommonDominator(EntryBB, Entries[I]);
318 return EntryBB;
319}
320
321void SILowerSGPRSpills::updateLaneVGPRDomInstr(
322 int FI, MachineBasicBlock *MBB, MachineBasicBlock::iterator InsertPt,
323 DenseMap<Register, LaneVGPRInsertPt> &LaneVGPRDomInstr) {
324 // For the Def of a virtual LaneVGPR to dominate all its uses, we should
325 // insert an IMPLICIT_DEF before the dominating spill. Switching to a
326 // depth first order doesn't really help since the machine function can be in
327 // the unstructured control flow post-SSA. For each virtual register, hence
328 // finding the common dominator to get either the dominating spill or a block
329 // dominating all spills.
330 SIMachineFunctionInfo *FuncInfo =
331 MBB->getParent()->getInfo<SIMachineFunctionInfo>();
333 FuncInfo->getSGPRSpillToVirtualVGPRLanes(FI);
334 Register PrevLaneVGPR;
335 for (auto &Spill : VGPRSpills) {
336 if (PrevLaneVGPR == Spill.VGPR)
337 continue;
338
339 PrevLaneVGPR = Spill.VGPR;
340 auto I = LaneVGPRDomInstr.find(Spill.VGPR);
341 if (Spill.Lane == 0 && I == LaneVGPRDomInstr.end()) {
342 LaneVGPRDomInstr[Spill.VGPR] = insertPt(MBB, InsertPt);
343 } else {
344 assert(I != LaneVGPRDomInstr.end());
345 LaneVGPRInsertPt Prev = I->second;
346 MachineBasicBlock *PrevInsertMBB = Prev.MBB;
347 MachineBasicBlock::iterator PrevInsertPt = Prev.It;
348 MachineBasicBlock *DomMBB = PrevInsertMBB;
349 if (DomMBB == MBB) {
350 // The insertion point earlier selected in a predecessor block whose
351 // spills are currently being lowered. The earlier InsertPt would be
352 // the one just before the block terminator and it should be changed
353 // if we insert any new spill in it.
354 if (PrevInsertPt == MBB->end() ||
355 MDT->dominates(&*InsertPt, &*PrevInsertPt))
356 I->second = insertPt(MBB, InsertPt);
357
358 continue;
359 }
360
361 // Find the common dominator block between PrevInsertPt and the
362 // current spill.
363 DomMBB = MDT->findNearestCommonDominator(DomMBB, MBB);
364
365 if (DomMBB == MBB)
366 I->second = insertPt(MBB, InsertPt);
367 else if (DomMBB != PrevInsertMBB)
368 I->second = insertPt(DomMBB, DomMBB->getFirstTerminator());
369 }
370 }
371}
372
373void SILowerSGPRSpills::determineRegsForWWMAllocation(MachineFunction &MF,
374 BitVector &RegMask) {
375 // Determine an optimal number of VGPRs for WWM allocation. The complement
376 // list will be available for allocating other VGPR virtual registers.
377 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
378 MachineRegisterInfo &MRI = MF.getRegInfo();
379 BitVector ReservedRegs = TRI->getReservedRegs(MF);
380 BitVector NonWwmAllocMask(TRI->getNumRegs());
381 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
382
383 // FIXME: MaxNumVGPRsForWwmAllocation might need to be adjusted in the future
384 // to have a balanced allocation between WWM values and per-thread vector
385 // register operands.
386 unsigned NumRegs = MaxNumVGPRsForWwmAllocation;
387 NumRegs =
388 std::min(static_cast<unsigned>(MFI->getSGPRSpillVGPRs().size()), NumRegs);
389
390 auto [MaxNumVGPRs, MaxNumAGPRs] = ST.getMaxNumVectorRegs(MF.getFunction());
391 // Try to use the highest available registers for now. Later after
392 // vgpr-regalloc, they can be shifted to the lowest range.
393 unsigned I = 0;
394 for (unsigned Reg = AMDGPU::VGPR0 + MaxNumVGPRs - 1;
395 (I < NumRegs) && (Reg >= AMDGPU::VGPR0); --Reg) {
396 if (!ReservedRegs.test(Reg) &&
397 !MRI.isPhysRegUsed(Reg, /*SkipRegMaskTest=*/true)) {
398 TRI->markSuperRegs(RegMask, Reg);
399 ++I;
400 }
401 }
402
403 if (I != NumRegs) {
404 // Reserve an arbitrary register and report the error.
405 TRI->markSuperRegs(RegMask, AMDGPU::VGPR0);
407 "cannot find enough VGPRs for wwm-regalloc");
408 }
409}
410
411bool SILowerSGPRSpillsLegacy::runOnMachineFunction(MachineFunction &MF) {
412 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
413 LiveIntervals *LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
414 auto *SIWrapper = getAnalysisIfAvailable<SlotIndexesWrapperPass>();
415 SlotIndexes *Indexes = SIWrapper ? &SIWrapper->getSI() : nullptr;
416 MachineDominatorTree *MDT =
417 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
418 MachineCycleInfo *MCI =
419 &getAnalysis<MachineCycleInfoWrapperPass>().getCycleInfo();
420 return SILowerSGPRSpills(LIS, Indexes, MDT, MCI).run(MF);
421}
422
423bool SILowerSGPRSpills::run(MachineFunction &MF) {
424 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
425 TII = ST.getInstrInfo();
426 TRI = &TII->getRegisterInfo();
427
428 assert(SaveBlocks.empty() && RestoreBlocks.empty());
429
430 // First, expose any CSR SGPR spills. This is mostly the same as what PEI
431 // does, but somewhat simpler.
432 calculateSaveRestoreBlocks(MF);
433 SmallVector<int> CalleeSavedFIs;
434 bool HasCSRs = spillCalleeSavedRegs(MF, CalleeSavedFIs);
435
436 MachineFrameInfo &MFI = MF.getFrameInfo();
437 MachineRegisterInfo &MRI = MF.getRegInfo();
438 SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
439
440 if (!MFI.hasStackObjects() && !HasCSRs) {
441 SaveBlocks.clear();
442 RestoreBlocks.clear();
443 return false;
444 }
445
446 bool MadeChange = false;
447 bool SpilledToVirtVGPRLanes = false;
448
449 // TODO: CSR VGPRs will never be spilled to AGPRs. These can probably be
450 // handled as SpilledToReg in regular PrologEpilogInserter.
451 const bool HasSGPRSpillToVGPR = TRI->spillSGPRToVGPR() &&
452 (HasCSRs || FuncInfo->hasSpilledSGPRs());
453 if (HasSGPRSpillToVGPR) {
454 // Process all SGPR spills before frame offsets are finalized. Ideally SGPRs
455 // are spilled to VGPRs, in which case we can eliminate the stack usage.
456 //
457 // This operates under the assumption that only other SGPR spills are users
458 // of the frame index.
459
460 // To track the spill frame indices handled in this pass.
461 BitVector SpillFIs(MFI.getObjectIndexEnd(), false);
462
463 // To track the IMPLICIT_DEF insertion point for the lane vgprs.
464 DenseMap<Register, LaneVGPRInsertPt> LaneVGPRDomInstr;
465
466 for (MachineBasicBlock &MBB : MF) {
467 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
468 if (!TII->isSGPRSpill(MI))
469 continue;
470
471 if (MI.getOperand(0).isUndef()) {
472 if (Indexes)
474 MI.eraseFromParent();
475 continue;
476 }
477
478 int FI = TII->getNamedOperand(MI, AMDGPU::OpName::addr)->getIndex();
480
481 bool IsCalleeSaveSGPRSpill = llvm::is_contained(CalleeSavedFIs, FI);
482 if (IsCalleeSaveSGPRSpill) {
483 // Spill callee-saved SGPRs into physical VGPR lanes.
484
485 // TODO: This is to ensure the CFIs are static for efficient frame
486 // unwinding in the debugger. Spilling them into virtual VGPR lanes
487 // involve regalloc to allocate the physical VGPRs and that might
488 // cause intermediate spill/split of such liveranges for successful
489 // allocation. This would result in broken CFI encoding unless the
490 // regalloc aware CFI generation to insert new CFIs along with the
491 // intermediate spills is implemented. There is no such support
492 // currently exist in the LLVM compiler.
493 if (FuncInfo->allocateSGPRSpillToVGPRLane(
494 MF, FI, /*SpillToPhysVGPRLane=*/true)) {
495 bool Spilled = TRI->eliminateSGPRToVGPRSpillFrameIndex(
496 MI, FI, nullptr, Indexes, LIS, true);
497 if (!Spilled)
499 "failed to spill SGPR to physical VGPR lane when allocated");
500 }
501 } else {
502 MachineInstrSpan MIS(&MI, &MBB);
503 if (FuncInfo->allocateSGPRSpillToVGPRLane(MF, FI)) {
504 bool Spilled = TRI->eliminateSGPRToVGPRSpillFrameIndex(
505 MI, FI, nullptr, Indexes, LIS);
506 if (!Spilled)
508 "failed to spill SGPR to virtual VGPR lane when allocated");
509 SpillFIs.set(FI);
510 updateLaneVGPRDomInstr(FI, &MBB, MIS.begin(), LaneVGPRDomInstr);
511 SpilledToVirtVGPRLanes = true;
512 }
513 }
514 }
515 }
516
517 for (auto Reg : FuncInfo->getSGPRSpillVGPRs()) {
518 LaneVGPRInsertPt IP = LaneVGPRDomInstr[Reg];
519 if (MachineCycle *C = MCI->getTopLevelParentCycle(IP.MBB)) {
520 MachineBasicBlock *AdjMBB = getCycleDomBB(C);
521 IP = insertPt(AdjMBB, AdjMBB->getFirstTerminator());
522 }
523 // Insert the IMPLICIT_DEF at the identified points.
524 MachineBasicBlock &Block = *IP.MBB;
525 DebugLoc DL = Block.findDebugLoc(IP.It);
526 auto MIB = BuildMI(Block, IP.It, DL, TII->get(AMDGPU::IMPLICIT_DEF), Reg);
527
528 // Add WWM flag to the virtual register.
530
531 // Set SGPR_SPILL asm printer flag
532 MIB->setAsmPrinterFlag(AMDGPU::SGPR_SPILL);
533 if (LIS) {
534 LIS->InsertMachineInstrInMaps(*MIB);
536 }
537 }
538
539 // Determine the registers for WWM allocation and also compute the register
540 // mask for non-wwm VGPR allocation.
541 if (FuncInfo->getSGPRSpillVGPRs().size()) {
542 BitVector WwmRegMask(TRI->getNumRegs());
543
544 determineRegsForWWMAllocation(MF, WwmRegMask);
545
546 BitVector NonWwmRegMask(WwmRegMask);
547 NonWwmRegMask.flip().clearBitsNotInMask(TRI->getAllVGPRRegMask());
548
549 // The complement set will be the registers for non-wwm (per-thread) vgpr
550 // allocation.
551 FuncInfo->updateNonWWMRegMask(NonWwmRegMask);
552 }
553
554 for (MachineBasicBlock &MBB : MF)
555 clearDebugInfoForSpillFIs(MFI, MBB, SpillFIs);
556
557 // All those frame indices which are dead by now should be removed from the
558 // function frame. Otherwise, there is a side effect such as re-mapping of
559 // free frame index ids by the later pass(es) like "stack slot coloring"
560 // which in turn could mess-up with the book keeping of "frame index to VGPR
561 // lane".
562 FuncInfo->removeDeadFrameIndices(MFI, /*ResetSGPRSpillStackIDs*/ false);
563
564 MadeChange = true;
565 }
566
567 if (SpilledToVirtVGPRLanes) {
568 const TargetRegisterClass *RC = TRI->getWaveMaskRegClass();
569 // Shift back the reserved SGPR for EXEC copy into the lowest range.
570 // This SGPR is reserved to handle the whole-wave spill/copy operations
571 // that might get inserted during vgpr regalloc.
572 Register UnusedLowSGPR = TRI->findUnusedRegister(MRI, RC, MF);
573 if (UnusedLowSGPR && TRI->getHWRegIndex(UnusedLowSGPR) <
574 TRI->getHWRegIndex(FuncInfo->getSGPRForEXECCopy()))
575 FuncInfo->setSGPRForEXECCopy(UnusedLowSGPR);
576 } else {
577 // No SGPR spills to virtual VGPR lanes and hence there won't be any WWM
578 // spills/copies. Reset the SGPR reserved for EXEC copy.
579 FuncInfo->setSGPRForEXECCopy(AMDGPU::NoRegister);
580 }
581
582 SaveBlocks.clear();
583 RestoreBlocks.clear();
584
585 return MadeChange;
586}
587
588PreservedAnalyses
591 MFPropsModifier _(*this, MF);
592 auto *LIS = MFAM.getCachedResult<LiveIntervalsAnalysis>(MF);
593 auto *Indexes = MFAM.getCachedResult<SlotIndexesAnalysis>(MF);
596 SILowerSGPRSpills(LIS, Indexes, MDT, &MCI).run(MF);
597 return PreservedAnalyses::all();
598}
#define Success
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static void insertCSRRestores(MachineBasicBlock &RestoreBlock, std::vector< CalleeSavedInfo > &CSI)
Insert restore code for the callee-saved registers used in the function.
SmallVector< MachineBasicBlock *, 4 > MBBVector
static void insertCSRSaves(MachineBasicBlock &SaveBlock, ArrayRef< CalleeSavedInfo > CSI)
Insert spill code for the callee-saved registers used in the function.
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
This file declares the machine register scavenger class.
static void insertCSRRestores(MachineBasicBlock &RestoreBlock, MutableArrayRef< CalleeSavedInfo > CSI, SlotIndexes *Indexes, LiveIntervals *LIS)
Insert restore code for the callee-saved registers used in the function.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
iterator end()
Definition DenseMap.h:85
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
CycleT * getTopLevelParentCycle(const BlockT *Block) const
const HexagonRegisterInfo & getRegisterInfo() const
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Legacy analysis pass which computes a MachineCycleInfo.
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void setCalleeSavedInfoValid(bool v)
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasStackObjects() const
Return true if there are any stack objects in this function.
uint8_t getStackID(int ObjectIdx) const
const SaveRestorePoints & getRestorePoints() const
const SaveRestorePoints & getSavePoints() const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
MachineInstrSpan provides an interface to get an iteration range containing the instruction it was in...
Representation of each machine instruction.
LLVM_ABI const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void setFlag(Register Reg, uint8_t Flag)
ArrayRef< SIRegisterInfo::SpilledReg > getSGPRSpillToVirtualVGPRLanes(int FrameIndex) const
bool allocateSGPRSpillToVGPRLane(MachineFunction &MF, int FI, bool SpillToPhysVGPRLane=false, bool IsPrologEpilog=false)
bool removeDeadFrameIndices(MachineFrameInfo &MFI, bool ResetSGPRSpillStackIDs)
If ResetSGPRSpillStackIDs is true, reset the stack ID from sgpr-spill to the default stack.
void updateNonWWMRegMask(BitVector &RegMask)
ArrayRef< Register > getSGPRSpillVGPRs() const
SlotIndexes pass.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
LLVM_ABI void removeMachineInstrFromMaps(MachineInstr &MI, bool AllowBundled=false)
Removes machine instruction (bundle) MI from the mapping.
LLVM_ABI void repairIndexesInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End)
Repair indexes after adding and removing instructions.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Information about stack frame layout on the target.
void restoreCalleeSavedRegister(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void clearDebugInfoForSpillFIs(MachineFrameInfo &MFI, MachineBasicBlock &MBB, const BitVector &SpillFIs)
Replace frame index operands with null registers in debug value instructions for the specified spill ...
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
char & SILowerSGPRSpillsLegacyID
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
MachineCycleInfo::CycleT MachineCycle