LLVM 24.0.0git
AMDGPURewriteAGPRCopyMFMA.cpp
Go to the documentation of this file.
1//===-- AMDGPURewriteAGPRCopyMFMA.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/// \file \brief Try to replace MFMA instructions using VGPRs with MFMA
10/// instructions using AGPRs. We expect MFMAs to be selected using VGPRs, and
11/// only use AGPRs if it helps avoid spilling. In this case, the MFMA will have
12/// copies between AGPRs and VGPRs and the AGPR variant of an MFMA pseudo. This
13/// pass will attempt to delete the cross register bank copy and replace the
14/// MFMA opcode.
15///
16/// TODO:
17/// - Handle rewrites of phis. This must be more careful than normal about the
18/// reassignment. We do not want to introduce an AGPR-to-AGPR copy inside of a
19/// loop, so it depends on the exact assignment of the copy.
20///
21/// - Update LiveIntervals incrementally instead of recomputing from scratch
22///
23//===----------------------------------------------------------------------===//
24
25#include "AMDGPU.h"
26#include "GCNSubtarget.h"
28#include "SIRegisterInfo.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/Statistic.h"
42
43using namespace llvm;
44
45#define DEBUG_TYPE "amdgpu-rewrite-agpr-copy-mfma"
46
47DEBUG_COUNTER(RewriteAGPRCopyMFMACounter, DEBUG_TYPE,
48 "Controls which MFMA chains are rewritten to AGPR form");
49
50namespace {
51
52STATISTIC(NumMFMAsRewrittenToAGPR,
53 "Number of MFMA instructions rewritten to use AGPR form");
54
55/// Map from spill slot frame index to list of instructions which reference it.
56using SpillReferenceMap = DenseMap<int, SmallVector<MachineInstr *, 4>>;
57
58class AMDGPURewriteAGPRCopyMFMAImpl {
60 const GCNSubtarget &ST;
61 const SIInstrInfo &TII;
62 const SIRegisterInfo &TRI;
64 VirtRegMap &VRM;
65 LiveRegMatrix &LRM;
66 LiveIntervals &LIS;
67 LiveStacks &LSS;
68 const RegisterClassInfo &RegClassInfo;
70
71 bool attemptReassignmentsToAGPR(SmallSetVector<Register, 4> &InterferingRegs,
72 MCPhysReg PrefPhysReg) const;
73
74public:
75 AMDGPURewriteAGPRCopyMFMAImpl(MachineFunction &MF, VirtRegMap &VRM,
77 LiveStacks &LSS,
78 const RegisterClassInfo &RegClassInfo,
80 : MF(MF), ST(MF.getSubtarget<GCNSubtarget>()), TII(*ST.getInstrInfo()),
81 TRI(*ST.getRegisterInfo()), MRI(MF.getRegInfo()), VRM(VRM), LRM(LRM),
82 LIS(LIS), LSS(LSS), RegClassInfo(RegClassInfo), MDT(MDT) {}
83
84 bool isRewriteCandidate(const MachineInstr &MI) const {
85 return TII.isMAI(MI) && AMDGPU::getAGPRFormOp(MI.getOpcode()) != -1;
86 }
87
88 /// Find AV_* registers assigned to AGPRs (or virtual registers which were
89 /// already required to be AGPR).
90 ///
91 /// \return the assigned physical register that \p VReg is assigned to if it
92 /// is an AGPR, otherwise MCRegister().
93 MCRegister getAssignedAGPR(Register VReg) const {
94 MCRegister PhysReg = VRM.getPhys(VReg);
95 if (!PhysReg)
96 return MCRegister();
97
98 // If this is an AV register, we have to check if the actual assignment is
99 // to an AGPR
100 const TargetRegisterClass *AssignedRC = TRI.getPhysRegBaseClass(PhysReg);
101 return TRI.isAGPRClass(AssignedRC) ? PhysReg : MCRegister();
102 }
103
104 bool tryReassigningMFMAChain(MachineInstr &MFMA, Register MFMAHintReg,
105 MCPhysReg PhysRegHint) const;
106
107 /// Compute the register class constraints based on the uses of \p Reg,
108 /// excluding MFMA uses from which can be rewritten to change the register
109 /// class constraint. MFMA scale operands need to be constraint checked.
110 /// This should be nearly identical to MachineRegisterInfo::recomputeRegClass.
111
112 /// \p RewriteCandidates will collect the set of MFMA instructions that need
113 /// to have the opcode mutated to perform the replacement.
114 ///
115 /// \p RewriteRegs will accumulate the set of register used by those MFMAs
116 /// that need to have the register classes adjusted.
117 bool recomputeRegClassExceptRewritable(
118 Register Reg, SmallVectorImpl<MachineInstr *> &RewriteCandidates,
119 SmallSetVector<Register, 4> &RewriteRegs) const;
120
121 bool tryFoldCopiesToAGPR(Register VReg, MCRegister AssignedAGPR) const;
122 bool tryFoldCopiesFromAGPR(Register VReg, MCRegister AssignedAGPR) const;
123
124 /// Replace spill instruction \p SpillMI which loads/stores from/to \p SpillFI
125 /// with a COPY to the replacement register value \p VReg.
126 void replaceSpillWithCopyToVReg(MachineInstr &SpillMI, int SpillFI,
127 Register VReg) const;
128
129 /// Create a map from frame index to use instructions for spills. If a use of
130 /// the frame index does not consist only of spill instructions, it will not
131 /// be included in the map.
132 void collectSpillIndexUses(ArrayRef<LiveInterval *> StackIntervals,
133 SpillReferenceMap &Map) const;
134
135 /// Return true if the reload \p LoadMI of the stack slot with live interval
136 /// \p SlotLI is jointly dominated by the slot's spill stores, i.e. every path
137 /// from the entry block to the load passes through a store to the slot before
138 /// the load. \p StoreFreeReachable is the set of blocks reachable from the
139 /// entry block without passing through any store block for the slot.
140 bool isLoadJointlyDominatedByStores(
141 const MachineInstr &LoadMI, const LiveInterval &SlotLI,
142 const SmallPtrSetImpl<MachineBasicBlock *> &StoreFreeReachable) const;
143
144 /// Attempt to unspill VGPRs by finding a free register and replacing the
145 /// spill instructions with copies.
146 void eliminateSpillsOfReassignedVGPRs() const;
147
148 bool run(MachineFunction &MF) const;
149};
150
151bool AMDGPURewriteAGPRCopyMFMAImpl::recomputeRegClassExceptRewritable(
152 Register StartReg, SmallVectorImpl<MachineInstr *> &RewriteCandidates,
153 SmallSetVector<Register, 4> &RewriteRegs) const {
154 SmallVector<Register, 8> Worklist = {StartReg};
155
156 // Recursively visit all transitive MFMA users
157 while (!Worklist.empty()) {
158 Register Reg = Worklist.pop_back_val();
159 const TargetRegisterClass *OldRC = MRI.getRegClass(Reg);
160
161 // Inflate to the equivalent AV_* class.
162 const TargetRegisterClass *NewRC = TRI.getLargestLegalSuperClass(OldRC, MF);
163 if (OldRC == NewRC)
164 return false;
165
166 // Accumulate constraints from all uses.
167 for (MachineOperand &MO : MRI.reg_nodbg_operands(Reg)) {
168 // Apply the effect of the given operand to NewRC.
169 MachineInstr *MI = MO.getParent();
170
171 // We can swap the classes of dst + src2 as a pair to AGPR, so ignore the
172 // effects of rewrite candidates. It just so happens that we can use
173 // either AGPR or VGPR in src0/src1. We still need to check constraint
174 // effects for scale variant, which does not allow AGPR.
175 if (isRewriteCandidate(*MI)) {
176 int AGPROp = AMDGPU::getAGPRFormOp(MI->getOpcode());
177 const MCInstrDesc &AGPRDesc = TII.get(AGPROp);
178 const TargetRegisterClass *NewRC =
179 TII.getRegClass(AGPRDesc, MO.getOperandNo());
180 if (!TRI.hasAGPRs(NewRC))
181 return false;
182
183 const MachineOperand *VDst =
184 TII.getNamedOperand(*MI, AMDGPU::OpName::vdst);
185 const MachineOperand *Src2 =
186 TII.getNamedOperand(*MI, AMDGPU::OpName::src2);
187 for (const MachineOperand *Op : {VDst, Src2}) {
188 if (!Op->isReg())
189 continue;
190
191 Register OtherReg = Op->getReg();
192 if (OtherReg.isPhysical())
193 return false;
194
195 if (OtherReg != Reg && RewriteRegs.insert(OtherReg))
196 Worklist.push_back(OtherReg);
197 }
198
199 if (!is_contained(RewriteCandidates, MI)) {
200 LLVM_DEBUG({
201 Register VDstPhysReg = VRM.getPhys(VDst->getReg());
202 dbgs() << "Attempting to replace VGPR MFMA with AGPR version:"
203 << " Dst=[" << printReg(VDst->getReg()) << " => "
204 << printReg(VDstPhysReg, &TRI);
205
206 if (Src2->isReg()) {
207 Register Src2PhysReg = VRM.getPhys(Src2->getReg());
208 dbgs() << "], Src2=[" << printReg(Src2->getReg(), &TRI) << " => "
209 << printReg(Src2PhysReg, &TRI);
210 }
211
212 dbgs() << "]: " << MI;
213 });
214
215 RewriteCandidates.push_back(MI);
216 }
217
218 continue;
219 }
220
221 unsigned OpNo = &MO - &MI->getOperand(0);
222 NewRC = MI->getRegClassConstraintEffect(OpNo, NewRC, &TII, &TRI);
223 if (!NewRC || NewRC == OldRC) {
224 LLVM_DEBUG(dbgs() << "User of " << printReg(Reg, &TRI)
225 << " cannot be reassigned to "
226 << (NewRC ? TRI.getRegClassName(NewRC) : "NULL")
227 << ": " << *MI);
228 return false;
229 }
230 }
231 }
232
233 return true;
234}
235
236bool AMDGPURewriteAGPRCopyMFMAImpl::tryReassigningMFMAChain(
237 MachineInstr &MFMA, Register MFMAHintReg, MCPhysReg PhysRegHint) const {
238 // src2 and dst have the same physical class constraint; try to preserve
239 // the original src2 subclass if one were to exist.
240 SmallVector<MachineInstr *, 4> RewriteCandidates = {&MFMA};
241 SmallSetVector<Register, 4> RewriteRegs;
242
243 // Make sure we reassign the MFMA we found the copy from first. We want
244 // to ensure dst ends up in the physreg we were originally copying to.
245 RewriteRegs.insert(MFMAHintReg);
246
247 // We've found av = COPY (MFMA) (or MFMA (v = COPY av)) and need to verify
248 // that we can trivially rewrite src2 to use the new AGPR. If we can't
249 // trivially replace it, we're going to induce as many copies as we would have
250 // emitted in the first place, as well as need to assign another register, and
251 // need to figure out where to put them. The live range splitting is smarter
252 // than anything we're doing here, so trust it did something reasonable.
253 //
254 // Note recomputeRegClassExceptRewritable will consider the constraints of
255 // this MFMA's src2 as well as the src2/dst of any transitive MFMA users.
256 if (!recomputeRegClassExceptRewritable(MFMAHintReg, RewriteCandidates,
257 RewriteRegs)) {
258 LLVM_DEBUG(dbgs() << "Could not recompute the regclass of dst reg "
259 << printReg(MFMAHintReg, &TRI) << '\n');
260 return false;
261 }
262
263 // If src2 and dst are different registers, we need to also reassign the
264 // input to an available AGPR if it is compatible with all other uses.
265 //
266 // If we can't reassign it, we'd need to introduce a different copy
267 // which is likely worse than the copy we'd be saving.
268 //
269 // It's likely that the MFMA is used in sequence with other MFMAs; if we
270 // cannot migrate the full use/def chain of MFMAs, we would need to
271 // introduce intermediate copies somewhere. So we only make the
272 // transform if all the interfering MFMAs can also be migrated. Collect
273 // the set of rewritable MFMAs and check if we can assign an AGPR at
274 // that point.
275 //
276 // If any of the MFMAs aren't reassignable, we give up and rollback to
277 // the original register assignments.
278
279 using RecoloringStack =
281 RecoloringStack TentativeReassignments;
282
283 for (Register RewriteReg : RewriteRegs) {
284 LiveInterval &LI = LIS.getInterval(RewriteReg);
285 TentativeReassignments.push_back({&LI, VRM.getPhys(RewriteReg)});
286 LRM.unassign(LI);
287 }
288
289 if (!DebugCounter::shouldExecute(RewriteAGPRCopyMFMACounter) ||
290 !attemptReassignmentsToAGPR(RewriteRegs, PhysRegHint)) {
291 // Roll back the register assignments to the original state.
292 for (auto [LI, OldAssign] : TentativeReassignments) {
293 if (VRM.hasPhys(LI->reg()))
294 LRM.unassign(*LI);
295 LRM.assign(*LI, OldAssign);
296 }
297
298 return false;
299 }
300
301 // Fixup the register classes of the virtual registers now that we've
302 // committed to the reassignments.
303 for (Register InterferingReg : RewriteRegs) {
304 const TargetRegisterClass *EquivalentAGPRRegClass =
305 TRI.getEquivalentAGPRClass(MRI.getRegClass(InterferingReg));
306 MRI.setRegClass(InterferingReg, EquivalentAGPRRegClass);
307 }
308
309 for (MachineInstr *RewriteCandidate : RewriteCandidates) {
310 int NewMFMAOp = AMDGPU::getAGPRFormOp(RewriteCandidate->getOpcode());
311 RewriteCandidate->setDesc(TII.get(NewMFMAOp));
312 ++NumMFMAsRewrittenToAGPR;
313 }
314
315 return true;
316}
317
318/// Attempt to reassign the registers in \p InterferingRegs to be AGPRs, with a
319/// preference to use \p PhysReg first. Returns false if the reassignments
320/// cannot be trivially performed.
321bool AMDGPURewriteAGPRCopyMFMAImpl::attemptReassignmentsToAGPR(
322 SmallSetVector<Register, 4> &InterferingRegs, MCPhysReg PrefPhysReg) const {
323 // FIXME: The ordering may matter here, but we're just taking uselistorder
324 // with the special case of ensuring to process the starting instruction
325 // first. We probably should extract the priority advisor out of greedy and
326 // use that ordering.
327 for (Register InterferingReg : InterferingRegs) {
328 LiveInterval &ReassignLI = LIS.getInterval(InterferingReg);
329 const TargetRegisterClass *EquivalentAGPRRegClass =
330 TRI.getEquivalentAGPRClass(MRI.getRegClass(InterferingReg));
331
332 MCPhysReg Assignable = AMDGPU::NoRegister;
333 if (EquivalentAGPRRegClass->contains(PrefPhysReg) &&
334 LRM.checkInterference(ReassignLI, PrefPhysReg) ==
336 // First try to assign to the AGPR we were already copying to. This
337 // should be the first assignment we attempt. We have to guard
338 // against the use being a subregister (which doesn't have an exact
339 // class match).
340
341 // TODO: If this does happen to be a subregister use, we should
342 // still try to assign to a subregister of the original copy result.
343 Assignable = PrefPhysReg;
344 } else {
345 ArrayRef<MCPhysReg> AllocOrder =
346 RegClassInfo.getOrder(EquivalentAGPRRegClass);
347 for (MCPhysReg Reg : AllocOrder) {
348 if (LRM.checkInterference(ReassignLI, Reg) == LiveRegMatrix::IK_Free) {
349 Assignable = Reg;
350 break;
351 }
352 }
353 }
354
355 if (!Assignable) {
356 LLVM_DEBUG(dbgs() << "Unable to reassign VGPR "
357 << printReg(InterferingReg, &TRI)
358 << " to a free AGPR\n");
359 return false;
360 }
361
362 LLVM_DEBUG(dbgs() << "Reassigning VGPR " << printReg(InterferingReg, &TRI)
363 << " to " << printReg(Assignable, &TRI) << '\n');
364 LRM.assign(ReassignLI, Assignable);
365 }
366
367 return true;
368}
369
370/// Identify copies that look like:
371/// %vdst:vgpr = V_MFMA_.. %src0:av, %src1:av, %src2:vgpr
372/// %agpr = COPY %vgpr
373///
374/// Then try to replace the transitive uses of %src2 and %vdst with the AGPR
375/// versions of the MFMA. This should cover the common case.
376bool AMDGPURewriteAGPRCopyMFMAImpl::tryFoldCopiesToAGPR(
377 Register VReg, MCRegister AssignedAGPR) const {
378 bool MadeChange = false;
379 for (MachineInstr &UseMI : MRI.def_instructions(VReg)) {
380 if (!UseMI.isCopy())
381 continue;
382
383 Register CopySrcReg = UseMI.getOperand(1).getReg();
384 if (!CopySrcReg.isVirtual())
385 continue;
386
387 // TODO: Handle loop phis copied to AGPR. e.g.
388 //
389 // loop:
390 // %phi:vgpr = COPY %mfma:vgpr
391 // %mfma:vgpr = V_MFMA_xxx_vgprcd_e64 %a, %b, %phi
392 // s_cbranch_vccnz loop
393 //
394 // endloop:
395 // %agpr = mfma
396 //
397 // We need to be sure that %phi is assigned to the same physical register as
398 // %mfma, or else we will just be moving copies into the loop.
399
400 for (MachineInstr &CopySrcDefMI : MRI.def_instructions(CopySrcReg)) {
401 if (isRewriteCandidate(CopySrcDefMI) &&
402 tryReassigningMFMAChain(
403 CopySrcDefMI, CopySrcDefMI.getOperand(0).getReg(), AssignedAGPR))
404 MadeChange = true;
405 }
406 }
407
408 return MadeChange;
409}
410
411/// Identify copies that look like:
412/// %src:vgpr = COPY %src:agpr
413/// %vdst:vgpr = V_MFMA_... %src0:av, %src1:av, %src:vgpr
414///
415/// Then try to replace the transitive uses of %src2 and %vdst with the AGPR
416/// versions of the MFMA. This should cover rarer cases, and will generally be
417/// redundant with tryFoldCopiesToAGPR.
418bool AMDGPURewriteAGPRCopyMFMAImpl::tryFoldCopiesFromAGPR(
419 Register VReg, MCRegister AssignedAGPR) const {
420 bool MadeChange = false;
421 for (MachineInstr &UseMI : MRI.use_instructions(VReg)) {
422 if (!UseMI.isCopy())
423 continue;
424
425 Register CopyDstReg = UseMI.getOperand(0).getReg();
426 if (!CopyDstReg.isVirtual())
427 continue;
428 for (MachineOperand &CopyUseMO : MRI.reg_nodbg_operands(CopyDstReg)) {
429 if (!CopyUseMO.readsReg())
430 continue;
431
432 MachineInstr &CopyUseMI = *CopyUseMO.getParent();
433 if (isRewriteCandidate(CopyUseMI)) {
434 if (tryReassigningMFMAChain(CopyUseMI, CopyDstReg,
435 VRM.getPhys(CopyDstReg)))
436 MadeChange = true;
437 }
438 }
439 }
440
441 return MadeChange;
442}
443
444void AMDGPURewriteAGPRCopyMFMAImpl::replaceSpillWithCopyToVReg(
445 MachineInstr &SpillMI, int SpillFI, Register VReg) const {
446 const DebugLoc &DL = SpillMI.getDebugLoc();
447 MachineBasicBlock &MBB = *SpillMI.getParent();
448 MachineInstr *NewCopy;
449 if (SpillMI.mayStore()) {
450 NewCopy = BuildMI(MBB, SpillMI, DL, TII.get(TargetOpcode::COPY), VReg)
451 .add(SpillMI.getOperand(0));
452 } else {
453 NewCopy = BuildMI(MBB, SpillMI, DL, TII.get(TargetOpcode::COPY))
454 .add(SpillMI.getOperand(0))
455 .addReg(VReg);
456 }
457
458 LIS.ReplaceMachineInstrInMaps(SpillMI, *NewCopy);
459 SpillMI.eraseFromParent();
460}
461
462void AMDGPURewriteAGPRCopyMFMAImpl::collectSpillIndexUses(
463 ArrayRef<LiveInterval *> StackIntervals, SpillReferenceMap &Map) const {
464
465 SmallSet<int, 4> NeededFrameIndexes;
466 for (const LiveInterval *LI : StackIntervals)
467 NeededFrameIndexes.insert(LI->reg().stackSlotIndex());
468
469 for (MachineBasicBlock &MBB : MF) {
470 for (MachineInstr &MI : MBB) {
471 for (MachineOperand &MO : MI.operands()) {
472 if (!MO.isFI() || !NeededFrameIndexes.count(MO.getIndex()))
473 continue;
474
475 if (TII.isVGPRSpill(MI)) {
476 SmallVector<MachineInstr *, 4> &References = Map[MO.getIndex()];
477 References.push_back(&MI);
478 break;
479 }
480
481 // Verify this was really a spill instruction, if it's not just ignore
482 // all uses.
483
484 // TODO: This should probably be verifier enforced.
485 NeededFrameIndexes.erase(MO.getIndex());
486 Map.erase(MO.getIndex());
487 }
488 }
489 }
490}
491
492bool AMDGPURewriteAGPRCopyMFMAImpl::isLoadJointlyDominatedByStores(
493 const MachineInstr &LoadMI, const LiveInterval &SlotLI,
494 const SmallPtrSetImpl<MachineBasicBlock *> &StoreFreeReachable) const {
495 const MachineBasicBlock *LoadMBB = LoadMI.getParent();
496 if (!MDT.isReachableFromEntry(LoadMBB))
497 return true;
498
499 // Check if every path passed through a store block.
500 if (!StoreFreeReachable.contains(LoadMBB))
501 return true;
502
503 // Otherwise, there exists a path to this block that has not seen any store
504 // yet. We must ensure that within this block there is a store to this slot
505 // before the load. Consult the slot's LiveStacks interval: a store to the
506 // slot before the load means the slot is not live into this block but is
507 // live at the load. If the load reads an undef value, the slot is not live
508 // at the load, failing the joint-dominance check.
509 SlotIndex LoadIdx = LIS.getInstructionIndex(LoadMI);
510 return SlotLI.liveAt(LoadIdx) && !LIS.isLiveInToMBB(SlotLI, LoadMBB);
511}
512
513void AMDGPURewriteAGPRCopyMFMAImpl::eliminateSpillsOfReassignedVGPRs() const {
514 unsigned NumSlots = LSS.getNumIntervals();
515 if (NumSlots == 0)
516 return;
517
518 MachineFrameInfo &MFI = MF.getFrameInfo();
519
520 SmallVector<LiveInterval *, 32> StackIntervals;
521 StackIntervals.reserve(NumSlots);
522
523 for (auto &[Slot, LI] : LSS) {
524 if (!MFI.isSpillSlotObjectIndex(Slot) || MFI.isDeadObjectIndex(Slot))
525 continue;
526
527 const TargetRegisterClass *RC = LSS.getIntervalRegClass(Slot);
528 if (TRI.hasVGPRs(RC))
529 StackIntervals.push_back(&LI);
530 }
531
532 sort(StackIntervals, [](const LiveInterval *A, const LiveInterval *B) {
533 // The ordering has to be strictly weak.
534 /// Sort heaviest intervals first to prioritize their unspilling
535 if (A->weight() != B->weight())
536 return A->weight() > B->weight();
537
538 if (A->getSize() != B->getSize())
539 return A->getSize() > B->getSize();
540
541 // Tie breaker by number to avoid need for stable sort
542 return A->reg().stackSlotIndex() < B->reg().stackSlotIndex();
543 });
544
545 // FIXME: The APIs for dealing with the LiveInterval of a frame index are
546 // cumbersome. LiveStacks owns its LiveIntervals which refer to stack
547 // slots. We cannot use the usual LiveRegMatrix::assign and unassign on these,
548 // and must create a substitute virtual register to do so. This makes
549 // incremental updating here difficult; we need to actually perform the IR
550 // mutation to get the new vreg references in place to compute the register
551 // LiveInterval to perform an assignment to track the new interference
552 // correctly, and we can't simply migrate the LiveInterval we already have.
553 //
554 // To avoid walking through the entire function for each index, pre-collect
555 // all the instructions slot referencess.
556
557 DenseMap<int, SmallVector<MachineInstr *, 4>> SpillSlotReferences;
558 collectSpillIndexUses(StackIntervals, SpillSlotReferences);
559
560 for (LiveInterval *LI : StackIntervals) {
561 int Slot = LI->reg().stackSlotIndex();
562 auto SpillReferences = SpillSlotReferences.find(Slot);
563 if (SpillReferences == SpillSlotReferences.end())
564 continue;
565
566 // For each spill reload, every path from entry to the reload must pass
567 // through at least one spill store to the same stack slot.
568 SmallPtrSet<MachineBasicBlock *, 4> StoreBlocks;
569 for (MachineInstr *MI : SpillReferences->second) {
570 if (MI->mayStore() && MDT.isReachableFromEntry(MI->getParent()))
571 StoreBlocks.insert(MI->getParent());
572 }
573
574 if (StoreBlocks.empty()) {
575 LLVM_DEBUG(dbgs() << "Skipping " << printReg(LI->reg(), &TRI)
576 << ": no reachable stores\n");
577 continue;
578 }
579
580 // Compute blocks reachable from entry without passing through a store
581 // block.
582 MachineBasicBlock &EntryMBB = MF.front();
583 SmallPtrSet<MachineBasicBlock *, 16> StoreFreeReachable = {&EntryMBB};
584 SmallVector<MachineBasicBlock *, 16> Worklist = {&EntryMBB};
585
586 while (!Worklist.empty()) {
587 MachineBasicBlock *MBB = Worklist.pop_back_val();
588 if (StoreBlocks.contains(MBB))
589 continue;
590
591 for (MachineBasicBlock *Succ : MBB->successors()) {
592 if (StoreFreeReachable.insert(Succ).second)
593 Worklist.push_back(Succ);
594 }
595 }
596
597 // Every reachable reload must be jointly dominated by the slot's stores.
598 if (!llvm::all_of(SpillReferences->second, [&](const MachineInstr *MI) {
599 return !MI->mayLoad() ||
600 isLoadJointlyDominatedByStores(*MI, *LI, StoreFreeReachable);
601 })) {
603 dbgs() << "Skipping " << printReg(LI->reg(), &TRI)
604 << ": some reachable load not jointly dominated by stores\n");
605 continue;
606 }
607
608 const TargetRegisterClass *RC = LSS.getIntervalRegClass(Slot);
609
610 LLVM_DEBUG(dbgs() << "Trying to eliminate " << printReg(LI->reg(), &TRI)
611 << " by reassigning\n");
612
613 ArrayRef<MCPhysReg> AllocOrder = RegClassInfo.getOrder(RC);
614
615 // The stack slot's LiveInterval may be discontiguous: a slot can be live
616 // in memory around a spill store and around a much later reload. Once
617 // we unspill the slot into a register, however, the value must reside in
618 // that register continuously from its first reference to its last (modulo
619 // the live range splitting that happens later below). Checking
620 // interference against the slot's discontiguous interval could let us pick
621 // a PhysReg that is busy inside a gap, corrupting it. Instead, check
622 // interference over the range the replacement register will occupy.
623 for (MCPhysReg PhysReg : AllocOrder) {
624 if (LRM.checkInterference(LI->beginIndex(), LI->endIndex(), PhysReg))
625 continue;
626
627 LLVM_DEBUG(dbgs() << "Reassigning " << *LI << " to "
628 << printReg(PhysReg, &TRI) << '\n');
629
630 const TargetRegisterClass *RC = LSS.getIntervalRegClass(Slot);
631 Register NewVReg = MRI.createVirtualRegister(RC);
632
633 for (MachineInstr *SpillMI : SpillReferences->second)
634 replaceSpillWithCopyToVReg(*SpillMI, Slot, NewVReg);
635
636 // TODO: Transferring the stack slot's LiveInterval instead of recomputing
637 // would not be a straight copy: its segments would have to be widened to
638 // cover each store's reaching reloads.
639 LiveInterval &NewLI = LIS.createAndComputeVirtRegInterval(NewVReg);
640 VRM.grow();
641
642 // A spill slot can be stored to multiple times, so the replacement
643 // vreg may have multiple disconnected live range components. Split
644 // them into separate vregs to maintain the single-component invariant.
646 LIS.splitSeparateComponents(NewLI, SplitLIs);
647
648 LLVM_DEBUG({
649 if (!SplitLIs.empty()) {
650 dbgs() << "Split unspilled interval into " << (SplitLIs.size() + 1)
651 << " components\n";
652 }
653 });
654
655 LRM.assign(NewLI, PhysReg);
656 for (LiveInterval *SplitLI : SplitLIs) {
657 VRM.grow();
658 LRM.assign(*SplitLI, PhysReg);
659 }
660
661 MFI.RemoveStackObject(Slot);
662 break;
663 }
664 }
665}
666
667bool AMDGPURewriteAGPRCopyMFMAImpl::run(MachineFunction &MF) const {
668 assert(RegClassInfo.hasCurrentReservedRegs() &&
669 "RegisterClassInfo misses a change to the reserved registers");
670
671 // This only applies on subtargets that have a configurable AGPR vs. VGPR
672 // allocation.
673 if (!ST.hasGFX90AInsts())
674 return false;
675
676 // MRI tracks physical operands and reg masks, not assigned virtual
677 // intervals. Reserved low AGPRs can leave AGPR0 unassigned.
678 if (llvm::none_of(RegClassInfo.getOrder(&AMDGPU::AGPR_32RegClass),
679 [&](MCPhysReg Reg) { return LRM.isPhysRegUsed(Reg); })) {
680 LLVM_DEBUG(dbgs() << "skipping function that did not allocate AGPRs\n");
681 return false;
682 }
683
684 bool MadeChange = false;
685
686 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
687 Register VReg = Register::index2VirtReg(I);
688 MCRegister AssignedAGPR = getAssignedAGPR(VReg);
689 if (!AssignedAGPR)
690 continue;
691
692 if (tryFoldCopiesToAGPR(VReg, AssignedAGPR))
693 MadeChange = true;
694 if (tryFoldCopiesFromAGPR(VReg, AssignedAGPR))
695 MadeChange = true;
696 }
697
698 // If we've successfully rewritten some MFMAs, we've alleviated some VGPR
699 // pressure. See if we can eliminate some spills now that those registers are
700 // more available.
701 if (MadeChange)
702 eliminateSpillsOfReassignedVGPRs();
703
704 return MadeChange;
705}
706
707class AMDGPURewriteAGPRCopyMFMALegacy : public MachineFunctionPass {
708public:
709 static char ID;
710
711 AMDGPURewriteAGPRCopyMFMALegacy() : MachineFunctionPass(ID) {}
712
713 bool runOnMachineFunction(MachineFunction &MF) override;
714
715 StringRef getPassName() const override {
716 return "AMDGPU Rewrite AGPR-Copy-MFMA";
717 }
718
719 void getAnalysisUsage(AnalysisUsage &AU) const override {
720 AU.addRequired<LiveIntervalsWrapperPass>();
721 AU.addRequired<VirtRegMapWrapperLegacy>();
722 AU.addRequired<LiveRegMatrixWrapperLegacy>();
723 AU.addRequired<LiveStacksWrapperLegacy>();
724 AU.addRequired<MachineRegisterClassInfoWrapperPass>();
725 AU.addRequired<MachineDominatorTreeWrapperPass>();
726
727 AU.addPreserved<LiveIntervalsWrapperPass>();
728 AU.addPreserved<VirtRegMapWrapperLegacy>();
729 AU.addPreserved<LiveRegMatrixWrapperLegacy>();
730 AU.addPreserved<LiveStacksWrapperLegacy>();
731 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
732 AU.addPreserved<MachineDominatorTreeWrapperPass>();
733
734 AU.setPreservesAll();
736 }
737};
738
739} // End anonymous namespace.
740
741INITIALIZE_PASS_BEGIN(AMDGPURewriteAGPRCopyMFMALegacy, DEBUG_TYPE,
742 "AMDGPU Rewrite AGPR-Copy-MFMA", false, false)
749INITIALIZE_PASS_END(AMDGPURewriteAGPRCopyMFMALegacy, DEBUG_TYPE,
750 "AMDGPU Rewrite AGPR-Copy-MFMA", false, false)
751
752char AMDGPURewriteAGPRCopyMFMALegacy::ID = 0;
753
755 AMDGPURewriteAGPRCopyMFMALegacy::ID;
756
757bool AMDGPURewriteAGPRCopyMFMALegacy::runOnMachineFunction(
758 MachineFunction &MF) {
759 if (skipFunction(MF.getFunction()))
760 return false;
761
762 auto &VRM = getAnalysis<VirtRegMapWrapperLegacy>().getVRM();
763 auto &LRM = getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM();
764 auto &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
765 auto &LSS = getAnalysis<LiveStacksWrapperLegacy>().getLS();
766 auto &RCI = getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
767 auto &MDT = getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
768 AMDGPURewriteAGPRCopyMFMAImpl Impl(MF, VRM, LRM, LIS, LSS, RCI, MDT);
769 return Impl.run(MF);
770}
771
775 VirtRegMap &VRM = MFAM.getResult<VirtRegMapAnalysis>(MF);
778 LiveStacks &LSS = MFAM.getResult<LiveStacksAnalysis>(MF);
781
782 AMDGPURewriteAGPRCopyMFMAImpl Impl(MF, VRM, LRM, LIS, LSS, RCI, MDT);
783 if (!Impl.run(MF))
784 return PreservedAnalyses::all();
786 PA.preserveSet<CFGAnalyses>()
787 .preserve<LiveStacksAnalysis>()
788 .preserve<VirtRegMapAnalysis>()
789 .preserve<SlotIndexesAnalysis>()
790 .preserve<LiveIntervalsAnalysis>()
791 .preserve<LiveRegMatrixAnalysis>()
792 .preserve<MachineRegisterClassAnalysis>();
793 return PA;
794}
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
AMDGPU Rewrite AGPR Copy MFMA
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
#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
MachineRegisterInfo & MRI
Interface definition for SIRegisterInfo.
This file contains some templates that are useful if you are working with the STL at all.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static bool shouldExecute(CounterInfo &Counter)
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
Register reg() const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
LiveInterval & getInterval(Register Reg)
LLVM_ABI void splitSeparateComponents(LiveInterval &LI, SmallVectorImpl< LiveInterval * > &SplitLIs)
Split separate components in LiveInterval LI into separate intervals.
bool isLiveInToMBB(const LiveRange &LR, const MachineBasicBlock *mbb) const
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
bool liveAt(SlotIndex index) const
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
LLVM_ABI void unassign(const LiveInterval &VirtReg, bool ClearAllReferencingSegments=false)
Unassign VirtReg from its PhysReg.
@ IK_Free
No interference, go ahead and assign.
LLVM_ABI void assign(const LiveInterval &VirtReg, MCRegister PhysReg)
Assign VirtReg to PhysReg.
LLVM_ABI InterferenceKind checkInterference(const LiveInterval &VirtReg, MCRegister PhysReg)
Check for interference before assigning VirtReg to PhysReg.
unsigned getNumIntervals() const
Definition LiveStacks.h:60
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
iterator_range< succ_iterator > successors()
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 isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
void RemoveStackObject(int ObjectIdx)
Remove or mark dead a statically sized stack object.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineBasicBlock * getParent() const
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI void setRegClass(Register Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
iterator_range< reg_nodbg_iterator > reg_nodbg_operands(Register Reg) const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
LLVM_ABI bool hasCurrentReservedRegs() const
Whether the cached information was filtered by MRI's frozen reserved registers, i....
ArrayRef< MCPhysReg > getOrder(const TargetRegisterClass *RC) const
getOrder - Returns the preferred allocation order for RC.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
int stackSlotIndex() const
Compute the frame index from a register value representing a stack slot.
Definition Register.h:93
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void push_back(const T &Elt)
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
Definition VirtRegMap.h:89
LLVM_ABI void grow()
bool hasPhys(Register virtReg) const
returns true if the specified virtual register is mapped to a physical register
Definition VirtRegMap.h:85
LLVM_READONLY int32_t getAGPRFormOp(uint32_t Opcode)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
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:1963
char & AMDGPURewriteAGPRCopyMFMALegacyID
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58