Skip to content

Commit cfdee22

Browse files
committed
AMDGPU: Introduce a pass to replace VGPR MFMAs with AGPR
In gfx90a-gfx950, it's possible to emit MFMAs which use AGPRs or VGPRs for vdst and src2. We do not want to do use the AGPR form, unless required by register pressure as it requires cross bank register copies from most other instructions. Currently we select the AGPR or VGPR version depending on a crude heuristic for whether it's possible AGPRs will be required. We really need the register allocation to be complete to make a good decision, which is what this pass is for. This adds the pass, but does not yet remove the selection patterns for AGPRs. This is a WIP, and NFC-ish. It should be a no-op on any currently selected code. It also does not yet trigger on the real examples of interest, which require handling batches of MFMAs at once.
1 parent f5e76ab commit cfdee22

File tree

10 files changed

+339
-12
lines changed

10 files changed

+339
-12
lines changed

llvm/lib/Target/AMDGPU/AMDGPU.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,17 @@ extern char &GCNRewritePartialRegUsesID;
541541
void initializeAMDGPUWaitSGPRHazardsLegacyPass(PassRegistry &);
542542
extern char &AMDGPUWaitSGPRHazardsLegacyID;
543543

544+
class AMDGPURewriteAGPRCopyMFMAPass
545+
: public PassInfoMixin<AMDGPURewriteAGPRCopyMFMAPass> {
546+
public:
547+
AMDGPURewriteAGPRCopyMFMAPass() = default;
548+
PreservedAnalyses run(MachineFunction &MF,
549+
MachineFunctionAnalysisManager &MFAM);
550+
};
551+
552+
void initializeAMDGPURewriteAGPRCopyMFMALegacyPass(PassRegistry &);
553+
extern char &AMDGPURewriteAGPRCopyMFMALegacyID;
554+
544555
namespace AMDGPU {
545556
enum TargetIndex {
546557
TI_CONSTDATA_START,

llvm/lib/Target/AMDGPU/AMDGPUPassRegistry.def

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ MACHINE_FUNCTION_PASS("amdgpu-isel", AMDGPUISelDAGToDAGPass(*this))
102102
MACHINE_FUNCTION_PASS("amdgpu-mark-last-scratch-load", AMDGPUMarkLastScratchLoadPass())
103103
MACHINE_FUNCTION_PASS("amdgpu-pre-ra-long-branch-reg", GCNPreRALongBranchRegPass())
104104
MACHINE_FUNCTION_PASS("amdgpu-reserve-wwm-regs", AMDGPUReserveWWMRegsPass())
105+
MACHINE_FUNCTION_PASS("amdgpu-rewrite-agpr-copy-mfma", AMDGPURewriteAGPRCopyMFMAPass())
105106
MACHINE_FUNCTION_PASS("amdgpu-rewrite-partial-reg-uses", GCNRewritePartialRegUsesPass())
106107
MACHINE_FUNCTION_PASS("amdgpu-set-wave-priority", AMDGPUSetWavePriorityPass())
107108
MACHINE_FUNCTION_PASS("amdgpu-pre-ra-optimizations", GCNPreRAOptimizationsPass())
Lines changed: 300 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,300 @@
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 non-tied dst+src2 cases. We need to try to find a copy from an
18+
/// AGPR from src2, or reassign src2 to an available AGPR (which should work
19+
/// in the common case of a load).
20+
///
21+
/// - Handle multiple MFMA uses of the same register. e.g. chained MFMAs that
22+
/// can be rewritten as a set
23+
///
24+
/// - Update LiveIntervals incrementally instead of recomputing from scratch
25+
///
26+
//===----------------------------------------------------------------------===//
27+
28+
#include "AMDGPU.h"
29+
#include "GCNSubtarget.h"
30+
#include "SIMachineFunctionInfo.h"
31+
#include "SIRegisterInfo.h"
32+
#include "llvm/CodeGen/LiveIntervals.h"
33+
#include "llvm/CodeGen/LiveRegMatrix.h"
34+
#include "llvm/CodeGen/MachineFunctionPass.h"
35+
#include "llvm/CodeGen/VirtRegMap.h"
36+
#include "llvm/InitializePasses.h"
37+
38+
using namespace llvm;
39+
40+
#define DEBUG_TYPE "amdgpu-rewrite-agpr-copy-mfma"
41+
42+
namespace {
43+
44+
class AMDGPURewriteAGPRCopyMFMAImpl {
45+
const GCNSubtarget &ST;
46+
const SIInstrInfo &TII;
47+
const SIRegisterInfo &TRI;
48+
MachineRegisterInfo &MRI;
49+
VirtRegMap &VRM;
50+
LiveRegMatrix &LRM;
51+
LiveIntervals &LIS;
52+
53+
public:
54+
AMDGPURewriteAGPRCopyMFMAImpl(MachineFunction &MF, VirtRegMap &VRM,
55+
LiveRegMatrix &LRM, LiveIntervals &LIS)
56+
: ST(MF.getSubtarget<GCNSubtarget>()), TII(*ST.getInstrInfo()),
57+
TRI(*ST.getRegisterInfo()), MRI(MF.getRegInfo()), VRM(VRM), LRM(LRM),
58+
LIS(LIS) {}
59+
60+
/// Compute the register class constraints based on the uses of \p Reg,
61+
/// excluding uses from \p ExceptMI. This should be nearly identical to
62+
/// MachineRegisterInfo::recomputeRegClass.
63+
const TargetRegisterClass *
64+
recomputeRegClassExcept(Register Reg, const TargetRegisterClass *OldRC,
65+
const TargetRegisterClass *NewRC,
66+
const MachineInstr *ExceptMI) const;
67+
68+
bool run(MachineFunction &MF) const;
69+
};
70+
71+
const TargetRegisterClass *
72+
AMDGPURewriteAGPRCopyMFMAImpl::recomputeRegClassExcept(
73+
Register Reg, const TargetRegisterClass *OldRC,
74+
const TargetRegisterClass *NewRC, const MachineInstr *ExceptMI) const {
75+
76+
// Accumulate constraints from all uses.
77+
for (MachineOperand &MO : MRI.reg_nodbg_operands(Reg)) {
78+
// Apply the effect of the given operand to NewRC.
79+
MachineInstr *MI = MO.getParent();
80+
if (MI == ExceptMI)
81+
continue;
82+
83+
unsigned OpNo = &MO - &MI->getOperand(0);
84+
NewRC = MI->getRegClassConstraintEffect(OpNo, NewRC, &TII, &TRI);
85+
if (!NewRC || NewRC == OldRC)
86+
return nullptr;
87+
}
88+
89+
return NewRC;
90+
}
91+
92+
bool AMDGPURewriteAGPRCopyMFMAImpl::run(MachineFunction &MF) const {
93+
// This only applies on subtargets that have a configurable AGPR vs. VGPR
94+
// allocation.
95+
if (!ST.hasGFX90AInsts())
96+
return false;
97+
98+
// Early exit if no AGPRs were assigned.
99+
if (!LRM.isPhysRegUsed(AMDGPU::AGPR0))
100+
return false;
101+
102+
bool MadeChange = false;
103+
104+
for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
105+
Register VReg = Register::index2VirtReg(I);
106+
Register PhysReg = VRM.getPhys(VReg);
107+
if (!PhysReg)
108+
continue;
109+
110+
// Find AV_* registers assigned to AGPRs.
111+
const TargetRegisterClass *VirtRegRC = MRI.getRegClass(VReg);
112+
if (!TRI.isVectorSuperClass(VirtRegRC))
113+
continue;
114+
115+
const TargetRegisterClass *AssignedRC = TRI.getPhysRegBaseClass(PhysReg);
116+
if (!TRI.isAGPRClass(AssignedRC))
117+
continue;
118+
119+
LiveInterval &LI = LIS.getInterval(VReg);
120+
121+
// TODO: Test multiple uses
122+
for (VNInfo *VNI : LI.vnis()) {
123+
MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
124+
125+
// TODO: Handle SplitKit produced copy bundles for partially defined
126+
// registers.
127+
if (!DefMI || !DefMI->isFullCopy())
128+
continue;
129+
130+
Register CopySrcReg = DefMI->getOperand(1).getReg();
131+
LiveInterval &CopySrcLI = LIS.getInterval(CopySrcReg);
132+
133+
LiveQueryResult LRQ = CopySrcLI.Query(VNI->def.getRegSlot());
134+
135+
MachineInstr *CopySrcMI = LIS.getInstructionFromIndex(LRQ.valueIn()->def);
136+
int AGPROp = AMDGPU::getMFMASrcCVDstAGPROp(CopySrcMI->getOpcode());
137+
if (AGPROp == -1)
138+
continue;
139+
140+
MachineOperand *Src2 =
141+
TII.getNamedOperand(*CopySrcMI, AMDGPU::OpName::src2);
142+
143+
// FIXME: getMinimalPhysRegClass returns a nonsense AV_* subclass instead
144+
// of an AGPR or VGPR subclass, so we can't simply use the result on the
145+
// assignment.
146+
147+
LLVM_DEBUG({
148+
Register Src2PhysReg = VRM.getPhys(Src2->getReg());
149+
dbgs() << "Attempting to replace VGPR MFMA with AGPR version:"
150+
<< " Dst=[" << printReg(VReg) << " => "
151+
<< printReg(PhysReg, &TRI) << "], Src2=["
152+
<< printReg(Src2->getReg(), &TRI) << " => "
153+
<< printReg(Src2PhysReg, &TRI) << "]: " << *CopySrcMI;
154+
});
155+
156+
// If the inputs are tied and the same register, we can shortcut and
157+
// directly replace the register.
158+
if (Src2->getReg() != CopySrcReg) {
159+
LLVM_DEBUG(
160+
dbgs()
161+
<< "Replacing untied VGPR MFMAs with AGPR form not yet handled\n");
162+
// TODO: Only handles the tied case for now. If the input operand is a
163+
// different register, we need to also reassign it (either by looking
164+
// for a compatible copy-from-AGPR, or by seeing if an available AGPR is
165+
// compatible with all other uses.
166+
167+
// If we can't reassign it, we'd need to introduce a different copy
168+
// which is likely worse than the copy we'd be saving.
169+
continue;
170+
}
171+
172+
const TargetRegisterClass *Src2VirtRegRC =
173+
MRI.getRegClass(Src2->getReg());
174+
175+
// We've found av = COPY (MFMA), and need to verify that we can trivially
176+
// rewrite src2 to use the new AGPR. If we can't trivially replace it,
177+
// we're going to induce as many copies as we would have emitted in the
178+
// first place, as well as need to assign another register, and need to
179+
// figure out where to put them. The live range splitting is smarter than
180+
// anything we're doing here, so trust it did something reasonable.
181+
const TargetRegisterClass *Src2ExceptRC = recomputeRegClassExcept(
182+
Src2->getReg(), Src2VirtRegRC, VirtRegRC, CopySrcMI);
183+
if (!Src2ExceptRC)
184+
continue;
185+
186+
const TargetRegisterClass *NewSrc2ConstraintRC =
187+
TII.getRegClass(TII.get(AGPROp), Src2->getOperandNo(), &TRI, MF);
188+
189+
// Try to constrain src2 to the replacement instruction candidate's
190+
// register class.
191+
const TargetRegisterClass *NewSrc2RC =
192+
TRI.getCommonSubClass(Src2ExceptRC, NewSrc2ConstraintRC);
193+
if (!NewSrc2RC) {
194+
// TODO: This is ignoring ther rewritable uses. e.g. a rewritable MFMA
195+
// using a rewritable MFMA can be rewritten as a pair.
196+
LLVM_DEBUG(dbgs() << "Other uses of " << printReg(Src2->getReg(), &TRI)
197+
<< " are incompatible with replacement class\n");
198+
continue;
199+
}
200+
201+
MRI.setRegClass(VReg, AssignedRC);
202+
MRI.setRegClass(Src2->getReg(), NewSrc2RC);
203+
204+
CopySrcMI->setDesc(TII.get(AGPROp));
205+
206+
// TODO: Is replacing too aggressive, fixup these instructions only?
207+
MRI.replaceRegWith(CopySrcReg, VReg);
208+
209+
LLVM_DEBUG(dbgs() << "Replaced VGPR MFMA with AGPR: " << *CopySrcMI);
210+
211+
// We left behind an identity copy, so delete it.
212+
LIS.RemoveMachineInstrFromMaps(*DefMI);
213+
DefMI->eraseFromParent();
214+
215+
LRM.unassign(CopySrcLI);
216+
217+
// We don't need the liveness information anymore, so don't bother
218+
// updating the intervals. Just delete the stale information.
219+
// TODO: Is it worth preserving these?
220+
LIS.removeInterval(CopySrcReg);
221+
LIS.removeInterval(VReg);
222+
LIS.createAndComputeVirtRegInterval(VReg);
223+
224+
MadeChange = true;
225+
}
226+
}
227+
228+
return MadeChange;
229+
}
230+
231+
class AMDGPURewriteAGPRCopyMFMALegacy : public MachineFunctionPass {
232+
public:
233+
static char ID;
234+
235+
AMDGPURewriteAGPRCopyMFMALegacy() : MachineFunctionPass(ID) {
236+
initializeAMDGPURewriteAGPRCopyMFMALegacyPass(
237+
*PassRegistry::getPassRegistry());
238+
}
239+
240+
bool runOnMachineFunction(MachineFunction &MF) override;
241+
242+
StringRef getPassName() const override {
243+
return "AMDGPU Rewrite AGPR-Copy-MFMA";
244+
}
245+
246+
void getAnalysisUsage(AnalysisUsage &AU) const override {
247+
AU.addRequired<LiveIntervalsWrapperPass>();
248+
AU.addRequired<VirtRegMapWrapperLegacy>();
249+
AU.addRequired<LiveRegMatrixWrapperLegacy>();
250+
251+
AU.addPreserved<LiveIntervalsWrapperPass>();
252+
AU.addPreserved<VirtRegMapWrapperLegacy>();
253+
AU.addPreserved<LiveRegMatrixWrapperLegacy>();
254+
AU.setPreservesAll();
255+
MachineFunctionPass::getAnalysisUsage(AU);
256+
}
257+
};
258+
259+
} // End anonymous namespace.
260+
261+
INITIALIZE_PASS_BEGIN(AMDGPURewriteAGPRCopyMFMALegacy, DEBUG_TYPE,
262+
"AMDGPU Rewrite AGPR-Copy-MFMA", false, false)
263+
INITIALIZE_PASS_DEPENDENCY(LiveIntervalsWrapperPass)
264+
INITIALIZE_PASS_DEPENDENCY(VirtRegMapWrapperLegacy)
265+
INITIALIZE_PASS_DEPENDENCY(LiveRegMatrixWrapperLegacy)
266+
INITIALIZE_PASS_END(AMDGPURewriteAGPRCopyMFMALegacy, DEBUG_TYPE,
267+
"AMDGPU Rewrite AGPR-Copy-MFMA", false, false)
268+
269+
char AMDGPURewriteAGPRCopyMFMALegacy::ID = 0;
270+
271+
char &llvm::AMDGPURewriteAGPRCopyMFMALegacyID =
272+
AMDGPURewriteAGPRCopyMFMALegacy::ID;
273+
274+
bool AMDGPURewriteAGPRCopyMFMALegacy::runOnMachineFunction(
275+
MachineFunction &MF) {
276+
if (skipFunction(MF.getFunction()))
277+
return false;
278+
279+
auto &VRM = getAnalysis<VirtRegMapWrapperLegacy>().getVRM();
280+
auto &LRM = getAnalysis<LiveRegMatrixWrapperLegacy>().getLRM();
281+
auto &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
282+
283+
AMDGPURewriteAGPRCopyMFMAImpl Impl(MF, VRM, LRM, LIS);
284+
return Impl.run(MF);
285+
}
286+
287+
PreservedAnalyses
288+
AMDGPURewriteAGPRCopyMFMAPass::run(MachineFunction &MF,
289+
MachineFunctionAnalysisManager &MFAM) {
290+
VirtRegMap &VRM = MFAM.getResult<VirtRegMapAnalysis>(MF);
291+
LiveRegMatrix &LRM = MFAM.getResult<LiveRegMatrixAnalysis>(MF);
292+
LiveIntervals &LIS = MFAM.getResult<LiveIntervalsAnalysis>(MF);
293+
294+
AMDGPURewriteAGPRCopyMFMAImpl Impl(MF, VRM, LRM, LIS);
295+
if (!Impl.run(MF))
296+
return PreservedAnalyses::all();
297+
auto PA = getMachineFunctionPassPreservedAnalyses();
298+
PA.preserveSet<CFGAnalyses>();
299+
return PA;
300+
}

llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,7 @@ extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget() {
535535
initializeAMDGPULowerModuleLDSLegacyPass(*PR);
536536
initializeAMDGPULowerBufferFatPointersPass(*PR);
537537
initializeAMDGPUReserveWWMRegsLegacyPass(*PR);
538+
initializeAMDGPURewriteAGPRCopyMFMALegacyPass(*PR);
538539
initializeAMDGPURewriteOutArgumentsPass(*PR);
539540
initializeAMDGPURewriteUndefForPHILegacyPass(*PR);
540541
initializeSIAnnotateControlFlowLegacyPass(*PR);
@@ -1578,6 +1579,8 @@ void GCNPassConfig::addOptimizedRegAlloc() {
15781579
bool GCNPassConfig::addPreRewrite() {
15791580
if (EnableRegReassign)
15801581
addPass(&GCNNSAReassignID);
1582+
1583+
addPass(&AMDGPURewriteAGPRCopyMFMALegacyID);
15811584
return true;
15821585
}
15831586

llvm/lib/Target/AMDGPU/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ add_llvm_target(AMDGPUCodeGen
102102
AMDGPURemoveIncompatibleFunctions.cpp
103103
AMDGPUReserveWWMRegs.cpp
104104
AMDGPUResourceUsageAnalysis.cpp
105+
AMDGPURewriteAGPRCopyMFMA.cpp
105106
AMDGPURewriteOutArguments.cpp
106107
AMDGPURewriteUndefForPHI.cpp
107108
AMDGPUSelectionDAGInfo.cpp

llvm/lib/Target/AMDGPU/SIRegisterInfo.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,10 @@ class SIRegisterInfo final : public AMDGPUGenRegisterInfo {
237237
return isSGPRClass(getPhysRegBaseClass(Reg));
238238
}
239239

240+
bool isVGPRPhysReg(Register Reg) const {
241+
return isVGPRClass(getPhysRegBaseClass(Reg));
242+
}
243+
240244
/// \returns true if this class contains only VGPR registers
241245
static bool isVGPRClass(const TargetRegisterClass *RC) {
242246
return hasVGPRs(RC) && !hasAGPRs(RC) && !hasSGPRs(RC);

0 commit comments

Comments
 (0)