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