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 if (Ptr && Memop->getAAInfo()) {
1945 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
1946 for (unsigned I = 0, E = LDSDMAStores.size(); I != E; ++I) {
1947 if (MI.mayAlias(AA, *LDSDMAStores[I], true))
1948 ScoreBrackets.determineWait(LOAD_CNT, RegNo + I + 1, Wait);
1949 }
1950 } else {
1951 ScoreBrackets.determineWait(LOAD_CNT, RegNo, Wait);
1952 }
1953 if (Memop->isStore()) {
1954 ScoreBrackets.determineWait(EXP_CNT, RegNo, Wait);
1955 }
1956 }
1957
1958 // Loop over use and def operands.
1959 for (const MachineOperand &Op : MI.operands()) {
1960 if (!Op.isReg())
1961 continue;
1962
1963 // If the instruction does not read tied source, skip the operand.
1964 if (Op.isTied() && Op.isUse() && TII->doesNotReadTiedSource(MI))
1965 continue;
1966
1967 RegInterval Interval = ScoreBrackets.getRegInterval(&MI, MRI, TRI, Op);
1968
1969 const bool IsVGPR = TRI->isVectorRegister(*MRI, Op.getReg());
1970 if (IsVGPR) {
1971 // Implicit VGPR defs and uses are never a part of the memory
1972 // instructions description and usually present to account for
1973 // super-register liveness.
1974 // TODO: Most of the other instructions also have implicit uses
1975 // for the liveness accounting only.
1976 if (Op.isImplicit() && MI.mayLoadOrStore())
1977 continue;
1978
1979 // RAW always needs an s_waitcnt. WAW needs an s_waitcnt unless the
1980 // previous write and this write are the same type of VMEM
1981 // instruction, in which case they are (in some architectures)
1982 // guaranteed to write their results in order anyway.
1983 // Additionally check instructions where Point Sample Acceleration
1984 // might be applied.
1985 if (Op.isUse() || !updateVMCntOnly(MI) ||
1986 ScoreBrackets.hasOtherPendingVmemTypes(Interval,
1987 getVmemType(MI)) ||
1988 ScoreBrackets.hasPointSamplePendingVmemTypes(MI, Interval) ||
1989 !ST->hasVmemWriteVgprInOrder()) {
1990 ScoreBrackets.determineWait(LOAD_CNT, Interval, Wait);
1991 ScoreBrackets.determineWait(SAMPLE_CNT, Interval, Wait);
1992 ScoreBrackets.determineWait(BVH_CNT, Interval, Wait);
1993 ScoreBrackets.clearVgprVmemTypes(Interval);
1994 }
1995
1996 if (Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
1997 ScoreBrackets.determineWait(EXP_CNT, Interval, Wait);
1998 }
1999 ScoreBrackets.determineWait(DS_CNT, Interval, Wait);
2000 } else {
2001 ScoreBrackets.determineWait(SmemAccessCounter, Interval, Wait);
2002 }
2003
2004 if (hasXcnt() && Op.isDef())
2005 ScoreBrackets.determineWait(X_CNT, Interval, Wait);
2006 }
2007 }
2008 }
2009
2010 // Ensure safety against exceptions from outstanding memory operations while
2011 // waiting for a barrier:
2012 //
2013 // * Some subtargets safely handle backing off the barrier in hardware
2014 // when an exception occurs.
2015 // * Some subtargets have an implicit S_WAITCNT 0 before barriers, so that
2016 // there can be no outstanding memory operations during the wait.
2017 // * Subtargets with split barriers don't need to back off the barrier; it
2018 // is up to the trap handler to preserve the user barrier state correctly.
2019 //
2020 // In all other cases, ensure safety by ensuring that there are no outstanding
2021 // memory operations.
2022 if (MI.getOpcode() == AMDGPU::S_BARRIER &&
2023 !ST->hasAutoWaitcntBeforeBarrier() && !ST->supportsBackOffBarrier()) {
2024 Wait = Wait.combined(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/true));
2025 }
2026
2027 // TODO: Remove this work-around, enable the assert for Bug 457939
2028 // after fixing the scheduler. Also, the Shader Compiler code is
2029 // independent of target.
2030 if (readsVCCZ(MI) && ST->hasReadVCCZBug()) {
2031 if (ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2032 Wait.DsCnt = 0;
2033 }
2034 }
2035
2036 // Verify that the wait is actually needed.
2037 ScoreBrackets.simplifyWaitcnt(Wait);
2038
2039 // When forcing emit, we need to skip terminators because that would break the
2040 // terminators of the MBB if we emit a waitcnt between terminators.
2041 if (ForceEmitZeroFlag && !MI.isTerminator())
2042 Wait = WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false);
2043
2044 if (ForceEmitWaitcnt[LOAD_CNT])
2045 Wait.LoadCnt = 0;
2046 if (ForceEmitWaitcnt[EXP_CNT])
2047 Wait.ExpCnt = 0;
2048 if (ForceEmitWaitcnt[DS_CNT])
2049 Wait.DsCnt = 0;
2050 if (ForceEmitWaitcnt[SAMPLE_CNT])
2051 Wait.SampleCnt = 0;
2052 if (ForceEmitWaitcnt[BVH_CNT])
2053 Wait.BvhCnt = 0;
2054 if (ForceEmitWaitcnt[KM_CNT])
2055 Wait.KmCnt = 0;
2056 if (ForceEmitWaitcnt[X_CNT])
2057 Wait.XCnt = 0;
2058
2059 if (FlushVmCnt) {
2060 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2061 Wait.LoadCnt = 0;
2062 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2063 Wait.SampleCnt = 0;
2064 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2065 Wait.BvhCnt = 0;
2066 }
2067
2068 if (ForceEmitZeroLoadFlag && Wait.LoadCnt != ~0u)
2069 Wait.LoadCnt = 0;
2070
2071 return generateWaitcnt(Wait, MI.getIterator(), *MI.getParent(), ScoreBrackets,
2072 OldWaitcntInstr);
2073}
2074
2075bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt Wait,
2077 MachineBasicBlock &Block,
2078 WaitcntBrackets &ScoreBrackets,
2079 MachineInstr *OldWaitcntInstr) {
2080 bool Modified = false;
2081
2082 if (OldWaitcntInstr)
2083 // Try to merge the required wait with preexisting waitcnt instructions.
2084 // Also erase redundant waitcnt.
2085 Modified =
2086 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr, Wait, It);
2087
2088 // Any counts that could have been applied to any existing waitcnt
2089 // instructions will have been done so, now deal with any remaining.
2090 ScoreBrackets.applyWaitcnt(Wait);
2091
2092 // ExpCnt can be merged into VINTERP.
2093 if (Wait.ExpCnt != ~0u && It != Block.instr_end() &&
2095 MachineOperand *WaitExp =
2096 TII->getNamedOperand(*It, AMDGPU::OpName::waitexp);
2097 if (Wait.ExpCnt < WaitExp->getImm()) {
2098 WaitExp->setImm(Wait.ExpCnt);
2099 Modified = true;
2100 }
2101 Wait.ExpCnt = ~0u;
2102
2103 LLVM_DEBUG(dbgs() << "generateWaitcnt\n"
2104 << "Update Instr: " << *It);
2105 }
2106
2107 // XCnt may be already consumed by a load wait.
2108 if (Wait.KmCnt == 0 && Wait.XCnt != ~0u &&
2109 !ScoreBrackets.hasPendingEvent(SMEM_GROUP))
2110 Wait.XCnt = ~0u;
2111
2112 if (Wait.LoadCnt == 0 && Wait.XCnt != ~0u &&
2113 !ScoreBrackets.hasPendingEvent(VMEM_GROUP))
2114 Wait.XCnt = ~0u;
2115
2116 // Since the translation for VMEM addresses occur in-order, we can skip the
2117 // XCnt if the current instruction is of VMEM type and has a memory dependency
2118 // with another VMEM instruction in flight.
2119 if (Wait.XCnt != ~0u && isVmemAccess(*It))
2120 Wait.XCnt = ~0u;
2121
2122 if (WCG->createNewWaitcnt(Block, It, Wait))
2123 Modified = true;
2124
2125 return Modified;
2126}
2127
2128// This is a flat memory operation. Check to see if it has memory tokens other
2129// than LDS. Other address spaces supported by flat memory operations involve
2130// global memory.
2131bool SIInsertWaitcnts::mayAccessVMEMThroughFlat(const MachineInstr &MI) const {
2132 assert(TII->isFLAT(MI));
2133
2134 // All flat instructions use the VMEM counter except prefetch.
2135 if (!TII->usesVM_CNT(MI))
2136 return false;
2137
2138 // If there are no memory operands then conservatively assume the flat
2139 // operation may access VMEM.
2140 if (MI.memoperands_empty())
2141 return true;
2142
2143 // See if any memory operand specifies an address space that involves VMEM.
2144 // Flat operations only supported FLAT, LOCAL (LDS), or address spaces
2145 // involving VMEM such as GLOBAL, CONSTANT, PRIVATE (SCRATCH), etc. The REGION
2146 // (GDS) address space is not supported by flat operations. Therefore, simply
2147 // return true unless only the LDS address space is found.
2148 for (const MachineMemOperand *Memop : MI.memoperands()) {
2149 unsigned AS = Memop->getAddrSpace();
2151 if (AS != AMDGPUAS::LOCAL_ADDRESS)
2152 return true;
2153 }
2154
2155 return false;
2156}
2157
2158// This is a flat memory operation. Check to see if it has memory tokens for
2159// either LDS or FLAT.
2160bool SIInsertWaitcnts::mayAccessLDSThroughFlat(const MachineInstr &MI) const {
2161 assert(TII->isFLAT(MI));
2162
2163 // Flat instruction such as SCRATCH and GLOBAL do not use the lgkm counter.
2164 if (!TII->usesLGKM_CNT(MI))
2165 return false;
2166
2167 // If in tgsplit mode then there can be no use of LDS.
2168 if (ST->isTgSplitEnabled())
2169 return false;
2170
2171 // If there are no memory operands then conservatively assume the flat
2172 // operation may access LDS.
2173 if (MI.memoperands_empty())
2174 return true;
2175
2176 // See if any memory operand specifies an address space that involves LDS.
2177 for (const MachineMemOperand *Memop : MI.memoperands()) {
2178 unsigned AS = Memop->getAddrSpace();
2180 return true;
2181 }
2182
2183 return false;
2184}
2185
2186bool SIInsertWaitcnts::isVmemAccess(const MachineInstr &MI) const {
2187 return (TII->isFLAT(MI) && mayAccessVMEMThroughFlat(MI)) ||
2188 (TII->isVMEM(MI) && !AMDGPU::getMUBUFIsBufferInv(MI.getOpcode()));
2189}
2190
2192 auto Opc = Inst.getOpcode();
2193 return Opc == AMDGPU::GLOBAL_INV || Opc == AMDGPU::GLOBAL_WB ||
2194 Opc == AMDGPU::GLOBAL_WBINV;
2195}
2196
2197// Return true if the next instruction is S_ENDPGM, following fallthrough
2198// blocks if necessary.
2199bool SIInsertWaitcnts::isNextENDPGM(MachineBasicBlock::instr_iterator It,
2200 MachineBasicBlock *Block) const {
2201 auto BlockEnd = Block->getParent()->end();
2202 auto BlockIter = Block->getIterator();
2203
2204 while (true) {
2205 if (It.isEnd()) {
2206 if (++BlockIter != BlockEnd) {
2207 It = BlockIter->instr_begin();
2208 continue;
2209 }
2210
2211 return false;
2212 }
2213
2214 if (!It->isMetaInstruction())
2215 break;
2216
2217 It++;
2218 }
2219
2220 assert(!It.isEnd());
2221
2222 return It->getOpcode() == AMDGPU::S_ENDPGM;
2223}
2224
2225// Add a wait after an instruction if architecture requirements mandate one.
2226bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2227 MachineBasicBlock &Block,
2228 WaitcntBrackets &ScoreBrackets) {
2229 AMDGPU::Waitcnt Wait;
2230 bool NeedsEndPGMCheck = false;
2231
2232 if (ST->isPreciseMemoryEnabled() && Inst.mayLoadOrStore())
2233 Wait = WCG->getAllZeroWaitcnt(Inst.mayStore() &&
2235
2236 if (TII->isAlwaysGDS(Inst.getOpcode())) {
2237 Wait.DsCnt = 0;
2238 NeedsEndPGMCheck = true;
2239 }
2240
2241 ScoreBrackets.simplifyWaitcnt(Wait);
2242
2243 auto SuccessorIt = std::next(Inst.getIterator());
2244 bool Result = generateWaitcnt(Wait, SuccessorIt, Block, ScoreBrackets,
2245 /*OldWaitcntInstr=*/nullptr);
2246
2247 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &Block)) {
2248 BuildMI(Block, SuccessorIt, Inst.getDebugLoc(), TII->get(AMDGPU::S_NOP))
2249 .addImm(0);
2250 }
2251
2252 return Result;
2253}
2254
2255void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2256 WaitcntBrackets *ScoreBrackets) {
2257 // Now look at the instruction opcode. If it is a memory access
2258 // instruction, update the upper-bound of the appropriate counter's
2259 // bracket and the destination operand scores.
2260 // TODO: Use the (TSFlags & SIInstrFlags::DS_CNT) property everywhere.
2261
2262 bool IsVMEMAccess = false;
2263 bool IsSMEMAccess = false;
2264 if (TII->isDS(Inst) && TII->usesLGKM_CNT(Inst)) {
2265 if (TII->isAlwaysGDS(Inst.getOpcode()) ||
2266 TII->hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2267 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_ACCESS, Inst);
2268 ScoreBrackets->updateByEvent(TII, TRI, MRI, GDS_GPR_LOCK, Inst);
2269 ScoreBrackets->setPendingGDS();
2270 } else {
2271 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
2272 }
2273 } else if (TII->isFLAT(Inst)) {
2274 if (isGFX12CacheInvOrWBInst(Inst)) {
2275 ScoreBrackets->updateByEvent(TII, TRI, MRI, getVmemWaitEventType(Inst),
2276 Inst);
2277 return;
2278 }
2279
2280 assert(Inst.mayLoadOrStore());
2281
2282 int FlatASCount = 0;
2283
2284 if (mayAccessVMEMThroughFlat(Inst)) {
2285 ++FlatASCount;
2286 IsVMEMAccess = true;
2287 ScoreBrackets->updateByEvent(TII, TRI, MRI, getVmemWaitEventType(Inst),
2288 Inst);
2289 }
2290
2291 if (mayAccessLDSThroughFlat(Inst)) {
2292 ++FlatASCount;
2293 ScoreBrackets->updateByEvent(TII, TRI, MRI, LDS_ACCESS, Inst);
2294 }
2295
2296 // This is a flat memory operation that access both VMEM and LDS, so note it
2297 // - it will require that both the VM and LGKM be flushed to zero if it is
2298 // pending when a VM or LGKM dependency occurs.
2299 if (FlatASCount > 1)
2300 ScoreBrackets->setPendingFlat();
2301 } else if (SIInstrInfo::isVMEM(Inst) &&
2303 IsVMEMAccess = true;
2304 ScoreBrackets->updateByEvent(TII, TRI, MRI, getVmemWaitEventType(Inst),
2305 Inst);
2306
2307 if (ST->vmemWriteNeedsExpWaitcnt() &&
2308 (Inst.mayStore() || SIInstrInfo::isAtomicRet(Inst))) {
2309 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMW_GPR_LOCK, Inst);
2310 }
2311 } else if (TII->isSMRD(Inst)) {
2312 IsSMEMAccess = true;
2313 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
2314 } else if (Inst.isCall()) {
2315 if (callWaitsOnFunctionReturn(Inst)) {
2316 // Act as a wait on everything
2317 ScoreBrackets->applyWaitcnt(
2318 WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false));
2319 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2320 } else {
2321 // May need to way wait for anything.
2322 ScoreBrackets->applyWaitcnt(AMDGPU::Waitcnt());
2323 }
2324 } else if (SIInstrInfo::isLDSDIR(Inst)) {
2325 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_LDS_ACCESS, Inst);
2326 } else if (TII->isVINTERP(Inst)) {
2327 int64_t Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2328 ScoreBrackets->applyWaitcnt(EXP_CNT, Imm);
2329 } else if (SIInstrInfo::isEXP(Inst)) {
2330 unsigned Imm = TII->getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2332 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_PARAM_ACCESS, Inst);
2333 else if (Imm >= AMDGPU::Exp::ET_POS0 && Imm <= AMDGPU::Exp::ET_POS_LAST)
2334 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_POS_ACCESS, Inst);
2335 else
2336 ScoreBrackets->updateByEvent(TII, TRI, MRI, EXP_GPR_LOCK, Inst);
2337 } else {
2338 switch (Inst.getOpcode()) {
2339 case AMDGPU::S_SENDMSG:
2340 case AMDGPU::S_SENDMSG_RTN_B32:
2341 case AMDGPU::S_SENDMSG_RTN_B64:
2342 case AMDGPU::S_SENDMSGHALT:
2343 ScoreBrackets->updateByEvent(TII, TRI, MRI, SQ_MESSAGE, Inst);
2344 break;
2345 case AMDGPU::S_MEMTIME:
2346 case AMDGPU::S_MEMREALTIME:
2347 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_M0:
2348 case AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM:
2349 case AMDGPU::S_BARRIER_LEAVE:
2350 case AMDGPU::S_GET_BARRIER_STATE_M0:
2351 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2352 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_ACCESS, Inst);
2353 break;
2354 }
2355 }
2356
2357 if (!hasXcnt())
2358 return;
2359
2360 if (IsVMEMAccess)
2361 ScoreBrackets->updateByEvent(TII, TRI, MRI, VMEM_GROUP, Inst);
2362
2363 if (IsSMEMAccess)
2364 ScoreBrackets->updateByEvent(TII, TRI, MRI, SMEM_GROUP, Inst);
2365}
2366
2367bool WaitcntBrackets::mergeScore(const MergeInfo &M, unsigned &Score,
2368 unsigned OtherScore) {
2369 unsigned MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
2370 unsigned OtherShifted =
2371 OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
2372 Score = std::max(MyShifted, OtherShifted);
2373 return OtherShifted > MyShifted;
2374}
2375
2376/// Merge the pending events and associater score brackets of \p Other into
2377/// this brackets status.
2378///
2379/// Returns whether the merge resulted in a change that requires tighter waits
2380/// (i.e. the merged brackets strictly dominate the original brackets).
2381bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
2382 bool StrictDom = false;
2383
2384 VgprUB = std::max(VgprUB, Other.VgprUB);
2385 SgprUB = std::max(SgprUB, Other.SgprUB);
2386
2387 for (auto T : inst_counter_types(Context->MaxCounter)) {
2388 // Merge event flags for this counter
2389 const unsigned *WaitEventMaskForInst = Context->WaitEventMaskForInst;
2390 const unsigned OldEvents = PendingEvents & WaitEventMaskForInst[T];
2391 const unsigned OtherEvents = Other.PendingEvents & WaitEventMaskForInst[T];
2392 if (OtherEvents & ~OldEvents)
2393 StrictDom = true;
2394 PendingEvents |= OtherEvents;
2395
2396 // Merge scores for this counter
2397 const unsigned MyPending = ScoreUBs[T] - ScoreLBs[T];
2398 const unsigned OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
2399 const unsigned NewUB = ScoreLBs[T] + std::max(MyPending, OtherPending);
2400 if (NewUB < ScoreLBs[T])
2401 report_fatal_error("waitcnt score overflow");
2402
2403 MergeInfo M;
2404 M.OldLB = ScoreLBs[T];
2405 M.OtherLB = Other.ScoreLBs[T];
2406 M.MyShift = NewUB - ScoreUBs[T];
2407 M.OtherShift = NewUB - Other.ScoreUBs[T];
2408
2409 ScoreUBs[T] = NewUB;
2410
2411 StrictDom |= mergeScore(M, LastFlat[T], Other.LastFlat[T]);
2412
2413 if (T == DS_CNT)
2414 StrictDom |= mergeScore(M, LastGDS, Other.LastGDS);
2415
2416 for (int J = 0; J <= VgprUB; J++)
2417 StrictDom |= mergeScore(M, VgprScores[T][J], Other.VgprScores[T][J]);
2418
2419 if (isSmemCounter(T)) {
2420 unsigned Idx = getSgprScoresIdx(T);
2421 for (int J = 0; J <= SgprUB; J++)
2422 StrictDom |=
2423 mergeScore(M, SgprScores[Idx][J], Other.SgprScores[Idx][J]);
2424 }
2425 }
2426
2427 for (int J = 0; J <= VgprUB; J++) {
2428 unsigned char NewVmemTypes = VgprVmemTypes[J] | Other.VgprVmemTypes[J];
2429 StrictDom |= NewVmemTypes != VgprVmemTypes[J];
2430 VgprVmemTypes[J] = NewVmemTypes;
2431 }
2432
2433 return StrictDom;
2434}
2435
2436static bool isWaitInstr(MachineInstr &Inst) {
2437 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Inst.getOpcode());
2438 return Opcode == AMDGPU::S_WAITCNT ||
2439 (Opcode == AMDGPU::S_WAITCNT_VSCNT && Inst.getOperand(0).isReg() &&
2440 Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL) ||
2441 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
2442 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
2443 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
2444 counterTypeForInstr(Opcode).has_value();
2445}
2446
2447// Generate s_waitcnt instructions where needed.
2448bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
2449 MachineBasicBlock &Block,
2450 WaitcntBrackets &ScoreBrackets) {
2451 bool Modified = false;
2452
2453 LLVM_DEBUG({
2454 dbgs() << "*** Begin Block: ";
2455 Block.printName(dbgs());
2456 ScoreBrackets.dump();
2457 });
2458
2459 // Track the correctness of vccz through this basic block. There are two
2460 // reasons why it might be incorrect; see ST->hasReadVCCZBug() and
2461 // ST->partialVCCWritesUpdateVCCZ().
2462 bool VCCZCorrect = true;
2463 if (ST->hasReadVCCZBug()) {
2464 // vccz could be incorrect at a basic block boundary if a predecessor wrote
2465 // to vcc and then issued an smem load.
2466 VCCZCorrect = false;
2467 } else if (!ST->partialVCCWritesUpdateVCCZ()) {
2468 // vccz could be incorrect at a basic block boundary if a predecessor wrote
2469 // to vcc_lo or vcc_hi.
2470 VCCZCorrect = false;
2471 }
2472
2473 // Walk over the instructions.
2474 MachineInstr *OldWaitcntInstr = nullptr;
2475
2476 for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(),
2477 E = Block.instr_end();
2478 Iter != E;) {
2479 MachineInstr &Inst = *Iter;
2480 if (Inst.isMetaInstruction()) {
2481 ++Iter;
2482 continue;
2483 }
2484
2485 // Track pre-existing waitcnts that were added in earlier iterations or by
2486 // the memory legalizer.
2487 if (isWaitInstr(Inst)) {
2488 if (!OldWaitcntInstr)
2489 OldWaitcntInstr = &Inst;
2490 ++Iter;
2491 continue;
2492 }
2493
2494 bool FlushVmCnt = Block.getFirstTerminator() == Inst &&
2495 isPreheaderToFlush(Block, ScoreBrackets);
2496
2497 // Generate an s_waitcnt instruction to be placed before Inst, if needed.
2498 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
2499 FlushVmCnt);
2500 OldWaitcntInstr = nullptr;
2501
2502 // Restore vccz if it's not known to be correct already.
2503 bool RestoreVCCZ = !VCCZCorrect && readsVCCZ(Inst);
2504
2505 // Don't examine operands unless we need to track vccz correctness.
2506 if (ST->hasReadVCCZBug() || !ST->partialVCCWritesUpdateVCCZ()) {
2507 if (Inst.definesRegister(AMDGPU::VCC_LO, /*TRI=*/nullptr) ||
2508 Inst.definesRegister(AMDGPU::VCC_HI, /*TRI=*/nullptr)) {
2509 // Up to gfx9, writes to vcc_lo and vcc_hi don't update vccz.
2510 if (!ST->partialVCCWritesUpdateVCCZ())
2511 VCCZCorrect = false;
2512 } else if (Inst.definesRegister(AMDGPU::VCC, /*TRI=*/nullptr)) {
2513 // There is a hardware bug on CI/SI where SMRD instruction may corrupt
2514 // vccz bit, so when we detect that an instruction may read from a
2515 // corrupt vccz bit, we need to:
2516 // 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD
2517 // operations to complete.
2518 // 2. Restore the correct value of vccz by writing the current value
2519 // of vcc back to vcc.
2520 if (ST->hasReadVCCZBug() &&
2521 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2522 // Writes to vcc while there's an outstanding smem read may get
2523 // clobbered as soon as any read completes.
2524 VCCZCorrect = false;
2525 } else {
2526 // Writes to vcc will fix any incorrect value in vccz.
2527 VCCZCorrect = true;
2528 }
2529 }
2530 }
2531
2532 if (TII->isSMRD(Inst)) {
2533 for (const MachineMemOperand *Memop : Inst.memoperands()) {
2534 // No need to handle invariant loads when avoiding WAR conflicts, as
2535 // there cannot be a vector store to the same memory location.
2536 if (!Memop->isInvariant()) {
2537 const Value *Ptr = Memop->getValue();
2538 SLoadAddresses.insert(std::pair(Ptr, Inst.getParent()));
2539 }
2540 }
2541 if (ST->hasReadVCCZBug()) {
2542 // This smem read could complete and clobber vccz at any time.
2543 VCCZCorrect = false;
2544 }
2545 }
2546
2547 updateEventWaitcntAfter(Inst, &ScoreBrackets);
2548
2549 Modified |= insertForcedWaitAfter(Inst, Block, ScoreBrackets);
2550
2551 LLVM_DEBUG({
2552 Inst.print(dbgs());
2553 ScoreBrackets.dump();
2554 });
2555
2556 // TODO: Remove this work-around after fixing the scheduler and enable the
2557 // assert above.
2558 if (RestoreVCCZ) {
2559 // Restore the vccz bit. Any time a value is written to vcc, the vcc
2560 // bit is updated, so we can restore the bit by reading the value of
2561 // vcc and then writing it back to the register.
2562 BuildMI(Block, Inst, Inst.getDebugLoc(),
2563 TII->get(ST->isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
2564 TRI->getVCC())
2565 .addReg(TRI->getVCC());
2566 VCCZCorrect = true;
2567 Modified = true;
2568 }
2569
2570 ++Iter;
2571 }
2572
2573 // Flush the LOADcnt, SAMPLEcnt and BVHcnt counters at the end of the block if
2574 // needed.
2575 AMDGPU::Waitcnt Wait;
2576 if (Block.getFirstTerminator() == Block.end() &&
2577 isPreheaderToFlush(Block, ScoreBrackets)) {
2578 if (ScoreBrackets.hasPendingEvent(LOAD_CNT))
2579 Wait.LoadCnt = 0;
2580 if (ScoreBrackets.hasPendingEvent(SAMPLE_CNT))
2581 Wait.SampleCnt = 0;
2582 if (ScoreBrackets.hasPendingEvent(BVH_CNT))
2583 Wait.BvhCnt = 0;
2584 }
2585
2586 // Combine or remove any redundant waitcnts at the end of the block.
2587 Modified |= generateWaitcnt(Wait, Block.instr_end(), Block, ScoreBrackets,
2588 OldWaitcntInstr);
2589
2590 LLVM_DEBUG({
2591 dbgs() << "*** End Block: ";
2592 Block.printName(dbgs());
2593 ScoreBrackets.dump();
2594 });
2595
2596 return Modified;
2597}
2598
2599// Return true if the given machine basic block is a preheader of a loop in
2600// which we want to flush the vmcnt counter, and false otherwise.
2601bool SIInsertWaitcnts::isPreheaderToFlush(
2602 MachineBasicBlock &MBB, const WaitcntBrackets &ScoreBrackets) {
2603 auto [Iterator, IsInserted] = PreheadersToFlush.try_emplace(&MBB, false);
2604 if (!IsInserted)
2605 return Iterator->second;
2606
2607 MachineBasicBlock *Succ = MBB.getSingleSuccessor();
2608 if (!Succ)
2609 return false;
2610
2611 MachineLoop *Loop = MLI->getLoopFor(Succ);
2612 if (!Loop)
2613 return false;
2614
2615 if (Loop->getLoopPreheader() == &MBB &&
2616 shouldFlushVmCnt(Loop, ScoreBrackets)) {
2617 Iterator->second = true;
2618 return true;
2619 }
2620
2621 return false;
2622}
2623
2624bool SIInsertWaitcnts::isVMEMOrFlatVMEM(const MachineInstr &MI) const {
2626 return mayAccessVMEMThroughFlat(MI);
2627 return SIInstrInfo::isVMEM(MI);
2628}
2629
2630// Return true if it is better to flush the vmcnt counter in the preheader of
2631// the given loop. We currently decide to flush in two situations:
2632// 1. The loop contains vmem store(s), no vmem load and at least one use of a
2633// vgpr containing a value that is loaded outside of the loop. (Only on
2634// targets with no vscnt counter).
2635// 2. The loop contains vmem load(s), but the loaded values are not used in the
2636// loop, and at least one use of a vgpr containing a value that is loaded
2637// outside of the loop.
2638bool SIInsertWaitcnts::shouldFlushVmCnt(MachineLoop *ML,
2639 const WaitcntBrackets &Brackets) {
2640 bool HasVMemLoad = false;
2641 bool HasVMemStore = false;
2642 bool UsesVgprLoadedOutside = false;
2643 DenseSet<Register> VgprUse;
2644 DenseSet<Register> VgprDef;
2645
2646 for (MachineBasicBlock *MBB : ML->blocks()) {
2647 for (MachineInstr &MI : *MBB) {
2648 if (isVMEMOrFlatVMEM(MI)) {
2649 if (MI.mayLoad())
2650 HasVMemLoad = true;
2651 if (MI.mayStore())
2652 HasVMemStore = true;
2653 }
2654 for (const MachineOperand &Op : MI.all_uses()) {
2655 if (!TRI->isVectorRegister(*MRI, Op.getReg()))
2656 continue;
2657 RegInterval Interval = Brackets.getRegInterval(&MI, MRI, TRI, Op);
2658 // Vgpr use
2659 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
2660 // If we find a register that is loaded inside the loop, 1. and 2.
2661 // are invalidated and we can exit.
2662 if (VgprDef.contains(RegNo))
2663 return false;
2664 VgprUse.insert(RegNo);
2665 // If at least one of Op's registers is in the score brackets, the
2666 // value is likely loaded outside of the loop.
2667 if (Brackets.getRegScore(RegNo, LOAD_CNT) >
2668 Brackets.getScoreLB(LOAD_CNT) ||
2669 Brackets.getRegScore(RegNo, SAMPLE_CNT) >
2670 Brackets.getScoreLB(SAMPLE_CNT) ||
2671 Brackets.getRegScore(RegNo, BVH_CNT) >
2672 Brackets.getScoreLB(BVH_CNT)) {
2673 UsesVgprLoadedOutside = true;
2674 break;
2675 }
2676 }
2677 }
2678
2679 // VMem load vgpr def
2680 if (isVMEMOrFlatVMEM(MI) && MI.mayLoad()) {
2681 for (const MachineOperand &Op : MI.all_defs()) {
2682 RegInterval Interval = Brackets.getRegInterval(&MI, MRI, TRI, Op);
2683 for (int RegNo = Interval.first; RegNo < Interval.second; ++RegNo) {
2684 // If we find a register that is loaded inside the loop, 1. and 2.
2685 // are invalidated and we can exit.
2686 if (VgprUse.contains(RegNo))
2687 return false;
2688 VgprDef.insert(RegNo);
2689 }
2690 }
2691 }
2692 }
2693 }
2694 if (!ST->hasVscnt() && HasVMemStore && !HasVMemLoad && UsesVgprLoadedOutside)
2695 return true;
2696 return HasVMemLoad && UsesVgprLoadedOutside && ST->hasVmemWriteVgprInOrder();
2697}
2698
2699bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
2700 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
2701 auto *PDT =
2702 &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
2703 AliasAnalysis *AA = nullptr;
2704 if (auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
2705 AA = &AAR->getAAResults();
2706
2707 return SIInsertWaitcnts(MLI, PDT, AA).run(MF);
2708}
2709
2710PreservedAnalyses
2713 auto *MLI = &MFAM.getResult<MachineLoopAnalysis>(MF);
2714 auto *PDT = &MFAM.getResult<MachinePostDominatorTreeAnalysis>(MF);
2716 .getManager()
2717 .getCachedResult<AAManager>(MF.getFunction());
2718
2719 if (!SIInsertWaitcnts(MLI, PDT, AA).run(MF))
2720 return PreservedAnalyses::all();
2721
2724 .preserve<AAManager>();
2725}
2726
2727bool SIInsertWaitcnts::run(MachineFunction &MF) {
2728 ST = &MF.getSubtarget<GCNSubtarget>();
2729 TII = ST->getInstrInfo();
2730 TRI = &TII->getRegisterInfo();
2731 MRI = &MF.getRegInfo();
2733
2735
2736 if (ST->hasExtendedWaitCounts()) {
2737 MaxCounter = NUM_EXTENDED_INST_CNTS;
2738 WCGGFX12Plus = WaitcntGeneratorGFX12Plus(MF, MaxCounter);
2739 WCG = &WCGGFX12Plus;
2740 } else {
2741 MaxCounter = NUM_NORMAL_INST_CNTS;
2742 WCGPreGFX12 = WaitcntGeneratorPreGFX12(MF);
2743 WCG = &WCGPreGFX12;
2744 }
2745
2746 for (auto T : inst_counter_types())
2747 ForceEmitWaitcnt[T] = false;
2748
2749 WaitEventMaskForInst = WCG->getWaitEventMask();
2750
2751 SmemAccessCounter = eventCounter(WaitEventMaskForInst, SMEM_ACCESS);
2752
2753 if (ST->hasExtendedWaitCounts()) {
2754 Limits.LoadcntMax = AMDGPU::getLoadcntBitMask(IV);
2755 Limits.DscntMax = AMDGPU::getDscntBitMask(IV);
2756 } else {
2757 Limits.LoadcntMax = AMDGPU::getVmcntBitMask(IV);
2758 Limits.DscntMax = AMDGPU::getLgkmcntBitMask(IV);
2759 }
2760 Limits.ExpcntMax = AMDGPU::getExpcntBitMask(IV);
2761 Limits.StorecntMax = AMDGPU::getStorecntBitMask(IV);
2762 Limits.SamplecntMax = AMDGPU::getSamplecntBitMask(IV);
2763 Limits.BvhcntMax = AMDGPU::getBvhcntBitMask(IV);
2764 Limits.KmcntMax = AMDGPU::getKmcntBitMask(IV);
2765 Limits.XcntMax = AMDGPU::getXcntBitMask(IV);
2766
2767 [[maybe_unused]] unsigned NumVGPRsMax =
2768 ST->getAddressableNumVGPRs(MFI->getDynamicVGPRBlockSize());
2769 [[maybe_unused]] unsigned NumSGPRsMax = ST->getAddressableNumSGPRs();
2770 assert(NumVGPRsMax <= SQ_MAX_PGM_VGPRS);
2771 assert(NumSGPRsMax <= SQ_MAX_PGM_SGPRS);
2772
2773 BlockInfos.clear();
2774 bool Modified = false;
2775
2776 MachineBasicBlock &EntryBB = MF.front();
2778
2779 if (!MFI->isEntryFunction()) {
2780 // Wait for any outstanding memory operations that the input registers may
2781 // depend on. We can't track them and it's better to do the wait after the
2782 // costly call sequence.
2783
2784 // TODO: Could insert earlier and schedule more liberally with operations
2785 // that only use caller preserved registers.
2786 for (MachineBasicBlock::iterator E = EntryBB.end();
2787 I != E && (I->isPHI() || I->isMetaInstruction()); ++I)
2788 ;
2789
2790 if (ST->hasExtendedWaitCounts()) {
2791 BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
2792 .addImm(0);
2793 for (auto CT : inst_counter_types(NUM_EXTENDED_INST_CNTS)) {
2794 if (CT == LOAD_CNT || CT == DS_CNT || CT == STORE_CNT || CT == X_CNT)
2795 continue;
2796
2797 if (!ST->hasImageInsts() &&
2798 (CT == EXP_CNT || CT == SAMPLE_CNT || CT == BVH_CNT))
2799 continue;
2800
2801 BuildMI(EntryBB, I, DebugLoc(),
2802 TII->get(instrsForExtendedCounterTypes[CT]))
2803 .addImm(0);
2804 }
2805 } else {
2806 BuildMI(EntryBB, I, DebugLoc(), TII->get(AMDGPU::S_WAITCNT)).addImm(0);
2807 }
2808
2809 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(this);
2810 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
2811 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
2812
2813 Modified = true;
2814 }
2815
2816 // Keep iterating over the blocks in reverse post order, inserting and
2817 // updating s_waitcnt where needed, until a fix point is reached.
2818 for (auto *MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
2819 BlockInfos.try_emplace(MBB);
2820
2821 std::unique_ptr<WaitcntBrackets> Brackets;
2822 bool Repeat;
2823 do {
2824 Repeat = false;
2825
2826 for (auto BII = BlockInfos.begin(), BIE = BlockInfos.end(); BII != BIE;
2827 ++BII) {
2828 MachineBasicBlock *MBB = BII->first;
2829 BlockInfo &BI = BII->second;
2830 if (!BI.Dirty)
2831 continue;
2832
2833 if (BI.Incoming) {
2834 if (!Brackets)
2835 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
2836 else
2837 *Brackets = *BI.Incoming;
2838 } else {
2839 if (!Brackets) {
2840 Brackets = std::make_unique<WaitcntBrackets>(this);
2841 } else {
2842 // Reinitialize in-place. N.B. do not do this by assigning from a
2843 // temporary because the WaitcntBrackets class is large and it could
2844 // cause this function to use an unreasonable amount of stack space.
2845 Brackets->~WaitcntBrackets();
2846 new (Brackets.get()) WaitcntBrackets(this);
2847 }
2848 }
2849
2850 Modified |= insertWaitcntInBlock(MF, *MBB, *Brackets);
2851 BI.Dirty = false;
2852
2853 if (Brackets->hasPendingEvent()) {
2854 BlockInfo *MoveBracketsToSucc = nullptr;
2855 for (MachineBasicBlock *Succ : MBB->successors()) {
2856 auto *SuccBII = BlockInfos.find(Succ);
2857 BlockInfo &SuccBI = SuccBII->second;
2858 if (!SuccBI.Incoming) {
2859 SuccBI.Dirty = true;
2860 if (SuccBII <= BII) {
2861 LLVM_DEBUG(dbgs() << "repeat on backedge\n");
2862 Repeat = true;
2863 }
2864 if (!MoveBracketsToSucc) {
2865 MoveBracketsToSucc = &SuccBI;
2866 } else {
2867 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
2868 }
2869 } else if (SuccBI.Incoming->merge(*Brackets)) {
2870 SuccBI.Dirty = true;
2871 if (SuccBII <= BII) {
2872 LLVM_DEBUG(dbgs() << "repeat on backedge\n");
2873 Repeat = true;
2874 }
2875 }
2876 }
2877 if (MoveBracketsToSucc)
2878 MoveBracketsToSucc->Incoming = std::move(Brackets);
2879 }
2880 }
2881 } while (Repeat);
2882
2883 if (ST->hasScalarStores()) {
2884 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
2885 bool HaveScalarStores = false;
2886
2887 for (MachineBasicBlock &MBB : MF) {
2888 for (MachineInstr &MI : MBB) {
2889 if (!HaveScalarStores && TII->isScalarStore(MI))
2890 HaveScalarStores = true;
2891
2892 if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
2893 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
2894 EndPgmBlocks.push_back(&MBB);
2895 }
2896 }
2897
2898 if (HaveScalarStores) {
2899 // If scalar writes are used, the cache must be flushed or else the next
2900 // wave to reuse the same scratch memory can be clobbered.
2901 //
2902 // Insert s_dcache_wb at wave termination points if there were any scalar
2903 // stores, and only if the cache hasn't already been flushed. This could
2904 // be improved by looking across blocks for flushes in postdominating
2905 // blocks from the stores but an explicitly requested flush is probably
2906 // very rare.
2907 for (MachineBasicBlock *MBB : EndPgmBlocks) {
2908 bool SeenDCacheWB = false;
2909
2910 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
2911 I != E; ++I) {
2912 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
2913 SeenDCacheWB = true;
2914 else if (TII->isScalarStore(*I))
2915 SeenDCacheWB = false;
2916
2917 // FIXME: It would be better to insert this before a waitcnt if any.
2918 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
2919 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
2920 !SeenDCacheWB) {
2921 Modified = true;
2922 BuildMI(*MBB, I, I->getDebugLoc(), TII->get(AMDGPU::S_DCACHE_WB));
2923 }
2924 }
2925 }
2926 }
2927 }
2928
2929 // Deallocate the VGPRs before previously identified S_ENDPGM instructions.
2930 // This is done in different ways depending on how the VGPRs were allocated
2931 // (i.e. whether we're in dynamic VGPR mode or not).
2932 // Skip deallocation if kernel is waveslot limited vs VGPR limited. A short
2933 // waveslot limited kernel runs slower with the deallocation.
2934 if (MFI->isDynamicVGPREnabled()) {
2935 for (MachineInstr *MI : ReleaseVGPRInsts) {
2936 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2937 TII->get(AMDGPU::S_ALLOC_VGPR))
2938 .addImm(0);
2939 Modified = true;
2940 }
2941 } else {
2942 if (!ReleaseVGPRInsts.empty() &&
2943 (MF.getFrameInfo().hasCalls() ||
2944 ST->getOccupancyWithNumVGPRs(
2945 TRI->getNumUsedPhysRegs(*MRI, AMDGPU::VGPR_32RegClass),
2946 /*IsDynamicVGPR=*/false) <
2948 for (MachineInstr *MI : ReleaseVGPRInsts) {
2949 if (ST->requiresNopBeforeDeallocVGPRs()) {
2950 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2951 TII->get(AMDGPU::S_NOP))
2952 .addImm(0);
2953 }
2954 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
2955 TII->get(AMDGPU::S_SENDMSG))
2957 Modified = true;
2958 }
2959 }
2960 }
2961 ReleaseVGPRInsts.clear();
2962 PreheadersToFlush.clear();
2963 SLoadAddresses.clear();
2964
2965 return Modified;
2966}
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:114
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:626
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:405
@ 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.