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