LLVM 24.0.0git
GCNHazardRecognizer.h
Go to the documentation of this file.
1//===-- GCNHazardRecognizers.h - GCN Hazard Recognizers ---------*- C++ -*-===//
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// This file defines hazard recognizers for scheduling on GCN processors.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_LIB_TARGET_AMDGPUHAZARDRECOGNIZERS_H
14#define LLVM_LIB_TARGET_AMDGPUHAZARDRECOGNIZERS_H
15
16#include "AMDGPUCoExecInfo.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/STLExtras.h"
22#include <array>
23#include <list>
24#include <optional>
25
26namespace llvm {
27
28class MachineFunction;
29class MachineInstr;
30class MachineOperand;
32class SIInstrInfo;
33class SIRegisterInfo;
34class GCNSubtarget;
35
37public:
39 typedef function_ref<bool(const MachineInstr &, int WaitStates)> IsExpiredFn;
40 typedef function_ref<unsigned int(const MachineInstr &)> GetNumWaitStatesFn;
41
42 /// Operating mode for the hazard recognizer. Two independent properties
43 /// follow from it.
44 ///
45 /// The scheduler modes (PreRA, PostRA) report a hazard so that the scheduler
46 /// can pick some other instruction, and to do that they track pipeline state
47 /// across the cycles they are told about. HazardRecognizerMode inserts s_nop
48 /// or v_nop to ensure correctness of the generated code.
49 ///
50 /// Operands are physical registers in every mode but PreRA, so hazards
51 /// defined by register dependences are checked only when hasPhysRegs()
52 /// holds.
54
55private:
56 // Operating mode determines which hazards are checked.
57 OperatingMode Mode;
58
59 // This variable stores the instruction that has been emitted this cycle. It
60 // will be added to EmittedInstrs, when AdvanceCycle() or RecedeCycle() is
61 // called.
62 MachineInstr *CurrCycleInstr;
63 std::list<MachineInstr*> EmittedInstrs;
64
65 // WMMA co-execution hazards are only resolved by VALU-pipe activity (VALU
66 // ops or V_NOPs), never by S_NOPs, so track those instructions separately
67 // from EmittedInstrs.
68 std::list<MachineInstr *> EmittedVALUInstrs;
69 // Lookahead bound for EmittedVALUInstrs. It must be at least as large as the
70 // largest WMMA co-execution wait-state requirement (the maximum value in
71 // WMMAWaitStates/VALUWaitStates in checkWMMACoexecutionHazards). Increase
72 // this if those wait-state limits grow.
73 static constexpr unsigned MaxVALULookAhead = 18;
74 // When true, an unresolved WMMA co-execution hazard is pending, so stall
75 // cycles are optimistically recorded in EmittedVALUInstrs (they will become
76 // V_NOPs unless a non-VALU instruction is scheduled into them).
77 bool HasPendingWMMACoexecHazard = false;
78
79 const MachineFunction &MF;
80 const GCNSubtarget &ST;
81 const SIInstrInfo &TII;
82 const SIRegisterInfo &TRI;
83 const TargetSchedModel &TSchedModel;
84
85 // Loop info for V_NOP hoisting, passed from the pass manager.
86 MachineLoopInfo *MLI = nullptr;
87
88 bool RunLdsBranchVmemWARHazardFixup;
89
90 //===--------------------------------------------------------------------===//
91 // WMMA Co-execution Window State
92 //===--------------------------------------------------------------------===//
93
94 /// Active WMMA co-execution info (slot masks, preferences).
95 AMDGPU::CoExecInfo ActiveCoExecInfo;
96
97 /// Current stage within the WMMA co-execution window (0-based).
98 /// nullopt when not in a WMMA window.
99 std::optional<unsigned> CurrentCoExecStage;
100
101 /// Tracks cycles until TRANS can be issued again (back-to-back TRANS hazard).
102 unsigned CyclesUntilTRANS = 0;
103
104 /// Tracks cycles until next VALU after multi-cycle VALU (CVT hazard).
105 unsigned CyclesUntilVALU = 0;
106
107 /// Debug: log of what was scheduled at each stage of the co-exec window.
108 /// '.' = not yet reached, '-' = stall, else CoExecMask short char.
109 std::array<char, AMDGPU::MaxCoExecStages> CoExecWindowLog;
110
111 /// Debug: print the co-exec window visual summary.
112 void dumpCoExecWindow() const;
113
114 /// Returns true if the co-execution window model applies to this subtarget.
115 bool hasCoExecWindowModel() const;
116
117 /// Check WMMA co-execution slot hazard.
118 /// Returns stall cycles needed before MI can be issued in the current slot.
119 unsigned checkWMMACoexecSlot(const MachineInstr &MI) const;
120
121 /// Check TRANS-after-TRANS hazard. Returns stall cycles if MI is TRANS
122 /// or multi-cycle VALU and a previous TRANS shadow is still active.
123 unsigned checkTRANSHazard(const MachineInstr &MI) const;
124
125 /// Check multi-cycle VALU hazard. Returns stall cycles if MI is a VALU
126 /// that would conflict with an active multi-cycle VALU pipeline.
127 unsigned checkMultiCycleVALUHazard(const MachineInstr &MI) const;
128
129 /// Check if we have both a TRANS and WMMA window active. If so, for VALU
130 /// instructions, return the number of stall cycles until one shadow clears.
131 unsigned checkMultiShadowHazard(const MachineInstr &MI) const;
132
133 /// Update WMMA window state when a WMMA instruction is emitted.
134 void updateWMMAWindowState(const MachineInstr &MI);
135
136 /// Update TRANS state when an instruction is emitted.
137 void updateTRANSState(const MachineInstr &MI);
138
139 /// Update multi-cycle VALU state when an instruction is emitted.
140 void updateMultiCycleVALUState(const MachineInstr &MI);
141
142 /// Scheduler-mode part of EmitInstruction().
143 void schedulerEmitInstruction(MachineInstr *MI);
144
145 /// Scheduler-mode part of AdvanceCycle().
146 void schedulerAdvanceCycle();
147
148 /// Scheduler-mode part of Reset().
149 void schedulerReset();
150
151 /// RegUnits of uses in the current soft memory clause.
152 mutable BitVector ClauseUses;
153
154 /// RegUnits of defs in the current soft memory clause.
155 mutable BitVector ClauseDefs;
156
157 void resetClause() const {
158 ClauseUses.reset();
159 ClauseDefs.reset();
160 }
161
162 void addClauseInst(const MachineInstr &MI) const;
163
164 /// \returns the number of wait states before another MFMA instruction can be
165 /// issued after \p MI.
166 unsigned getMFMAPipelineWaitStates(const MachineInstr &MI) const;
167
168 // Advance over a MachineInstr bundle. Look for hazards in the bundled
169 // instructions.
170 void processBundle();
171
172 // Run on an individual instruction in hazard recognizer mode. This can be
173 // used on a newly inserted instruction before returning from PreEmitNoops.
174 void runOnInstruction(MachineInstr *MI);
175
176 /// Wait states required after \p MI, or nullopt if \p MI is not waited for.
177 /// Must return nullopt for terminators.
178 using WindowForFn = function_ref<std::optional<int>(const MachineInstr &)>;
179
180 /// Returns the largest WindowFor(I) - distance(I) over the instructions
181 /// preceding the one being checked within \p MaxWindow, which must bound
182 /// every window WindowFor can return, and zero if it accepts none. Each
183 /// window is paired with the distance to the instruction that supplied it.
184 int getMaxWindowDeficit(int MaxWindow, WindowForFn WindowFor) const;
185 int getMaxVALUWindowDeficit(int MaxWindow, WindowForFn WindowFor) const;
186
187 int getWaitStatesSince(IsHazardFn IsHazard, int Limit,
188 GetNumWaitStatesFn GetNumWaitStates) const;
189 int getWaitStatesSince(IsHazardFn IsHazard, int Limit) const;
190 int getWaitStatesSinceDef(unsigned Reg, IsHazardFn IsHazardDef,
191 int Limit) const;
192 int getWaitStatesSinceSetReg(IsHazardFn IsHazard, int Limit) const;
193
194 int checkSoftClauseHazards(MachineInstr *SMEM) const;
195 int checkSMRDHazards(MachineInstr *SMRD) const;
196 int checkVMEMHazards(MachineInstr *VMEM) const;
197 int checkDPPHazards(MachineInstr *DPP) const;
198 int checkDivFMasHazards(MachineInstr *DivFMas) const;
199 int checkGetRegHazards(MachineInstr *GetRegInstr) const;
200 int checkSetRegHazards(MachineInstr *SetRegInstr) const;
201 int createsVALUHazard(const MachineInstr &MI) const;
202 int checkVALUHazards(MachineInstr *VALU) const;
203 int checkVALUHazardsHelper(const MachineOperand &Def,
204 const MachineRegisterInfo &MRI) const;
205 int checkUniformWindowVALUHazardsHelper(Register Reg) const;
206 int checkSOFFSETWindowVALUHazardsHelper(Register Reg) const;
207 int checkRWLaneHazards(MachineInstr *RWLane) const;
208 int checkRFEHazards(MachineInstr *RFE) const;
209 int checkInlineAsmHazards(MachineInstr *IA) const;
210 int checkReadM0Hazards(MachineInstr *SMovRel) const;
211 int checkNSAtoVMEMHazard(MachineInstr *MI) const;
212 int checkFPAtomicToDenormModeHazard(MachineInstr *MI) const;
213 // Emit \p WaitStatesNeeded V_NOP instructions before \p InsertPt.
214 // If IsHoisting is true, uses empty DebugLoc for compiler-inserted NOPs.
215 void emitVNops(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertPt,
216 int WaitStatesNeeded, bool IsHoisting = false);
217 void fixHazards(MachineInstr *MI);
218 bool fixVcmpxPermlaneHazards(MachineInstr *MI);
219 bool fixVMEMtoScalarWriteHazards(MachineInstr *MI);
220 bool fixSMEMtoVectorWriteHazards(MachineInstr *MI);
221 bool fixVcmpxExecWARHazard(MachineInstr *MI);
222 bool fixLdsBranchVmemWARHazard(MachineInstr *MI);
223 bool fixLdsDirectVALUHazard(MachineInstr *MI);
224 bool fixLdsDirectVMEMHazard(MachineInstr *MI);
225 bool fixVALUPartialForwardingHazard(MachineInstr *MI);
226 bool fixVALUTransUseHazard(MachineInstr *MI);
227 bool fixVALUTransCoexecutionHazards(MachineInstr *MI);
228 bool fixWMMAHazards(MachineInstr *MI);
229 int checkWMMACoexecutionHazards(MachineInstr *MI) const;
230 bool fixWMMACoexecutionHazards(MachineInstr *MI);
231 bool tryHoistWMMAVnopsFromLoop(MachineInstr *MI, int WaitStatesNeeded);
232 bool hasWMMAHazardInLoop(MachineLoop *L, MachineInstr *MI,
233 bool IncludeSubloops = true);
234 bool hasWMMAToWMMARegOverlap(const MachineInstr &WMMA,
235 const MachineInstr &MI) const;
236 bool hasWMMAToVALURegOverlap(const MachineInstr &WMMA,
237 const MachineInstr &MI) const;
238 bool isCoexecutionHazardFor(const MachineInstr &I,
239 const MachineInstr &MI) const;
240 bool fixShift64HighRegBug(MachineInstr *MI);
241 bool fixVPermPk16Hazard(MachineInstr *MI);
242 bool fixVALUMaskWriteHazard(MachineInstr *MI);
243 bool fixRequiredExportPriority(MachineInstr *MI);
244 bool fixGetRegWaitIdle(MachineInstr *MI);
245 bool fixDsAtomicAsyncBarrierArriveB64(MachineInstr *MI);
246 bool fixScratchBaseForwardingHazard(MachineInstr *MI);
247 bool fixSetRegMode(MachineInstr *MI);
248 bool fixTDM(MachineInstr *MI);
249 bool fixTransF16ToPartialVGPRWriteHazard(MachineInstr *MI);
250
251 /// Wait states before \p Consumer may read \p Reg, holding \p Producer's
252 /// result, as srcC if \p IsSrcC or as srcA/srcB otherwise.
253 int getMFMAReadWaitStates(const MachineInstr &Consumer,
254 const MachineInstr &Producer, Register Reg,
255 bool IsSrcC) const;
256
257 int checkMAIHazards(MachineInstr *MI) const;
258 int checkMAIHazards908(MachineInstr *MI) const;
259 int checkMAIHazards90A(MachineInstr *MI) const;
260 /// Wait states needed when MFMA \p Reader reads as src2/C a register that the
261 /// earlier MFMA \p Writer wrote, taken from the wait state tables for
262 /// overlapping register tuples.
263 int getMFMAOverlappedSrcCWaitStates(const MachineInstr *Reader,
264 const MachineInstr *Writer) const;
265 /// Pad the latency between neighboring MFMA instructions with s_nops. The
266 /// percentage of wait states to fill with s_nops is specified by the command
267 /// line option '-amdgpu-mfma-padding-ratio'.
268 ///
269 /// For example, with '-amdgpu-mfma-padding-ratio=100':
270 ///
271 /// 2 pass MFMA instructions have a latency of 2 wait states. Therefore, a
272 /// 'S_NOP 1' will be added between sequential MFMA instructions.
273 ///
274 /// V_MFMA_F32_4X4X1F32
275 /// V_MFMA_F32_4X4X1F32
276 ///-->
277 /// V_MFMA_F32_4X4X1F32
278 /// S_NOP 1
279 /// V_MFMA_F32_4X4X1F32
280 int checkMFMAPadding(MachineInstr *MI) const;
281 int checkMAIVALUHazards(MachineInstr *MI) const;
282 int checkMAILdStHazards(MachineInstr *MI) const;
283 int checkPermlaneHazards(MachineInstr *MI) const;
284
285public:
286 /// Construct with explicit operating mode.
287 GCNHazardRecognizer(const MachineFunction &MF, OperatingMode Mode,
288 MachineLoopInfo *MLI = nullptr);
289
290 /// Legacy constructor - defaults to PostRA mode.
292 MachineLoopInfo *MLI = nullptr);
293
295
296 /// Returns true if running in pre-RA scheduling mode.
297 bool isPreRA() const { return Mode == OperatingMode::PreRA; }
298
299 /// Returns true if running in post-RA scheduling mode.
300 bool isPostRA() const { return Mode == OperatingMode::PostRA; }
301
302 /// Returns true if running as a scheduler (pre-RA or post-RA).
303 bool isSchedulerMode() const { return isPreRA() || isPostRA(); }
304
305 /// Returns true if instruction operands are physical registers, so that
306 /// hazards defined by register dependences can be detected.
307 bool hasPhysRegs() const { return !isPreRA(); }
308
309 /// Returns true if running as the standalone hazard recognizer pass.
312 }
313
314 //===--------------------------------------------------------------------===//
315 // Co-execution Window Queries
316 //===--------------------------------------------------------------------===//
317
318 /// Get the CoExecMask for a given instruction.
320 const SIInstrInfo &TII);
321 // We can only issue one instruction per cycle.
322 bool atIssueLimit() const override { return true; }
323 void EmitInstruction(SUnit *SU) override;
324 void EmitInstruction(MachineInstr *MI) override;
325 HazardType getHazardType(SUnit *SU, int Stalls) override;
326
327 /// Returns the number of wait states until all hazards for \p MI are
328 /// resolved. This is useful for scheduling heuristics that want
329 /// cycle-accurate hazard information rather than just a boolean. Unlike
330 /// PreEmitNoops, this does not modify state or fix hazards.
331 unsigned getHazardWaitStates(MachineInstr *MI) const;
332 void EmitNoop() override;
333 unsigned PreEmitNoops(MachineInstr *) override;
334 unsigned PreEmitNoopsCommon(MachineInstr *) const;
335 void AdvanceCycle() override;
336 void RecedeCycle() override;
337 bool ShouldPreferAnother(SUnit *SU) const override;
338 void Reset() override;
339};
340
341} // end namespace llvm
342
343#endif //LLVM_LIB_TARGET_AMDGPUHAZARDRECOGNIZERS_H
Shared types for co-execution modeling used by GCNHazardRecognizer and the schedulers.
MachineBasicBlock & MBB
This file implements the BitVector class.
static int getWaitStatesSince(GCNHazardRecognizer::IsHazardFn IsHazard, const MachineBasicBlock *MBB, MachineBasicBlock::const_reverse_instr_iterator I, int WaitStates, GCNHazardRecognizer::IsExpiredFn IsExpired, DenseSet< const MachineBasicBlock * > &Visited, GCNHazardRecognizer::GetNumWaitStatesFn GetNumWaitStates=SIInstrInfo::getNumWaitStates)
const HexagonInstrInfo * TII
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
MachineRegisterInfo & MRI
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains some templates that are useful if you are working with the STL at all.
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:410
unsigned getHazardWaitStates(MachineInstr *MI) const
Returns the number of wait states until all hazards for MI are resolved.
unsigned PreEmitNoopsCommon(MachineInstr *) const
OperatingMode
Operating mode for the hazard recognizer.
void EmitNoop() override
EmitNoop - This callback is invoked when a noop was added to the instruction stream.
void Reset() override
Reset - This callback is invoked when a new block of instructions is about to be schedule.
unsigned PreEmitNoops(MachineInstr *) override
This overload will be used when the hazard recognizer is being used by a non-scheduling pass,...
void EmitInstruction(SUnit *SU) override
EmitInstruction - This callback is invoked when an instruction is emitted, to advance the hazard stat...
function_ref< bool(const MachineInstr &)> IsHazardFn
void AdvanceCycle() override
AdvanceCycle - This callback is invoked whenever the next top-down instruction to be scheduled cannot...
bool isPostRA() const
Returns true if running in post-RA scheduling mode.
function_ref< unsigned int(const MachineInstr &)> GetNumWaitStatesFn
bool ShouldPreferAnother(SUnit *SU) const override
ShouldPreferAnother - This callback may be invoked if getHazardType returns NoHazard.
bool hasPhysRegs() const
Returns true if instruction operands are physical registers, so that hazards defined by register depe...
function_ref< bool(const MachineInstr &, int WaitStates)> IsExpiredFn
bool isSchedulerMode() const
Returns true if running as a scheduler (pre-RA or post-RA).
GCNHazardRecognizer(const MachineFunction &MF, OperatingMode Mode, MachineLoopInfo *MLI=nullptr)
Construct with explicit operating mode.
static AMDGPU::CoExecMaskT getCoExecMaskForMI(const MachineInstr &MI, const SIInstrInfo &TII)
Get the CoExecMask for a given instruction.
HazardType getHazardType(SUnit *SU, int Stalls) override
getHazardType - Return the hazard type of emitting this node.
void RecedeCycle() override
RecedeCycle - This callback is invoked whenever the next bottom-up instruction to be scheduled cannot...
bool isHazardRecognizerMode() const
Returns true if running as the standalone hazard recognizer pass.
bool atIssueLimit() const override
atIssueLimit - Return true if no more instructions may be issued in this cycle.
bool isPreRA() const
Returns true if running in pre-RA scheduling mode.
MachineInstrBundleIterator< MachineInstr > iterator
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Scheduling unit. This is a node in the scheduling DAG.
Provide an instruction scheduling machine model to CodeGen passes.
An efficient, type-erasing, non-owning reference to a callable.
CoExecMask CoExecMaskT
This is an optimization pass for GlobalISel generic memory operations.
Co-execution characteristics for a multi-cycle instruction.