LLVM 22.0.0git
SIInsertWaitcnts.cpp
Go to the documentation of this file.
1//===- SIInsertWaitcnts.cpp - Insert Wait Instructions --------------------===//
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
10/// Insert wait instructions for memory reads and writes.
11///
12/// Memory reads and writes are issued asynchronously, so we need to insert
13/// S_WAITCNT instructions when we want to access any of their results or
14/// overwrite any register that's used asynchronously.
15///
16/// TODO: This pass currently keeps one timeline per hardware counter. A more
17/// finely-grained approach that keeps one timeline per event type could
18/// sometimes get away with generating weaker s_waitcnt instructions. For
19/// example, when both SMEM and LDS are in flight and we need to wait for
20/// the i-th-last LDS instruction, then an lgkmcnt(i) is actually sufficient,
21/// but the pass will currently generate a conservative lgkmcnt(0) because
22/// multiple event types are in flight.
23//
24//===----------------------------------------------------------------------===//
25
26#include "AMDGPU.h"
27#include "GCNSubtarget.h"
31#include "llvm/ADT/MapVector.h"
33#include "llvm/ADT/Sequence.h"
39#include "llvm/IR/Dominators.h"
43
44using namespace llvm;
45
46#define DEBUG_TYPE "si-insert-waitcnts"
47
48DEBUG_COUNTER(ForceExpCounter, DEBUG_TYPE "-forceexp",
49 "Force emit s_waitcnt expcnt(0) instrs");
50DEBUG_COUNTER(ForceLgkmCounter, DEBUG_TYPE "-forcelgkm",
51 "Force emit s_waitcnt lgkmcnt(0) instrs");
52DEBUG_COUNTER(ForceVMCounter, DEBUG_TYPE "-forcevm",
53 "Force emit s_waitcnt vmcnt(0) instrs");
54
55static cl::opt<bool>
56 ForceEmitZeroFlag("amdgpu-waitcnt-forcezero",
57 cl::desc("Force all waitcnt instrs to be emitted as "
58 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
59 cl::init(false), cl::Hidden);
60
62 "amdgpu-waitcnt-load-forcezero",
63 cl::desc("Force all waitcnt load counters to wait until 0"),
64 cl::init(false), cl::Hidden);
65
66namespace {
67// Class of object that encapsulates latest instruction counter score
68// associated with the operand. Used for determining whether
69// s_waitcnt instruction needs to be emitted.
70
71enum InstCounterType {
72 LOAD_CNT = 0, // VMcnt prior to gfx12.
73 DS_CNT, // LKGMcnt prior to gfx12.
74 EXP_CNT, //
75 STORE_CNT, // VScnt in gfx10/gfx11.
76 NUM_NORMAL_INST_CNTS,
77 SAMPLE_CNT = NUM_NORMAL_INST_CNTS, // gfx12+ only.
78 BVH_CNT, // gfx12+ only.
79 KM_CNT, // gfx12+ only.
80 X_CNT, // gfx1250.
81 NUM_EXTENDED_INST_CNTS,
82 NUM_INST_CNTS = NUM_EXTENDED_INST_CNTS
83};
84} // namespace
85
86namespace llvm {
87template <> struct enum_iteration_traits<InstCounterType> {
88 static constexpr bool is_iterable = true;
89};
90} // namespace llvm
91
92namespace {
93// Return an iterator over all counters between LOAD_CNT (the first counter)
94// and \c MaxCounter (exclusive, default value yields an enumeration over
95// all counters).
96auto inst_counter_types(InstCounterType MaxCounter = NUM_INST_CNTS) {
97 return enum_seq(LOAD_CNT, MaxCounter);
98}
99
100using RegInterval = std::pair<int, int>;
101
102struct HardwareLimits {
103 unsigned LoadcntMax; // Corresponds to VMcnt prior to gfx12.
104 unsigned ExpcntMax;
105 unsigned DscntMax; // Corresponds to LGKMcnt prior to gfx12.
106 unsigned StorecntMax; // Corresponds to VScnt in gfx10/gfx11.
107 unsigned SamplecntMax; // gfx12+ only.
108 unsigned BvhcntMax; // gfx12+ only.
109 unsigned KmcntMax; // gfx12+ only.
110 unsigned XcntMax; // gfx1250.
111};
112
113#define AMDGPU_DECLARE_WAIT_EVENTS(DECL) \
114 DECL(VMEM_ACCESS) /* vmem read & write */ \
115 DECL(VMEM_READ_ACCESS) /* vmem read */ \
116 DECL(VMEM_SAMPLER_READ_ACCESS) /* vmem SAMPLER read (gfx12+ only) */ \
117 DECL(VMEM_BVH_READ_ACCESS) /* vmem BVH read (gfx12+ only) */ \
118 DECL(VMEM_WRITE_ACCESS) /* vmem write that is not scratch */ \
119 DECL(SCRATCH_WRITE_ACCESS) /* vmem write that may be scratch */ \
120 DECL(VMEM_GROUP) /* vmem group */ \
121 DECL(LDS_ACCESS) /* lds read & write */ \
122 DECL(GDS_ACCESS) /* gds read & write */ \
123 DECL(SQ_MESSAGE) /* send message */ \
124 DECL(SMEM_ACCESS) /* scalar-memory read & write */ \
125 DECL(SMEM_GROUP) /* scalar-memory group */ \
126 DECL(EXP_GPR_LOCK) /* export holding on its data src */ \
127 DECL(GDS_GPR_LOCK) /* GDS holding on its data and addr src */ \
128 DECL(EXP_POS_ACCESS) /* write to export position */ \
129 DECL(EXP_PARAM_ACCESS) /* write to export parameter */ \
130 DECL(VMW_GPR_LOCK) /* vmem write holding on its data src */ \
131 DECL(EXP_LDS_ACCESS) /* read by ldsdir counting as export */
132
133// clang-format off
134#define AMDGPU_EVENT_ENUM(Name) Name,
135enum WaitEventType {
137 NUM_WAIT_EVENTS
138};
139#undef AMDGPU_EVENT_ENUM
140
141#define AMDGPU_EVENT_NAME(Name) #Name,
142static constexpr StringLiteral WaitEventTypeName[] = {
144};
145#undef AMDGPU_EVENT_NAME
146// clang-format on
147
148// The mapping is:
149// 0 .. SQ_MAX_PGM_VGPRS-1 real VGPRs
150// SQ_MAX_PGM_VGPRS .. NUM_ALL_VGPRS-1 extra VGPR-like slots
151// NUM_ALL_VGPRS .. NUM_ALL_VGPRS+SQ_MAX_PGM_SGPRS-1 real SGPRs
152// We reserve a fixed number of VGPR slots in the scoring tables for
153// special tokens like SCMEM_LDS (needed for buffer load to LDS).
154enum RegisterMapping {
155 SQ_MAX_PGM_VGPRS = 2048, // Maximum programmable VGPRs across all targets.
156 AGPR_OFFSET = 512, // Maximum programmable ArchVGPRs across all targets.
157 SQ_MAX_PGM_SGPRS = 128, // Maximum programmable SGPRs across all targets.
158 // Artificial register slots to track LDS writes into specific LDS locations
159 // if a location is known. When slots are exhausted or location is
160 // unknown use the first slot. The first slot is also always updated in
161 // addition to known location's slot to properly generate waits if dependent
162 // instruction's location is unknown.
163 FIRST_LDS_VGPR = SQ_MAX_PGM_VGPRS, // Extra slots for LDS stores.
164 NUM_LDS_VGPRS = 9, // One more than the stores we track.
165 NUM_ALL_VGPRS = SQ_MAX_PGM_VGPRS + NUM_LDS_VGPRS, // Where SGPRs start.
166};
167
168// Enumerate different types of result-returning VMEM operations. Although
169// s_waitcnt orders them all with a single vmcnt counter, in the absence of
170// s_waitcnt only instructions of the same VmemType are guaranteed to write
171// their results in order -- so there is no need to insert an s_waitcnt between
172// two instructions of the same type that write the same vgpr.
173enum VmemType {
174 // BUF instructions and MIMG instructions without a sampler.
175 VMEM_NOSAMPLER,
176 // MIMG instructions with a sampler.
177 VMEM_SAMPLER,
178 // BVH instructions
179 VMEM_BVH,
180 NUM_VMEM_TYPES
181};
182
183// Maps values of InstCounterType to the instruction that waits on that
184// counter. Only used if GCNSubtarget::hasExtendedWaitCounts()
185// returns true.
186static const unsigned instrsForExtendedCounterTypes[NUM_EXTENDED_INST_CNTS] = {
187 AMDGPU::S_WAIT_LOADCNT, AMDGPU::S_WAIT_DSCNT, AMDGPU::S_WAIT_EXPCNT,
188 AMDGPU::S_WAIT_STORECNT, AMDGPU::S_WAIT_SAMPLECNT, AMDGPU::S_WAIT_BVHCNT,
189 AMDGPU::S_WAIT_KMCNT, AMDGPU::S_WAIT_XCNT};
190
191static bool updateVMCntOnly(const MachineInstr &Inst) {
192 return (SIInstrInfo::isVMEM(Inst) && !SIInstrInfo::isFLAT(Inst)) ||
194}
195
196#ifndef NDEBUG
197static bool isNormalMode(InstCounterType MaxCounter) {
198 return MaxCounter == NUM_NORMAL_INST_CNTS;
199}
200#endif // NDEBUG
201
202VmemType getVmemType(const MachineInstr &Inst) {
203 assert(updateVMCntOnly(Inst));
204 if (!SIInstrInfo::isImage(Inst))
205 return VMEM_NOSAMPLER;
207 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
209
210 if (BaseInfo->BVH)
211 return VMEM_BVH;
212
213 // We have to make an additional check for isVSAMPLE here since some
214 // instructions don't have a sampler, but are still classified as sampler
215 // instructions for the purposes of e.g. waitcnt.
216 if (BaseInfo->Sampler || BaseInfo->MSAA || SIInstrInfo::isVSAMPLE(Inst))
217 return VMEM_SAMPLER;
218
219 return VMEM_NOSAMPLER;
220}
221
222unsigned &getCounterRef(AMDGPU::Waitcnt &Wait, InstCounterType T) {
223 switch (T) {
224 case LOAD_CNT:
225 return Wait.LoadCnt;
226 case EXP_CNT:
227 return Wait.ExpCnt;
228 case DS_CNT:
229 return Wait.DsCnt;
230 case STORE_CNT:
231 return Wait.StoreCnt;
232 case SAMPLE_CNT:
233 return Wait.SampleCnt;
234 case BVH_CNT:
235 return Wait.BvhCnt;
236 case KM_CNT:
237 return Wait.KmCnt;
238 case X_CNT:
239 return Wait.XCnt;
240 default:
241 llvm_unreachable("bad InstCounterType");
242 }
243}
244
245void addWait(AMDGPU::Waitcnt &Wait, InstCounterType T, unsigned Count) {
246 unsigned &WC = getCounterRef(Wait, T);
247 WC = std::min(WC, Count);
248}
249
250void setNoWait(AMDGPU::Waitcnt &Wait, InstCounterType T) {
251 getCounterRef(Wait, T) = ~0u;
252}
253
254unsigned getWait(AMDGPU::Waitcnt &Wait, InstCounterType T) {
255 return getCounterRef(Wait, T);
256}
257
258// Mapping from event to counter according to the table masks.
259InstCounterType eventCounter(const unsigned *masks, WaitEventType E) {
260 for (auto T : inst_counter_types()) {
261 if (masks[T] & (1 << E))
262 return T;
263 }
264 llvm_unreachable("event type has no associated counter");
265}
266
267class WaitcntBrackets;
268
269// This abstracts the logic for generating and updating S_WAIT* instructions
270// away from the analysis that determines where they are needed. This was
271// done because the set of counters and instructions for waiting on them
272// underwent a major shift with gfx12, sufficiently so that having this
273// abstraction allows the main analysis logic to be simpler than it would
274// otherwise have had to become.
275class WaitcntGenerator {
276protected:
277 const GCNSubtarget *ST = nullptr;
278 const SIInstrInfo *TII = nullptr;
279 AMDGPU::IsaVersion IV;
280 InstCounterType MaxCounter;
281 bool OptNone;
282
283public:
284 WaitcntGenerator() = default;
285 WaitcntGenerator(const MachineFunction &MF, InstCounterType MaxCounter)
286 : ST(&MF.getSubtarget<GCNSubtarget>()), TII(ST->getInstrInfo()),
287 IV(AMDGPU::getIsaVersion(ST->getCPU())), MaxCounter(MaxCounter),
288 OptNone(MF.getFunction().hasOptNone() ||
289 MF.getTarget().getOptLevel() == CodeGenOptLevel::None) {}
290
291 // Return true if the current function should be compiled with no
292 // optimization.
293 bool isOptNone() const { return OptNone; }
294
295 // Edits an existing sequence of wait count instructions according
296 // to an incoming Waitcnt value, which is itself updated to reflect
297 // any new wait count instructions which may need to be generated by
298 // WaitcntGenerator::createNewWaitcnt(). It will return true if any edits
299 // were made.
300 //
301 // This editing will usually be merely updated operands, but it may also
302 // delete instructions if the incoming Wait value indicates they are not
303 // needed. It may also remove existing instructions for which a wait
304 // is needed if it can be determined that it is better to generate new
305 // instructions later, as can happen on gfx12.
306 virtual bool
307 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
308 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
310
311 // Transform a soft waitcnt into a normal one.
312 bool promoteSoftWaitCnt(MachineInstr *Waitcnt) const;
313
314 // Generates new wait count instructions according to the value of
315 // Wait, returning true if any new instructions were created.
316 virtual bool createNewWaitcnt(MachineBasicBlock &Block,
318 AMDGPU::Waitcnt Wait) = 0;
319
320 // Returns an array of bit masks which can be used to map values in
321 // WaitEventType to corresponding counter values in InstCounterType.
322 virtual const unsigned *getWaitEventMask() const = 0;
323
324 // Returns a new waitcnt with all counters except VScnt set to 0. If
325 // IncludeVSCnt is true, VScnt is set to 0, otherwise it is set to ~0u.
326 virtual AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const = 0;
327
328 virtual ~WaitcntGenerator() = default;
329
330 // Create a mask value from the initializer list of wait event types.
331 static constexpr unsigned
332 eventMask(std::initializer_list<WaitEventType> Events) {
333 unsigned Mask = 0;
334 for (auto &E : Events)
335 Mask |= 1 << E;
336
337 return Mask;
338 }
339};
340
341class WaitcntGeneratorPreGFX12 : public WaitcntGenerator {
342public:
343 WaitcntGeneratorPreGFX12() = default;
344 WaitcntGeneratorPreGFX12(const MachineFunction &MF)
345 : WaitcntGenerator(MF, NUM_NORMAL_INST_CNTS) {}
346
347 bool
348 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
349 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
350 MachineBasicBlock::instr_iterator It) const override;
351
352 bool createNewWaitcnt(MachineBasicBlock &Block,
354 AMDGPU::Waitcnt Wait) override;
355
356 const unsigned *getWaitEventMask() const override {
357 assert(ST);
358
359 static const unsigned WaitEventMaskForInstPreGFX12[NUM_INST_CNTS] = {
360 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS,
361 VMEM_BVH_READ_ACCESS}),
362 eventMask({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
363 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
364 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
365 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
366 0,
367 0,
368 0,
369 0};
370
371 return WaitEventMaskForInstPreGFX12;
372 }
373
374 AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const override;
375};
376
377class WaitcntGeneratorGFX12Plus : public WaitcntGenerator {
378public:
379 WaitcntGeneratorGFX12Plus() = default;
380 WaitcntGeneratorGFX12Plus(const MachineFunction &MF,
381 InstCounterType MaxCounter)
382 : WaitcntGenerator(MF, MaxCounter) {}
383
384 bool
385 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
386 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
387 MachineBasicBlock::instr_iterator It) const override;
388
389 bool createNewWaitcnt(MachineBasicBlock &Block,
391 AMDGPU::Waitcnt Wait) override;
392
393 const unsigned *getWaitEventMask() const override {
394 assert(ST);
395
396 static const unsigned WaitEventMaskForInstGFX12Plus[NUM_INST_CNTS] = {
397 eventMask({VMEM_ACCESS, VMEM_READ_ACCESS}),
398 eventMask({LDS_ACCESS, GDS_ACCESS}),
399 eventMask({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK, EXP_PARAM_ACCESS,
400 EXP_POS_ACCESS, EXP_LDS_ACCESS}),
401 eventMask({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
402 eventMask({VMEM_SAMPLER_READ_ACCESS}),
403 eventMask({VMEM_BVH_READ_ACCESS}),
404 eventMask({SMEM_ACCESS, SQ_MESSAGE}),
405 eventMask({VMEM_GROUP, SMEM_GROUP})};
406
407 return WaitEventMaskForInstGFX12Plus;
408 }
409
410 AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const override;
411};
412
413class SIInsertWaitcnts {
414public:
415 const GCNSubtarget *ST;
416 InstCounterType SmemAccessCounter;
417 InstCounterType MaxCounter;
418 const unsigned *WaitEventMaskForInst;
419
420private:
421 const SIInstrInfo *TII = nullptr;
422 const SIRegisterInfo *TRI = nullptr;
423 const MachineRegisterInfo *MRI = nullptr;
424
425 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
426 DenseMap<MachineBasicBlock *, bool> PreheadersToFlush;
427 MachineLoopInfo *MLI;
428 MachinePostDominatorTree *PDT;
429 AliasAnalysis *AA = nullptr;
430
431 struct BlockInfo {
432 std::unique_ptr<WaitcntBrackets> Incoming;
433 bool Dirty = true;
434 };
435
436 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
437
438 bool ForceEmitWaitcnt[NUM_INST_CNTS];
439
440 // In any given run of this pass, WCG will point to one of these two
441 // generator objects, which must have been re-initialised before use
442 // from a value made using a subtarget constructor.
443 WaitcntGeneratorPreGFX12 WCGPreGFX12;
444 WaitcntGeneratorGFX12Plus WCGGFX12Plus;
445
446 WaitcntGenerator *WCG = nullptr;
447
448 // S_ENDPGM instructions before which we should insert a DEALLOC_VGPRS
449 // message.
450 DenseSet<MachineInstr *> ReleaseVGPRInsts;
451
452 HardwareLimits Limits;
453
454public:
455 SIInsertWaitcnts(MachineLoopInfo *MLI, MachinePostDominatorTree *PDT,
456 AliasAnalysis *AA)
457 : MLI(MLI), PDT(PDT), AA(AA) {
458 (void)ForceExpCounter;
459 (void)ForceLgkmCounter;
460 (void)ForceVMCounter;
461 }
462
463 unsigned getWaitCountMax(InstCounterType T) const {
464 switch (T) {
465 case LOAD_CNT:
466 return Limits.LoadcntMax;
467 case DS_CNT:
468 return Limits.DscntMax;
469 case EXP_CNT:
470 return Limits.ExpcntMax;
471 case STORE_CNT:
472 return Limits.StorecntMax;
473 case SAMPLE_CNT:
474 return Limits.SamplecntMax;
475 case BVH_CNT:
476 return Limits.BvhcntMax;
477 case KM_CNT:
478 return Limits.KmcntMax;
479 case X_CNT:
480 return Limits.XcntMax;
481 default:
482 break;
483 }
484 return 0;
485 }
486
487 bool shouldFlushVmCnt(MachineLoop *ML, const WaitcntBrackets &Brackets);
488 bool isPreheaderToFlush(MachineBasicBlock &MBB,
489 const WaitcntBrackets &ScoreBrackets);
490 bool isVMEMOrFlatVMEM(const MachineInstr &MI) const;
491 bool run(MachineFunction &MF);
492
493 bool isForceEmitWaitcnt() const {
494 for (auto T : inst_counter_types())
495 if (ForceEmitWaitcnt[T])
496 return true;
497 return false;
498 }
499
500 void setForceEmitWaitcnt() {
501// For non-debug builds, ForceEmitWaitcnt has been initialized to false;
502// For debug builds, get the debug counter info and adjust if need be
503#ifndef NDEBUG
504 if (DebugCounter::isCounterSet(ForceExpCounter) &&
505 DebugCounter::shouldExecute(ForceExpCounter)) {
506 ForceEmitWaitcnt[EXP_CNT] = true;
507 } else {
508 ForceEmitWaitcnt[EXP_CNT] = false;
509 }
510
511 if (DebugCounter::isCounterSet(ForceLgkmCounter) &&
512 DebugCounter::shouldExecute(ForceLgkmCounter)) {
513 ForceEmitWaitcnt[DS_CNT] = true;
514 ForceEmitWaitcnt[KM_CNT] = true;
515 } else {
516 ForceEmitWaitcnt[DS_CNT] = false;
517 ForceEmitWaitcnt[KM_CNT] = false;
518 }
519
520 if (DebugCounter::isCounterSet(ForceVMCounter) &&
521 DebugCounter::shouldExecute(ForceVMCounter)) {
522 ForceEmitWaitcnt[LOAD_CNT] = true;
523 ForceEmitWaitcnt[SAMPLE_CNT] = true;
524 ForceEmitWaitcnt[BVH_CNT] = true;
525 } else {
526 ForceEmitWaitcnt[LOAD_CNT] = false;
527 ForceEmitWaitcnt[SAMPLE_CNT] = false;
528 ForceEmitWaitcnt[BVH_CNT] = false;
529 }
530#endif // NDEBUG
531 }
532
533 // Return the appropriate VMEM_*_ACCESS type for Inst, which must be a VMEM
534 // instruction.
535 WaitEventType getVmemWaitEventType(const MachineInstr &Inst) const {
536 switch (Inst.getOpcode()) {
537 case AMDGPU::GLOBAL_INV:
538 return VMEM_READ_ACCESS; // tracked using loadcnt
539 case AMDGPU::GLOBAL_WB:
540 case AMDGPU::GLOBAL_WBINV:
541 return VMEM_WRITE_ACCESS; // tracked using storecnt
542 default:
543 break;
544 }
545
546 // Maps VMEM access types to their corresponding WaitEventType.
547 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
548 VMEM_READ_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
549
551 // LDS DMA loads are also stores, but on the LDS side. On the VMEM side
552 // these should use VM_CNT.
553 if (!ST->hasVscnt() || SIInstrInfo::mayWriteLDSThroughDMA(Inst))
554 return VMEM_ACCESS;
555 if (Inst.mayStore() &&
556 (!Inst.mayLoad() || SIInstrInfo::isAtomicNoRet(Inst))) {
557 // FLAT and SCRATCH instructions may access scratch. Other VMEM
558 // instructions do not.
559 if (TII->mayAccessScratchThroughFlat(Inst))
560 return SCRATCH_WRITE_ACCESS;
561 return VMEM_WRITE_ACCESS;
562 }
563 if (!ST->hasExtendedWaitCounts() || SIInstrInfo::isFLAT(Inst))
564 return VMEM_READ_ACCESS;
565 return VmemReadMapping[getVmemType(Inst)];
566 }
567
568 bool hasXcnt() const { return ST->hasWaitXCnt(); }
569
570 bool mayAccessVMEMThroughFlat(const MachineInstr &MI) const;
571 bool mayAccessLDSThroughFlat(const MachineInstr &MI) const;
572 bool isVmemAccess(const MachineInstr &MI) const;
573 bool generateWaitcntInstBefore(MachineInstr &MI,
574 WaitcntBrackets &ScoreBrackets,
575 MachineInstr *OldWaitcntInstr,
576 bool FlushVmCnt);
577 bool generateWaitcnt(AMDGPU::Waitcnt Wait,
579 MachineBasicBlock &Block, WaitcntBrackets &ScoreBrackets,
580 MachineInstr *OldWaitcntInstr);
581 void updateEventWaitcntAfter(MachineInstr &Inst,
582 WaitcntBrackets *ScoreBrackets);
583 bool isNextENDPGM(MachineBasicBlock::instr_iterator It,
584 MachineBasicBlock *Block) const;
585 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &Block,
586 WaitcntBrackets &ScoreBrackets);
587 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block,
588 WaitcntBrackets &ScoreBrackets);
589};
590
591// This objects maintains the current score brackets of each wait counter, and
592// a per-register scoreboard for each wait counter.
593//
594// We also maintain the latest score for every event type that can change the
595// waitcnt in order to know if there are multiple types of events within
596// the brackets. When multiple types of event happen in the bracket,
597// wait count may get decreased out of order, therefore we need to put in
598// "s_waitcnt 0" before use.
599class WaitcntBrackets {
600public:
601 WaitcntBrackets(const SIInsertWaitcnts *Context) : Context(Context) {}
602
603 bool isSmemCounter(InstCounterType T) const {
604 return T == Context->SmemAccessCounter || T == X_CNT;
605 }
606
607 unsigned getSgprScoresIdx(InstCounterType T) const {
608 assert(isSmemCounter(T) && "Invalid SMEM counter");
609 return T == X_CNT ? 1 : 0;
610 }
611
612 unsigned getScoreLB(InstCounterType T) const {
613 assert(T < NUM_INST_CNTS);
614 return ScoreLBs[T];
615 }
616
617 unsigned getScoreUB(InstCounterType T) const {
618 assert(T < NUM_INST_CNTS);
619 return ScoreUBs[T];
620 }
621
622 unsigned getScoreRange(InstCounterType T) const {
623 return getScoreUB(T) - getScoreLB(T);
624 }
625
626 unsigned getRegScore(int GprNo, InstCounterType T) const {
627 if (GprNo < NUM_ALL_VGPRS)
628 return VgprScores[T][GprNo];
629 return SgprScores[getSgprScoresIdx(T)][GprNo - NUM_ALL_VGPRS];
630 }
631
632 bool merge(const WaitcntBrackets &Other);
633
634 RegInterval getRegInterval(const MachineInstr *MI,
635 const MachineRegisterInfo *MRI,
636 const SIRegisterInfo *TRI,
637 const MachineOperand &Op) const;
638
639 bool counterOutOfOrder(InstCounterType T) const;
640 void simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const;
641 void simplifyWaitcnt(InstCounterType T, unsigned &Count) const;
642
643 void determineWait(InstCounterType T, RegInterval Interval,
644 AMDGPU::Waitcnt &Wait) const;
645 void determineWait(InstCounterType T, int RegNo,
646 AMDGPU::Waitcnt &Wait) const {
647 determineWait(T, {RegNo, RegNo + 1}, Wait);
648 }
649
650 void applyWaitcnt(const AMDGPU::Waitcnt &Wait);
651 void applyWaitcnt(InstCounterType T, unsigned Count);
652 void applyXcnt(const AMDGPU::Waitcnt &Wait);
653 void updateByEvent(const SIInstrInfo *TII, const SIRegisterInfo *TRI,
654 const MachineRegisterInfo *MRI, WaitEventType E,
655 MachineInstr &MI);
656
657 unsigned hasPendingEvent() const { return PendingEvents; }
658 unsigned hasPendingEvent(WaitEventType E) const {
659 return PendingEvents & (1 << E);
660 }
661 unsigned hasPendingEvent(InstCounterType T) const {
662 unsigned HasPending = PendingEvents & Context->WaitEventMaskForInst[T];
663 assert((HasPending != 0) == (getScoreRange(T) != 0));
664 return HasPending;
665 }
666
667 bool hasMixedPendingEvents(InstCounterType T) const {
668 unsigned Events = hasPendingEvent(T);
669 // Return true if more than one bit is set in Events.
670 return Events & (Events - 1);
671 }
672
673 bool hasPendingFlat() const {
674 return ((LastFlat[DS_CNT] > ScoreLBs[DS_CNT] &&
675 LastFlat[DS_CNT] <= ScoreUBs[DS_CNT]) ||
676 (LastFlat[LOAD_CNT] > ScoreLBs[LOAD_CNT] &&
677 LastFlat[LOAD_CNT] <= ScoreUBs[LOAD_CNT]));
678 }
679
680 void setPendingFlat() {
681 LastFlat[LOAD_CNT] = ScoreUBs[LOAD_CNT];
682 LastFlat[DS_CNT] = ScoreUBs[DS_CNT];
683 }
684
685 bool hasPendingGDS() const {
686 return LastGDS > ScoreLBs[DS_CNT] && LastGDS <= ScoreUBs[DS_CNT];
687 }
688
689 unsigned getPendingGDSWait() const {
690 return std::min(getScoreUB(DS_CNT) - LastGDS,
691 Context->getWaitCountMax(DS_CNT) - 1);
692 }
693
694 void setPendingGDS() { LastGDS = ScoreUBs[DS_CNT]; }
695
696 // Return true if there might be pending writes to the vgpr-interval by VMEM
697 // instructions with types different from V.
698 bool hasOtherPendingVmemTypes(RegInterval Interval, VmemType V) const {
699 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
700 assert(RegNo < NUM_ALL_VGPRS);
701 if (VgprVmemTypes[RegNo] & ~(1 << V))
702 return true;
703 }
704 return false;
705 }
706
707 void clearVgprVmemTypes(RegInterval Interval) {
708 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
709 assert(RegNo < NUM_ALL_VGPRS);
710 VgprVmemTypes[RegNo] = 0;
711 }
712 }
713
714 void setStateOnFunctionEntryOrReturn() {
715 setScoreUB(STORE_CNT,
716 getScoreUB(STORE_CNT) + Context->getWaitCountMax(STORE_CNT));
717 PendingEvents |= Context->WaitEventMaskForInst[STORE_CNT];
718 }
719
720 ArrayRef<const MachineInstr *> getLDSDMAStores() const {
721 return LDSDMAStores;
722 }
723
724 bool hasPointSampleAccel(const MachineInstr &MI) const;
725 bool hasPointSamplePendingVmemTypes(const MachineInstr &MI,
726 RegInterval Interval) const;
727
728 void print(raw_ostream &) const;
729 void dump() const { print(dbgs()); }
730
731private:
732 struct MergeInfo {
733 unsigned OldLB;
734 unsigned OtherLB;
735 unsigned MyShift;
736 unsigned OtherShift;
737 };
738 static bool mergeScore(const MergeInfo &M, unsigned &Score,
739 unsigned OtherScore);
740
741 void setScoreLB(InstCounterType T, unsigned Val) {
742 assert(T < NUM_INST_CNTS);
743 ScoreLBs[T] = Val;
744 }
745
746 void setScoreUB(InstCounterType T, unsigned Val) {
747 assert(T < NUM_INST_CNTS);
748 ScoreUBs[T] = Val;
749
750 if (T != EXP_CNT)
751 return;
752
753 if (getScoreRange(EXP_CNT) > Context->getWaitCountMax(EXP_CNT))
754 ScoreLBs[EXP_CNT] = ScoreUBs[EXP_CNT] - Context->getWaitCountMax(EXP_CNT);
755 }
756
757 void setRegScore(int GprNo, InstCounterType T, unsigned Val) {
758 setScoreByInterval({GprNo, GprNo + 1}, T, Val);
759 }
760
761 void setScoreByInterval(RegInterval Interval, InstCounterType CntTy,
762 unsigned Score);
763
764 void setScoreByOperand(const MachineInstr *MI, const SIRegisterInfo *TRI,
765 const MachineRegisterInfo *MRI,
766 const MachineOperand &Op, InstCounterType CntTy,
767 unsigned Val);
768
769 const SIInsertWaitcnts *Context;
770
771 unsigned ScoreLBs[NUM_INST_CNTS] = {0};
772 unsigned ScoreUBs[NUM_INST_CNTS] = {0};
773 unsigned PendingEvents = 0;
774 // Remember the last flat memory operation.
775 unsigned LastFlat[NUM_INST_CNTS] = {0};
776 // Remember the last GDS operation.
777 unsigned LastGDS = 0;
778 // wait_cnt scores for every vgpr.
779 // Keep track of the VgprUB and SgprUB to make merge at join efficient.
780 int VgprUB = -1;
781 int SgprUB = -1;
782 unsigned VgprScores[NUM_INST_CNTS][NUM_ALL_VGPRS] = {{0}};
783 // Wait cnt scores for every sgpr, the DS_CNT (corresponding to LGKMcnt
784 // pre-gfx12) or KM_CNT (gfx12+ only), and X_CNT (gfx1250) are relevant.
785 // Row 0 represents the score for either DS_CNT or KM_CNT and row 1 keeps the
786 // X_CNT score.
787 unsigned SgprScores[2][SQ_MAX_PGM_SGPRS] = {{0}};
788 // Bitmask of the VmemTypes of VMEM instructions that might have a pending
789 // write to each vgpr.
790 unsigned char VgprVmemTypes[NUM_ALL_VGPRS] = {0};
791 // Store representative LDS DMA operations. The only useful info here is
792 // alias info. One store is kept per unique AAInfo.
793 SmallVector<const MachineInstr *, NUM_LDS_VGPRS - 1> LDSDMAStores;
794};
795
796class SIInsertWaitcntsLegacy : public MachineFunctionPass {
797public:
798 static char ID;
799 SIInsertWaitcntsLegacy() : MachineFunctionPass(ID) {}
800
801 bool runOnMachineFunction(MachineFunction &MF) override;
802
803 StringRef getPassName() const override {
804 return "SI insert wait instructions";
805 }
806
807 void getAnalysisUsage(AnalysisUsage &AU) const override {
808 AU.setPreservesCFG();
809 AU.addRequired<MachineLoopInfoWrapperPass>();
810 AU.addRequired<MachinePostDominatorTreeWrapperPass>();
811 AU.addUsedIfAvailable<AAResultsWrapperPass>();
812 AU.addPreserved<AAResultsWrapperPass>();
814 }
815};
816
817} // end anonymous namespace
818
819RegInterval WaitcntBrackets::getRegInterval(const MachineInstr *MI,
821 const SIRegisterInfo *TRI,
822 const MachineOperand &Op) const {
823 if (!TRI->isInAllocatableClass(Op.getReg()))
824 return {-1, -1};
825
826 // A use via a PW operand does not need a waitcnt.
827 // A partial write is not a WAW.
828 assert(!Op.getSubReg() || !Op.isUndef());
829
830 RegInterval Result;
831
832 MCRegister MCReg = AMDGPU::getMCReg(Op.getReg(), *Context->ST);
833 unsigned RegIdx = TRI->getHWRegIndex(MCReg);
834
835 const TargetRegisterClass *RC = TRI->getPhysRegBaseClass(Op.getReg());
836 unsigned Size = TRI->getRegSizeInBits(*RC);
837
838 // AGPRs/VGPRs are tracked every 16 bits, SGPRs by 32 bits
839 if (TRI->isVectorRegister(*MRI, Op.getReg())) {
840 unsigned Reg = RegIdx << 1 | (AMDGPU::isHi16Reg(MCReg, *TRI) ? 1 : 0);
841 assert(!Context->ST->hasMAIInsts() || Reg < AGPR_OFFSET);
842 Result.first = Reg;
843 if (TRI->isAGPR(*MRI, Op.getReg()))
844 Result.first += AGPR_OFFSET;
845 assert(Result.first >= 0 && Result.first < SQ_MAX_PGM_VGPRS);
846 assert(Size % 16 == 0);
847 Result.second = Result.first + (Size / 16);
848 } else if (TRI->isSGPRReg(*MRI, Op.getReg()) && RegIdx < SQ_MAX_PGM_SGPRS) {
849 // SGPRs including VCC, TTMPs and EXEC but excluding read-only scalar
850 // sources like SRC_PRIVATE_BASE.
851 Result.first = RegIdx + NUM_ALL_VGPRS;
852 Result.second = Result.first + divideCeil(Size, 32);
853 } else {
854 return {-1, -1};
855 }
856
857 return Result;
858}
859
860void WaitcntBrackets::setScoreByInterval(RegInterval Interval,
861 InstCounterType CntTy,
862 unsigned Score) {
863 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
864 if (RegNo < NUM_ALL_VGPRS) {
865 VgprUB = std::max(VgprUB, RegNo);
866 VgprScores[CntTy][RegNo] = Score;
867 } else {
868 SgprUB = std::max(SgprUB, RegNo - NUM_ALL_VGPRS);
869 SgprScores[getSgprScoresIdx(CntTy)][RegNo - NUM_ALL_VGPRS] = Score;
870 }
871 }
872}
873
874void WaitcntBrackets::setScoreByOperand(const MachineInstr *MI,
875 const SIRegisterInfo *TRI,
876 const MachineRegisterInfo *MRI,
877 const MachineOperand &Op,
878 InstCounterType CntTy, unsigned Score) {
879 RegInterval Interval = getRegInterval(MI, MRI, TRI, Op);
880 setScoreByInterval(Interval, CntTy, Score);
881}
882
883// Return true if the subtarget is one that enables Point Sample Acceleration
884// and the MachineInstr passed in is one to which it might be applied (the
885// hardware makes this decision based on several factors, but we can't determine
886// this at compile time, so we have to assume it might be applied if the
887// instruction supports it).
888bool WaitcntBrackets::hasPointSampleAccel(const MachineInstr &MI) const {
889 if (!Context->ST->hasPointSampleAccel() || !SIInstrInfo::isMIMG(MI))
890 return false;
891
892 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(MI.getOpcode());
893 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
895 return BaseInfo->PointSampleAccel;
896}
897
898// Return true if the subtarget enables Point Sample Acceleration, the supplied
899// MachineInstr is one to which it might be applied and the supplied interval is
900// one that has outstanding writes to vmem-types different than VMEM_NOSAMPLER
901// (this is the type that a point sample accelerated instruction effectively
902// becomes)
903bool WaitcntBrackets::hasPointSamplePendingVmemTypes(
904 const MachineInstr &MI, RegInterval Interval) const {
905 if (!hasPointSampleAccel(MI))
906 return false;
907
908 return hasOtherPendingVmemTypes(Interval, VMEM_NOSAMPLER);
909}
910
911void WaitcntBrackets::updateByEvent(const SIInstrInfo *TII,
912 const SIRegisterInfo *TRI,
913 const MachineRegisterInfo *MRI,
914 WaitEventType E, MachineInstr &Inst) {
915 InstCounterType T = eventCounter(Context->WaitEventMaskForInst, E);
916
917 unsigned UB = getScoreUB(T);
918 unsigned CurrScore = UB + 1;
919 if (CurrScore == 0)
920 report_fatal_error("InsertWaitcnt score wraparound");
921 // PendingEvents and ScoreUB need to be update regardless if this event
922 // changes the score of a register or not.
923 // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
924 PendingEvents |= 1 << E;
925 setScoreUB(T, CurrScore);
926
927 if (T == EXP_CNT) {
928 // Put score on the source vgprs. If this is a store, just use those
929 // specific register(s).
930 if (TII->isDS(Inst) && Inst.mayLoadOrStore()) {
931 // All GDS operations must protect their address register (same as
932 // export.)
933 if (const auto *AddrOp = TII->getNamedOperand(Inst, AMDGPU::OpName::addr))
934 setScoreByOperand(&Inst, TRI, MRI, *AddrOp, EXP_CNT, CurrScore);
935
936 if (Inst.mayStore()) {
937 if (const auto *Data0 =
938 TII->getNamedOperand(Inst, AMDGPU::OpName::data0))
939 setScoreByOperand(&Inst, TRI, MRI, *Data0, EXP_CNT, CurrScore);
940 if (const auto *Data1 =
941 TII->getNamedOperand(Inst, AMDGPU::OpName::data1))
942 setScoreByOperand(&Inst, TRI, MRI, *Data1, EXP_CNT, CurrScore);
943 } else if (SIInstrInfo::isAtomicRet(Inst) && !SIInstrInfo::isGWS(Inst) &&
944 Inst.getOpcode() != AMDGPU::DS_APPEND &&
945 Inst.getOpcode() != AMDGPU::DS_CONSUME &&
946 Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
947 for (const MachineOperand &Op : Inst.all_uses()) {
948 if (TRI->isVectorRegister(*MRI, Op.getReg()))
949 setScoreByOperand(&Inst, TRI, MRI, Op, EXP_CNT, CurrScore);
950 }
951 }
952 } else if (TII->isFLAT(Inst)) {
953 if (Inst.mayStore()) {
954 setScoreByOperand(&Inst, TRI, MRI,
955 *TII->getNamedOperand(Inst, AMDGPU::OpName::data),
956 EXP_CNT, CurrScore);
957 } else if (SIInstrInfo::isAtomicRet(Inst)) {
958 setScoreByOperand(&Inst, TRI, MRI,
959 *TII->getNamedOperand(Inst, AMDGPU::OpName::data),
960 EXP_CNT, CurrScore);
961 }
962 } else if (TII->isMIMG(Inst)) {
963 if (Inst.mayStore()) {
964 setScoreByOperand(&Inst, TRI, MRI, Inst.getOperand(0), EXP_CNT,
965 CurrScore);
966 } else if (SIInstrInfo::isAtomicRet(Inst)) {
967 setScoreByOperand(&Inst, TRI, MRI,
968 *TII->getNamedOperand(Inst, AMDGPU::OpName::data),
969 EXP_CNT, CurrScore);
970 }
971 } else if (TII->isMTBUF(Inst)) {
972 if (Inst.mayStore())
973 setScoreByOperand(&Inst, TRI, MRI, Inst.getOperand(0), EXP_CNT,
974 CurrScore);
975 } else if (TII->isMUBUF(Inst)) {
976 if (Inst.mayStore()) {
977 setScoreByOperand(&Inst, TRI, MRI, Inst.getOperand(0), EXP_CNT,
978 CurrScore);
979 } else if (SIInstrInfo::isAtomicRet(Inst)) {
980 setScoreByOperand(&Inst, TRI, MRI,
981 *TII->getNamedOperand(Inst, AMDGPU::OpName::data),
982 EXP_CNT, CurrScore);
983 }
984 } else if (TII->isLDSDIR(Inst)) {
985 // LDSDIR instructions attach the score to the destination.
986 setScoreByOperand(&Inst, TRI, MRI,
987 *TII->getNamedOperand(Inst, AMDGPU::OpName::vdst),
988 EXP_CNT, CurrScore);
989 } else {
990 if (TII->isEXP(Inst)) {
991 // For export the destination registers are really temps that
992 // can be used as the actual source after export patching, so
993 // we need to treat them like sources and set the EXP_CNT
994 // score.
995 for (MachineOperand &DefMO : Inst.all_defs()) {
996 if (TRI->isVGPR(*MRI, DefMO.getReg())) {
997 setScoreByOperand(&Inst, TRI, MRI, DefMO, EXP_CNT, CurrScore);
998 }
999 }
1000 }
1001 for (const MachineOperand &Op : Inst.all_uses()) {
1002 if (TRI->isVectorRegister(*MRI, Op.getReg()))
1003 setScoreByOperand(&Inst, TRI, MRI, Op, EXP_CNT, CurrScore);
1004 }
1005 }
1006 } else if (T == X_CNT) {
1007 for (const MachineOperand &Op : Inst.all_uses())
1008 setScoreByOperand(&Inst, TRI, MRI, Op, T, CurrScore);
1009 } else /* LGKM_CNT || EXP_CNT || VS_CNT || NUM_INST_CNTS */ {
1010 // Match the score to the destination registers.
1011 //
1012 // Check only explicit operands. Stores, especially spill stores, include
1013 // implicit uses and defs of their super registers which would create an
1014 // artificial dependency, while these are there only for register liveness
1015 // accounting purposes.
1016 //
1017 // Special cases where implicit register defs exists, such as M0 or VCC,
1018 // but none with memory instructions.
1019 for (const MachineOperand &Op : Inst.defs()) {
1020 RegInterval Interval = getRegInterval(&Inst, MRI, TRI, Op);
1021 if (T == LOAD_CNT || T == SAMPLE_CNT || T == BVH_CNT) {
1022 if (Interval.first >= NUM_ALL_VGPRS)
1023 continue;
1024 if (updateVMCntOnly(Inst)) {
1025 // updateVMCntOnly should only leave us with VGPRs
1026 // MUBUF, MTBUF, MIMG, FlatGlobal, and FlatScratch only have VGPR/AGPR
1027 // defs. That's required for a sane index into `VgprMemTypes` below
1028 assert(TRI->isVectorRegister(*MRI, Op.getReg()));
1029 VmemType V = getVmemType(Inst);
1030 unsigned char TypesMask = 1 << V;
1031 // If instruction can have Point Sample Accel applied, we have to flag
1032 // this with another potential dependency
1033 if (hasPointSampleAccel(Inst))
1034 TypesMask |= 1 << VMEM_NOSAMPLER;
1035 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo)
1036 VgprVmemTypes[RegNo] |= TypesMask;
1037 }
1038 }
1039 setScoreByInterval(Interval, T, CurrScore);
1040 }
1041 if (Inst.mayStore() &&
1042 (TII->isDS(Inst) || TII->mayWriteLDSThroughDMA(Inst))) {
1043 // MUBUF and FLAT LDS DMA operations need a wait on vmcnt before LDS
1044 // written can be accessed. A load from LDS to VMEM does not need a wait.
1045 unsigned Slot = 0;
1046 for (const auto *MemOp : Inst.memoperands()) {
1047 if (!MemOp->isStore() ||
1048 MemOp->getAddrSpace() != AMDGPUAS::LOCAL_ADDRESS)
1049 continue;
1050 // Comparing just AA info does not guarantee memoperands are equal
1051 // in general, but this is so for LDS DMA in practice.
1052 auto AAI = MemOp->getAAInfo();
1053 // Alias scope information gives a way to definitely identify an
1054 // original memory object and practically produced in the module LDS
1055 // lowering pass. If there is no scope available we will not be able
1056 // to disambiguate LDS aliasing as after the module lowering all LDS
1057 // is squashed into a single big object. Do not attempt to use one of
1058 // the limited LDSDMAStores for something we will not be able to use
1059 // anyway.
1060 if (!AAI || !AAI.Scope)
1061 break;
1062 for (unsigned I = 0, E = LDSDMAStores.size(); I != E && !Slot; ++I) {
1063 for (const auto *MemOp : LDSDMAStores[I]->memoperands()) {
1064 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1065 Slot = I + 1;
1066 break;
1067 }
1068 }
1069 }
1070 if (Slot || LDSDMAStores.size() == NUM_LDS_VGPRS - 1)
1071 break;
1072 LDSDMAStores.push_back(&Inst);
1073 Slot = LDSDMAStores.size();
1074 break;
1075 }
1076 setRegScore(FIRST_LDS_VGPR + Slot, T, CurrScore);
1077 if (Slot)
1078 setRegScore(FIRST_LDS_VGPR, T, CurrScore);
1079 }
1080 }
1081}
1082
1083void WaitcntBrackets::print(raw_ostream &OS) const {
1084 const GCNSubtarget *ST = Context->ST;
1085
1086 OS << '\n';
1087 for (auto T : inst_counter_types(Context->MaxCounter)) {
1088 unsigned SR = getScoreRange(T);
1089
1090 switch (T) {
1091 case LOAD_CNT:
1092 OS << " " << (ST->hasExtendedWaitCounts() ? "LOAD" : "VM") << "_CNT("
1093 << SR << "): ";
1094 break;
1095 case DS_CNT:
1096 OS << " " << (ST->hasExtendedWaitCounts() ? "DS" : "LGKM") << "_CNT("
1097 << SR << "): ";
1098 break;
1099 case EXP_CNT:
1100 OS << " EXP_CNT(" << SR << "): ";
1101 break;
1102 case STORE_CNT:
1103 OS << " " << (ST->hasExtendedWaitCounts() ? "STORE" : "VS") << "_CNT("
1104 << SR << "): ";
1105 break;
1106 case SAMPLE_CNT:
1107 OS << " SAMPLE_CNT(" << SR << "): ";
1108 break;
1109 case BVH_CNT:
1110 OS << " BVH_CNT(" << SR << "): ";
1111 break;
1112 case KM_CNT:
1113 OS << " KM_CNT(" << SR << "): ";
1114 break;
1115 case X_CNT:
1116 OS << " X_CNT(" << SR << "): ";
1117 break;
1118 default:
1119 OS << " UNKNOWN(" << SR << "): ";
1120 break;
1121 }
1122
1123 if (SR != 0) {
1124 // Print vgpr scores.
1125 unsigned LB = getScoreLB(T);
1126
1127 for (int J = 0; J <= VgprUB; J++) {
1128 unsigned RegScore = getRegScore(J, T);
1129 if (RegScore <= LB)
1130 continue;
1131 unsigned RelScore = RegScore - LB - 1;
1132 if (J < FIRST_LDS_VGPR) {
1133 OS << RelScore << ":v" << J << " ";
1134 } else {
1135 OS << RelScore << ":ds ";
1136 }
1137 }
1138 // Also need to print sgpr scores for lgkm_cnt or xcnt.
1139 if (isSmemCounter(T)) {
1140 for (int J = 0; J <= SgprUB; J++) {
1141 unsigned RegScore = getRegScore(J + NUM_ALL_VGPRS, T);
1142 if (RegScore <= LB)
1143 continue;
1144 unsigned RelScore = RegScore - LB - 1;
1145 OS << RelScore << ":s" << J << " ";
1146 }
1147 }
1148 }
1149 OS << '\n';
1150 }
1151
1152 OS << "Pending Events: ";
1153 if (hasPendingEvent()) {
1154 ListSeparator LS;
1155 for (unsigned I = 0; I != NUM_WAIT_EVENTS; ++I) {
1156 if (hasPendingEvent((WaitEventType)I)) {
1157 OS << LS << WaitEventTypeName[I];
1158 }
1159 }
1160 } else {
1161 OS << "none";
1162 }
1163 OS << '\n';
1164
1165 OS << '\n';
1166}
1167
1168/// Simplify the waitcnt, in the sense of removing redundant counts, and return
1169/// whether a waitcnt instruction is needed at all.
1170void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
1171 simplifyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1172 simplifyWaitcnt(EXP_CNT, Wait.ExpCnt);
1173 simplifyWaitcnt(DS_CNT, Wait.DsCnt);
1174 simplifyWaitcnt(STORE_CNT, Wait.StoreCnt);
1175 simplifyWaitcnt(SAMPLE_CNT, Wait.SampleCnt);
1176 simplifyWaitcnt(BVH_CNT, Wait.BvhCnt);
1177 simplifyWaitcnt(KM_CNT, Wait.KmCnt);
1178 simplifyWaitcnt(X_CNT, Wait.XCnt);
1179}
1180
1181void WaitcntBrackets::simplifyWaitcnt(InstCounterType T,
1182 unsigned &Count) const {
1183 // The number of outstanding events for this type, T, can be calculated
1184 // as (UB - LB). If the current Count is greater than or equal to the number
1185 // of outstanding events, then the wait for this counter is redundant.
1186 if (Count >= getScoreRange(T))
1187 Count = ~0u;
1188}
1189
1190void WaitcntBrackets::determineWait(InstCounterType T, RegInterval Interval,
1191 AMDGPU::Waitcnt &Wait) const {
1192 const unsigned LB = getScoreLB(T);
1193 const unsigned UB = getScoreUB(T);
1194 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
1195 unsigned ScoreToWait = getRegScore(RegNo, T);
1196
1197 // If the score of src_operand falls within the bracket, we need an
1198 // s_waitcnt instruction.
1199 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1200 if ((T == LOAD_CNT || T == DS_CNT) && hasPendingFlat() &&
1201 !Context->ST->hasFlatLgkmVMemCountInOrder()) {
1202 // If there is a pending FLAT operation, and this is a VMem or LGKM
1203 // waitcnt and the target can report early completion, then we need
1204 // to force a waitcnt 0.
1205 addWait(Wait, T, 0);
1206 } else if (counterOutOfOrder(T)) {
1207 // Counter can get decremented out-of-order when there
1208 // are multiple types event in the bracket. Also emit an s_wait counter
1209 // with a conservative value of 0 for the counter.
1210 addWait(Wait, T, 0);
1211 } else {
1212 // If a counter has been maxed out avoid overflow by waiting for
1213 // MAX(CounterType) - 1 instead.
1214 unsigned NeededWait =
1215 std::min(UB - ScoreToWait, Context->getWaitCountMax(T) - 1);
1216 addWait(Wait, T, NeededWait);
1217 }
1218 }
1219 }
1220}
1221
1222void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) {
1223 applyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1224 applyWaitcnt(EXP_CNT, Wait.ExpCnt);
1225 applyWaitcnt(DS_CNT, Wait.DsCnt);
1226 applyWaitcnt(STORE_CNT, Wait.StoreCnt);
1227 applyWaitcnt(SAMPLE_CNT, Wait.SampleCnt);
1228 applyWaitcnt(BVH_CNT, Wait.BvhCnt);
1229 applyWaitcnt(KM_CNT, Wait.KmCnt);
1230 applyXcnt(Wait);
1231}
1232
1233void WaitcntBrackets::applyWaitcnt(InstCounterType T, unsigned Count) {
1234 const unsigned UB = getScoreUB(T);
1235 if (Count >= UB)
1236 return;
1237 if (Count != 0) {
1238 if (counterOutOfOrder(T))
1239 return;
1240 setScoreLB(T, std::max(getScoreLB(T), UB - Count));
1241 } else {
1242 setScoreLB(T, UB);
1243 PendingEvents &= ~Context->WaitEventMaskForInst[T];
1244 }
1245}
1246
1247void WaitcntBrackets::applyXcnt(const AMDGPU::Waitcnt &Wait) {
1248 // Wait on XCNT is redundant if we are already waiting for a load to complete.
1249 // SMEM can return out of order, so only omit XCNT wait if we are waiting till
1250 // zero.
1251 if (Wait.KmCnt == 0 && hasPendingEvent(SMEM_GROUP))
1252 return applyWaitcnt(X_CNT, 0);
1253
1254 // If we have pending store we cannot optimize XCnt because we do not wait for
1255 // stores. VMEM loads retun in order, so if we only have loads XCnt is
1256 // decremented to the same number as LOADCnt.
1257 if (Wait.LoadCnt != ~0u && hasPendingEvent(VMEM_GROUP) &&
1258 !hasPendingEvent(STORE_CNT))
1259 return applyWaitcnt(X_CNT, std::min(Wait.XCnt, Wait.LoadCnt));
1260
1261 applyWaitcnt(X_CNT, Wait.XCnt);
1262}
1263
1264// Where there are multiple types of event in the bracket of a counter,
1265// the decrement may go out of order.
1266bool WaitcntBrackets::counterOutOfOrder(InstCounterType T) const {
1267 // Scalar memory read always can go out of order.
1268 if ((T == Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1269 (T == X_CNT && hasPendingEvent(SMEM_GROUP)))
1270 return true;
1271 return hasMixedPendingEvents(T);
1272}
1273
1274INITIALIZE_PASS_BEGIN(SIInsertWaitcntsLegacy, DEBUG_TYPE, "SI Insert Waitcnts",
1275 false, false)
1278INITIALIZE_PASS_END(SIInsertWaitcntsLegacy, DEBUG_TYPE, "SI Insert Waitcnts",
1280
1281char SIInsertWaitcntsLegacy::ID = 0;
1282
1283char &llvm::SIInsertWaitcntsID = SIInsertWaitcntsLegacy::ID;
1284
1286 return new SIInsertWaitcntsLegacy();
1287}
1288
1289static bool updateOperandIfDifferent(MachineInstr &MI, AMDGPU::OpName OpName,
1290 unsigned NewEnc) {
1291 int OpIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpName);
1292 assert(OpIdx >= 0);
1293
1294 MachineOperand &MO = MI.getOperand(OpIdx);
1295
1296 if (NewEnc == MO.getImm())
1297 return false;
1298
1299 MO.setImm(NewEnc);
1300 return true;
1301}
1302
1303/// Determine if \p MI is a gfx12+ single-counter S_WAIT_*CNT instruction,
1304/// and if so, which counter it is waiting on.
1305static std::optional<InstCounterType> counterTypeForInstr(unsigned Opcode) {
1306 switch (Opcode) {
1307 case AMDGPU::S_WAIT_LOADCNT:
1308 return LOAD_CNT;
1309 case AMDGPU::S_WAIT_EXPCNT:
1310 return EXP_CNT;
1311 case AMDGPU::S_WAIT_STORECNT:
1312 return STORE_CNT;
1313 case AMDGPU::S_WAIT_SAMPLECNT:
1314 return SAMPLE_CNT;
1315 case AMDGPU::S_WAIT_BVHCNT:
1316 return BVH_CNT;
1317 case AMDGPU::S_WAIT_DSCNT:
1318 return DS_CNT;
1319 case AMDGPU::S_WAIT_KMCNT:
1320 return KM_CNT;
1321 case AMDGPU::S_WAIT_XCNT:
1322 return X_CNT;
1323 default:
1324 return {};
1325 }
1326}
1327
1328bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt) const {
1329 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Waitcnt->getOpcode());
1330 if (Opcode == Waitcnt->getOpcode())
1331 return false;
1332
1333 Waitcnt->setDesc(TII->get(Opcode));
1334 return true;
1335}
1336
1337/// Combine consecutive S_WAITCNT and S_WAITCNT_VSCNT instructions that
1338/// precede \p It and follow \p OldWaitcntInstr and apply any extra waits
1339/// from \p Wait that were added by previous passes. Currently this pass
1340/// conservatively assumes that these preexisting waits are required for
1341/// correctness.
1342bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1343 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1344 AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
1345 assert(ST);
1346 assert(isNormalMode(MaxCounter));
1347
1348 bool Modified = false;
1349 MachineInstr *WaitcntInstr = nullptr;
1350 MachineInstr *WaitcntVsCntInstr = nullptr;
1351
1352 LLVM_DEBUG({
1353 dbgs() << "PreGFX12::applyPreexistingWaitcnt at: ";
1354 if (It == OldWaitcntInstr.getParent()->instr_end())
1355 dbgs() << "end of block\n";
1356 else
1357 dbgs() << *It;
1358 });
1359
1360 for (auto &II :
1361 make_early_inc_range(make_range(OldWaitcntInstr.getIterator(), It))) {
1362 LLVM_DEBUG(dbgs() << "pre-existing iter: " << II);
1363 if (II.isMetaInstruction()) {
1364 LLVM_DEBUG(dbgs() << "skipped meta instruction\n");
1365 continue;
1366 }
1367
1368 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
1369 bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
1370
1371 // Update required wait count. If this is a soft waitcnt (= it was added
1372 // by an earlier pass), it may be entirely removed.
1373 if (Opcode == AMDGPU::S_WAITCNT) {
1374 unsigned IEnc = II.getOperand(0).getImm();
1375 AMDGPU::Waitcnt OldWait = AMDGPU::decodeWaitcnt(IV, IEnc);
1376 if (TrySimplify)
1377 ScoreBrackets.simplifyWaitcnt(OldWait);
1378 Wait = Wait.combined(OldWait);
1379
1380 // Merge consecutive waitcnt of the same type by erasing multiples.
1381 if (WaitcntInstr || (!Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1382 II.eraseFromParent();
1383 Modified = true;
1384 } else
1385 WaitcntInstr = &II;
1386 } else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1387 assert(ST->hasVMemToLDSLoad());
1388 LLVM_DEBUG(dbgs() << "Processing S_WAITCNT_lds_direct: " << II
1389 << "Before: " << Wait.LoadCnt << '\n';);
1390 ScoreBrackets.determineWait(LOAD_CNT, FIRST_LDS_VGPR, Wait);
1391 LLVM_DEBUG(dbgs() << "After: " << Wait.LoadCnt << '\n';);
1392
1393 // It is possible (but unlikely) that this is the only wait instruction,
1394 // in which case, we exit this loop without a WaitcntInstr to consume
1395 // `Wait`. But that works because `Wait` was passed in by reference, and
1396 // the callee eventually calls createNewWaitcnt on it. We test this
1397 // possibility in an articial MIR test since such a situation cannot be
1398 // recreated by running the memory legalizer.
1399 II.eraseFromParent();
1400 } else {
1401 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1402 assert(II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1403
1404 unsigned OldVSCnt =
1405 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1406 if (TrySimplify)
1407 ScoreBrackets.simplifyWaitcnt(InstCounterType::STORE_CNT, OldVSCnt);
1408 Wait.StoreCnt = std::min(Wait.StoreCnt, OldVSCnt);
1409
1410 if (WaitcntVsCntInstr || (!Wait.hasWaitStoreCnt() && TrySimplify)) {
1411 II.eraseFromParent();
1412 Modified = true;
1413 } else
1414 WaitcntVsCntInstr = &II;
1415 }
1416 }
1417
1418 if (WaitcntInstr) {
1419 Modified |= updateOperandIfDifferent(*WaitcntInstr, AMDGPU::OpName::simm16,
1421 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1422
1423 ScoreBrackets.applyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1424 ScoreBrackets.applyWaitcnt(EXP_CNT, Wait.ExpCnt);
1425 ScoreBrackets.applyWaitcnt(DS_CNT, Wait.DsCnt);
1426 Wait.LoadCnt = ~0u;
1427 Wait.ExpCnt = ~0u;
1428 Wait.DsCnt = ~0u;
1429
1430 LLVM_DEBUG(It == WaitcntInstr->getParent()->end()
1431 ? dbgs()
1432 << "applied pre-existing waitcnt\n"
1433 << "New Instr at block end: " << *WaitcntInstr << '\n'
1434 : dbgs() << "applied pre-existing waitcnt\n"
1435 << "Old Instr: " << *It
1436 << "New Instr: " << *WaitcntInstr << '\n');
1437 }
1438
1439 if (WaitcntVsCntInstr) {
1440 Modified |= updateOperandIfDifferent(*WaitcntVsCntInstr,
1441 AMDGPU::OpName::simm16, Wait.StoreCnt);
1442 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1443
1444 ScoreBrackets.applyWaitcnt(STORE_CNT, Wait.StoreCnt);
1445 Wait.StoreCnt = ~0u;
1446
1447 LLVM_DEBUG(It == WaitcntVsCntInstr->getParent()->end()
1448 ? dbgs() << "applied pre-existing waitcnt\n"
1449 << "New Instr at block end: " << *WaitcntVsCntInstr
1450 << '\n'
1451 : dbgs() << "applied pre-existing waitcnt\n"
1452 << "Old Instr: " << *It
1453 << "New Instr: " << *WaitcntVsCntInstr << '\n');
1454 }
1455
1456 return Modified;
1457}
1458
1459/// Generate S_WAITCNT and/or S_WAITCNT_VSCNT instructions for any
1460/// required counters in \p Wait
1461bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1462 MachineBasicBlock &Block, MachineBasicBlock::instr_iterator It,
1463 AMDGPU::Waitcnt Wait) {
1464 assert(ST);
1465 assert(isNormalMode(MaxCounter));
1466
1467 bool Modified = false;
1468 const DebugLoc &DL = Block.findDebugLoc(It);
1469
1470 // Waits for VMcnt, LKGMcnt and/or EXPcnt are encoded together into a
1471 // single instruction while VScnt has its own instruction.
1472 if (Wait.hasWaitExceptStoreCnt()) {
1473 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
1474 [[maybe_unused]] auto SWaitInst =
1475 BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAITCNT)).addImm(Enc);
1476 Modified = true;
1477
1478 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1479 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1480 dbgs() << "New Instr: " << *SWaitInst << '\n');
1481 }
1482
1483 if (Wait.hasWaitStoreCnt()) {
1484 assert(ST->hasVscnt());
1485
1486 [[maybe_unused]] auto SWaitInst =
1487 BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAITCNT_VSCNT))
1488 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
1489 .addImm(Wait.StoreCnt);
1490 Modified = true;
1491
1492 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1493 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1494 dbgs() << "New Instr: " << *SWaitInst << '\n');
1495 }
1496
1497 return Modified;
1498}
1499
1500AMDGPU::Waitcnt
1501WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(bool IncludeVSCnt) const {
1502 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt && ST->hasVscnt() ? 0 : ~0u);
1503}
1504
1505AMDGPU::Waitcnt
1506WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(bool IncludeVSCnt) const {
1507 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
1508 ~0u /* XCNT */);
1509}
1510
1511/// Combine consecutive S_WAIT_*CNT instructions that precede \p It and
1512/// follow \p OldWaitcntInstr and apply any extra waits from \p Wait that
1513/// were added by previous passes. Currently this pass conservatively
1514/// assumes that these preexisting waits are required for correctness.
1515bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
1516 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1517 AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
1518 assert(ST);
1519 assert(!isNormalMode(MaxCounter));
1520
1521 bool Modified = false;
1522 MachineInstr *CombinedLoadDsCntInstr = nullptr;
1523 MachineInstr *CombinedStoreDsCntInstr = nullptr;
1524 MachineInstr *WaitInstrs[NUM_EXTENDED_INST_CNTS] = {};
1525
1526 LLVM_DEBUG({
1527 dbgs() << "GFX12Plus::applyPreexistingWaitcnt at: ";
1528 if (It == OldWaitcntInstr.getParent()->instr_end())
1529 dbgs() << "end of block\n";
1530 else
1531 dbgs() << *It;
1532 });
1533
1534 for (auto &II :
1535 make_early_inc_range(make_range(OldWaitcntInstr.getIterator(), It))) {
1536 LLVM_DEBUG(dbgs() << "pre-existing iter: " << II);
1537 if (II.isMetaInstruction()) {
1538 LLVM_DEBUG(dbgs() << "skipped meta instruction\n");
1539 continue;
1540 }
1541
1542 MachineInstr **UpdatableInstr;
1543
1544 // Update required wait count. If this is a soft waitcnt (= it was added
1545 // by an earlier pass), it may be entirely removed.
1546
1547 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
1548 bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
1549
1550 // Don't crash if the programmer used legacy waitcnt intrinsics, but don't
1551 // attempt to do more than that either.
1552 if (Opcode == AMDGPU::S_WAITCNT)
1553 continue;
1554
1555 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
1556 unsigned OldEnc =
1557 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1558 AMDGPU::Waitcnt OldWait = AMDGPU::decodeLoadcntDscnt(IV, OldEnc);
1559 if (TrySimplify)
1560 ScoreBrackets.simplifyWaitcnt(OldWait);
1561 Wait = Wait.combined(OldWait);
1562 UpdatableInstr = &CombinedLoadDsCntInstr;
1563 } else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
1564 unsigned OldEnc =
1565 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1566 AMDGPU::Waitcnt OldWait = AMDGPU::decodeStorecntDscnt(IV, OldEnc);
1567 if (TrySimplify)
1568 ScoreBrackets.simplifyWaitcnt(OldWait);
1569 Wait = Wait.combined(OldWait);
1570 UpdatableInstr = &CombinedStoreDsCntInstr;
1571 } else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1572 // Architectures higher than GFX10 do not have direct loads to
1573 // LDS, so no work required here yet.
1574 II.eraseFromParent();
1575 continue;
1576 } else {
1577 std::optional<InstCounterType> CT = counterTypeForInstr(Opcode);
1578 assert(CT.has_value());
1579 unsigned OldCnt =
1580 TII->getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1581 if (TrySimplify)
1582 ScoreBrackets.simplifyWaitcnt(CT.value(), OldCnt);
1583 addWait(Wait, CT.value(), OldCnt);
1584 UpdatableInstr = &WaitInstrs[CT.value()];
1585 }
1586
1587 // Merge consecutive waitcnt of the same type by erasing multiples.
1588 if (!*UpdatableInstr) {
1589 *UpdatableInstr = &II;
1590 } else {
1591 II.eraseFromParent();
1592 Modified = true;
1593 }
1594 }
1595
1596 if (CombinedLoadDsCntInstr) {
1597 // Only keep an S_WAIT_LOADCNT_DSCNT if both counters actually need
1598 // to be waited for. Otherwise, let the instruction be deleted so
1599 // the appropriate single counter wait instruction can be inserted
1600 // instead, when new S_WAIT_*CNT instructions are inserted by
1601 // createNewWaitcnt(). As a side effect, resetting the wait counts will
1602 // cause any redundant S_WAIT_LOADCNT or S_WAIT_DSCNT to be removed by
1603 // the loop below that deals with single counter instructions.
1604 if (Wait.LoadCnt != ~0u && Wait.DsCnt != ~0u) {
1605 unsigned NewEnc = AMDGPU::encodeLoadcntDscnt(IV, Wait);
1606 Modified |= updateOperandIfDifferent(*CombinedLoadDsCntInstr,
1607 AMDGPU::OpName::simm16, NewEnc);
1608 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
1609 ScoreBrackets.applyWaitcnt(LOAD_CNT, Wait.LoadCnt);
1610 ScoreBrackets.applyWaitcnt(DS_CNT, Wait.DsCnt);
1611 Wait.LoadCnt = ~0u;
1612 Wait.DsCnt = ~0u;
1613
1614 LLVM_DEBUG(It == OldWaitcntInstr.getParent()->end()
1615 ? dbgs() << "applied pre-existing waitcnt\n"
1616 << "New Instr at block end: "
1617 << *CombinedLoadDsCntInstr << '\n'
1618 : dbgs() << "applied pre-existing waitcnt\n"
1619 << "Old Instr: " << *It << "New Instr: "
1620 << *CombinedLoadDsCntInstr << '\n');
1621 } else {
1622 CombinedLoadDsCntInstr->eraseFromParent();
1623 Modified = true;
1624 }
1625 }
1626
1627 if (CombinedStoreDsCntInstr) {
1628 // Similarly for S_WAIT_STORECNT_DSCNT.
1629 if (Wait.StoreCnt != ~0u && Wait.DsCnt != ~0u) {
1630 unsigned NewEnc = AMDGPU::encodeStorecntDscnt(IV, Wait);
1631 Modified |= updateOperandIfDifferent(*CombinedStoreDsCntInstr,
1632 AMDGPU::OpName::simm16, NewEnc);
1633 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
1634 ScoreBrackets.applyWaitcnt(STORE_CNT, Wait.StoreCnt);
1635 ScoreBrackets.applyWaitcnt(DS_CNT, Wait.DsCnt);
1636 Wait.StoreCnt = ~0u;
1637 Wait.DsCnt = ~0u;
1638
1639 LLVM_DEBUG(It == OldWaitcntInstr.getParent()->end()
1640 ? dbgs() << "applied pre-existing waitcnt\n"
1641 << "New Instr at block end: "
1642 << *CombinedStoreDsCntInstr << '\n'
1643 : dbgs() << "applied pre-existing waitcnt\n"
1644 << "Old Instr: " << *It << "New Instr: "
1645 << *CombinedStoreDsCntInstr << '\n');
1646 } else {
1647 CombinedStoreDsCntInstr->eraseFromParent();
1648 Modified = true;
1649 }
1650 }
1651
1652 // Look for an opportunity to convert existing S_WAIT_LOADCNT,
1653 // S_WAIT_STORECNT and S_WAIT_DSCNT into new S_WAIT_LOADCNT_DSCNT
1654 // or S_WAIT_STORECNT_DSCNT. This is achieved by selectively removing
1655 // instructions so that createNewWaitcnt() will create new combined
1656 // instructions to replace them.
1657
1658 if (Wait.DsCnt != ~0u) {
1659 // This is a vector of addresses in WaitInstrs pointing to instructions
1660 // that should be removed if they are present.
1662
1663 // If it's known that both DScnt and either LOADcnt or STOREcnt (but not
1664 // both) need to be waited for, ensure that there are no existing
1665 // individual wait count instructions for these.
1666
1667 if (Wait.LoadCnt != ~0u) {
1668 WaitsToErase.push_back(&WaitInstrs[LOAD_CNT]);
1669 WaitsToErase.push_back(&WaitInstrs[DS_CNT]);
1670 } else if (Wait.StoreCnt != ~0u) {
1671 WaitsToErase.push_back(&WaitInstrs[STORE_CNT]);
1672 WaitsToErase.push_back(&WaitInstrs[DS_CNT]);
1673 }
1674
1675 for (MachineInstr **WI : WaitsToErase) {
1676 if (!*WI)
1677 continue;
1678
1679 (*WI)->eraseFromParent();
1680 *WI = nullptr;
1681 Modified = true;
1682 }
1683 }
1684
1685 for (auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1686 if (!WaitInstrs[CT])
1687 continue;
1688
1689 unsigned NewCnt = getWait(Wait, CT);
1690 if (NewCnt != ~0u) {
1691 Modified |= updateOperandIfDifferent(*WaitInstrs[CT],
1692 AMDGPU::OpName::simm16, NewCnt);
1693 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
1694
1695 ScoreBrackets.applyWaitcnt(CT, NewCnt);
1696 setNoWait(Wait, CT);
1697
1698 LLVM_DEBUG(It == OldWaitcntInstr.getParent()->end()
1699 ? dbgs() << "applied pre-existing waitcnt\n"
1700 << "New Instr at block end: " << *WaitInstrs[CT]
1701 << '\n'
1702 : dbgs() << "applied pre-existing waitcnt\n"
1703 << "Old Instr: " << *It
1704 << "New Instr: " << *WaitInstrs[CT] << '\n');
1705 } else {
1706 WaitInstrs[CT]->eraseFromParent();
1707 Modified = true;
1708 }
1709 }
1710
1711 return Modified;
1712}
1713
1714/// Generate S_WAIT_*CNT instructions for any required counters in \p Wait
1715bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
1716 MachineBasicBlock &Block, MachineBasicBlock::instr_iterator It,
1717 AMDGPU::Waitcnt Wait) {
1718 assert(ST);
1719 assert(!isNormalMode(MaxCounter));
1720
1721 bool Modified = false;
1722 const DebugLoc &DL = Block.findDebugLoc(It);
1723
1724 // Check for opportunities to use combined wait instructions.
1725 if (Wait.DsCnt != ~0u) {
1726 MachineInstr *SWaitInst = nullptr;
1727
1728 if (Wait.LoadCnt != ~0u) {
1729 unsigned Enc = AMDGPU::encodeLoadcntDscnt(IV, Wait);
1730
1731 SWaitInst = BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
1732 .addImm(Enc);
1733
1734 Wait.LoadCnt = ~0u;
1735 Wait.DsCnt = ~0u;
1736 } else if (Wait.StoreCnt != ~0u) {
1737 unsigned Enc = AMDGPU::encodeStorecntDscnt(IV, Wait);
1738
1739 SWaitInst =
1740 BuildMI(Block, It, DL, TII->get(AMDGPU::S_WAIT_STORECNT_DSCNT))
1741 .addImm(Enc);
1742
1743 Wait.StoreCnt = ~0u;
1744 Wait.DsCnt = ~0u;
1745 }
1746
1747 if (SWaitInst) {
1748 Modified = true;
1749
1750 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1751 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1752 dbgs() << "New Instr: " << *SWaitInst << '\n');
1753 }
1754 }
1755
1756 // Generate an instruction for any remaining counter that needs
1757 // waiting for.
1758
1759 for (auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
1760 unsigned Count = getWait(Wait, CT);
1761 if (Count == ~0u)
1762 continue;
1763
1764 [[maybe_unused]] auto SWaitInst =
1765 BuildMI(Block, It, DL, TII->get(instrsForExtendedCounterTypes[CT]))
1766 .addImm(Count);
1767
1768 Modified = true;
1769
1770 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
1771 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1772 dbgs() << "New Instr: " << *SWaitInst << '\n');
1773 }
1774
1775 return Modified;
1776}
1777
1778static bool readsVCCZ(const MachineInstr &MI) {
1779 unsigned Opc = MI.getOpcode();
1780 return (Opc == AMDGPU::S_CBRANCH_VCCNZ || Opc == AMDGPU::S_CBRANCH_VCCZ) &&
1781 !MI.getOperand(1).isUndef();
1782}
1783
1784/// \returns true if the callee inserts an s_waitcnt 0 on function entry.
1786 // Currently all conventions wait, but this may not always be the case.
1787 //
1788 // TODO: If IPRA is enabled, and the callee is isSafeForNoCSROpt, it may make
1789 // senses to omit the wait and do it in the caller.
1790 return true;
1791}
1792
1793/// \returns true if the callee is expected to wait for any outstanding waits
1794/// before returning.
1795static bool callWaitsOnFunctionReturn(const MachineInstr &MI) { return true; }
1796
1797/// Generate s_waitcnt instruction to be placed before cur_Inst.
1798/// Instructions of a given type are returned in order,
1799/// but instructions of different types can complete out of order.
1800/// We rely on this in-order completion
1801/// and simply assign a score to the memory access instructions.
1802/// We keep track of the active "score bracket" to determine
1803/// if an access of a memory read requires an s_waitcnt
1804/// and if so what the value of each counter is.
1805/// The "score bracket" is bound by the lower bound and upper bound
1806/// scores (*_score_LB and *_score_ub respectively).
1807/// If FlushVmCnt is true, that means that we want to generate a s_waitcnt to
1808/// flush the vmcnt counter here.
1809bool SIInsertWaitcnts::generateWaitcntInstBefore(MachineInstr &MI,
1810 WaitcntBrackets &ScoreBrackets,
1811 MachineInstr *OldWaitcntInstr,
1812 bool FlushVmCnt) {
1813 setForceEmitWaitcnt();
1814
1815 assert(!MI.isMetaInstruction());
1816
1817 AMDGPU::Waitcnt Wait;
1818
1819 // FIXME: This should have already been handled by the memory legalizer.
1820 // Removing this currently doesn't affect any lit tests, but we need to
1821 // verify that nothing was relying on this. The number of buffer invalidates
1822 // being handled here should not be expanded.
1823 if (MI.getOpcode() == AMDGPU::BUFFER_WBINVL1 ||
1824 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_SC ||
1825 MI.getOpcode() == AMDGPU::BUFFER_WBINVL1_VOL ||
1826 MI.getOpcode() == AMDGPU::BUFFER_GL0_INV ||
1827 MI.getOpcode() == AMDGPU::BUFFER_GL1_INV) {
1828 Wait.LoadCnt = 0;
1829 }
1830
1831 // All waits must be resolved at call return.
1832 // NOTE: this could be improved with knowledge of all call sites or
1833 // with knowledge of the called routines.
1834 if (MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
1835 MI.getOpcode() == AMDGPU::SI_RETURN ||
1836 MI.getOpcode() == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1837 MI.getOpcode() == AMDGPU::S_SETPC_B64_return ||
1838 (MI.isReturn() && MI.isCall() && !callWaitsOnFunctionEntry(MI))) {
1839 Wait = Wait.combined(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false));
1840 }
1841 // In dynamic VGPR mode, we want to release the VGPRs before the wave exits.
1842 // Technically the hardware will do this on its own if we don't, but that
1843 // might cost extra cycles compared to doing it explicitly.
1844 // When not in dynamic VGPR mode, identify S_ENDPGM instructions which may
1845 // have to wait for outstanding VMEM stores. In this case it can be useful to
1846 // send a message to explicitly release all VGPRs before the stores have
1847 // completed, but it is only safe to do this if there are no outstanding
1848 // scratch stores.
1849 else if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
1850 MI.getOpcode() == AMDGPU::S_ENDPGM_SAVED) {
1851 if (!WCG->isOptNone() &&
1852 (MI.getMF()->getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() ||
1853 (ST->getGeneration() >= AMDGPUSubtarget::GFX11 &&
1854 ScoreBrackets.getScoreRange(STORE_CNT) != 0 &&
1855 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS))))
1856 ReleaseVGPRInsts.insert(&MI);
1857 }
1858 // Resolve vm waits before gs-done.
1859 else if ((MI.getOpcode() == AMDGPU::S_SENDMSG ||
1860 MI.getOpcode() == AMDGPU::S_SENDMSGHALT) &&
1861 ST->hasLegacyGeometry() &&
1862 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_PreGFX11_) ==
1864 Wait.LoadCnt = 0;
1865 }
1866
1867 // Export & GDS instructions do not read the EXEC mask until after the export
1868 // is granted (which can occur well after the instruction is issued).
1869 // The shader program must flush all EXP operations on the export-count
1870 // before overwriting the EXEC mask.
1871 else {
1872 if (MI.modifiesRegister(AMDGPU::EXEC, TRI)) {
1873 // Export and GDS are tracked individually, either may trigger a waitcnt
1874 // for EXEC.
1875 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
1876 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
1877 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
1878 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
1879 Wait.ExpCnt = 0;
1880 }
1881 }
1882
1883 // Wait for any pending GDS instruction to complete before any
1884 // "Always GDS" instruction.
1885 if (TII->isAlwaysGDS(MI.getOpcode()) && ScoreBrackets.hasPendingGDS())
1886 addWait(Wait, DS_CNT, ScoreBrackets.getPendingGDSWait());
1887
1888 if (MI.isCall() && callWaitsOnFunctionEntry(MI)) {
1889 // The function is going to insert a wait on everything in its prolog.
1890 // This still needs to be careful if the call target is a load (e.g. a GOT
1891 // load). We also need to check WAW dependency with saved PC.
1892 Wait = AMDGPU::Waitcnt();
1893
1894 const auto &CallAddrOp = *TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1895 if (CallAddrOp.isReg()) {
1896 RegInterval CallAddrOpInterval =
1897 ScoreBrackets.getRegInterval(&MI, MRI, TRI, CallAddrOp);
1898
1899 ScoreBrackets.determineWait(SmemAccessCounter, CallAddrOpInterval,
1900 Wait);
1901
1902 if (const auto *RtnAddrOp =
1903 TII->getNamedOperand(MI, AMDGPU::OpName::dst)) {
1904 RegInterval RtnAddrOpInterval =
1905 ScoreBrackets.getRegInterval(&MI, MRI, TRI, *RtnAddrOp);
1906
1907 ScoreBrackets.determineWait(SmemAccessCounter, RtnAddrOpInterval,
1908 Wait);
1909 }
1910 }
1911 } else {
1912 // FIXME: Should not be relying on memoperands.
1913 // Look at the source operands of every instruction to see if
1914 // any of them results from a previous memory operation that affects
1915 // its current usage. If so, an s_waitcnt instruction needs to be
1916 // emitted.
1917 // If the source operand was defined by a load, add the s_waitcnt
1918 // instruction.
1919 //
1920 // Two cases are handled for destination operands:
1921 // 1) If the destination operand was defined by a load, add the s_waitcnt
1922 // instruction to guarantee the right WAW order.
1923 // 2) If a destination operand that was used by a recent export/store ins,
1924 // add s_waitcnt on exp_cnt to guarantee the WAR order.
1925
1926 for (const MachineMemOperand *Memop : MI.memoperands()) {
1927 const Value *Ptr = Memop->getValue();
1928 if (Memop->isStore()) {
1929 if (auto It = SLoadAddresses.find(Ptr); It != SLoadAddresses.end()) {
1930 addWait(Wait, SmemAccessCounter, 0);
1931 if (PDT->dominates(MI.getParent(), It->second))
1932 SLoadAddresses.erase(It);
1933 }
1934 }
1935 unsigned AS = Memop->getAddrSpace();
1937 continue;
1938 // No need to wait before load from VMEM to LDS.
1939 if (TII->mayWriteLDSThroughDMA(MI))
1940 continue;
1941
1942 // LOAD_CNT is only relevant to vgpr or LDS.
1943 unsigned RegNo = FIRST_LDS_VGPR;
1944 // Only objects with alias scope info were added to LDSDMAScopes array.
1945 // In the absense of the scope info we will not be able to disambiguate
1946 // aliasing here. There is no need to try searching for a corresponding
1947 // store slot. This is conservatively correct because in that case we
1948 // will produce a wait using the first (general) LDS DMA wait slot which
1949 // will wait on all of them anyway.
1950 if (Ptr && Memop->getAAInfo() && Memop->getAAInfo().Scope) {
1951 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
1952 for (unsigned I = 0, E = LDSDMAStores.size(); I != E; ++I) {
1953 if (MI.mayAlias(AA, *LDSDMAStores[I], true))
1954 ScoreBrackets.determineWait(LOAD_CNT, RegNo + I + 1, Wait);
1955 }
1956 } else {
1957 ScoreBrackets.determineWait(LOAD_CNT, RegNo, Wait);
1958 }
1959 if (Memop->isStore()) {
1960 ScoreBrackets.determineWait(EXP_CNT, RegNo, Wait);
1961 }
1962 }
1963
1964 // Loop over use and def operands.
1965 for (const MachineOperand &Op : MI.operands()) {
1966 if (!Op.isReg())
1967 continue;
1968
1969 // If the instruction does not read tied source, skip the operand.
1970 if (Op.isTied() && Op.isUse() && TII->doesNotReadTiedSource(MI))
1971 continue;
1972
1973 RegInterval Interval = ScoreBrackets.getRegInterval(&MI, MRI, TRI, Op);
1974
1975 const bool IsVGPR = TRI->isVectorRegister(*MRI, Op.getReg());
1976 if (IsVGPR) {
1977 // Implicit VGPR defs and uses are never a part of the memory
1978 // instructions description and usually present to account for
1979 // super-register liveness.
1980 // TODO: Most of the other instructions also have implicit uses
1981 // for the liveness accounting only.
1982 if (Op.isImplicit() && MI.mayLoadOrStore())
1983 continue;
1984
1985 // RAW always needs an s_waitcnt. WAW needs an s_waitcnt unless the
1986 // previous write and this write are the same type of VMEM
1987 // instruction, in which case they are (in some architectures)
1988 // guaranteed to write their results in order anyway.
1989 // Additionally check instructions where Point Sample Acceleration
1990 // might be applied.
1991 if (Op.isUse() || !updateVMCntOnly(MI) ||
1992 ScoreBrackets.hasOtherPendingVmemTypes(Interval,
1993 getVmemType(MI)) ||
1994 ScoreBrackets.hasPointSamplePendingVmemTypes(MI, Interval) ||
1995 !ST->hasVmemWriteVgprInOrder()) {
1996 ScoreBrackets.determineWait(LOAD_CNT, Interval, Wait);
1997 ScoreBrackets.determineWait(SAMPLE_CNT, Interval, Wait);
1998 ScoreBrackets.determineWait(BVH_CNT, Interval, Wait);
1999 ScoreBrackets.clearVgprVmemTypes(Interval);
2000 }
2001
2002 if (Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2003 ScoreBrackets.determineWait(EXP_CNT, Interval, Wait);
2004 }
2005 ScoreBrackets.determineWait(DS_CNT, Interval, Wait);
2006 } else {
2007 ScoreBrackets.determineWait(SmemAccessCounter, Interval, Wait);
2008 }
2009
2010 if (hasXcnt() && Op.isDef())
2011 ScoreBrackets.determineWait(X_CNT, Interval, Wait);
2012 }
2013 }
2014 }
2015
2016 // Ensure safety against exceptions from outstanding memory operations while
2017 // waiting for a barrier:
2018 //
2019 // * Some subtargets safely handle backing off the barrier in hardware
2020 // when an exception occurs.
2021 // * Some subtargets have an implicit S_WAITCNT 0 before barriers, so that
2022 // there can be no outstanding memory operations during the wait.
2023 // * Subtargets with split barriers don't need to back off the barrier; it
2024 // is up to the trap handler to preserve the user barrier state correctly.
2025 //
2026 // In all other cases, ensure safety by ensuring that there are no outstanding
2027 // memory operations.
2028 if (MI.getOpcode() == AMDGPU::S_BARRIER &&
2029 !ST->hasAutoWaitcntBeforeBarrier() && !ST->supportsBackOffBarrier()) {
2030 Wait = Wait.combined(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/true));
2031 }
2032
2033 // TODO: Remove this work-around, enable the assert for Bug 457939
2034 // after fixing the scheduler. Also, the Shader Compiler code is
2035 // independent of target.
2036 if (readsVCCZ(MI) && ST->hasReadVCCZBug()) {
2037 if (ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2038 Wait.DsCnt = 0;
2039 }
2040 }
2041
2042 // Verify that the wait is actually needed.
2043 ScoreBrackets.simplifyWaitcnt(Wait);
2044
2045 // When forcing emit, we need to skip terminators because that would break the
2046 // terminators of the MBB if we emit a waitcnt between terminators.
2047 if (ForceEmitZeroFlag && !MI.isTerminator())
2048 Wait = WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false);
2049
2050 if (ForceEmitWaitcnt[LOAD_CNT])
2051 Wait.LoadCnt = 0;
2052 if (ForceEmitWaitcnt[EXP_CNT])
2053 Wait.ExpCnt = 0;
2054 if (ForceEmitWaitcnt[DS_CNT])
2055 Wait.DsCnt = 0;
2056 if (ForceEmitWaitcnt[SAMPLE_CNT])
2057 Wait.SampleCnt = 0;
2058 if (ForceEmitWaitcnt[BVH_CNT])
2059 Wait.BvhCnt = 0;
2060 if (ForceEmitWaitcnt[KM_CNT])
2061 Wait.KmCnt = 0;
2062 if (ForceEmitWaitcnt[X_CNT])
2063 Wait.XCnt = 0;
2064
2065 if (FlushVmCnt) {
2066 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2067 Wait.LoadCnt = 0;
2068 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2069 Wait.SampleCnt = 0;
2070 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2071 Wait.BvhCnt = 0;
2072 }
2073
2074 if (ForceEmitZeroLoadFlag && Wait.LoadCnt != ~0u)
2075 Wait.LoadCnt = 0;
2076
2077 return generateWaitcnt(Wait, MI.getIterator(), *MI.getParent(), ScoreBrackets,
2078 OldWaitcntInstr);
2079}
2080
2081bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt Wait,
2083 MachineBasicBlock &Block,
2084 WaitcntBrackets &ScoreBrackets,
2085 MachineInstr *OldWaitcntInstr) {
2086 bool Modified = false;
2087
2088 if (OldWaitcntInstr)
2089 // Try to merge the required wait with preexisting waitcnt instructions.
2090 // Also erase redundant waitcnt.
2091 Modified =
2092 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr, Wait, It);
2093
2094 // Any counts that could have been applied to any existing waitcnt
2095 // instructions will have been done so, now deal with any remaining.
2096 ScoreBrackets.applyWaitcnt(Wait);
2097
2098 // ExpCnt can be merged into VINTERP.
2099 if (Wait.ExpCnt != ~0u && It != Block.instr_end() &&
2101 MachineOperand *WaitExp =
2102 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2103 if (Wait.ExpCnt < WaitExp->getImm()) {
2104 WaitExp->setImm(Wait.ExpCnt);
2105 Modified = true;
2106 }
2107 Wait.ExpCnt = ~0u;
2108
2109 LLVM_DEBUG(dbgs() << "generateWaitcnt\n"
2110 << "Update Instr: " << *It);
2111 }
2112
2113 // XCnt may be already consumed by a load wait.
2114 if (Wait.KmCnt == 0 && Wait.XCnt != ~0u &&
2115 !ScoreBrackets.hasPendingEvent(SMEM_GROUP))
2116 Wait.XCnt = ~0u;
2117
2118 if (Wait.LoadCnt == 0 && Wait.XCnt != ~0u &&
2119 !ScoreBrackets.hasPendingEvent(VMEM_GROUP))
2120 Wait.XCnt = ~0u;
2121
2122 // Since the translation for VMEM addresses occur in-order, we can skip the
2123 // XCnt if the current instruction is of VMEM type and has a memory dependency
2124 // with another VMEM instruction in flight.
2125 if (Wait.XCnt != ~0u && isVmemAccess(*It))
2126 Wait.XCnt = ~0u;
2127
2128 if (WCG->createNewWaitcnt(Block, It, Wait))
2129 Modified = true;
2130
2131 return Modified;
2132}
2133
2134// This is a flat memory operation. Check to see if it has memory tokens other
2135// than LDS. Other address spaces supported by flat memory operations involve
2136// global memory.
2137bool SIInsertWaitcnts::mayAccessVMEMThroughFlat(const MachineInstr &MI) const {
2138 assert(TII->isFLAT(MI));
2139
2140 // All flat instructions use the VMEM counter except prefetch.
2141 if (!TII->usesVM_CNT(MI))
2142 return false;
2143
2144 // If there are no memory operands then conservatively assume the flat
2145 // operation may access VMEM.
2146 if (MI.memoperands_empty())
2147 return true;
2148
2149 // See if any memory operand specifies an address space that involves VMEM.
2150 // Flat operations only supported FLAT, LOCAL (LDS), or address spaces
2151 // involving VMEM such as GLOBAL, CONSTANT, PRIVATE (SCRATCH), etc. The REGION
2152 // (GDS) address space is not supported by flat operations. Therefore, simply
2153 // return true unless only the LDS address space is found.
2154 for (const MachineMemOperand *Memop : MI.memoperands()) {
2155 unsigned AS = Memop->getAddrSpace();
2157 if (AS != AMDGPUAS::LOCAL_ADDRESS)
2158 return true;
2159 }
2160
2161 return false;
2162}
2163
2164// This is a flat memory operation. Check to see if it has memory tokens for
2165// either LDS or FLAT.
2166bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
2167 assert(TII->isFLAT(MI));
2168
2169 // Flat instruction such as SCRATCH and GLOBAL do not use the lgkm counter.
2170 if (!TII->usesLGKM_CNT(MI))
2171 return false;
2172
2173 // If in tgsplit mode then there can be no use of LDS.
2174 if (ST->isTgSplitEnabled())
2175 return false;
2176
2177 // If there are no memory operands then conservatively assume the flat
2178 // operation may access LDS.
2179 if (MI.memoperands_empty())
2180 return true;
2181
2182 // See if any memory operand specifies an address space that involves LDS.
2183 for (const MachineMemOperand *Memop : MI.memoperands()) {
2184 unsigned AS = Memop->getAddrSpace();
2186 return true;
2187 }
2188
2189 return false;
2190}
2191
2192bool SIInsertWaitcnts::isVmemAccess(const MachineInstr &MI) const {
2193 return (TII->isFLAT(MI) && mayAccessVMEMThroughFlat(MI)) ||
2194 (TII->isVMEM(MI) && !AMDGPU::getMUBUFIsBufferInv(MI.getOpcode()));
2195}
2196
2198 auto Opc = Inst.getOpcode();
2199 return Opc == AMDGPU::GLOBAL_INV || Opc == AMDGPU::GLOBAL_WB ||
2200 Opc == AMDGPU::GLOBAL_WBINV;
2201}
2202
2203// Return true if the next instruction is S_ENDPGM, following fallthrough
2204// blocks if necessary.
2205bool SIInsertWaitcnts::isNextENDPGM(MachineBasicBlock::instr_iterator It,
2206 MachineBasicBlock *Block) const {
2207 auto BlockEnd = Block->getParent()->end();
2208 auto BlockIter = Block->getIterator();
2209
2210 while (true) {
2211 if (It.isEnd()) {
2212 if (++BlockIter != BlockEnd) {
2213 It = BlockIter->instr_begin();
2214 continue;
2215 }
2216
2217 return false;
2218 }
2219
2220 if (!It->isMetaInstruction())
2221 break;
2222
2223 It++;
2224 }
2225
2226 assert(!It.isEnd());
2227
2228 return It->getOpcode() == AMDGPU::S_ENDPGM;
2229}
2230
2231// Add a wait after an instruction if architecture requirements mandate one.
2232bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2233 MachineBasicBlock &Block,
2234 WaitcntBrackets &ScoreBrackets) {
2235 AMDGPU::Waitcnt Wait;
2236 bool NeedsEndPGMCheck = false;
2237
2238 if (ST->isPreciseMemoryEnabled() && Inst.mayLoadOrStore())
2239 Wait = WCG->getAllZeroWaitcnt(Inst.mayStore() &&
2241
2242 if (TII->isAlwaysGDS(Inst.getOpcode())) {
2243 Wait.DsCnt = 0;
2244 NeedsEndPGMCheck = true;
2245 }
2246
2247 ScoreBrackets.simplifyWaitcnt(Wait);
2248
2249 auto SuccessorIt = std::next(Inst.getIterator());
2250 bool Result = generateWaitcnt(Wait, SuccessorIt, Block, ScoreBrackets,
2251 /*OldWaitcntInstr=*/nullptr);
2252
2253 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &Block)) {
2254 BuildMI(Block, SuccessorIt, Inst.getDebugLoc(), TII->get(AMDGPU::S_NOP))
2255 .addImm(0);
2256 }
2257
2258 return Result;
2259}
2260
2261void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2262 WaitcntBrackets *ScoreBrackets) {
2263 // Now look at the instruction opcode. If it is a memory access
2264 // instruction, update the upper-bound of the appropriate counter's
2265 // bracket and the destination operand scores.
2266 // TODO: Use the (TSFlags & SIInstrFlags::DS_CNT) property everywhere.
2267
2268 bool IsVMEMAccess = false;
2269 bool IsSMEMAccess = false;
2270 if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
2271 if (TII->isAlwaysGDS(Inst.getOpcode()) ||
2272 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2273 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
2274 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
2275 ScoreBrackets->setPendingGDS();
2276 } else {
2277 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
2278 }
2279 } else if (TII->isFLAT(Inst)) {
2280 if (isGFX12CacheInvOrWBInst(Inst)) {
2281 ScoreBrackets->updateByEvent(TII, TRI, MRI, getVmemWaitEventType(Inst),
2282 Inst);
2283 return;
2284 }
2285
2286 assert(Inst.mayLoadOrStore());
2287
2288 int FlatASCount = 0;
2289
2290 if (mayAccessVMEMThroughFlat(Inst)) {
2291 ++FlatASCount;
2292 IsVMEMAccess = true;
2293 ScoreBrackets->updateByEvent(TII, TRI, MRI, getVmemWaitEventType(Inst),
2294 Inst);
2295 }
2296
2297 if (mayAccessLDSThroughFlat(Inst)) {
2298 ++FlatASCount;
2299 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
2300 }
2301
2302 // This is a flat memory operation that access both VMEM and LDS, so note it
2303 // - it will require that both the VM and LGKM be flushed to zero if it is
2304 // pending when a VM or LGKM dependency occurs.
2305 if (FlatASCount > 1)
2306 ScoreBrackets->setPendingFlat();
2307 } else if (SIInstrInfo::isVMEM(Inst) &&
2309 IsVMEMAccess = true;
2310 ScoreBrackets->updateByEvent(TII, TRI, MRI, getVmemWaitEventType(Inst),
2311 Inst);
2312
2313 if (ST->vmemWriteNeedsExpWaitcnt() &&
2314 (Inst.mayStore() || SIInstrInfo::isAtomicRet(Inst))) {
2315 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
2316 }
2317 } else if (TII->isSMRD(Inst)) {
2318 IsSMEMAccess = true;
2319 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
2320 } else if (Inst.isCall()) {
2321 if (callWaitsOnFunctionReturn(Inst)) {
2322 // Act as a wait on everything
2323 ScoreBrackets->applyWaitcnt(
2324 WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false));
2325 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2326 } else {
2327 // May need to way wait for anything.
2328 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2329 }
2330 } else if (SIInstrInfo::isLDSDIR(Inst)) {
2331 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_LDS_ACCESS, Inst);
2332 } else if (TII->isVINTERP(Inst)) {
2333 int64_t Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2334 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2335 } else if (SIInstrInfo::isEXP(Inst)) {
2336 unsigned Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2338 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
2339 else if (Imm >= AMDGPU::Exp::ET_POS0 && Imm <= AMDGPU::Exp::ET_POS_LAST)
2340 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
2341 else
2342 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
2343 } else {
2344 switch (Inst.getOpcode()) {
2345 case AMDGPU::S_SENDMSG:
2346 case AMDGPU::S_SENDMSG_RTN_B32:
2347 case AMDGPU::S_SENDMSG_RTN_B64:
2348 case AMDGPU::S_SENDMSGHALT:
2349 ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
2350 break;
2351 case AMDGPU::S_MEMTIME:
2352 case AMDGPU::S_MEMREALTIME:
2353 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_M0:
2354 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM:
2355 case AMDGPU::S_BARRIER_LEAVE:
2356 case AMDGPU::S_GET_BARRIER_STATE_M0:
2357 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2358 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
2359 break;
2360 }
2361 }
2362
2363 if (!hasXcnt())
2364 return;
2365
2366 if (IsVMEMAccess)
2367 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_GROUP, Inst);
2368
2369 if (IsSMEMAccess)
2370 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_GROUP, Inst);
2371}
2372
2373bool WaitcntBrackets::mergeScore(const MergeInfo &M, unsigned &Score,
2374 unsigned OtherScore) {
2375 unsigned MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
2376 unsigned OtherShifted =
2377 OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
2378 Score = std::max(MyShifted, OtherShifted);
2379 return OtherShifted > MyShifted;
2380}
2381
2382/// Merge the pending events and associater score brackets of \p Other into
2383/// this brackets status.
2384///
2385/// Returns whether the merge resulted in a change that requires tighter waits
2386/// (i.e. the merged brackets strictly dominate the original brackets).
2387bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
2388 bool StrictDom = false;
2389
2390 VgprUB = std::max(VgprUB, Other.VgprUB);
2391 SgprUB = std::max(SgprUB, Other.SgprUB);
2392
2393 for (auto T : inst_counter_types(Context->MaxCounter)) {
2394 // Merge event flags for this counter
2395 const unsigned *WaitEventMaskForInst = Context->WaitEventMaskForInst;
2396 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[T];
2397 const unsigned OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T];
2398 if (OtherEvents & ~OldEvents)
2399 StrictDom = true;
2400 PendingEvents |= OtherEvents;
2401
2402 // Merge scores for this counter
2403 const unsigned MyPending = ScoreUBs[T] - ScoreLBs[T];
2404 const unsigned OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
2405 const unsigned NewUB = ScoreLBs[T] + std::max(MyPending, OtherPending);
2406 if (NewUB < ScoreLBs[T])
2407 report_fatal_error("waitcnt score overflow");
2408
2409 MergeInfo M;
2410 M.OldLB = ScoreLBs[T];
2411 M.OtherLB = Other.ScoreLBs[T];
2412 M.MyShift = NewUB - ScoreUBs[T];
2413 M.OtherShift = NewUB - Other.ScoreUBs[T];
2414
2415 ScoreUBs[T] = NewUB;
2416
2417 StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
2418
2419 if (T == DS_CNT)
2420 StrictDom |= mergeScore(M, LastGDS, Other.LastGDS);
2421
2422 for (int J = 0; J <= VgprUB; J++)
2423 StrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]);
2424
2425 if (isSmemCounter(T)) {
2426 unsigned Idx = getSgprScoresIdx(T);
2427 for (int J = 0; J <= SgprUB; J++)
2428 StrictDom |=
2429 mergeScore(M, SgprScores[Idx][J], Other.SgprScores[Idx][J]);
2430 }
2431 }
2432
2433 for (int J = 0; J <= VgprUB; J++) {
2434 unsigned char NewVmemTypes = VgprVmemTypes[J] | Other.VgprVmemTypes[J];
2435 StrictDom |= NewVmemTypes != VgprVmemTypes[J];
2436 VgprVmemTypes[J] = NewVmemTypes;
2437 }
2438
2439 return StrictDom;
2440}
2441
2442static bool isWaitInstr(MachineInstr &Inst) {
2443 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Inst.getOpcode());
2444 return Opcode == AMDGPU::S_WAITCNT ||
2445 (Opcode == AMDGPU::S_WAITCNT_VSCNT && Inst.getOperand(0).isReg() &&
2446 Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL) ||
2447 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2448 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2449 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2450 counterTypeForInstr(Opcode).has_value();
2451}
2452
2453// Generate s_waitcnt instructions where needed.
2454bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2455 MachineBasicBlock &Block,
2456 WaitcntBrackets &ScoreBrackets) {
2457 bool Modified = false;
2458
2459 LLVM_DEBUG({
2460 dbgs() << "*** Begin Block: ";
2461 Block.printName(dbgs());
2462 ScoreBrackets.dump();
2463 });
2464
2465 // Track the correctness of vccz through this basic block. There are two
2466 // reasons why it might be incorrect; see ST->hasReadVCCZBug() and
2467 // ST->partialVCCWritesUpdateVCCZ().
2468 bool VCCZCorrect = true;
2469 if (ST->hasReadVCCZBug()) {
2470 // vccz could be incorrect at a basic block boundary if a predecessor wrote
2471 // to vcc and then issued an smem load.
2472 VCCZCorrect = false;
2473 } else if (!ST->partialVCCWritesUpdateVCCZ()) {
2474 // vccz could be incorrect at a basic block boundary if a predecessor wrote
2475 // to vcc_lo or vcc_hi.
2476 VCCZCorrect = false;
2477 }
2478
2479 // Walk over the instructions.
2480 MachineInstr *OldWaitcntInstr = nullptr;
2481
2482 for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(),
2483 E = Block.instr_end();
2484 Iter != E;) {
2485 MachineInstr &Inst = *Iter;
2486 if (Inst.isMetaInstruction()) {
2487 ++Iter;
2488 continue;
2489 }
2490
2491 // Track pre-existing waitcnts that were added in earlier iterations or by
2492 // the memory legalizer.
2493 if (isWaitInstr(Inst)) {
2494 if (!OldWaitcntInstr)
2495 OldWaitcntInstr = &Inst;
2496 ++Iter;
2497 continue;
2498 }
2499
2500 bool FlushVmCnt = Block.getFirstTerminator() == Inst &&
2501 isPreheaderToFlush(Block, ScoreBrackets);
2502
2503 // Generate an s_waitcnt instruction to be placed before Inst, if needed.
2504 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2505 FlushVmCnt);
2506 OldWaitcntInstr = nullptr;
2507
2508 // Restore vccz if it's not known to be correct already.
2509 bool RestoreVCCZ = !VCCZCorrect && readsVCCZ(Inst);
2510
2511 // Don't examine operands unless we need to track vccz correctness.
2512 if (ST->hasReadVCCZBug() || !ST->partialVCCWritesUpdateVCCZ()) {
2513 if (Inst.definesRegister(AMDGPU::VCC_LO, /*TRI=*/nullptr) ||
2514 Inst.definesRegister(AMDGPU::VCC_HI, /*TRI=*/nullptr)) {
2515 // Up to gfx9, writes to vcc_lo and vcc_hi don't update vccz.
2516 if (!ST->partialVCCWritesUpdateVCCZ())
2517 VCCZCorrect = false;
2518 } else if (Inst.definesRegister(AMDGPU::VCC, /*TRI=*/nullptr)) {
2519 // There is a hardware bug on CI/SI where SMRD instruction may corrupt
2520 // vccz bit, so when we detect that an instruction may read from a
2521 // corrupt vccz bit, we need to:
2522 // 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD
2523 // operations to complete.
2524 // 2. Restore the correct value of vccz by writing the current value
2525 // of vcc back to vcc.
2526 if (ST->hasReadVCCZBug() &&
2527 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2528 // Writes to vcc while there's an outstanding smem read may get
2529 // clobbered as soon as any read completes.
2530 VCCZCorrect = false;
2531 } else {
2532 // Writes to vcc will fix any incorrect value in vccz.
2533 VCCZCorrect = true;
2534 }
2535 }
2536 }
2537
2538 if (TII->isSMRD(Inst)) {
2539 for (const MachineMemOperand *Memop : Inst.memoperands()) {
2540 // No need to handle invariant loads when avoiding WAR conflicts, as
2541 // there cannot be a vector store to the same memory location.
2542 if (!Memop->isInvariant()) {
2543 const Value *Ptr = Memop->getValue();
2544 SLoadAddresses.insert(std::pair(Ptr, Inst.getParent()));
2545 }
2546 }
2547 if (ST->hasReadVCCZBug()) {
2548 // This smem read could complete and clobber vccz at any time.
2549 VCCZCorrect = false;
2550 }
2551 }
2552
2553 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2554
2555 Modified |= insertForcedWaitAfter(Inst, Block, ScoreBrackets);
2556
2557 LLVM_DEBUG({
2558 Inst.print(dbgs());
2559 ScoreBrackets.dump();
2560 });
2561
2562 // TODO: Remove this work-around after fixing the scheduler and enable the
2563 // assert above.
2564 if (RestoreVCCZ) {
2565 // Restore the vccz bit. Any time a value is written to vcc, the vcc
2566 // bit is updated, so we can restore the bit by reading the value of
2567 // vcc and then writing it back to the register.
2568 BuildMI(Block, Inst, Inst.getDebugLoc(),
2569 TII->get(ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2570 TRI->getVCC())
2571 .addReg(TRI->getVCC());
2572 VCCZCorrect = true;
2573 Modified = true;
2574 }
2575
2576 ++Iter;
2577 }
2578
2579 // Flush the LOADcnt, SAMPLEcnt and BVHcnt counters at the end of the block if
2580 // needed.
2581 AMDGPU::Waitcnt Wait;
2582 if (Block.getFirstTerminator() == Block.end() &&
2583 isPreheaderToFlush(Block, ScoreBrackets)) {
2584 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2585 Wait.LoadCnt = 0;
2586 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2587 Wait.SampleCnt = 0;
2588 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2589 Wait.BvhCnt = 0;
2590 }
2591
2592 // Combine or remove any redundant waitcnts at the end of the block.
2593 Modified |= generateWaitcnt(Wait, Block.instr_end(), Block, ScoreBrackets,
2594 OldWaitcntInstr);
2595
2596 LLVM_DEBUG({
2597 dbgs() << "*** End Block: ";
2598 Block.printName(dbgs());
2599 ScoreBrackets.dump();
2600 });
2601
2602 return Modified;
2603}
2604
2605// Return true if the given machine basic block is a preheader of a loop in
2606// which we want to flush the vmcnt counter, and false otherwise.
2607bool SIInsertWaitcnts::isPreheaderToFlush(
2608 MachineBasicBlock &MBB, const WaitcntBrackets &ScoreBrackets) {
2609 auto [Iterator, IsInserted] = PreheadersToFlush.try_emplace(&MBB, false);
2610 if (!IsInserted)
2611 return Iterator->second;
2612
2613 MachineBasicBlock *Succ = MBB.getSingleSuccessor();
2614 if (!Succ)
2615 return false;
2616
2617 MachineLoop *Loop = MLI->getLoopFor(Succ);
2618 if (!Loop)
2619 return false;
2620
2621 if (Loop->getLoopPreheader() == &MBB &&
2622 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2623 Iterator->second = true;
2624 return true;
2625 }
2626
2627 return false;
2628}
2629
2630bool SIInsertWaitcnts::isVMEMOrFlatVMEM(const MachineInstr &MI) const {
2632 return mayAccessVMEMThroughFlat(MI);
2633 return SIInstrInfo::isVMEM(MI);
2634}
2635
2636// Return true if it is better to flush the vmcnt counter in the preheader of
2637// the given loop. We currently decide to flush in two situations:
2638// 1. The loop contains vmem store(s), no vmem load and at least one use of a
2639// vgpr containing a value that is loaded outside of the loop. (Only on
2640// targets with no vscnt counter).
2641// 2. The loop contains vmem load(s), but the loaded values are not used in the
2642// loop, and at least one use of a vgpr containing a value that is loaded
2643// outside of the loop.
2644bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *ML,
2645 const WaitcntBrackets &Brackets) {
2646 bool HasVMemLoad = false;
2647 bool HasVMemStore = false;
2648 bool UsesVgprLoadedOutside = false;
2649 DenseSet<Register> VgprUse;
2650 DenseSet<Register> VgprDef;
2651
2652 for (MachineBasicBlock *MBB : ML->blocks()) {
2653 for (MachineInstr &MI : *MBB) {
2654 if (isVMEMOrFlatVMEM(MI)) {
2655 if (MI.mayLoad())
2656 HasVMemLoad = true;
2657 if (MI.mayStore())
2658 HasVMemStore = true;
2659 }
2660 for (const MachineOperand &Op : MI.all_uses()) {
2661 if (!TRI->isVectorRegister(*MRI, Op.getReg()))
2662 continue;
2663 RegInterval Interval = Brackets.getRegInterval(&MI, MRI, TRI, Op);
2664 // Vgpr use
2665 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
2666 // If we find a register that is loaded inside the loop, 1. and 2.
2667 // are invalidated and we can exit.
2668 if (VgprDef.contains(RegNo))
2669 return false;
2670 VgprUse.insert(RegNo);
2671 // If at least one of Op's registers is in the score brackets, the
2672 // value is likely loaded outside of the loop.
2673 if (Brackets.getRegScore(RegNo, LOAD_CNT) >
2674 Brackets.getScoreLB(LOAD_CNT) ||
2675 Brackets.getRegScore(RegNo, SAMPLE_CNT) >
2676 Brackets.getScoreLB(SAMPLE_CNT) ||
2677 Brackets.getRegScore(RegNo, BVH_CNT) >
2678 Brackets.getScoreLB(BVH_CNT)) {
2679 UsesVgprLoadedOutside = true;
2680 break;
2681 }
2682 }
2683 }
2684
2685 // VMem load vgpr def
2686 if (isVMEMOrFlatVMEM(MI) && MI.mayLoad()) {
2687 for (const MachineOperand &Op : MI.all_defs()) {
2688 RegInterval Interval = Brackets.getRegInterval(&MI, MRI, TRI, Op);
2689 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
2690 // If we find a register that is loaded inside the loop, 1. and 2.
2691 // are invalidated and we can exit.
2692 if (VgprUse.contains(RegNo))
2693 return false;
2694 VgprDef.insert(RegNo);
2695 }
2696 }
2697 }
2698 }
2699 }
2700 if (!ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2701 return true;
2702 return HasVMemLoad && UsesVgprLoadedOutside && ST->hasVmemWriteVgprInOrder();
2703}
2704
2705bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2706 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2707 auto *PDT =
2708 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2709 AliasAnalysis *AA = nullptr;
2710 if (auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2711 AA = &AAR->getAAResults();
2712
2713 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2714}
2715
2716PreservedAnalyses
2719 auto *MLI = &MFAM.getResult<MachineLoopAnalysis>(MF);
2720 auto *PDT = &MFAM.getResult<MachinePostDominatorTreeAnalysis>(MF);
2722 .getManager()
2723 .getCachedResult<AAManager>(MF.getFunction());
2724
2725 if (!SIInsertWaitcnts(MLI, PDT, AA).run(MF))
2726 return PreservedAnalyses::all();
2727
2730 .preserve<AAManager>();
2731}
2732
2733bool SIInsertWaitcnts::run(MachineFunction &MF) {
2734 ST = &MF.getSubtarget<GCNSubtarget>();
2735 TII = ST->getInstrInfo();
2736 TRI = &TII->getRegisterInfo();
2737 MRI = &MF.getRegInfo();
2739
2741
2742 if (ST->hasExtendedWaitCounts()) {
2743 MaxCounter = NUM_EXTENDED_INST_CNTS;
2744 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2745 WCG = &WCGGFX12Plus;
2746 } else {
2747 MaxCounter = NUM_NORMAL_INST_CNTS;
2748 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF);
2749 WCG = &WCGPreGFX12;
2750 }
2751
2752 for (auto T : inst_counter_types())
2753 ForceEmitWaitcnt[T] = false;
2754
2755 WaitEventMaskForInst = WCG->getWaitEventMask();
2756
2757 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2758
2759 if (ST->hasExtendedWaitCounts()) {
2760 Limits.LoadcntMax = AMDGPU::getLoadcntBitMask(IV);
2761 Limits.DscntMax = AMDGPU::getDscntBitMask(IV);
2762 } else {
2763 Limits.LoadcntMax = AMDGPU::getVmcntBitMask(IV);
2764 Limits.DscntMax = AMDGPU::getLgkmcntBitMask(IV);
2765 }
2766 Limits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
2767 Limits.StorecntMax = AMDGPU::getStorecntBitMask(IV);
2768 Limits.SamplecntMax = AMDGPU::getSamplecntBitMask(IV);
2769 Limits.BvhcntMax = AMDGPU::getBvhcntBitMask(IV);
2770 Limits.KmcntMax = AMDGPU::getKmcntBitMask(IV);
2771 Limits.XcntMax = AMDGPU::getXcntBitMask(IV);
2772
2773 [[maybe_unused]] unsigned NumVGPRsMax =
2774 ST->getAddressableNumVGPRs(MFI->getDynamicVGPRBlockSize());
2775 [[maybe_unused]] unsigned NumSGPRsMax = ST->getAddressableNumSGPRs();
2776 assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
2777 assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
2778
2779 BlockInfos.clear();
2780 bool Modified = false;
2781
2782 MachineBasicBlock &EntryBB = MF.front();
2784
2785 if (!MFI->isEntryFunction()) {
2786 // Wait for any outstanding memory operations that the input registers may
2787 // depend on. We can't track them and it's better to do the wait after the
2788 // costly call sequence.
2789
2790 // TODO: Could insert earlier and schedule more liberally with operations
2791 // that only use caller preserved registers.
2792 for (MachineBasicBlock::iterator E = EntryBB.end();
2793 I != E && (I->isPHI() || I->isMetaInstruction()); ++I)
2794 ;
2795
2796 if (ST->hasExtendedWaitCounts()) {
2797 BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
2798 .addImm(0);
2799 for (auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2800 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2801 continue;
2802
2803 if (!ST->hasImageInsts() &&
2804 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2805 continue;
2806
2807 BuildMI(EntryBB, I, DebugLoc(),
2808 TII->get(instrsForExtendedCounterTypes[CT]))
2809 .addImm(0);
2810 }
2811 } else {
2812 BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT)).addImm(0);
2813 }
2814
2815 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(this);
2816 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2817 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2818
2819 Modified = true;
2820 }
2821
2822 // Keep iterating over the blocks in reverse post order, inserting and
2823 // updating s_waitcnt where needed, until a fix point is reached.
2824 for (auto *MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2825 BlockInfos.try_emplace(MBB);
2826
2827 std::unique_ptr<WaitcntBrackets> Brackets;
2828 bool Repeat;
2829 do {
2830 Repeat = false;
2831
2832 for (auto BII = BlockInfos.begin(), BIE = BlockInfos.end(); BII != BIE;
2833 ++BII) {
2834 MachineBasicBlock *MBB = BII->first;
2835 BlockInfo &BI = BII->second;
2836 if (!BI.Dirty)
2837 continue;
2838
2839 if (BI.Incoming) {
2840 if (!Brackets)
2841 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2842 else
2843 *Brackets = *BI.Incoming;
2844 } else {
2845 if (!Brackets) {
2846 Brackets = std::make_unique<WaitcntBrackets>(this);
2847 } else {
2848 // Reinitialize in-place. N.B. do not do this by assigning from a
2849 // temporary because the WaitcntBrackets class is large and it could
2850 // cause this function to use an unreasonable amount of stack space.
2851 Brackets->~WaitcntBrackets();
2852 new (Brackets.get()) WaitcntBrackets(this);
2853 }
2854 }
2855
2856 Modified |= insertWaitcntInBlock(MF, *MBB, *Brackets);
2857 BI.Dirty = false;
2858
2859 if (Brackets->hasPendingEvent()) {
2860 BlockInfo *MoveBracketsToSucc = nullptr;
2861 for (MachineBasicBlock *Succ : MBB->successors()) {
2862 auto *SuccBII = BlockInfos.find(Succ);
2863 BlockInfo &SuccBI = SuccBII->second;
2864 if (!SuccBI.Incoming) {
2865 SuccBI.Dirty = true;
2866 if (SuccBII <= BII) {
2867 LLVM_DEBUG(dbgs() << "repeat on backedge\n");
2868 Repeat = true;
2869 }
2870 if (!MoveBracketsToSucc) {
2871 MoveBracketsToSucc = &SuccBI;
2872 } else {
2873 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2874 }
2875 } else if (SuccBI.Incoming->merge(*Brackets)) {
2876 SuccBI.Dirty = true;
2877 if (SuccBII <= BII) {
2878 LLVM_DEBUG(dbgs() << "repeat on backedge\n");
2879 Repeat = true;
2880 }
2881 }
2882 }
2883 if (MoveBracketsToSucc)
2884 MoveBracketsToSucc->Incoming = std::move(Brackets);
2885 }
2886 }
2887 } while (Repeat);
2888
2889 if (ST->hasScalarStores()) {
2890 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2891 bool HaveScalarStores = false;
2892
2893 for (MachineBasicBlock &MBB : MF) {
2894 for (MachineInstr &MI : MBB) {
2895 if (!HaveScalarStores && TII->isScalarStore(MI))
2896 HaveScalarStores = true;
2897
2898 if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
2899 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2900 EndPgmBlocks.push_back(&MBB);
2901 }
2902 }
2903
2904 if (HaveScalarStores) {
2905 // If scalar writes are used, the cache must be flushed or else the next
2906 // wave to reuse the same scratch memory can be clobbered.
2907 //
2908 // Insert s_dcache_wb at wave termination points if there were any scalar
2909 // stores, and only if the cache hasn't already been flushed. This could
2910 // be improved by looking across blocks for flushes in postdominating
2911 // blocks from the stores but an explicitly requested flush is probably
2912 // very rare.
2913 for (MachineBasicBlock *MBB : EndPgmBlocks) {
2914 bool SeenDCacheWB = false;
2915
2916 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
2917 I != E; ++I) {
2918 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
2919 SeenDCacheWB = true;
2920 else if (TII->isScalarStore(*I))
2921 SeenDCacheWB = false;
2922
2923 // FIXME: It would be better to insert this before a waitcnt if any.
2924 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
2925 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2926 !SeenDCacheWB) {
2927 Modified = true;
2928 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
2929 }
2930 }
2931 }
2932 }
2933 }
2934
2935 // Deallocate the VGPRs before previously identified S_ENDPGM instructions.
2936 // This is done in different ways depending on how the VGPRs were allocated
2937 // (i.e. whether we're in dynamic VGPR mode or not).
2938 // Skip deallocation if kernel is waveslot limited vs VGPR limited. A short
2939 // waveslot limited kernel runs slower with the deallocation.
2940 if (MFI->isDynamicVGPREnabled()) {
2941 for (MachineInstr *MI : ReleaseVGPRInsts) {
2942 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2943 TII->get(AMDGPU::S_ALLOC_VGPR))
2944 .addImm(0);
2945 Modified = true;
2946 }
2947 } else {
2948 if (!ReleaseVGPRInsts.empty() &&
2949 (MF.getFrameInfo().hasCalls() ||
2950 ST->getOccupancyWithNumVGPRs(
2951 TRI->getNumUsedPhysRegs(*MRI, AMDGPU::VGPR_32RegClass),
2952 /*IsDynamicVGPR=*/false) <
2954 for (MachineInstr *MI : ReleaseVGPRInsts) {
2955 if (ST->requiresNopBeforeDeallocVGPRs()) {
2956 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2957 TII->get(AMDGPU::S_NOP))
2958 .addImm(0);
2959 }
2960 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2961 TII->get(AMDGPU::S_SENDMSG))
2963 Modified = true;
2964 }
2965 }
2966 }
2967 ReleaseVGPRInsts.clear();
2968 PreheadersToFlush.clear();
2969 SLoadAddresses.clear();
2970
2971 return Modified;
2972}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
static bool isOptNone(const MachineFunction &MF)
IRTranslator LLVM IR MI
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
#define I(x, y, z)
Definition MD5.cpp:58
Register Reg
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
std::pair< uint64_t, uint64_t > Interval
#define T
static bool isReg(const MCInst &MI, unsigned OpNo)
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
#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
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static cl::opt< bool > ForceEmitZeroLoadFlag("amdgpu-waitcnt-load-forcezero", cl::desc("Force all waitcnt load counters to wait until 0"), cl::init(false), cl::Hidden)
static bool callWaitsOnFunctionReturn(const MachineInstr &MI)
#define AMDGPU_EVENT_NAME(Name)
static bool callWaitsOnFunctionEntry(const MachineInstr &MI)
static bool updateOperandIfDifferent(MachineInstr &MI, AMDGPU::OpName OpName, unsigned NewEnc)
static bool isGFX12CacheInvOrWBInst(MachineInstr &Inst)
static bool isWaitInstr(MachineInstr &Inst)
static std::optional< InstCounterType > counterTypeForInstr(unsigned Opcode)
Determine if MI is a gfx12+ single-counter S_WAIT_*CNT instruction, and if so, which counter it is wa...
static bool readsVCCZ(const MachineInstr &MI)
static cl::opt< bool > ForceEmitZeroFlag("amdgpu-waitcnt-forcezero", cl::desc("Force all waitcnt instrs to be emitted as " "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"), cl::init(false), cl::Hidden)
#define AMDGPU_DECLARE_WAIT_EVENTS(DECL)
#define AMDGPU_EVENT_ENUM(Name)
Provides some synthesis utilities to produce sequences of values.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
static const uint32_t IV[8]
Definition blake3_impl.h:83
A manager for alias analyses.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static bool isCounterSet(unsigned ID)
static bool shouldExecute(unsigned CounterName)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:165
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:229
bool erase(const KeyT &Val)
Definition DenseMap.h:303
iterator end()
Definition DenseMap.h:81
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:214
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI const MachineBasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
Instructions::iterator instr_iterator
iterator_range< succ_iterator > successors()
MachineInstrBundleIterator< MachineInstr > iterator
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.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
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
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool isCall(QueryType Type=AnyInBundle) const
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
LLVM_ABI void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
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.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
const MachineOperand & getOperand(unsigned i) const
bool isMetaInstruction(QueryType Type=IgnoreBundle) const
Return true if this instruction doesn't produce any output in the form of executable instructions.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
void setImm(int64_t immVal)
int64_t getImm() const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator end()
Definition MapVector.h:67
iterator find(const KeyT &Key)
Definition MapVector.h:141
iterator begin()
Definition MapVector.h:65
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:107
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static bool isVMEM(const MachineInstr &MI)
static bool isFLATScratch(const MachineInstr &MI)
static bool isEXP(const MachineInstr &MI)
static bool mayWriteLDSThroughDMA(const MachineInstr &MI)
static bool isLDSDIR(const MachineInstr &MI)
static bool isGWS(const MachineInstr &MI)
static bool isFLATGlobal(const MachineInstr &MI)
static bool isVSAMPLE(const MachineInstr &MI)
static bool isAtomicRet(const MachineInstr &MI)
static bool isImage(const MachineInstr &MI)
static unsigned getNonSoftWaitcntOpcode(unsigned Opcode)
static bool isVINTERP(const MachineInstr &MI)
static bool isMIMG(const MachineInstr &MI)
static bool isFLAT(const MachineInstr &MI)
static bool isAtomicNoRet(const MachineInstr &MI)
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
void push_back(const T &Elt)
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:862
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:194
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:169
self_iterator getIterator()
Definition ilist_node.h:134
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
@ FLAT_ADDRESS
Address space for flat memory.
unsigned getMaxWavesPerEU(const MCSubtargetInfo *STI)
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
void decodeWaitcnt(const IsaVersion &Version, unsigned Waitcnt, unsigned &Vmcnt, unsigned &Expcnt, unsigned &Lgkmcnt)
Decodes Vmcnt, Expcnt and Lgkmcnt from given Waitcnt for given isa Version, and writes decoded values...
MCRegister getMCReg(MCRegister Reg, const MCSubtargetInfo &STI)
If Reg is a pseudo reg, return the correct hardware register given STI otherwise return Reg.
bool isHi16Reg(MCRegister Reg, const MCRegisterInfo &MRI)
unsigned getStorecntBitMask(const IsaVersion &Version)
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
unsigned encodeWaitcnt(const IsaVersion &Version, unsigned Vmcnt, unsigned Expcnt, unsigned Lgkmcnt)
Encodes Vmcnt, Expcnt and Lgkmcnt into Waitcnt for given isa Version.
unsigned getSamplecntBitMask(const IsaVersion &Version)
unsigned getKmcntBitMask(const IsaVersion &Version)
unsigned getVmcntBitMask(const IsaVersion &Version)
unsigned getXcntBitMask(const IsaVersion &Version)
Waitcnt decodeStorecntDscnt(const IsaVersion &Version, unsigned StorecntDscnt)
unsigned getLgkmcntBitMask(const IsaVersion &Version)
unsigned getBvhcntBitMask(const IsaVersion &Version)
unsigned getExpcntBitMask(const IsaVersion &Version)
Waitcnt decodeLoadcntDscnt(const IsaVersion &Version, unsigned LoadcntDscnt)
static unsigned encodeStorecntDscnt(const IsaVersion &Version, unsigned Storecnt, unsigned Dscnt)
bool getMUBUFIsBufferInv(unsigned Opc)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
unsigned getLoadcntBitMask(const IsaVersion &Version)
static unsigned encodeLoadcntDscnt(const IsaVersion &Version, unsigned Loadcnt, unsigned Dscnt)
unsigned getDscntBitMask(const IsaVersion &Version)
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Undef
Value of the register doesn't matter.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
auto enum_seq(EnumT Begin, EnumT End)
Iterate over an enum type from Begin up to - but not including - End.
Definition Sequence.h:337
@ Wait
Definition Threading.h:60
static StringRef getCPU(StringRef CPU)
Processes a CPU name.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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:646
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
char & SIInsertWaitcntsID
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:82
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:399
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
FunctionPass * createSIInsertWaitcntsPass()
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
Instruction set architecture version.
Represents the counter values to wait for in an s_waitcnt instruction.