LLVM 23.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 "AMDGPUWaitcntUtils.h"
28#include "GCNSubtarget.h"
32#include "llvm/ADT/MapVector.h"
34#include "llvm/ADT/Sequence.h"
40#include "llvm/IR/Dominators.h"
44
45using namespace llvm;
46
47#define DEBUG_TYPE "si-insert-waitcnts"
48
49DEBUG_COUNTER(ForceExpCounter, DEBUG_TYPE "-forceexp",
50 "Force emit s_waitcnt expcnt(0) instrs");
51DEBUG_COUNTER(ForceLgkmCounter, DEBUG_TYPE "-forcelgkm",
52 "Force emit s_waitcnt lgkmcnt(0) instrs");
53DEBUG_COUNTER(ForceVMCounter, DEBUG_TYPE "-forcevm",
54 "Force emit s_waitcnt vmcnt(0) instrs");
55
56static cl::opt<bool>
57 ForceEmitZeroFlag("amdgpu-waitcnt-forcezero",
58 cl::desc("Force all waitcnt instrs to be emitted as "
59 "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)"),
60 cl::init(false), cl::Hidden);
61
63 "amdgpu-waitcnt-load-forcezero",
64 cl::desc("Force all waitcnt load counters to wait until 0"),
65 cl::init(false), cl::Hidden);
66
68 "amdgpu-expert-scheduling-mode",
69 cl::desc("Enable expert scheduling mode 2 for all functions (GFX12+ only)"),
70 cl::init(false), cl::Hidden);
71
72namespace {
73// Get the maximum wait count value for a given counter type.
74static unsigned getWaitCountMax(const AMDGPU::HardwareLimits &Limits,
76 switch (T) {
78 return Limits.LoadcntMax;
79 case AMDGPU::DS_CNT:
80 return Limits.DscntMax;
81 case AMDGPU::EXP_CNT:
82 return Limits.ExpcntMax;
84 return Limits.StorecntMax;
86 return Limits.SamplecntMax;
87 case AMDGPU::BVH_CNT:
88 return Limits.BvhcntMax;
89 case AMDGPU::KM_CNT:
90 return Limits.KmcntMax;
91 case AMDGPU::X_CNT:
92 return Limits.XcntMax;
93 case AMDGPU::VA_VDST:
94 return Limits.VaVdstMax;
95 case AMDGPU::VM_VSRC:
96 return Limits.VmVsrcMax;
97 default:
98 return 0;
99 }
100}
101
102/// Integer IDs used to track vector memory locations we may have to wait on.
103/// Encoded as u16 chunks:
104///
105/// [0, REGUNITS_END ): MCRegUnit
106/// [LDSDMA_BEGIN, LDSDMA_END ) : LDS DMA IDs
107///
108/// NOTE: The choice of encoding these as "u16 chunks" is arbitrary.
109/// It gives (2 << 16) - 1 entries per category which is more than enough
110/// for all register units. MCPhysReg is u16 so we don't even support >u16
111/// physical register numbers at this time, let alone >u16 register units.
112/// In any case, an assertion in "WaitcntBrackets" ensures REGUNITS_END
113/// is enough for all register units.
114using VMEMID = uint32_t;
115
116enum : VMEMID {
117 TRACKINGID_RANGE_LEN = (1 << 16),
118
119 // Important: MCRegUnits must always be tracked starting from 0, as we
120 // need to be able to convert between a MCRegUnit and a VMEMID freely.
121 REGUNITS_BEGIN = 0,
122 REGUNITS_END = REGUNITS_BEGIN + TRACKINGID_RANGE_LEN,
123
124 // Note for LDSDMA: LDSDMA_BEGIN corresponds to the "common"
125 // entry, which is updated for all LDS DMA operations encountered.
126 // Specific LDS DMA IDs start at LDSDMA_BEGIN + 1.
127 NUM_LDSDMA = TRACKINGID_RANGE_LEN,
128 LDSDMA_BEGIN = REGUNITS_END,
129 LDSDMA_END = LDSDMA_BEGIN + NUM_LDSDMA,
130};
131
132/// Convert a MCRegUnit to a VMEMID.
133static constexpr VMEMID toVMEMID(MCRegUnit RU) {
134 return static_cast<unsigned>(RU);
135}
136
137#define AMDGPU_DECLARE_WAIT_EVENTS(DECL) \
138 DECL(VMEM_ACCESS) /* vmem read & write (pre-gfx10), vmem read (gfx10+) */ \
139 DECL(VMEM_SAMPLER_READ_ACCESS) /* vmem SAMPLER read (gfx12+ only) */ \
140 DECL(VMEM_BVH_READ_ACCESS) /* vmem BVH read (gfx12+ only) */ \
141 DECL(GLOBAL_INV_ACCESS) /* GLOBAL_INV (gfx12+ only) */ \
142 DECL(VMEM_WRITE_ACCESS) /* vmem write that is not scratch */ \
143 DECL(SCRATCH_WRITE_ACCESS) /* vmem write that may be scratch */ \
144 DECL(VMEM_GROUP) /* vmem group */ \
145 DECL(LDS_ACCESS) /* lds read & write */ \
146 DECL(GDS_ACCESS) /* gds read & write */ \
147 DECL(SQ_MESSAGE) /* send message */ \
148 DECL(SCC_WRITE) /* write to SCC from barrier */ \
149 DECL(SMEM_ACCESS) /* scalar-memory read & write */ \
150 DECL(SMEM_GROUP) /* scalar-memory group */ \
151 DECL(EXP_GPR_LOCK) /* export holding on its data src */ \
152 DECL(GDS_GPR_LOCK) /* GDS holding on its data and addr src */ \
153 DECL(EXP_POS_ACCESS) /* write to export position */ \
154 DECL(EXP_PARAM_ACCESS) /* write to export parameter */ \
155 DECL(VMW_GPR_LOCK) /* vmem write holding on its data src */ \
156 DECL(EXP_LDS_ACCESS) /* read by ldsdir counting as export */ \
157 DECL(VGPR_CSMACC_WRITE) /* write VGPR dest in Core/Side-MACC VALU */ \
158 DECL(VGPR_DPMACC_WRITE) /* write VGPR dest in DPMACC VALU */ \
159 DECL(VGPR_TRANS_WRITE) /* write VGPR dest in TRANS VALU */ \
160 DECL(VGPR_XDL_WRITE) /* write VGPR dest in XDL VALU */ \
161 DECL(VGPR_LDS_READ) /* read VGPR source in LDS */ \
162 DECL(VGPR_FLAT_READ) /* read VGPR source in FLAT */ \
163 DECL(VGPR_VMEM_READ) /* read VGPR source in other VMEM */ \
164 DECL(ASYNC_ACCESS) /* access that uses ASYNC_CNT */
165
166// clang-format off
167#define AMDGPU_EVENT_ENUM(Name) Name,
168enum WaitEventType {
170 NUM_WAIT_EVENTS
171};
172#undef AMDGPU_EVENT_ENUM
173} // namespace
174
175namespace llvm {
176template <> struct enum_iteration_traits<WaitEventType> {
177 static constexpr bool is_iterable = true;
178};
179} // namespace llvm
180
181namespace {
182
183/// Return an iterator over all events between VMEM_ACCESS (the first event)
184/// and \c MaxEvent (exclusive, default value yields an enumeration over
185/// all counters).
186auto wait_events(WaitEventType MaxEvent = NUM_WAIT_EVENTS) {
187 return enum_seq(VMEM_ACCESS, MaxEvent);
188}
189
190#define AMDGPU_EVENT_NAME(Name) #Name,
191static constexpr StringLiteral WaitEventTypeName[] = {
193};
194#undef AMDGPU_EVENT_NAME
195static constexpr StringLiteral getWaitEventTypeName(WaitEventType Event) {
196 return WaitEventTypeName[Event];
197}
198// clang-format on
199
200// Enumerate different types of result-returning VMEM operations. Although
201// s_waitcnt orders them all with a single vmcnt counter, in the absence of
202// s_waitcnt only instructions of the same VmemType are guaranteed to write
203// their results in order -- so there is no need to insert an s_waitcnt between
204// two instructions of the same type that write the same vgpr.
205enum VmemType {
206 // BUF instructions and MIMG instructions without a sampler.
207 VMEM_NOSAMPLER,
208 // MIMG instructions with a sampler.
209 VMEM_SAMPLER,
210 // BVH instructions
211 VMEM_BVH,
212 NUM_VMEM_TYPES
213};
214
215// Maps values of InstCounterType to the instruction that waits on that
216// counter. Only used if GCNSubtarget::hasExtendedWaitCounts()
217// returns true, and does not cover VA_VDST or VM_VSRC.
218static const unsigned
219 instrsForExtendedCounterTypes[AMDGPU::NUM_EXTENDED_INST_CNTS] = {
220 AMDGPU::S_WAIT_LOADCNT, AMDGPU::S_WAIT_DSCNT,
221 AMDGPU::S_WAIT_EXPCNT, AMDGPU::S_WAIT_STORECNT,
222 AMDGPU::S_WAIT_SAMPLECNT, AMDGPU::S_WAIT_BVHCNT,
223 AMDGPU::S_WAIT_KMCNT, AMDGPU::S_WAIT_XCNT,
224 AMDGPU::S_WAIT_ASYNCCNT};
225
226static bool updateVMCntOnly(const MachineInstr &Inst) {
227 return (SIInstrInfo::isVMEM(Inst) && !SIInstrInfo::isFLAT(Inst)) ||
229}
230
231#ifndef NDEBUG
232static bool isNormalMode(AMDGPU::InstCounterType MaxCounter) {
233 return MaxCounter == AMDGPU::NUM_NORMAL_INST_CNTS;
234}
235#endif // NDEBUG
236
237VmemType getVmemType(const MachineInstr &Inst) {
238 assert(updateVMCntOnly(Inst));
239 if (!SIInstrInfo::isImage(Inst))
240 return VMEM_NOSAMPLER;
241 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Inst.getOpcode());
242 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
243 AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
244
245 if (BaseInfo->BVH)
246 return VMEM_BVH;
247
248 // We have to make an additional check for isVSAMPLE here since some
249 // instructions don't have a sampler, but are still classified as sampler
250 // instructions for the purposes of e.g. waitcnt.
251 if (BaseInfo->Sampler || BaseInfo->MSAA || SIInstrInfo::isVSAMPLE(Inst))
252 return VMEM_SAMPLER;
253
254 return VMEM_NOSAMPLER;
255}
256
257void addWait(AMDGPU::Waitcnt &Wait, AMDGPU::InstCounterType T, unsigned Count) {
258 Wait.set(T, std::min(Wait.get(T), Count));
259}
260
262 Wait.set(T, ~0u);
263}
264
265/// A small set of events.
266class WaitEventSet {
267 unsigned Mask = 0;
268
269public:
270 WaitEventSet() = default;
271 explicit constexpr WaitEventSet(WaitEventType Event) {
272 static_assert(NUM_WAIT_EVENTS <= sizeof(Mask) * 8,
273 "Not enough bits in Mask for all the events");
274 Mask |= 1 << Event;
275 }
276 constexpr WaitEventSet(std::initializer_list<WaitEventType> Events) {
277 for (auto &E : Events) {
278 Mask |= 1 << E;
279 }
280 }
281 void insert(const WaitEventType &Event) { Mask |= 1 << Event; }
282 void remove(const WaitEventType &Event) { Mask &= ~(1 << Event); }
283 void remove(const WaitEventSet &Other) { Mask &= ~Other.Mask; }
284 bool contains(const WaitEventType &Event) const {
285 return Mask & (1 << Event);
286 }
287 /// \Returns true if this set contains all elements of \p Other.
288 bool contains(const WaitEventSet &Other) const {
289 return (~Mask & Other.Mask) == 0;
290 }
291 /// \Returns the intersection of this and \p Other.
292 WaitEventSet operator&(const WaitEventSet &Other) const {
293 auto Copy = *this;
294 Copy.Mask &= Other.Mask;
295 return Copy;
296 }
297 /// \Returns the union of this and \p Other.
298 WaitEventSet operator|(const WaitEventSet &Other) const {
299 auto Copy = *this;
300 Copy.Mask |= Other.Mask;
301 return Copy;
302 }
303 /// This set becomes the union of this and \p Other.
304 WaitEventSet &operator|=(const WaitEventSet &Other) {
305 Mask |= Other.Mask;
306 return *this;
307 }
308 /// This set becomes the intersection of this and \p Other.
309 WaitEventSet &operator&=(const WaitEventSet &Other) {
310 Mask &= Other.Mask;
311 return *this;
312 }
313 bool operator==(const WaitEventSet &Other) const {
314 return Mask == Other.Mask;
315 }
316 bool operator!=(const WaitEventSet &Other) const { return !(*this == Other); }
317 bool empty() const { return Mask == 0; }
318 /// \Returns true if the set contains more than one element.
319 bool twoOrMore() const { return Mask & (Mask - 1); }
320 operator bool() const { return !empty(); }
321 void print(raw_ostream &OS) const {
322 ListSeparator LS(", ");
323 for (WaitEventType Event : wait_events()) {
324 if (contains(Event))
325 OS << LS << getWaitEventTypeName(Event);
326 }
327 }
328 LLVM_DUMP_METHOD void dump() const;
329};
330
331void WaitEventSet::dump() const {
332 print(dbgs());
333 dbgs() << "\n";
334}
335
336class WaitcntBrackets;
337
338// This abstracts the logic for generating and updating S_WAIT* instructions
339// away from the analysis that determines where they are needed. This was
340// done because the set of counters and instructions for waiting on them
341// underwent a major shift with gfx12, sufficiently so that having this
342// abstraction allows the main analysis logic to be simpler than it would
343// otherwise have had to become.
344class WaitcntGenerator {
345protected:
346 const GCNSubtarget &ST;
347 const SIInstrInfo &TII;
348 AMDGPU::IsaVersion IV;
349 AMDGPU::InstCounterType MaxCounter;
350 bool OptNone;
351 bool ExpandWaitcntProfiling = false;
352 const AMDGPU::HardwareLimits &Limits;
353
354public:
355 WaitcntGenerator() = delete;
356 WaitcntGenerator(const WaitcntGenerator &) = delete;
357 WaitcntGenerator(const MachineFunction &MF,
358 AMDGPU::InstCounterType MaxCounter,
359 const AMDGPU::HardwareLimits &Limits)
360 : ST(MF.getSubtarget<GCNSubtarget>()), TII(*ST.getInstrInfo()),
361 IV(AMDGPU::getIsaVersion(ST.getCPU())), MaxCounter(MaxCounter),
362 OptNone(MF.getFunction().hasOptNone() ||
363 MF.getTarget().getOptLevel() == CodeGenOptLevel::None),
364 ExpandWaitcntProfiling(
365 MF.getFunction().hasFnAttribute("amdgpu-expand-waitcnt-profiling")),
366 Limits(Limits) {}
367
368 // Return true if the current function should be compiled with no
369 // optimization.
370 bool isOptNone() const { return OptNone; }
371
372 const AMDGPU::HardwareLimits &getLimits() const { return Limits; }
373
374 // Edits an existing sequence of wait count instructions according
375 // to an incoming Waitcnt value, which is itself updated to reflect
376 // any new wait count instructions which may need to be generated by
377 // WaitcntGenerator::createNewWaitcnt(). It will return true if any edits
378 // were made.
379 //
380 // This editing will usually be merely updated operands, but it may also
381 // delete instructions if the incoming Wait value indicates they are not
382 // needed. It may also remove existing instructions for which a wait
383 // is needed if it can be determined that it is better to generate new
384 // instructions later, as can happen on gfx12.
385 virtual bool
386 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
387 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
389
390 // Transform a soft waitcnt into a normal one.
391 bool promoteSoftWaitCnt(MachineInstr *Waitcnt) const;
392
393 // Generates new wait count instructions according to the value of
394 // Wait, returning true if any new instructions were created.
395 // ScoreBrackets is used for profiling expansion.
396 virtual bool createNewWaitcnt(MachineBasicBlock &Block,
398 AMDGPU::Waitcnt Wait,
399 const WaitcntBrackets &ScoreBrackets) = 0;
400
401 // Returns the WaitEventSet that corresponds to counter \p T.
402 virtual const WaitEventSet &
403 getWaitEvents(AMDGPU::InstCounterType T) const = 0;
404
405 /// \returns the counter that corresponds to event \p E.
406 AMDGPU::InstCounterType getCounterFromEvent(WaitEventType E) const {
407 for (auto T : AMDGPU::inst_counter_types()) {
408 if (getWaitEvents(T).contains(E))
409 return T;
410 }
411 llvm_unreachable("event type has no associated counter");
412 }
413
414 // Returns a new waitcnt with all counters except VScnt set to 0. If
415 // IncludeVSCnt is true, VScnt is set to 0, otherwise it is set to ~0u.
416 // AsyncCnt always defaults to ~0u (don't wait for it). It is only updated
417 // when a call to @llvm.amdgcn.wait.asyncmark() is processed.
418 virtual AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const = 0;
419
420 virtual ~WaitcntGenerator() = default;
421};
422
423class WaitcntGeneratorPreGFX12 final : public WaitcntGenerator {
424 static constexpr const WaitEventSet
425 WaitEventMaskForInstPreGFX12[AMDGPU::NUM_INST_CNTS] = {
426 WaitEventSet(
427 {VMEM_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS}),
428 WaitEventSet({SMEM_ACCESS, LDS_ACCESS, GDS_ACCESS, SQ_MESSAGE}),
429 WaitEventSet({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK,
430 EXP_PARAM_ACCESS, EXP_POS_ACCESS, EXP_LDS_ACCESS}),
431 WaitEventSet({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
432 WaitEventSet(),
433 WaitEventSet(),
434 WaitEventSet(),
435 WaitEventSet(),
436 WaitEventSet(),
437 WaitEventSet()};
438
439public:
440 using WaitcntGenerator::WaitcntGenerator;
441 bool
442 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
443 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
444 MachineBasicBlock::instr_iterator It) const override;
445
446 bool createNewWaitcnt(MachineBasicBlock &Block,
448 AMDGPU::Waitcnt Wait,
449 const WaitcntBrackets &ScoreBrackets) override;
450
451 const WaitEventSet &getWaitEvents(AMDGPU::InstCounterType T) const override {
452 return WaitEventMaskForInstPreGFX12[T];
453 }
454
455 AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const override;
456};
457
458class WaitcntGeneratorGFX12Plus final : public WaitcntGenerator {
459protected:
460 bool IsExpertMode;
461 static constexpr const WaitEventSet
462 WaitEventMaskForInstGFX12Plus[AMDGPU::NUM_INST_CNTS] = {
463 WaitEventSet({VMEM_ACCESS, GLOBAL_INV_ACCESS}),
464 WaitEventSet({LDS_ACCESS, GDS_ACCESS}),
465 WaitEventSet({EXP_GPR_LOCK, GDS_GPR_LOCK, VMW_GPR_LOCK,
466 EXP_PARAM_ACCESS, EXP_POS_ACCESS, EXP_LDS_ACCESS}),
467 WaitEventSet({VMEM_WRITE_ACCESS, SCRATCH_WRITE_ACCESS}),
468 WaitEventSet({VMEM_SAMPLER_READ_ACCESS}),
469 WaitEventSet({VMEM_BVH_READ_ACCESS}),
470 WaitEventSet({SMEM_ACCESS, SQ_MESSAGE, SCC_WRITE}),
471 WaitEventSet({VMEM_GROUP, SMEM_GROUP}),
472 WaitEventSet({ASYNC_ACCESS}),
473 WaitEventSet({VGPR_CSMACC_WRITE, VGPR_DPMACC_WRITE, VGPR_TRANS_WRITE,
474 VGPR_XDL_WRITE}),
475 WaitEventSet({VGPR_LDS_READ, VGPR_FLAT_READ, VGPR_VMEM_READ})};
476
477public:
478 WaitcntGeneratorGFX12Plus() = delete;
479 WaitcntGeneratorGFX12Plus(const MachineFunction &MF,
480 AMDGPU::InstCounterType MaxCounter,
481 const AMDGPU::HardwareLimits &Limits,
482 bool IsExpertMode)
483 : WaitcntGenerator(MF, MaxCounter, Limits), IsExpertMode(IsExpertMode) {}
484
485 bool
486 applyPreexistingWaitcnt(WaitcntBrackets &ScoreBrackets,
487 MachineInstr &OldWaitcntInstr, AMDGPU::Waitcnt &Wait,
488 MachineBasicBlock::instr_iterator It) const override;
489
490 bool createNewWaitcnt(MachineBasicBlock &Block,
492 AMDGPU::Waitcnt Wait,
493 const WaitcntBrackets &ScoreBrackets) override;
494
495 const WaitEventSet &getWaitEvents(AMDGPU::InstCounterType T) const override {
496 return WaitEventMaskForInstGFX12Plus[T];
497 }
498
499 AMDGPU::Waitcnt getAllZeroWaitcnt(bool IncludeVSCnt) const override;
500};
501
502// Flags indicating which counters should be flushed in a loop preheader.
503struct PreheaderFlushFlags {
504 bool FlushVmCnt = false;
505 bool FlushDsCnt = false;
506};
507
508class SIInsertWaitcnts {
509 DenseMap<const Value *, MachineBasicBlock *> SLoadAddresses;
510 DenseMap<MachineBasicBlock *, PreheaderFlushFlags> PreheadersToFlush;
511 MachineLoopInfo &MLI;
512 MachinePostDominatorTree &PDT;
513 AliasAnalysis *AA = nullptr;
514 MachineFunction &MF;
515
516 struct BlockInfo {
517 std::unique_ptr<WaitcntBrackets> Incoming;
518 bool Dirty = true;
519 };
520
521 MapVector<MachineBasicBlock *, BlockInfo> BlockInfos;
522
523 bool ForceEmitWaitcnt[AMDGPU::NUM_INST_CNTS] = {};
524
525 std::unique_ptr<WaitcntGenerator> WCG;
526
527 // Remember call and return instructions in the function.
528 DenseSet<MachineInstr *> CallInsts;
529 DenseSet<MachineInstr *> ReturnInsts;
530
531 // Remember all S_ENDPGM instructions. The boolean flag is true if there might
532 // be outstanding stores but definitely no outstanding scratch stores, to help
533 // with insertion of DEALLOC_VGPRS messages.
534 DenseMap<MachineInstr *, bool> EndPgmInsts;
535
536 AMDGPU::HardwareLimits Limits;
537
538public:
539 const GCNSubtarget &ST;
540 const SIInstrInfo &TII;
541 const SIRegisterInfo &TRI;
542 const MachineRegisterInfo &MRI;
543 AMDGPU::InstCounterType SmemAccessCounter;
544 AMDGPU::InstCounterType MaxCounter;
545 bool IsExpertMode = false;
546
547 SIInsertWaitcnts(MachineLoopInfo &MLI, MachinePostDominatorTree &PDT,
548 AliasAnalysis *AA, MachineFunction &MF)
549 : MLI(MLI), PDT(PDT), AA(AA), MF(MF), ST(MF.getSubtarget<GCNSubtarget>()),
550 TII(*ST.getInstrInfo()), TRI(TII.getRegisterInfo()),
551 MRI(MF.getRegInfo()) {
552 (void)ForceExpCounter;
553 (void)ForceLgkmCounter;
554 (void)ForceVMCounter;
555 }
556
557 const AMDGPU::HardwareLimits &getLimits() const { return Limits; }
558
559 PreheaderFlushFlags getPreheaderFlushFlags(MachineLoop *ML,
560 const WaitcntBrackets &Brackets);
561 PreheaderFlushFlags isPreheaderToFlush(MachineBasicBlock &MBB,
562 const WaitcntBrackets &ScoreBrackets);
563 bool isVMEMOrFlatVMEM(const MachineInstr &MI) const;
564 bool isDSRead(const MachineInstr &MI) const;
565 bool mayStoreIncrementingDSCNT(const MachineInstr &MI) const;
566 bool run();
567
568 void setForceEmitWaitcnt() {
569// For non-debug builds, ForceEmitWaitcnt has been initialized to false;
570// For debug builds, get the debug counter info and adjust if need be
571#ifndef NDEBUG
572 if (DebugCounter::isCounterSet(ForceExpCounter) &&
573 DebugCounter::shouldExecute(ForceExpCounter)) {
574 ForceEmitWaitcnt[AMDGPU::EXP_CNT] = true;
575 } else {
576 ForceEmitWaitcnt[AMDGPU::EXP_CNT] = false;
577 }
578
579 if (DebugCounter::isCounterSet(ForceLgkmCounter) &&
580 DebugCounter::shouldExecute(ForceLgkmCounter)) {
581 ForceEmitWaitcnt[AMDGPU::DS_CNT] = true;
582 ForceEmitWaitcnt[AMDGPU::KM_CNT] = true;
583 } else {
584 ForceEmitWaitcnt[AMDGPU::DS_CNT] = false;
585 ForceEmitWaitcnt[AMDGPU::KM_CNT] = false;
586 }
587
588 if (DebugCounter::isCounterSet(ForceVMCounter) &&
589 DebugCounter::shouldExecute(ForceVMCounter)) {
590 ForceEmitWaitcnt[AMDGPU::LOAD_CNT] = true;
591 ForceEmitWaitcnt[AMDGPU::SAMPLE_CNT] = true;
592 ForceEmitWaitcnt[AMDGPU::BVH_CNT] = true;
593 } else {
594 ForceEmitWaitcnt[AMDGPU::LOAD_CNT] = false;
595 ForceEmitWaitcnt[AMDGPU::SAMPLE_CNT] = false;
596 ForceEmitWaitcnt[AMDGPU::BVH_CNT] = false;
597 }
598
599 ForceEmitWaitcnt[AMDGPU::VA_VDST] = false;
600 ForceEmitWaitcnt[AMDGPU::VM_VSRC] = false;
601#endif // NDEBUG
602 }
603
604 // Return the appropriate VMEM_*_ACCESS type for Inst, which must be a VMEM
605 // instruction.
606 WaitEventType getVmemWaitEventType(const MachineInstr &Inst) const {
607 switch (Inst.getOpcode()) {
608 // FIXME: GLOBAL_INV needs to be tracked with xcnt too.
609 case AMDGPU::GLOBAL_INV:
610 return GLOBAL_INV_ACCESS; // tracked using loadcnt, but doesn't write
611 // VGPRs
612 case AMDGPU::GLOBAL_WB:
613 case AMDGPU::GLOBAL_WBINV:
614 return VMEM_WRITE_ACCESS; // tracked using storecnt
615 default:
616 break;
617 }
618
619 // Maps VMEM access types to their corresponding WaitEventType.
620 static const WaitEventType VmemReadMapping[NUM_VMEM_TYPES] = {
621 VMEM_ACCESS, VMEM_SAMPLER_READ_ACCESS, VMEM_BVH_READ_ACCESS};
622
624 // LDS DMA loads are also stores, but on the LDS side. On the VMEM side
625 // these should use VM_CNT.
626 if (!ST.hasVscnt() || SIInstrInfo::mayWriteLDSThroughDMA(Inst))
627 return VMEM_ACCESS;
628 if (Inst.mayStore() &&
629 (!Inst.mayLoad() || SIInstrInfo::isAtomicNoRet(Inst))) {
630 if (TII.mayAccessScratch(Inst))
631 return SCRATCH_WRITE_ACCESS;
632 return VMEM_WRITE_ACCESS;
633 }
634 if (!ST.hasExtendedWaitCounts() || SIInstrInfo::isFLAT(Inst))
635 return VMEM_ACCESS;
636 return VmemReadMapping[getVmemType(Inst)];
637 }
638
639 std::optional<WaitEventType>
640 getExpertSchedulingEventType(const MachineInstr &Inst) const;
641
642 bool isAsync(const MachineInstr &MI) const {
644 return false;
646 return true;
647 const MachineOperand *Async =
648 TII.getNamedOperand(MI, AMDGPU::OpName::IsAsync);
649 return Async && (Async->getImm());
650 }
651
652 bool isNonAsyncLdsDmaWrite(const MachineInstr &MI) const {
653 return SIInstrInfo::mayWriteLDSThroughDMA(MI) && !isAsync(MI);
654 }
655
656 bool isAsyncLdsDmaWrite(const MachineInstr &MI) const {
657 return SIInstrInfo::mayWriteLDSThroughDMA(MI) && isAsync(MI);
658 }
659
660 bool shouldUpdateAsyncMark(const MachineInstr &MI,
662 if (!isAsyncLdsDmaWrite(MI))
663 return false;
665 return T == AMDGPU::ASYNC_CNT;
666 return T == AMDGPU::LOAD_CNT;
667 }
668
669 bool isVmemAccess(const MachineInstr &MI) const;
670 bool generateWaitcntInstBefore(MachineInstr &MI,
671 WaitcntBrackets &ScoreBrackets,
672 MachineInstr *OldWaitcntInstr,
673 PreheaderFlushFlags FlushFlags);
674 bool generateWaitcnt(AMDGPU::Waitcnt Wait,
676 MachineBasicBlock &Block, WaitcntBrackets &ScoreBrackets,
677 MachineInstr *OldWaitcntInstr);
678 /// \returns all events that correspond to \p Inst.
679 WaitEventSet getEventsFor(const MachineInstr &Inst) const;
680 void updateEventWaitcntAfter(MachineInstr &Inst,
681 WaitcntBrackets *ScoreBrackets);
682 bool isNextENDPGM(MachineBasicBlock::instr_iterator It,
683 MachineBasicBlock *Block) const;
684 bool insertForcedWaitAfter(MachineInstr &Inst, MachineBasicBlock &Block,
685 WaitcntBrackets &ScoreBrackets);
686 bool insertWaitcntInBlock(MachineFunction &MF, MachineBasicBlock &Block,
687 WaitcntBrackets &ScoreBrackets);
688 /// Removes redundant Soft Xcnt Waitcnts in \p Block emitted by the Memory
689 /// Legalizer. Returns true if block was modified.
690 bool removeRedundantSoftXcnts(MachineBasicBlock &Block);
691 void setSchedulingMode(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
692 bool ExpertMode) const;
693 const WaitEventSet &getWaitEvents(AMDGPU::InstCounterType T) const {
694 return WCG->getWaitEvents(T);
695 }
696 AMDGPU::InstCounterType getCounterFromEvent(WaitEventType E) const {
697 return WCG->getCounterFromEvent(E);
698 }
699};
700
701// This objects maintains the current score brackets of each wait counter, and
702// a per-register scoreboard for each wait counter.
703//
704// We also maintain the latest score for every event type that can change the
705// waitcnt in order to know if there are multiple types of events within
706// the brackets. When multiple types of event happen in the bracket,
707// wait count may get decreased out of order, therefore we need to put in
708// "s_waitcnt 0" before use.
709class WaitcntBrackets {
710public:
711 WaitcntBrackets(const SIInsertWaitcnts *Context) : Context(Context) {
712 assert(Context->TRI.getNumRegUnits() < REGUNITS_END);
713 }
714
715#ifndef NDEBUG
716 ~WaitcntBrackets() {
717 unsigned NumUnusedVmem = 0, NumUnusedSGPRs = 0;
718 for (auto &[ID, Val] : VMem) {
719 if (Val.empty())
720 ++NumUnusedVmem;
721 }
722 for (auto &[ID, Val] : SGPRs) {
723 if (Val.empty())
724 ++NumUnusedSGPRs;
725 }
726
727 if (NumUnusedVmem || NumUnusedSGPRs) {
728 errs() << "WaitcntBracket had unused entries at destruction time: "
729 << NumUnusedVmem << " VMem and " << NumUnusedSGPRs
730 << " SGPR unused entries\n";
731 std::abort();
732 }
733 }
734#endif
735
736 bool isSmemCounter(AMDGPU::InstCounterType T) const {
737 return T == Context->SmemAccessCounter || T == AMDGPU::X_CNT;
738 }
739
740 unsigned getOutstanding(AMDGPU::InstCounterType T) const {
741 return ScoreUBs[T] - ScoreLBs[T];
742 }
743
744 bool hasPendingVMEM(VMEMID ID, AMDGPU::InstCounterType T) const {
745 return getVMemScore(ID, T) > getScoreLB(T);
746 }
747
748 /// \Return true if we have no score entries for counter \p T.
749 bool empty(AMDGPU::InstCounterType T) const { return getScoreRange(T) == 0; }
750
751private:
752 unsigned getScoreLB(AMDGPU::InstCounterType T) const {
754 return ScoreLBs[T];
755 }
756
757 unsigned getScoreUB(AMDGPU::InstCounterType T) const {
759 return ScoreUBs[T];
760 }
761
762 unsigned getScoreRange(AMDGPU::InstCounterType T) const {
763 return getScoreUB(T) - getScoreLB(T);
764 }
765
766 unsigned getSGPRScore(MCRegUnit RU, AMDGPU::InstCounterType T) const {
767 auto It = SGPRs.find(RU);
768 return It != SGPRs.end() ? It->second.get(T) : 0;
769 }
770
771 unsigned getVMemScore(VMEMID TID, AMDGPU::InstCounterType T) const {
772 auto It = VMem.find(TID);
773 return It != VMem.end() ? It->second.Scores[T] : 0;
774 }
775
776public:
777 bool merge(const WaitcntBrackets &Other);
778
779 bool counterOutOfOrder(AMDGPU::InstCounterType T) const;
780 void simplifyWaitcnt(AMDGPU::Waitcnt &Wait) const {
781 simplifyWaitcnt(Wait, Wait);
782 }
783 void simplifyWaitcnt(const AMDGPU::Waitcnt &CheckWait,
784 AMDGPU::Waitcnt &UpdateWait) const;
785 void simplifyWaitcnt(AMDGPU::InstCounterType T, unsigned &Count) const;
786 void simplifyWaitcnt(AMDGPU::Waitcnt &Wait, AMDGPU::InstCounterType T) const;
787 void simplifyXcnt(const AMDGPU::Waitcnt &CheckWait,
788 AMDGPU::Waitcnt &UpdateWait) const;
789 void simplifyVmVsrc(const AMDGPU::Waitcnt &CheckWait,
790 AMDGPU::Waitcnt &UpdateWait) const;
791
792 void determineWaitForPhysReg(AMDGPU::InstCounterType T, MCPhysReg Reg,
793 AMDGPU::Waitcnt &Wait) const;
794 void determineWaitForLDSDMA(AMDGPU::InstCounterType T, VMEMID TID,
795 AMDGPU::Waitcnt &Wait) const;
796 AMDGPU::Waitcnt determineAsyncWait(unsigned N);
797 void tryClearSCCWriteEvent(MachineInstr *Inst);
798
799 void applyWaitcnt(const AMDGPU::Waitcnt &Wait);
800 void applyWaitcnt(AMDGPU::InstCounterType T, unsigned Count);
801 void applyWaitcnt(const AMDGPU::Waitcnt &Wait, AMDGPU::InstCounterType T);
802 void updateByEvent(WaitEventType E, MachineInstr &MI);
803 void recordAsyncMark(MachineInstr &MI);
804
805 bool hasPendingEvent() const { return !PendingEvents.empty(); }
806 bool hasPendingEvent(WaitEventType E) const {
807 return PendingEvents.contains(E);
808 }
809 bool hasPendingEvent(AMDGPU::InstCounterType T) const {
810 bool HasPending = PendingEvents & Context->getWaitEvents(T);
811 assert(HasPending == !empty(T) &&
812 "Expected pending events iff scoreboard is not empty");
813 return HasPending;
814 }
815
816 bool hasMixedPendingEvents(AMDGPU::InstCounterType T) const {
817 WaitEventSet Events = PendingEvents & Context->getWaitEvents(T);
818 // Return true if more than one bit is set in Events.
819 return Events.twoOrMore();
820 }
821
822 bool hasPendingFlat() const {
823 return ((LastFlatDsCnt > ScoreLBs[AMDGPU::DS_CNT] &&
824 LastFlatDsCnt <= ScoreUBs[AMDGPU::DS_CNT]) ||
825 (LastFlatLoadCnt > ScoreLBs[AMDGPU::LOAD_CNT] &&
826 LastFlatLoadCnt <= ScoreUBs[AMDGPU::LOAD_CNT]));
827 }
828
829 void setPendingFlat() {
830 LastFlatLoadCnt = ScoreUBs[AMDGPU::LOAD_CNT];
831 LastFlatDsCnt = ScoreUBs[AMDGPU::DS_CNT];
832 }
833
834 bool hasPendingGDS() const {
835 return LastGDS > ScoreLBs[AMDGPU::DS_CNT] &&
836 LastGDS <= ScoreUBs[AMDGPU::DS_CNT];
837 }
838
839 unsigned getPendingGDSWait() const {
840 return std::min(getScoreUB(AMDGPU::DS_CNT) - LastGDS,
841 getWaitCountMax(Context->getLimits(), AMDGPU::DS_CNT) - 1);
842 }
843
844 void setPendingGDS() { LastGDS = ScoreUBs[AMDGPU::DS_CNT]; }
845
846 // Return true if there might be pending writes to the vgpr-interval by VMEM
847 // instructions with types different from V.
848 bool hasOtherPendingVmemTypes(MCPhysReg Reg, VmemType V) const {
849 for (MCRegUnit RU : regunits(Reg)) {
850 auto It = VMem.find(toVMEMID(RU));
851 if (It != VMem.end() && (It->second.VMEMTypes & ~(1 << V)))
852 return true;
853 }
854 return false;
855 }
856
857 void clearVgprVmemTypes(MCPhysReg Reg) {
858 for (MCRegUnit RU : regunits(Reg)) {
859 if (auto It = VMem.find(toVMEMID(RU)); It != VMem.end()) {
860 It->second.VMEMTypes = 0;
861 if (It->second.empty())
862 VMem.erase(It);
863 }
864 }
865 }
866
867 void setStateOnFunctionEntryOrReturn() {
868 setScoreUB(AMDGPU::STORE_CNT,
869 getScoreUB(AMDGPU::STORE_CNT) +
870 getWaitCountMax(Context->getLimits(), AMDGPU::STORE_CNT));
871 PendingEvents |= Context->getWaitEvents(AMDGPU::STORE_CNT);
872 }
873
874 ArrayRef<const MachineInstr *> getLDSDMAStores() const {
875 return LDSDMAStores;
876 }
877
878 bool hasPointSampleAccel(const MachineInstr &MI) const;
879 bool hasPointSamplePendingVmemTypes(const MachineInstr &MI,
880 MCPhysReg RU) const;
881
882 void print(raw_ostream &) const;
883 void dump() const { print(dbgs()); }
884
885 // Free up memory by removing empty entries from the DenseMap that track event
886 // scores.
887 void purgeEmptyTrackingData();
888
889private:
890 struct MergeInfo {
891 unsigned OldLB;
892 unsigned OtherLB;
893 unsigned MyShift;
894 unsigned OtherShift;
895 };
896
897 using CounterValueArray = std::array<unsigned, AMDGPU::NUM_INST_CNTS>;
898
899 void determineWaitForScore(AMDGPU::InstCounterType T, unsigned Score,
900 AMDGPU::Waitcnt &Wait) const;
901
902 static bool mergeScore(const MergeInfo &M, unsigned &Score,
903 unsigned OtherScore);
904 bool mergeAsyncMarks(ArrayRef<MergeInfo> MergeInfos,
905 ArrayRef<CounterValueArray> OtherMarks);
906
908 assert(Reg != AMDGPU::SCC && "Shouldn't be used on SCC");
909 if (!Context->TRI.isInAllocatableClass(Reg))
910 return {{}, {}};
911 const TargetRegisterClass *RC = Context->TRI.getPhysRegBaseClass(Reg);
912 unsigned Size = Context->TRI.getRegSizeInBits(*RC);
913 if (Size == 16 && Context->ST.hasD16Writes32BitVgpr())
914 Reg = Context->TRI.get32BitRegister(Reg);
915 return Context->TRI.regunits(Reg);
916 }
917
918 void setScoreLB(AMDGPU::InstCounterType T, unsigned Val) {
920 ScoreLBs[T] = Val;
921 }
922
923 void setScoreUB(AMDGPU::InstCounterType T, unsigned Val) {
925 ScoreUBs[T] = Val;
926
927 if (T != AMDGPU::EXP_CNT)
928 return;
929
930 if (getScoreRange(AMDGPU::EXP_CNT) >
931 getWaitCountMax(Context->getLimits(), AMDGPU::EXP_CNT))
932 ScoreLBs[AMDGPU::EXP_CNT] =
933 ScoreUBs[AMDGPU::EXP_CNT] -
934 getWaitCountMax(Context->getLimits(), AMDGPU::EXP_CNT);
935 }
936
937 void setRegScore(MCPhysReg Reg, AMDGPU::InstCounterType T, unsigned Val) {
938 const SIRegisterInfo &TRI = Context->TRI;
939 if (Reg == AMDGPU::SCC) {
940 SCCScore = Val;
941 } else if (TRI.isVectorRegister(Context->MRI, Reg)) {
942 for (MCRegUnit RU : regunits(Reg))
943 VMem[toVMEMID(RU)].Scores[T] = Val;
944 } else if (TRI.isSGPRReg(Context->MRI, Reg)) {
945 for (MCRegUnit RU : regunits(Reg))
946 SGPRs[RU].get(T) = Val;
947 } else {
948 llvm_unreachable("Register cannot be tracked/unknown register!");
949 }
950 }
951
952 void setVMemScore(VMEMID TID, AMDGPU::InstCounterType T, unsigned Val) {
953 VMem[TID].Scores[T] = Val;
954 }
955
956 void setScoreByOperand(const MachineOperand &Op,
957 AMDGPU::InstCounterType CntTy, unsigned Val);
958
959 const SIInsertWaitcnts *Context;
960
961 unsigned ScoreLBs[AMDGPU::NUM_INST_CNTS] = {0};
962 unsigned ScoreUBs[AMDGPU::NUM_INST_CNTS] = {0};
963 WaitEventSet PendingEvents;
964 // Remember the last flat memory operation.
965 unsigned LastFlatDsCnt = 0;
966 unsigned LastFlatLoadCnt = 0;
967 // Remember the last GDS operation.
968 unsigned LastGDS = 0;
969
970 // The score tracking logic is fragmented as follows:
971 // - VMem: VGPR RegUnits and LDS DMA IDs, see the VMEMID encoding.
972 // - SGPRs: SGPR RegUnits
973 // - SCC: Non-allocatable and not general purpose: not a SGPR.
974 //
975 // For the VMem case, if the key is within the range of LDS DMA IDs,
976 // then the corresponding index into the `LDSDMAStores` vector below is:
977 // Key - LDSDMA_BEGIN - 1
978 // This is because LDSDMA_BEGIN is a generic entry and does not have an
979 // associated MachineInstr.
980 //
981 // TODO: Could we track SCC alongside SGPRs so it's not longer a special case?
982
983 struct VMEMInfo {
984 // Scores for all instruction counters. Zero-initialized.
985 CounterValueArray Scores{};
986 // Bitmask of the VmemTypes of VMEM instructions for this VGPR.
987 unsigned VMEMTypes = 0;
988
989 bool empty() const { return all_of(Scores, equal_to(0)) && !VMEMTypes; }
990 };
991
992 /// Wait cnt scores for every sgpr, the DS_CNT (corresponding to LGKMcnt
993 /// pre-gfx12) or KM_CNT (gfx12+ only), and X_CNT (gfx1250) are relevant.
994 class SGPRInfo {
995 /// Either DS_CNT or KM_CNT score.
996 unsigned ScoreDsKmCnt = 0;
997 unsigned ScoreXCnt = 0;
998
999 public:
1000 unsigned get(AMDGPU::InstCounterType T) const {
1001 assert(
1002 (T == AMDGPU::DS_CNT || T == AMDGPU::KM_CNT || T == AMDGPU::X_CNT) &&
1003 "Invalid counter");
1004 return T == AMDGPU::X_CNT ? ScoreXCnt : ScoreDsKmCnt;
1005 }
1006 unsigned &get(AMDGPU::InstCounterType T) {
1007 assert(
1008 (T == AMDGPU::DS_CNT || T == AMDGPU::KM_CNT || T == AMDGPU::X_CNT) &&
1009 "Invalid counter");
1010 return T == AMDGPU::X_CNT ? ScoreXCnt : ScoreDsKmCnt;
1011 }
1012
1013 bool empty() const { return !ScoreDsKmCnt && !ScoreXCnt; }
1014 };
1015
1016 DenseMap<VMEMID, VMEMInfo> VMem; // VGPR + LDS DMA
1017 DenseMap<MCRegUnit, SGPRInfo> SGPRs;
1018
1019 // Reg score for SCC.
1020 unsigned SCCScore = 0;
1021 // The unique instruction that has an SCC write pending, if there is one.
1022 const MachineInstr *PendingSCCWrite = nullptr;
1023
1024 // Store representative LDS DMA operations. The only useful info here is
1025 // alias info. One store is kept per unique AAInfo.
1026 SmallVector<const MachineInstr *> LDSDMAStores;
1027
1028 // State of all counters at each async mark encountered so far.
1030
1031 // But in the rare pathological case, a nest of loops that pushes marks
1032 // without waiting on any mark can cause AsyncMarks to grow very large. We cap
1033 // it to a reasonable limit. We can tune this later or potentially introduce a
1034 // user option to control the value.
1035 static constexpr unsigned MaxAsyncMarks = 16;
1036
1037 // Track the upper bound score for async operations that are not part of a
1038 // mark yet. Initialized to all zeros.
1039 CounterValueArray AsyncScore{};
1040};
1041
1042class SIInsertWaitcntsLegacy : public MachineFunctionPass {
1043public:
1044 static char ID;
1045 SIInsertWaitcntsLegacy() : MachineFunctionPass(ID) {}
1046
1047 bool runOnMachineFunction(MachineFunction &MF) override;
1048
1049 StringRef getPassName() const override {
1050 return "SI insert wait instructions";
1051 }
1052
1053 void getAnalysisUsage(AnalysisUsage &AU) const override {
1054 AU.setPreservesCFG();
1055 AU.addRequired<MachineLoopInfoWrapperPass>();
1056 AU.addRequired<MachinePostDominatorTreeWrapperPass>();
1057 AU.addUsedIfAvailable<AAResultsWrapperPass>();
1058 AU.addPreserved<AAResultsWrapperPass>();
1060 }
1061};
1062
1063} // end anonymous namespace
1064
1065void WaitcntBrackets::setScoreByOperand(const MachineOperand &Op,
1067 unsigned Score) {
1068 setRegScore(Op.getReg().asMCReg(), CntTy, Score);
1069}
1070
1071// Return true if the subtarget is one that enables Point Sample Acceleration
1072// and the MachineInstr passed in is one to which it might be applied (the
1073// hardware makes this decision based on several factors, but we can't determine
1074// this at compile time, so we have to assume it might be applied if the
1075// instruction supports it).
1076bool WaitcntBrackets::hasPointSampleAccel(const MachineInstr &MI) const {
1077 if (!Context->ST.hasPointSampleAccel() || !SIInstrInfo::isMIMG(MI))
1078 return false;
1079
1080 const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(MI.getOpcode());
1081 const AMDGPU::MIMGBaseOpcodeInfo *BaseInfo =
1083 return BaseInfo->PointSampleAccel;
1084}
1085
1086// Return true if the subtarget enables Point Sample Acceleration, the supplied
1087// MachineInstr is one to which it might be applied and the supplied interval is
1088// one that has outstanding writes to vmem-types different than VMEM_NOSAMPLER
1089// (this is the type that a point sample accelerated instruction effectively
1090// becomes)
1091bool WaitcntBrackets::hasPointSamplePendingVmemTypes(const MachineInstr &MI,
1092 MCPhysReg Reg) const {
1093 if (!hasPointSampleAccel(MI))
1094 return false;
1095
1096 return hasOtherPendingVmemTypes(Reg, VMEM_NOSAMPLER);
1097}
1098
1099void WaitcntBrackets::updateByEvent(WaitEventType E, MachineInstr &Inst) {
1100 AMDGPU::InstCounterType T = Context->getCounterFromEvent(E);
1101 assert(T < Context->MaxCounter);
1102
1103 unsigned UB = getScoreUB(T);
1104 unsigned CurrScore = UB + 1;
1105 if (CurrScore == 0)
1106 report_fatal_error("InsertWaitcnt score wraparound");
1107 // PendingEvents and ScoreUB need to be update regardless if this event
1108 // changes the score of a register or not.
1109 // Examples including vm_cnt when buffer-store or lgkm_cnt when send-message.
1110 PendingEvents.insert(E);
1111 setScoreUB(T, CurrScore);
1112
1113 const SIRegisterInfo &TRI = Context->TRI;
1114 const MachineRegisterInfo &MRI = Context->MRI;
1115 const SIInstrInfo &TII = Context->TII;
1116
1117 if (T == AMDGPU::EXP_CNT) {
1118 // Put score on the source vgprs. If this is a store, just use those
1119 // specific register(s).
1120 if (TII.isDS(Inst) && Inst.mayLoadOrStore()) {
1121 // All GDS operations must protect their address register (same as
1122 // export.)
1123 if (const auto *AddrOp = TII.getNamedOperand(Inst, AMDGPU::OpName::addr))
1124 setScoreByOperand(*AddrOp, AMDGPU::EXP_CNT, CurrScore);
1125
1126 if (Inst.mayStore()) {
1127 if (const auto *Data0 =
1128 TII.getNamedOperand(Inst, AMDGPU::OpName::data0))
1129 setScoreByOperand(*Data0, AMDGPU::EXP_CNT, CurrScore);
1130 if (const auto *Data1 =
1131 TII.getNamedOperand(Inst, AMDGPU::OpName::data1))
1132 setScoreByOperand(*Data1, AMDGPU::EXP_CNT, CurrScore);
1133 } else if (SIInstrInfo::isAtomicRet(Inst) && !SIInstrInfo::isGWS(Inst) &&
1134 Inst.getOpcode() != AMDGPU::DS_APPEND &&
1135 Inst.getOpcode() != AMDGPU::DS_CONSUME &&
1136 Inst.getOpcode() != AMDGPU::DS_ORDERED_COUNT) {
1137 for (const MachineOperand &Op : Inst.all_uses()) {
1138 if (TRI.isVectorRegister(MRI, Op.getReg()))
1139 setScoreByOperand(Op, AMDGPU::EXP_CNT, CurrScore);
1140 }
1141 }
1142 } else if (TII.isFLAT(Inst)) {
1143 if (Inst.mayStore()) {
1144 setScoreByOperand(*TII.getNamedOperand(Inst, AMDGPU::OpName::data),
1145 AMDGPU::EXP_CNT, CurrScore);
1146 } else if (SIInstrInfo::isAtomicRet(Inst)) {
1147 setScoreByOperand(*TII.getNamedOperand(Inst, AMDGPU::OpName::data),
1148 AMDGPU::EXP_CNT, CurrScore);
1149 }
1150 } else if (TII.isMIMG(Inst)) {
1151 if (Inst.mayStore()) {
1152 setScoreByOperand(Inst.getOperand(0), AMDGPU::EXP_CNT, CurrScore);
1153 } else if (SIInstrInfo::isAtomicRet(Inst)) {
1154 setScoreByOperand(*TII.getNamedOperand(Inst, AMDGPU::OpName::data),
1155 AMDGPU::EXP_CNT, CurrScore);
1156 }
1157 } else if (TII.isMTBUF(Inst)) {
1158 if (Inst.mayStore())
1159 setScoreByOperand(Inst.getOperand(0), AMDGPU::EXP_CNT, CurrScore);
1160 } else if (TII.isMUBUF(Inst)) {
1161 if (Inst.mayStore()) {
1162 setScoreByOperand(Inst.getOperand(0), AMDGPU::EXP_CNT, CurrScore);
1163 } else if (SIInstrInfo::isAtomicRet(Inst)) {
1164 setScoreByOperand(*TII.getNamedOperand(Inst, AMDGPU::OpName::data),
1165 AMDGPU::EXP_CNT, CurrScore);
1166 }
1167 } else if (TII.isLDSDIR(Inst)) {
1168 // LDSDIR instructions attach the score to the destination.
1169 setScoreByOperand(*TII.getNamedOperand(Inst, AMDGPU::OpName::vdst),
1170 AMDGPU::EXP_CNT, CurrScore);
1171 } else {
1172 if (TII.isEXP(Inst)) {
1173 // For export the destination registers are really temps that
1174 // can be used as the actual source after export patching, so
1175 // we need to treat them like sources and set the EXP_CNT
1176 // score.
1177 for (MachineOperand &DefMO : Inst.all_defs()) {
1178 if (TRI.isVGPR(MRI, DefMO.getReg())) {
1179 setScoreByOperand(DefMO, AMDGPU::EXP_CNT, CurrScore);
1180 }
1181 }
1182 }
1183 for (const MachineOperand &Op : Inst.all_uses()) {
1184 if (TRI.isVectorRegister(MRI, Op.getReg()))
1185 setScoreByOperand(Op, AMDGPU::EXP_CNT, CurrScore);
1186 }
1187 }
1188 } else if (T == AMDGPU::X_CNT) {
1189 WaitEventType OtherEvent = E == SMEM_GROUP ? VMEM_GROUP : SMEM_GROUP;
1190 if (PendingEvents.contains(OtherEvent)) {
1191 // Hardware inserts an implicit xcnt between interleaved
1192 // SMEM and VMEM operations. So there will never be
1193 // outstanding address translations for both SMEM and
1194 // VMEM at the same time.
1195 setScoreLB(T, getScoreUB(T) - 1);
1196 PendingEvents.remove(OtherEvent);
1197 }
1198 for (const MachineOperand &Op : Inst.all_uses())
1199 setScoreByOperand(Op, T, CurrScore);
1200 } else if (T == AMDGPU::VA_VDST || T == AMDGPU::VM_VSRC) {
1201 // Match the score to the VGPR destination or source registers as
1202 // appropriate
1203 for (const MachineOperand &Op : Inst.operands()) {
1204 if (!Op.isReg() || (T == AMDGPU::VA_VDST && Op.isUse()) ||
1205 (T == AMDGPU::VM_VSRC && Op.isDef()))
1206 continue;
1207 if (TRI.isVectorRegister(Context->MRI, Op.getReg()))
1208 setScoreByOperand(Op, T, CurrScore);
1209 }
1210 } else /* LGKM_CNT || EXP_CNT || VS_CNT || NUM_INST_CNTS */ {
1211 // Match the score to the destination registers.
1212 //
1213 // Check only explicit operands. Stores, especially spill stores, include
1214 // implicit uses and defs of their super registers which would create an
1215 // artificial dependency, while these are there only for register liveness
1216 // accounting purposes.
1217 //
1218 // Special cases where implicit register defs exists, such as M0 or VCC,
1219 // but none with memory instructions.
1220 for (const MachineOperand &Op : Inst.defs()) {
1221 if (T == AMDGPU::LOAD_CNT || T == AMDGPU::SAMPLE_CNT ||
1222 T == AMDGPU::BVH_CNT) {
1223 if (!TRI.isVectorRegister(MRI, Op.getReg())) // TODO: add wrapper
1224 continue;
1225 if (updateVMCntOnly(Inst)) {
1226 // updateVMCntOnly should only leave us with VGPRs
1227 // MUBUF, MTBUF, MIMG, FlatGlobal, and FlatScratch only have VGPR/AGPR
1228 // defs. That's required for a sane index into `VgprMemTypes` below
1229 assert(TRI.isVectorRegister(MRI, Op.getReg()));
1230 VmemType V = getVmemType(Inst);
1231 unsigned char TypesMask = 1 << V;
1232 // If instruction can have Point Sample Accel applied, we have to flag
1233 // this with another potential dependency
1234 if (hasPointSampleAccel(Inst))
1235 TypesMask |= 1 << VMEM_NOSAMPLER;
1236 for (MCRegUnit RU : regunits(Op.getReg().asMCReg()))
1237 VMem[toVMEMID(RU)].VMEMTypes |= TypesMask;
1238 }
1239 }
1240 setScoreByOperand(Op, T, CurrScore);
1241 }
1242 if (Inst.mayStore() &&
1243 (TII.isDS(Inst) || Context->isNonAsyncLdsDmaWrite(Inst))) {
1244 // MUBUF and FLAT LDS DMA operations need a wait on vmcnt before LDS
1245 // written can be accessed. A load from LDS to VMEM does not need a wait.
1246 //
1247 // The "Slot" is the offset from LDSDMA_BEGIN. If it's non-zero, then
1248 // there is a MachineInstr in LDSDMAStores used to track this LDSDMA
1249 // store. The "Slot" is the index into LDSDMAStores + 1.
1250 unsigned Slot = 0;
1251 for (const auto *MemOp : Inst.memoperands()) {
1252 if (!MemOp->isStore() ||
1253 MemOp->getAddrSpace() != AMDGPUAS::LOCAL_ADDRESS)
1254 continue;
1255 // Comparing just AA info does not guarantee memoperands are equal
1256 // in general, but this is so for LDS DMA in practice.
1257 auto AAI = MemOp->getAAInfo();
1258 // Alias scope information gives a way to definitely identify an
1259 // original memory object and practically produced in the module LDS
1260 // lowering pass. If there is no scope available we will not be able
1261 // to disambiguate LDS aliasing as after the module lowering all LDS
1262 // is squashed into a single big object.
1263 if (!AAI || !AAI.Scope)
1264 break;
1265 for (unsigned I = 0, E = LDSDMAStores.size(); I != E && !Slot; ++I) {
1266 for (const auto *MemOp : LDSDMAStores[I]->memoperands()) {
1267 if (MemOp->isStore() && AAI == MemOp->getAAInfo()) {
1268 Slot = I + 1;
1269 break;
1270 }
1271 }
1272 }
1273 if (Slot)
1274 break;
1275 // The slot may not be valid because it can be >= NUM_LDSDMA which
1276 // means the scoreboard cannot track it. We still want to preserve the
1277 // MI in order to check alias information, though.
1278 LDSDMAStores.push_back(&Inst);
1279 Slot = LDSDMAStores.size();
1280 break;
1281 }
1282 setVMemScore(LDSDMA_BEGIN, T, CurrScore);
1283 if (Slot && Slot < NUM_LDSDMA)
1284 setVMemScore(LDSDMA_BEGIN + Slot, T, CurrScore);
1285 }
1286
1287 if (Context->shouldUpdateAsyncMark(Inst, T)) {
1288 AsyncScore[T] = CurrScore;
1289 }
1290
1292 setRegScore(AMDGPU::SCC, T, CurrScore);
1293 PendingSCCWrite = &Inst;
1294 }
1295 }
1296}
1297
1298void WaitcntBrackets::recordAsyncMark(MachineInstr &Inst) {
1299 // In the absence of loops, AsyncMarks can grow linearly with the program
1300 // until we encounter an ASYNCMARK_WAIT. We could drop the oldest mark above a
1301 // limit every time we push a new mark, but that seems like unnecessary work
1302 // in practical cases. We do separately truncate the array when processing a
1303 // loop, which should be sufficient.
1304 AsyncMarks.push_back(AsyncScore);
1305 AsyncScore = {};
1306 LLVM_DEBUG({
1307 dbgs() << "recordAsyncMark:\n" << Inst;
1308 for (const auto &Mark : AsyncMarks) {
1309 llvm::interleaveComma(Mark, dbgs());
1310 dbgs() << '\n';
1311 }
1312 });
1313}
1314
1315void WaitcntBrackets::print(raw_ostream &OS) const {
1316 const GCNSubtarget &ST = Context->ST;
1317
1318 for (auto T : inst_counter_types(Context->MaxCounter)) {
1319 unsigned SR = getScoreRange(T);
1320 switch (T) {
1321 case AMDGPU::LOAD_CNT:
1322 OS << " " << (ST.hasExtendedWaitCounts() ? "LOAD" : "VM") << "_CNT("
1323 << SR << "):";
1324 break;
1325 case AMDGPU::DS_CNT:
1326 OS << " " << (ST.hasExtendedWaitCounts() ? "DS" : "LGKM") << "_CNT("
1327 << SR << "):";
1328 break;
1329 case AMDGPU::EXP_CNT:
1330 OS << " EXP_CNT(" << SR << "):";
1331 break;
1332 case AMDGPU::STORE_CNT:
1333 OS << " " << (ST.hasExtendedWaitCounts() ? "STORE" : "VS") << "_CNT("
1334 << SR << "):";
1335 break;
1336 case AMDGPU::SAMPLE_CNT:
1337 OS << " SAMPLE_CNT(" << SR << "):";
1338 break;
1339 case AMDGPU::BVH_CNT:
1340 OS << " BVH_CNT(" << SR << "):";
1341 break;
1342 case AMDGPU::KM_CNT:
1343 OS << " KM_CNT(" << SR << "):";
1344 break;
1345 case AMDGPU::X_CNT:
1346 OS << " X_CNT(" << SR << "):";
1347 break;
1348 case AMDGPU::ASYNC_CNT:
1349 OS << " ASYNC_CNT(" << SR << "):";
1350 break;
1351 case AMDGPU::VA_VDST:
1352 OS << " VA_VDST(" << SR << "): ";
1353 break;
1354 case AMDGPU::VM_VSRC:
1355 OS << " VM_VSRC(" << SR << "): ";
1356 break;
1357 default:
1358 OS << " UNKNOWN(" << SR << "):";
1359 break;
1360 }
1361
1362 if (SR != 0) {
1363 // Print vgpr scores.
1364 unsigned LB = getScoreLB(T);
1365
1366 SmallVector<VMEMID> SortedVMEMIDs(VMem.keys());
1367 sort(SortedVMEMIDs);
1368
1369 for (auto ID : SortedVMEMIDs) {
1370 unsigned RegScore = VMem.at(ID).Scores[T];
1371 if (RegScore <= LB)
1372 continue;
1373 unsigned RelScore = RegScore - LB - 1;
1374 if (ID < REGUNITS_END) {
1375 OS << ' ' << RelScore << ":vRU" << ID;
1376 } else {
1377 assert(ID >= LDSDMA_BEGIN && ID < LDSDMA_END &&
1378 "Unhandled/unexpected ID value!");
1379 OS << ' ' << RelScore << ":LDSDMA" << ID;
1380 }
1381 }
1382
1383 // Also need to print sgpr scores for lgkm_cnt or xcnt.
1384 if (isSmemCounter(T)) {
1385 SmallVector<MCRegUnit> SortedSMEMIDs(SGPRs.keys());
1386 sort(SortedSMEMIDs);
1387 for (auto ID : SortedSMEMIDs) {
1388 unsigned RegScore = SGPRs.at(ID).get(T);
1389 if (RegScore <= LB)
1390 continue;
1391 unsigned RelScore = RegScore - LB - 1;
1392 OS << ' ' << RelScore << ":sRU" << static_cast<unsigned>(ID);
1393 }
1394 }
1395
1396 if (T == AMDGPU::KM_CNT && SCCScore > 0)
1397 OS << ' ' << SCCScore << ":scc";
1398 }
1399 OS << '\n';
1400 }
1401
1402 OS << "Pending Events: ";
1403 if (hasPendingEvent()) {
1404 ListSeparator LS;
1405 for (unsigned I = 0; I != NUM_WAIT_EVENTS; ++I) {
1406 if (hasPendingEvent((WaitEventType)I)) {
1407 OS << LS << WaitEventTypeName[I];
1408 }
1409 }
1410 } else {
1411 OS << "none";
1412 }
1413 OS << '\n';
1414
1415 OS << "Async score: ";
1416 if (AsyncScore.empty())
1417 OS << "none";
1418 else
1419 llvm::interleaveComma(AsyncScore, OS);
1420 OS << '\n';
1421
1422 OS << "Async marks: " << AsyncMarks.size() << '\n';
1423
1424 for (const auto &Mark : AsyncMarks) {
1425 for (auto T : AMDGPU::inst_counter_types()) {
1426 unsigned MarkedScore = Mark[T];
1427 switch (T) {
1428 case AMDGPU::LOAD_CNT:
1429 OS << " " << (ST.hasExtendedWaitCounts() ? "LOAD" : "VM")
1430 << "_CNT: " << MarkedScore;
1431 break;
1432 case AMDGPU::DS_CNT:
1433 OS << " " << (ST.hasExtendedWaitCounts() ? "DS" : "LGKM")
1434 << "_CNT: " << MarkedScore;
1435 break;
1436 case AMDGPU::EXP_CNT:
1437 OS << " EXP_CNT: " << MarkedScore;
1438 break;
1439 case AMDGPU::STORE_CNT:
1440 OS << " " << (ST.hasExtendedWaitCounts() ? "STORE" : "VS")
1441 << "_CNT: " << MarkedScore;
1442 break;
1443 case AMDGPU::SAMPLE_CNT:
1444 OS << " SAMPLE_CNT: " << MarkedScore;
1445 break;
1446 case AMDGPU::BVH_CNT:
1447 OS << " BVH_CNT: " << MarkedScore;
1448 break;
1449 case AMDGPU::KM_CNT:
1450 OS << " KM_CNT: " << MarkedScore;
1451 break;
1452 case AMDGPU::X_CNT:
1453 OS << " X_CNT: " << MarkedScore;
1454 break;
1455 case AMDGPU::ASYNC_CNT:
1456 OS << " ASYNC_CNT: " << MarkedScore;
1457 break;
1458 default:
1459 OS << " UNKNOWN: " << MarkedScore;
1460 break;
1461 }
1462 }
1463 OS << '\n';
1464 }
1465 OS << '\n';
1466}
1467
1468/// Simplify \p UpdateWait by removing waits that are redundant based on the
1469/// current WaitcntBrackets and any other waits specified in \p CheckWait.
1470void WaitcntBrackets::simplifyWaitcnt(const AMDGPU::Waitcnt &CheckWait,
1471 AMDGPU::Waitcnt &UpdateWait) const {
1472 simplifyWaitcnt(UpdateWait, AMDGPU::LOAD_CNT);
1473 simplifyWaitcnt(UpdateWait, AMDGPU::EXP_CNT);
1474 simplifyWaitcnt(UpdateWait, AMDGPU::DS_CNT);
1475 simplifyWaitcnt(UpdateWait, AMDGPU::STORE_CNT);
1476 simplifyWaitcnt(UpdateWait, AMDGPU::SAMPLE_CNT);
1477 simplifyWaitcnt(UpdateWait, AMDGPU::BVH_CNT);
1478 simplifyWaitcnt(UpdateWait, AMDGPU::KM_CNT);
1479 simplifyXcnt(CheckWait, UpdateWait);
1480 simplifyWaitcnt(UpdateWait, AMDGPU::VA_VDST);
1481 simplifyVmVsrc(CheckWait, UpdateWait);
1482 simplifyWaitcnt(UpdateWait, AMDGPU::ASYNC_CNT);
1483}
1484
1485void WaitcntBrackets::simplifyWaitcnt(AMDGPU::InstCounterType T,
1486 unsigned &Count) const {
1487 // The number of outstanding events for this type, T, can be calculated
1488 // as (UB - LB). If the current Count is greater than or equal to the number
1489 // of outstanding events, then the wait for this counter is redundant.
1490 if (Count >= getScoreRange(T))
1491 Count = ~0u;
1492}
1493
1494void WaitcntBrackets::simplifyWaitcnt(AMDGPU::Waitcnt &Wait,
1495 AMDGPU::InstCounterType T) const {
1496 unsigned Cnt = Wait.get(T);
1497 simplifyWaitcnt(T, Cnt);
1498 Wait.set(T, Cnt);
1499}
1500
1501void WaitcntBrackets::simplifyXcnt(const AMDGPU::Waitcnt &CheckWait,
1502 AMDGPU::Waitcnt &UpdateWait) const {
1503 // Try to simplify xcnt further by checking for joint kmcnt and loadcnt
1504 // optimizations. On entry to a block with multiple predescessors, there may
1505 // be pending SMEM and VMEM events active at the same time.
1506 // In such cases, only clear one active event at a time.
1507 // TODO: Revisit xcnt optimizations for gfx1250.
1508 // Wait on XCNT is redundant if we are already waiting for a load to complete.
1509 // SMEM can return out of order, so only omit XCNT wait if we are waiting till
1510 // zero.
1511 if (CheckWait.get(AMDGPU::KM_CNT) == 0 && hasPendingEvent(SMEM_GROUP))
1512 UpdateWait.set(AMDGPU::X_CNT, ~0u);
1513 // If we have pending store we cannot optimize XCnt because we do not wait for
1514 // stores. VMEM loads retun in order, so if we only have loads XCnt is
1515 // decremented to the same number as LOADCnt.
1516 if (CheckWait.get(AMDGPU::LOAD_CNT) != ~0u && hasPendingEvent(VMEM_GROUP) &&
1517 !hasPendingEvent(AMDGPU::STORE_CNT) &&
1518 CheckWait.get(AMDGPU::X_CNT) >= CheckWait.get(AMDGPU::LOAD_CNT))
1519 UpdateWait.set(AMDGPU::X_CNT, ~0u);
1520 simplifyWaitcnt(UpdateWait, AMDGPU::X_CNT);
1521}
1522
1523void WaitcntBrackets::simplifyVmVsrc(const AMDGPU::Waitcnt &CheckWait,
1524 AMDGPU::Waitcnt &UpdateWait) const {
1525 // Waiting for some counters implies waiting for VM_VSRC, since an
1526 // instruction that decrements a counter on completion would have
1527 // decremented VM_VSRC once its VGPR operands had been read.
1528 if (CheckWait.get(AMDGPU::VM_VSRC) >=
1529 std::min({CheckWait.get(AMDGPU::LOAD_CNT),
1530 CheckWait.get(AMDGPU::STORE_CNT),
1531 CheckWait.get(AMDGPU::SAMPLE_CNT),
1532 CheckWait.get(AMDGPU::BVH_CNT), CheckWait.get(AMDGPU::DS_CNT)}))
1533 UpdateWait.set(AMDGPU::VM_VSRC, ~0u);
1534 simplifyWaitcnt(UpdateWait, AMDGPU::VM_VSRC);
1535}
1536
1537void WaitcntBrackets::purgeEmptyTrackingData() {
1538 for (auto &[K, V] : make_early_inc_range(VMem)) {
1539 if (V.empty())
1540 VMem.erase(K);
1541 }
1542 for (auto &[K, V] : make_early_inc_range(SGPRs)) {
1543 if (V.empty())
1544 SGPRs.erase(K);
1545 }
1546}
1547
1548void WaitcntBrackets::determineWaitForScore(AMDGPU::InstCounterType T,
1549 unsigned ScoreToWait,
1550 AMDGPU::Waitcnt &Wait) const {
1551 const unsigned LB = getScoreLB(T);
1552 const unsigned UB = getScoreUB(T);
1553
1554 // If the score falls within the bracket, we need a waitcnt.
1555 if ((UB >= ScoreToWait) && (ScoreToWait > LB)) {
1556 if ((T == AMDGPU::LOAD_CNT || T == AMDGPU::DS_CNT) && hasPendingFlat() &&
1557 !Context->ST.hasFlatLgkmVMemCountInOrder()) {
1558 // If there is a pending FLAT operation, and this is a VMem or LGKM
1559 // waitcnt and the target can report early completion, then we need
1560 // to force a waitcnt 0.
1561 addWait(Wait, T, 0);
1562 } else if (counterOutOfOrder(T)) {
1563 // Counter can get decremented out-of-order when there
1564 // are multiple types event in the bracket. Also emit an s_wait counter
1565 // with a conservative value of 0 for the counter.
1566 addWait(Wait, T, 0);
1567 } else {
1568 // If a counter has been maxed out avoid overflow by waiting for
1569 // MAX(CounterType) - 1 instead.
1570 unsigned NeededWait = std::min(
1571 UB - ScoreToWait, getWaitCountMax(Context->getLimits(), T) - 1);
1572 addWait(Wait, T, NeededWait);
1573 }
1574 }
1575}
1576
1577AMDGPU::Waitcnt WaitcntBrackets::determineAsyncWait(unsigned N) {
1578 LLVM_DEBUG({
1579 dbgs() << "Need " << N << " async marks. Found " << AsyncMarks.size()
1580 << ":\n";
1581 for (const auto &Mark : AsyncMarks) {
1582 llvm::interleaveComma(Mark, dbgs());
1583 dbgs() << '\n';
1584 }
1585 });
1586
1587 if (AsyncMarks.size() == MaxAsyncMarks) {
1588 // Enforcing MaxAsyncMarks here is unnecessary work because the size of
1589 // MaxAsyncMarks is linear when traversing straightline code. But we do
1590 // need to check if truncation may have occured at a merge, and adjust N
1591 // to ensure that a wait is generated.
1592 LLVM_DEBUG(dbgs() << "Possible truncation. Ensuring a non-trivial wait.\n");
1593 N = std::min(N, (unsigned)MaxAsyncMarks - 1);
1594 }
1595
1596 AMDGPU::Waitcnt Wait;
1597 if (AsyncMarks.size() <= N) {
1598 LLVM_DEBUG(dbgs() << "No additional wait for async mark.\n");
1599 return Wait;
1600 }
1601
1602 size_t MarkIndex = AsyncMarks.size() - N - 1;
1603 const auto &RequiredMark = AsyncMarks[MarkIndex];
1605 determineWaitForScore(T, RequiredMark[T], Wait);
1606
1607 // Immediately remove the waited mark and all older ones
1608 // This happens BEFORE the wait is actually inserted, which is fine
1609 // because we've already extracted the wait requirements
1610 LLVM_DEBUG({
1611 dbgs() << "Removing " << (MarkIndex + 1)
1612 << " async marks after determining wait\n";
1613 });
1614 AsyncMarks.erase(AsyncMarks.begin(), AsyncMarks.begin() + MarkIndex + 1);
1615
1616 LLVM_DEBUG(dbgs() << "Waits to add: " << Wait);
1617 return Wait;
1618}
1619
1620void WaitcntBrackets::determineWaitForPhysReg(AMDGPU::InstCounterType T,
1621 MCPhysReg Reg,
1622 AMDGPU::Waitcnt &Wait) const {
1623 if (Reg == AMDGPU::SCC) {
1624 determineWaitForScore(T, SCCScore, Wait);
1625 } else {
1626 bool IsVGPR = Context->TRI.isVectorRegister(Context->MRI, Reg);
1627 for (MCRegUnit RU : regunits(Reg))
1628 determineWaitForScore(
1629 T, IsVGPR ? getVMemScore(toVMEMID(RU), T) : getSGPRScore(RU, T),
1630 Wait);
1631 }
1632}
1633
1634void WaitcntBrackets::determineWaitForLDSDMA(AMDGPU::InstCounterType T,
1635 VMEMID TID,
1636 AMDGPU::Waitcnt &Wait) const {
1637 assert(TID >= LDSDMA_BEGIN && TID < LDSDMA_END);
1638 determineWaitForScore(T, getVMemScore(TID, T), Wait);
1639}
1640
1641void WaitcntBrackets::tryClearSCCWriteEvent(MachineInstr *Inst) {
1642 // S_BARRIER_WAIT on the same barrier guarantees that the pending write to
1643 // SCC has landed
1644 if (PendingSCCWrite &&
1645 PendingSCCWrite->getOpcode() == AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM &&
1646 PendingSCCWrite->getOperand(0).getImm() == Inst->getOperand(0).getImm()) {
1647 WaitEventSet SCC_WRITE_PendingEvent(SCC_WRITE);
1648 // If this SCC_WRITE is the only pending KM_CNT event, clear counter.
1649 if ((PendingEvents & Context->getWaitEvents(AMDGPU::KM_CNT)) ==
1650 SCC_WRITE_PendingEvent) {
1651 setScoreLB(AMDGPU::KM_CNT, getScoreUB(AMDGPU::KM_CNT));
1652 }
1653
1654 PendingEvents.remove(SCC_WRITE_PendingEvent);
1655 PendingSCCWrite = nullptr;
1656 }
1657}
1658
1659void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait) {
1661 applyWaitcnt(Wait, T);
1662}
1663
1664void WaitcntBrackets::applyWaitcnt(AMDGPU::InstCounterType T, unsigned Count) {
1665 const unsigned UB = getScoreUB(T);
1666 if (Count >= UB)
1667 return;
1668 if (Count != 0) {
1669 if (counterOutOfOrder(T))
1670 return;
1671 setScoreLB(T, std::max(getScoreLB(T), UB - Count));
1672 } else {
1673 setScoreLB(T, UB);
1674 PendingEvents.remove(Context->getWaitEvents(T));
1675 }
1676
1677 if (T == AMDGPU::KM_CNT && Count == 0 && hasPendingEvent(SMEM_GROUP)) {
1678 if (!hasMixedPendingEvents(AMDGPU::X_CNT))
1679 applyWaitcnt(AMDGPU::X_CNT, 0);
1680 else
1681 PendingEvents.remove(SMEM_GROUP);
1682 }
1683 if (T == AMDGPU::LOAD_CNT && hasPendingEvent(VMEM_GROUP) &&
1684 !hasPendingEvent(AMDGPU::STORE_CNT)) {
1685 if (!hasMixedPendingEvents(AMDGPU::X_CNT))
1686 applyWaitcnt(AMDGPU::X_CNT, Count);
1687 else if (Count == 0)
1688 PendingEvents.remove(VMEM_GROUP);
1689 }
1690}
1691
1692void WaitcntBrackets::applyWaitcnt(const AMDGPU::Waitcnt &Wait,
1694 unsigned Cnt = Wait.get(T);
1695 applyWaitcnt(T, Cnt);
1696}
1697
1698// Where there are multiple types of event in the bracket of a counter,
1699// the decrement may go out of order.
1700bool WaitcntBrackets::counterOutOfOrder(AMDGPU::InstCounterType T) const {
1701 // Scalar memory read always can go out of order.
1702 if ((T == Context->SmemAccessCounter && hasPendingEvent(SMEM_ACCESS)) ||
1703 (T == AMDGPU::X_CNT && hasPendingEvent(SMEM_GROUP)))
1704 return true;
1705
1706 // GLOBAL_INV completes in-order with other LOAD_CNT events (VMEM_ACCESS),
1707 // so having GLOBAL_INV_ACCESS mixed with other LOAD_CNT events doesn't cause
1708 // out-of-order completion.
1709 if (T == AMDGPU::LOAD_CNT) {
1710 WaitEventSet Events = PendingEvents & Context->getWaitEvents(T);
1711 // Remove GLOBAL_INV_ACCESS from the event mask before checking for mixed
1712 // events
1713 Events.remove(GLOBAL_INV_ACCESS);
1714 // Return true only if there are still multiple event types after removing
1715 // GLOBAL_INV
1716 return Events.twoOrMore();
1717 }
1718
1719 return hasMixedPendingEvents(T);
1720}
1721
1722INITIALIZE_PASS_BEGIN(SIInsertWaitcntsLegacy, DEBUG_TYPE, "SI Insert Waitcnts",
1723 false, false)
1726INITIALIZE_PASS_END(SIInsertWaitcntsLegacy, DEBUG_TYPE, "SI Insert Waitcnts",
1728
1729char SIInsertWaitcntsLegacy::ID = 0;
1730
1731char &llvm::SIInsertWaitcntsID = SIInsertWaitcntsLegacy::ID;
1732
1734 return new SIInsertWaitcntsLegacy();
1735}
1736
1737static bool updateOperandIfDifferent(MachineInstr &MI, AMDGPU::OpName OpName,
1738 unsigned NewEnc) {
1739 int OpIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OpName);
1740 assert(OpIdx >= 0);
1741
1742 MachineOperand &MO = MI.getOperand(OpIdx);
1743
1744 if (NewEnc == MO.getImm())
1745 return false;
1746
1747 MO.setImm(NewEnc);
1748 return true;
1749}
1750
1751/// Determine if \p MI is a gfx12+ single-counter S_WAIT_*CNT instruction,
1752/// and if so, which counter it is waiting on.
1753static std::optional<AMDGPU::InstCounterType>
1754counterTypeForInstr(unsigned Opcode) {
1755 switch (Opcode) {
1756 case AMDGPU::S_WAIT_LOADCNT:
1757 return AMDGPU::LOAD_CNT;
1758 case AMDGPU::S_WAIT_EXPCNT:
1759 return AMDGPU::EXP_CNT;
1760 case AMDGPU::S_WAIT_STORECNT:
1761 return AMDGPU::STORE_CNT;
1762 case AMDGPU::S_WAIT_SAMPLECNT:
1763 return AMDGPU::SAMPLE_CNT;
1764 case AMDGPU::S_WAIT_BVHCNT:
1765 return AMDGPU::BVH_CNT;
1766 case AMDGPU::S_WAIT_DSCNT:
1767 return AMDGPU::DS_CNT;
1768 case AMDGPU::S_WAIT_KMCNT:
1769 return AMDGPU::KM_CNT;
1770 case AMDGPU::S_WAIT_XCNT:
1771 return AMDGPU::X_CNT;
1772 case AMDGPU::S_WAIT_ASYNCCNT:
1773 return AMDGPU::ASYNC_CNT;
1774 default:
1775 return {};
1776 }
1777}
1778
1779bool WaitcntGenerator::promoteSoftWaitCnt(MachineInstr *Waitcnt) const {
1780 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Waitcnt->getOpcode());
1781 if (Opcode == Waitcnt->getOpcode())
1782 return false;
1783
1784 Waitcnt->setDesc(TII.get(Opcode));
1785 return true;
1786}
1787
1788/// Combine consecutive S_WAITCNT and S_WAITCNT_VSCNT instructions that
1789/// precede \p It and follow \p OldWaitcntInstr and apply any extra waits
1790/// from \p Wait that were added by previous passes. Currently this pass
1791/// conservatively assumes that these preexisting waits are required for
1792/// correctness.
1793bool WaitcntGeneratorPreGFX12::applyPreexistingWaitcnt(
1794 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
1795 AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
1796 assert(isNormalMode(MaxCounter));
1797
1798 bool Modified = false;
1799 MachineInstr *WaitcntInstr = nullptr;
1800 MachineInstr *WaitcntVsCntInstr = nullptr;
1801
1802 LLVM_DEBUG({
1803 dbgs() << "PreGFX12::applyPreexistingWaitcnt at: ";
1804 if (It.isEnd())
1805 dbgs() << "end of block\n";
1806 else
1807 dbgs() << *It;
1808 });
1809
1810 for (auto &II :
1811 make_early_inc_range(make_range(OldWaitcntInstr.getIterator(), It))) {
1812 LLVM_DEBUG(dbgs() << "pre-existing iter: " << II);
1813 if (II.isMetaInstruction()) {
1814 LLVM_DEBUG(dbgs() << "skipped meta instruction\n");
1815 continue;
1816 }
1817
1818 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
1819 bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
1820
1821 // Update required wait count. If this is a soft waitcnt (= it was added
1822 // by an earlier pass), it may be entirely removed.
1823 if (Opcode == AMDGPU::S_WAITCNT) {
1824 unsigned IEnc = II.getOperand(0).getImm();
1825 AMDGPU::Waitcnt OldWait = AMDGPU::decodeWaitcnt(IV, IEnc);
1826 if (TrySimplify)
1827 ScoreBrackets.simplifyWaitcnt(OldWait);
1828 Wait = Wait.combined(OldWait);
1829
1830 // Merge consecutive waitcnt of the same type by erasing multiples.
1831 if (WaitcntInstr || (!Wait.hasWaitExceptStoreCnt() && TrySimplify)) {
1832 II.eraseFromParent();
1833 Modified = true;
1834 } else
1835 WaitcntInstr = &II;
1836 } else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
1837 assert(ST.hasVMemToLDSLoad());
1838 LLVM_DEBUG(dbgs() << "Processing S_WAITCNT_lds_direct: " << II
1839 << "Before: " << Wait << '\n';);
1840 ScoreBrackets.determineWaitForLDSDMA(AMDGPU::LOAD_CNT, LDSDMA_BEGIN,
1841 Wait);
1842 LLVM_DEBUG(dbgs() << "After: " << Wait << '\n';);
1843
1844 // It is possible (but unlikely) that this is the only wait instruction,
1845 // in which case, we exit this loop without a WaitcntInstr to consume
1846 // `Wait`. But that works because `Wait` was passed in by reference, and
1847 // the callee eventually calls createNewWaitcnt on it. We test this
1848 // possibility in an articial MIR test since such a situation cannot be
1849 // recreated by running the memory legalizer.
1850 II.eraseFromParent();
1851 } else if (Opcode == AMDGPU::WAIT_ASYNCMARK) {
1852 unsigned N = II.getOperand(0).getImm();
1853 LLVM_DEBUG(dbgs() << "Processing WAIT_ASYNCMARK: " << II << '\n';);
1854 AMDGPU::Waitcnt OldWait = ScoreBrackets.determineAsyncWait(N);
1855 Wait = Wait.combined(OldWait);
1856 } else {
1857 assert(Opcode == AMDGPU::S_WAITCNT_VSCNT);
1858 assert(II.getOperand(0).getReg() == AMDGPU::SGPR_NULL);
1859
1860 unsigned OldVSCnt =
1861 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
1862 if (TrySimplify)
1863 ScoreBrackets.simplifyWaitcnt(AMDGPU::STORE_CNT, OldVSCnt);
1865 std::min(Wait.get(AMDGPU::STORE_CNT), OldVSCnt));
1866
1867 if (WaitcntVsCntInstr || (!Wait.hasWaitStoreCnt() && TrySimplify)) {
1868 II.eraseFromParent();
1869 Modified = true;
1870 } else
1871 WaitcntVsCntInstr = &II;
1872 }
1873 }
1874
1875 if (WaitcntInstr) {
1876 Modified |= updateOperandIfDifferent(*WaitcntInstr, AMDGPU::OpName::simm16,
1878 Modified |= promoteSoftWaitCnt(WaitcntInstr);
1879
1880 ScoreBrackets.applyWaitcnt(Wait, AMDGPU::LOAD_CNT);
1881 ScoreBrackets.applyWaitcnt(Wait, AMDGPU::EXP_CNT);
1882 ScoreBrackets.applyWaitcnt(Wait, AMDGPU::DS_CNT);
1883 Wait.set(AMDGPU::LOAD_CNT, ~0u);
1884 Wait.set(AMDGPU::EXP_CNT, ~0u);
1885 Wait.set(AMDGPU::DS_CNT, ~0u);
1886
1887 LLVM_DEBUG(It.isEnd() ? dbgs() << "applied pre-existing waitcnt\n"
1888 << "New Instr at block end: "
1889 << *WaitcntInstr << '\n'
1890 : dbgs() << "applied pre-existing waitcnt\n"
1891 << "Old Instr: " << *It
1892 << "New Instr: " << *WaitcntInstr << '\n');
1893 }
1894
1895 if (WaitcntVsCntInstr) {
1896 Modified |=
1897 updateOperandIfDifferent(*WaitcntVsCntInstr, AMDGPU::OpName::simm16,
1898 Wait.get(AMDGPU::STORE_CNT));
1899 Modified |= promoteSoftWaitCnt(WaitcntVsCntInstr);
1900
1901 ScoreBrackets.applyWaitcnt(AMDGPU::STORE_CNT, Wait.get(AMDGPU::STORE_CNT));
1902 Wait.set(AMDGPU::STORE_CNT, ~0u);
1903
1904 LLVM_DEBUG(It.isEnd()
1905 ? dbgs() << "applied pre-existing waitcnt\n"
1906 << "New Instr at block end: " << *WaitcntVsCntInstr
1907 << '\n'
1908 : dbgs() << "applied pre-existing waitcnt\n"
1909 << "Old Instr: " << *It
1910 << "New Instr: " << *WaitcntVsCntInstr << '\n');
1911 }
1912
1913 return Modified;
1914}
1915
1916/// Generate S_WAITCNT and/or S_WAITCNT_VSCNT instructions for any
1917/// required counters in \p Wait
1918bool WaitcntGeneratorPreGFX12::createNewWaitcnt(
1919 MachineBasicBlock &Block, MachineBasicBlock::instr_iterator It,
1920 AMDGPU::Waitcnt Wait, const WaitcntBrackets &ScoreBrackets) {
1921 assert(isNormalMode(MaxCounter));
1922
1923 bool Modified = false;
1924 const DebugLoc &DL = Block.findDebugLoc(It);
1925
1926 // Helper to emit expanded waitcnt sequence for profiling.
1927 // Emits waitcnts from (Outstanding-1) down to Target.
1928 // The EmitWaitcnt callback emits a single waitcnt.
1929 auto EmitExpandedWaitcnt = [&](unsigned Outstanding, unsigned Target,
1930 auto EmitWaitcnt) {
1931 do {
1932 EmitWaitcnt(--Outstanding);
1933 } while (Outstanding > Target);
1934 Modified = true;
1935 };
1936
1937 // Waits for VMcnt, LKGMcnt and/or EXPcnt are encoded together into a
1938 // single instruction while VScnt has its own instruction.
1939 if (Wait.hasWaitExceptStoreCnt()) {
1940 // If profiling expansion is enabled, emit an expanded sequence
1941 if (ExpandWaitcntProfiling) {
1942 // Check if any of the counters to be waited on are out-of-order.
1943 // If so, fall back to normal (non-expanded) behavior since expansion
1944 // would provide misleading profiling information.
1945 bool AnyOutOfOrder = false;
1946 for (auto CT : {AMDGPU::LOAD_CNT, AMDGPU::DS_CNT, AMDGPU::EXP_CNT}) {
1947 unsigned WaitCnt = Wait.get(CT);
1948 if (WaitCnt != ~0u && ScoreBrackets.counterOutOfOrder(CT)) {
1949 AnyOutOfOrder = true;
1950 break;
1951 }
1952 }
1953
1954 if (AnyOutOfOrder) {
1955 // Fall back to non-expanded wait
1956 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
1957 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT)).addImm(Enc);
1958 Modified = true;
1959 } else {
1960 // All counters are in-order, safe to expand
1961 for (auto CT : {AMDGPU::LOAD_CNT, AMDGPU::DS_CNT, AMDGPU::EXP_CNT}) {
1962 unsigned WaitCnt = Wait.get(CT);
1963 if (WaitCnt == ~0u)
1964 continue;
1965
1966 unsigned Outstanding = std::min(ScoreBrackets.getOutstanding(CT),
1967 getWaitCountMax(getLimits(), CT) - 1);
1968 EmitExpandedWaitcnt(Outstanding, WaitCnt, [&](unsigned Count) {
1969 AMDGPU::Waitcnt W;
1970 W.set(CT, Count);
1971 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT))
1973 });
1974 }
1975 }
1976 } else {
1977 // Normal behavior: emit single combined waitcnt
1978 unsigned Enc = AMDGPU::encodeWaitcnt(IV, Wait);
1979 [[maybe_unused]] auto SWaitInst =
1980 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT)).addImm(Enc);
1981 Modified = true;
1982
1983 LLVM_DEBUG(dbgs() << "PreGFX12::createNewWaitcnt\n";
1984 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
1985 dbgs() << "New Instr: " << *SWaitInst << '\n');
1986 }
1987 }
1988
1989 if (Wait.hasWaitStoreCnt()) {
1990 assert(ST.hasVscnt());
1991
1992 if (ExpandWaitcntProfiling && Wait.get(AMDGPU::STORE_CNT) != ~0u &&
1993 !ScoreBrackets.counterOutOfOrder(AMDGPU::STORE_CNT)) {
1994 // Only expand if counter is not out-of-order
1995 unsigned Outstanding =
1996 std::min(ScoreBrackets.getOutstanding(AMDGPU::STORE_CNT),
1997 getWaitCountMax(getLimits(), AMDGPU::STORE_CNT) - 1);
1998 EmitExpandedWaitcnt(
1999 Outstanding, Wait.get(AMDGPU::STORE_CNT), [&](unsigned Count) {
2000 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT_VSCNT))
2001 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
2002 .addImm(Count);
2003 });
2004 } else {
2005 [[maybe_unused]] auto SWaitInst =
2006 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT_VSCNT))
2007 .addReg(AMDGPU::SGPR_NULL, RegState::Undef)
2009 Modified = true;
2010
2011 LLVM_DEBUG(dbgs() << "PreGFX12::createNewWaitcnt\n";
2012 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
2013 dbgs() << "New Instr: " << *SWaitInst << '\n');
2014 }
2015 }
2016
2017 return Modified;
2018}
2019
2020AMDGPU::Waitcnt
2021WaitcntGeneratorPreGFX12::getAllZeroWaitcnt(bool IncludeVSCnt) const {
2022 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt && ST.hasVscnt() ? 0 : ~0u);
2023}
2024
2025AMDGPU::Waitcnt
2026WaitcntGeneratorGFX12Plus::getAllZeroWaitcnt(bool IncludeVSCnt) const {
2027 unsigned ExpertVal = IsExpertMode ? 0 : ~0u;
2028 return AMDGPU::Waitcnt(0, 0, 0, IncludeVSCnt ? 0 : ~0u, 0, 0, 0,
2029 ~0u /* XCNT */, ~0u /* ASYNC_CNT */, ExpertVal,
2030 ExpertVal);
2031}
2032
2033/// Combine consecutive S_WAIT_*CNT instructions that precede \p It and
2034/// follow \p OldWaitcntInstr and apply any extra waits from \p Wait that
2035/// were added by previous passes. Currently this pass conservatively
2036/// assumes that these preexisting waits are required for correctness.
2037bool WaitcntGeneratorGFX12Plus::applyPreexistingWaitcnt(
2038 WaitcntBrackets &ScoreBrackets, MachineInstr &OldWaitcntInstr,
2039 AMDGPU::Waitcnt &Wait, MachineBasicBlock::instr_iterator It) const {
2040 assert(!isNormalMode(MaxCounter));
2041
2042 bool Modified = false;
2043 MachineInstr *CombinedLoadDsCntInstr = nullptr;
2044 MachineInstr *CombinedStoreDsCntInstr = nullptr;
2045 MachineInstr *WaitcntDepctrInstr = nullptr;
2046 MachineInstr *WaitInstrs[AMDGPU::NUM_EXTENDED_INST_CNTS] = {};
2047
2048 LLVM_DEBUG({
2049 dbgs() << "GFX12Plus::applyPreexistingWaitcnt at: ";
2050 if (It.isEnd())
2051 dbgs() << "end of block\n";
2052 else
2053 dbgs() << *It;
2054 });
2055
2056 // Accumulate waits that should not be simplified.
2057 AMDGPU::Waitcnt RequiredWait;
2058
2059 for (auto &II :
2060 make_early_inc_range(make_range(OldWaitcntInstr.getIterator(), It))) {
2061 LLVM_DEBUG(dbgs() << "pre-existing iter: " << II);
2062 if (II.isMetaInstruction()) {
2063 LLVM_DEBUG(dbgs() << "skipped meta instruction\n");
2064 continue;
2065 }
2066
2067 // Update required wait count. If this is a soft waitcnt (= it was added
2068 // by an earlier pass), it may be entirely removed.
2069
2070 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(II.getOpcode());
2071 bool TrySimplify = Opcode != II.getOpcode() && !OptNone;
2072
2073 // Don't crash if the programmer used legacy waitcnt intrinsics, but don't
2074 // attempt to do more than that either.
2075 if (Opcode == AMDGPU::S_WAITCNT)
2076 continue;
2077
2078 if (Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT) {
2079 unsigned OldEnc =
2080 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
2081 AMDGPU::Waitcnt OldWait = AMDGPU::decodeLoadcntDscnt(IV, OldEnc);
2082 if (TrySimplify)
2083 Wait = Wait.combined(OldWait);
2084 else
2085 RequiredWait = RequiredWait.combined(OldWait);
2086 // Keep the first wait_loadcnt, erase the rest.
2087 if (CombinedLoadDsCntInstr == nullptr) {
2088 CombinedLoadDsCntInstr = &II;
2089 } else {
2090 II.eraseFromParent();
2091 Modified = true;
2092 }
2093 } else if (Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT) {
2094 unsigned OldEnc =
2095 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
2096 AMDGPU::Waitcnt OldWait = AMDGPU::decodeStorecntDscnt(IV, OldEnc);
2097 if (TrySimplify)
2098 Wait = Wait.combined(OldWait);
2099 else
2100 RequiredWait = RequiredWait.combined(OldWait);
2101 // Keep the first wait_storecnt, erase the rest.
2102 if (CombinedStoreDsCntInstr == nullptr) {
2103 CombinedStoreDsCntInstr = &II;
2104 } else {
2105 II.eraseFromParent();
2106 Modified = true;
2107 }
2108 } else if (Opcode == AMDGPU::S_WAITCNT_DEPCTR) {
2109 unsigned OldEnc =
2110 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
2111 AMDGPU::Waitcnt OldWait;
2114 if (TrySimplify)
2115 ScoreBrackets.simplifyWaitcnt(OldWait);
2116 Wait = Wait.combined(OldWait);
2117 if (WaitcntDepctrInstr == nullptr) {
2118 WaitcntDepctrInstr = &II;
2119 } else {
2120 // S_WAITCNT_DEPCTR requires special care. Don't remove a
2121 // duplicate if it is waiting on things other than VA_VDST or
2122 // VM_VSRC. If that is the case, just make sure the VA_VDST and
2123 // VM_VSRC subfields of the operand are set to the "no wait"
2124 // values.
2125
2126 unsigned Enc =
2127 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
2128 Enc = AMDGPU::DepCtr::encodeFieldVmVsrc(Enc, ~0u);
2129 Enc = AMDGPU::DepCtr::encodeFieldVaVdst(Enc, ~0u);
2130
2131 if (Enc != (unsigned)AMDGPU::DepCtr::getDefaultDepCtrEncoding(ST)) {
2132 Modified |= updateOperandIfDifferent(II, AMDGPU::OpName::simm16, Enc);
2133 Modified |= promoteSoftWaitCnt(&II);
2134 } else {
2135 II.eraseFromParent();
2136 Modified = true;
2137 }
2138 }
2139 } else if (Opcode == AMDGPU::S_WAITCNT_lds_direct) {
2140 // Architectures higher than GFX10 do not have direct loads to
2141 // LDS, so no work required here yet.
2142 II.eraseFromParent();
2143 Modified = true;
2144 } else if (Opcode == AMDGPU::WAIT_ASYNCMARK) {
2145 // Update the Waitcnt, but don't erase the wait.asyncmark() itself. It
2146 // shows up in the assembly as a comment with the original parameter N.
2147 unsigned N = II.getOperand(0).getImm();
2148 AMDGPU::Waitcnt OldWait = ScoreBrackets.determineAsyncWait(N);
2149 Wait = Wait.combined(OldWait);
2150 } else {
2151 std::optional<AMDGPU::InstCounterType> CT = counterTypeForInstr(Opcode);
2152 assert(CT.has_value());
2153 unsigned OldCnt =
2154 TII.getNamedOperand(II, AMDGPU::OpName::simm16)->getImm();
2155 if (TrySimplify)
2156 addWait(Wait, CT.value(), OldCnt);
2157 else
2158 addWait(RequiredWait, CT.value(), OldCnt);
2159 // Keep the first wait of its kind, erase the rest.
2160 if (WaitInstrs[CT.value()] == nullptr) {
2161 WaitInstrs[CT.value()] = &II;
2162 } else {
2163 II.eraseFromParent();
2164 Modified = true;
2165 }
2166 }
2167 }
2168
2169 ScoreBrackets.simplifyWaitcnt(Wait.combined(RequiredWait), Wait);
2170 Wait = Wait.combined(RequiredWait);
2171
2172 if (CombinedLoadDsCntInstr) {
2173 // Only keep an S_WAIT_LOADCNT_DSCNT if both counters actually need
2174 // to be waited for. Otherwise, let the instruction be deleted so
2175 // the appropriate single counter wait instruction can be inserted
2176 // instead, when new S_WAIT_*CNT instructions are inserted by
2177 // createNewWaitcnt(). As a side effect, resetting the wait counts will
2178 // cause any redundant S_WAIT_LOADCNT or S_WAIT_DSCNT to be removed by
2179 // the loop below that deals with single counter instructions.
2180 //
2181 // A wait for LOAD_CNT or DS_CNT implies a wait for VM_VSRC, since
2182 // instructions that have decremented LOAD_CNT or DS_CNT on completion
2183 // will have needed to wait for their register sources to be available
2184 // first.
2185 if (Wait.get(AMDGPU::LOAD_CNT) != ~0u && Wait.get(AMDGPU::DS_CNT) != ~0u) {
2186 unsigned NewEnc = AMDGPU::encodeLoadcntDscnt(IV, Wait);
2187 Modified |= updateOperandIfDifferent(*CombinedLoadDsCntInstr,
2188 AMDGPU::OpName::simm16, NewEnc);
2189 Modified |= promoteSoftWaitCnt(CombinedLoadDsCntInstr);
2190 ScoreBrackets.applyWaitcnt(AMDGPU::LOAD_CNT, Wait.get(AMDGPU::LOAD_CNT));
2191 ScoreBrackets.applyWaitcnt(AMDGPU::DS_CNT, Wait.get(AMDGPU::DS_CNT));
2192 Wait.set(AMDGPU::LOAD_CNT, ~0u);
2193 Wait.set(AMDGPU::DS_CNT, ~0u);
2194
2195 LLVM_DEBUG(It.isEnd() ? dbgs() << "applied pre-existing waitcnt\n"
2196 << "New Instr at block end: "
2197 << *CombinedLoadDsCntInstr << '\n'
2198 : dbgs() << "applied pre-existing waitcnt\n"
2199 << "Old Instr: " << *It << "New Instr: "
2200 << *CombinedLoadDsCntInstr << '\n');
2201 } else {
2202 CombinedLoadDsCntInstr->eraseFromParent();
2203 Modified = true;
2204 }
2205 }
2206
2207 if (CombinedStoreDsCntInstr) {
2208 // Similarly for S_WAIT_STORECNT_DSCNT.
2209 if (Wait.get(AMDGPU::STORE_CNT) != ~0u && Wait.get(AMDGPU::DS_CNT) != ~0u) {
2210 unsigned NewEnc = AMDGPU::encodeStorecntDscnt(IV, Wait);
2211 Modified |= updateOperandIfDifferent(*CombinedStoreDsCntInstr,
2212 AMDGPU::OpName::simm16, NewEnc);
2213 Modified |= promoteSoftWaitCnt(CombinedStoreDsCntInstr);
2214 ScoreBrackets.applyWaitcnt(Wait, AMDGPU::STORE_CNT);
2215 ScoreBrackets.applyWaitcnt(Wait, AMDGPU::DS_CNT);
2216 Wait.set(AMDGPU::STORE_CNT, ~0u);
2217 Wait.set(AMDGPU::DS_CNT, ~0u);
2218
2219 LLVM_DEBUG(It.isEnd() ? dbgs() << "applied pre-existing waitcnt\n"
2220 << "New Instr at block end: "
2221 << *CombinedStoreDsCntInstr << '\n'
2222 : dbgs() << "applied pre-existing waitcnt\n"
2223 << "Old Instr: " << *It << "New Instr: "
2224 << *CombinedStoreDsCntInstr << '\n');
2225 } else {
2226 CombinedStoreDsCntInstr->eraseFromParent();
2227 Modified = true;
2228 }
2229 }
2230
2231 // Look for an opportunity to convert existing S_WAIT_LOADCNT,
2232 // S_WAIT_STORECNT and S_WAIT_DSCNT into new S_WAIT_LOADCNT_DSCNT
2233 // or S_WAIT_STORECNT_DSCNT. This is achieved by selectively removing
2234 // instructions so that createNewWaitcnt() will create new combined
2235 // instructions to replace them.
2236
2237 if (Wait.get(AMDGPU::DS_CNT) != ~0u) {
2238 // This is a vector of addresses in WaitInstrs pointing to instructions
2239 // that should be removed if they are present.
2241
2242 // If it's known that both DScnt and either LOADcnt or STOREcnt (but not
2243 // both) need to be waited for, ensure that there are no existing
2244 // individual wait count instructions for these.
2245
2246 if (Wait.get(AMDGPU::LOAD_CNT) != ~0u) {
2247 WaitsToErase.push_back(&WaitInstrs[AMDGPU::LOAD_CNT]);
2248 WaitsToErase.push_back(&WaitInstrs[AMDGPU::DS_CNT]);
2249 } else if (Wait.get(AMDGPU::STORE_CNT) != ~0u) {
2250 WaitsToErase.push_back(&WaitInstrs[AMDGPU::STORE_CNT]);
2251 WaitsToErase.push_back(&WaitInstrs[AMDGPU::DS_CNT]);
2252 }
2253
2254 for (MachineInstr **WI : WaitsToErase) {
2255 if (!*WI)
2256 continue;
2257
2258 (*WI)->eraseFromParent();
2259 *WI = nullptr;
2260 Modified = true;
2261 }
2262 }
2263
2265 if (!WaitInstrs[CT])
2266 continue;
2267
2268 unsigned NewCnt = Wait.get(CT);
2269 if (NewCnt != ~0u) {
2270 Modified |= updateOperandIfDifferent(*WaitInstrs[CT],
2271 AMDGPU::OpName::simm16, NewCnt);
2272 Modified |= promoteSoftWaitCnt(WaitInstrs[CT]);
2273
2274 ScoreBrackets.applyWaitcnt(CT, NewCnt);
2275 setNoWait(Wait, CT);
2276
2277 LLVM_DEBUG(It.isEnd()
2278 ? dbgs() << "applied pre-existing waitcnt\n"
2279 << "New Instr at block end: " << *WaitInstrs[CT]
2280 << '\n'
2281 : dbgs() << "applied pre-existing waitcnt\n"
2282 << "Old Instr: " << *It
2283 << "New Instr: " << *WaitInstrs[CT] << '\n');
2284 } else {
2285 WaitInstrs[CT]->eraseFromParent();
2286 Modified = true;
2287 }
2288 }
2289
2290 if (WaitcntDepctrInstr) {
2291 // Get the encoded Depctr immediate and override the VA_VDST and VM_VSRC
2292 // subfields with the new required values.
2293 unsigned Enc =
2294 TII.getNamedOperand(*WaitcntDepctrInstr, AMDGPU::OpName::simm16)
2295 ->getImm();
2298
2299 ScoreBrackets.applyWaitcnt(AMDGPU::VA_VDST, Wait.get(AMDGPU::VA_VDST));
2300 ScoreBrackets.applyWaitcnt(AMDGPU::VM_VSRC, Wait.get(AMDGPU::VM_VSRC));
2301 Wait.set(AMDGPU::VA_VDST, ~0u);
2302 Wait.set(AMDGPU::VM_VSRC, ~0u);
2303
2304 // If that new encoded Depctr immediate would actually still wait
2305 // for anything, update the instruction's operand. Otherwise it can
2306 // just be deleted.
2307 if (Enc != (unsigned)AMDGPU::DepCtr::getDefaultDepCtrEncoding(ST)) {
2308 Modified |= updateOperandIfDifferent(*WaitcntDepctrInstr,
2309 AMDGPU::OpName::simm16, Enc);
2310 LLVM_DEBUG(It.isEnd() ? dbgs() << "applyPreexistingWaitcnt\n"
2311 << "New Instr at block end: "
2312 << *WaitcntDepctrInstr << '\n'
2313 : dbgs() << "applyPreexistingWaitcnt\n"
2314 << "Old Instr: " << *It << "New Instr: "
2315 << *WaitcntDepctrInstr << '\n');
2316 } else {
2317 WaitcntDepctrInstr->eraseFromParent();
2318 Modified = true;
2319 }
2320 }
2321
2322 return Modified;
2323}
2324
2325/// Generate S_WAIT_*CNT instructions for any required counters in \p Wait
2326bool WaitcntGeneratorGFX12Plus::createNewWaitcnt(
2327 MachineBasicBlock &Block, MachineBasicBlock::instr_iterator It,
2328 AMDGPU::Waitcnt Wait, const WaitcntBrackets &ScoreBrackets) {
2329 assert(!isNormalMode(MaxCounter));
2330
2331 bool Modified = false;
2332 const DebugLoc &DL = Block.findDebugLoc(It);
2333
2334 // Helper to emit expanded waitcnt sequence for profiling.
2335 auto EmitExpandedWaitcnt = [&](unsigned Outstanding, unsigned Target,
2336 auto EmitWaitcnt) {
2337 for (unsigned I = Outstanding - 1; I > Target && I != ~0u; --I)
2338 EmitWaitcnt(I);
2339 EmitWaitcnt(Target);
2340 Modified = true;
2341 };
2342
2343 // For GFX12+, we use separate wait instructions, which makes expansion
2344 // simpler
2345 if (ExpandWaitcntProfiling) {
2347 unsigned Count = Wait.get(CT);
2348 if (Count == ~0u)
2349 continue;
2350
2351 // Skip expansion for out-of-order counters - emit normal wait instead
2352 if (ScoreBrackets.counterOutOfOrder(CT)) {
2353 BuildMI(Block, It, DL, TII.get(instrsForExtendedCounterTypes[CT]))
2354 .addImm(Count);
2355 Modified = true;
2356 continue;
2357 }
2358
2359 unsigned Outstanding = std::min(ScoreBrackets.getOutstanding(CT),
2360 getWaitCountMax(getLimits(), CT) - 1);
2361 EmitExpandedWaitcnt(Outstanding, Count, [&](unsigned Val) {
2362 BuildMI(Block, It, DL, TII.get(instrsForExtendedCounterTypes[CT]))
2363 .addImm(Val);
2364 });
2365 }
2366 return Modified;
2367 }
2368
2369 // Normal behavior (no expansion)
2370 // Check for opportunities to use combined wait instructions.
2371 if (Wait.get(AMDGPU::DS_CNT) != ~0u) {
2372 MachineInstr *SWaitInst = nullptr;
2373
2374 if (Wait.get(AMDGPU::LOAD_CNT) != ~0u) {
2375 unsigned Enc = AMDGPU::encodeLoadcntDscnt(IV, Wait);
2376
2377 SWaitInst = BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
2378 .addImm(Enc);
2379
2380 Wait.set(AMDGPU::LOAD_CNT, ~0u);
2381 Wait.set(AMDGPU::DS_CNT, ~0u);
2382 } else if (Wait.get(AMDGPU::STORE_CNT) != ~0u) {
2383 unsigned Enc = AMDGPU::encodeStorecntDscnt(IV, Wait);
2384
2385 SWaitInst = BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAIT_STORECNT_DSCNT))
2386 .addImm(Enc);
2387
2388 Wait.set(AMDGPU::STORE_CNT, ~0u);
2389 Wait.set(AMDGPU::DS_CNT, ~0u);
2390 }
2391
2392 if (SWaitInst) {
2393 Modified = true;
2394
2395 LLVM_DEBUG(dbgs() << "GFX12Plus::createNewWaitcnt\n";
2396 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
2397 dbgs() << "New Instr: " << *SWaitInst << '\n');
2398 }
2399 }
2400
2401 // Generate an instruction for any remaining counter that needs
2402 // waiting for.
2403
2405 unsigned Count = Wait.get(CT);
2406 if (Count == ~0u)
2407 continue;
2408
2409 [[maybe_unused]] auto SWaitInst =
2410 BuildMI(Block, It, DL, TII.get(instrsForExtendedCounterTypes[CT]))
2411 .addImm(Count);
2412
2413 Modified = true;
2414
2415 LLVM_DEBUG(dbgs() << "GFX12Plus::createNewWaitcnt\n";
2416 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
2417 dbgs() << "New Instr: " << *SWaitInst << '\n');
2418 }
2419
2420 if (Wait.hasWaitDepctr()) {
2421 assert(IsExpertMode);
2422 unsigned Enc =
2425
2426 [[maybe_unused]] auto SWaitInst =
2427 BuildMI(Block, It, DL, TII.get(AMDGPU::S_WAITCNT_DEPCTR)).addImm(Enc);
2428
2429 Modified = true;
2430
2431 LLVM_DEBUG(dbgs() << "generateWaitcnt\n";
2432 if (It != Block.instr_end()) dbgs() << "Old Instr: " << *It;
2433 dbgs() << "New Instr: " << *SWaitInst << '\n');
2434 }
2435
2436 return Modified;
2437}
2438
2439/// Generate s_waitcnt instruction to be placed before cur_Inst.
2440/// Instructions of a given type are returned in order,
2441/// but instructions of different types can complete out of order.
2442/// We rely on this in-order completion
2443/// and simply assign a score to the memory access instructions.
2444/// We keep track of the active "score bracket" to determine
2445/// if an access of a memory read requires an s_waitcnt
2446/// and if so what the value of each counter is.
2447/// The "score bracket" is bound by the lower bound and upper bound
2448/// scores (*_score_LB and *_score_ub respectively).
2449/// If FlushFlags.FlushVmCnt is true, we want to flush the vmcnt counter here.
2450/// If FlushFlags.FlushDsCnt is true, we want to flush the dscnt counter here
2451/// (GFX12+ only, where DS_CNT is a separate counter).
2452bool SIInsertWaitcnts::generateWaitcntInstBefore(
2453 MachineInstr &MI, WaitcntBrackets &ScoreBrackets,
2454 MachineInstr *OldWaitcntInstr, PreheaderFlushFlags FlushFlags) {
2455 LLVM_DEBUG(dbgs() << "\n*** GenerateWaitcntInstBefore: "; MI.print(dbgs()););
2456 setForceEmitWaitcnt();
2457
2458 assert(!MI.isMetaInstruction());
2459
2460 AMDGPU::Waitcnt Wait;
2461 const unsigned Opc = MI.getOpcode();
2462
2463 switch (Opc) {
2464 case AMDGPU::BUFFER_WBINVL1:
2465 case AMDGPU::BUFFER_WBINVL1_SC:
2466 case AMDGPU::BUFFER_WBINVL1_VOL:
2467 case AMDGPU::BUFFER_GL0_INV:
2468 case AMDGPU::BUFFER_GL1_INV: {
2469 // FIXME: This should have already been handled by the memory legalizer.
2470 // Removing this currently doesn't affect any lit tests, but we need to
2471 // verify that nothing was relying on this. The number of buffer invalidates
2472 // being handled here should not be expanded.
2473 Wait.set(AMDGPU::LOAD_CNT, 0);
2474 break;
2475 }
2476 case AMDGPU::SI_RETURN_TO_EPILOG:
2477 case AMDGPU::SI_RETURN:
2478 case AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN:
2479 case AMDGPU::S_SETPC_B64_return: {
2480 // All waits must be resolved at call return.
2481 // NOTE: this could be improved with knowledge of all call sites or
2482 // with knowledge of the called routines.
2483 ReturnInsts.insert(&MI);
2484 AMDGPU::Waitcnt AllZeroWait =
2485 WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false);
2486 // On GFX12+, if LOAD_CNT is pending but no VGPRs are waiting for loads
2487 // (e.g., only GLOBAL_INV is pending), we can skip waiting on loadcnt.
2488 // GLOBAL_INV increments loadcnt but doesn't write to VGPRs, so there's
2489 // no need to wait for it at function boundaries.
2490 if (ST.hasExtendedWaitCounts() &&
2491 !ScoreBrackets.hasPendingEvent(VMEM_ACCESS))
2492 AllZeroWait.set(AMDGPU::LOAD_CNT, ~0u);
2493 Wait = AllZeroWait;
2494 break;
2495 }
2496 case AMDGPU::S_ENDPGM:
2497 case AMDGPU::S_ENDPGM_SAVED: {
2498 // In dynamic VGPR mode, we want to release the VGPRs before the wave exits.
2499 // Technically the hardware will do this on its own if we don't, but that
2500 // might cost extra cycles compared to doing it explicitly.
2501 // When not in dynamic VGPR mode, identify S_ENDPGM instructions which may
2502 // have to wait for outstanding VMEM stores. In this case it can be useful
2503 // to send a message to explicitly release all VGPRs before the stores have
2504 // completed, but it is only safe to do this if there are no outstanding
2505 // scratch stores.
2506 EndPgmInsts[&MI] = !ScoreBrackets.empty(AMDGPU::STORE_CNT) &&
2507 !ScoreBrackets.hasPendingEvent(SCRATCH_WRITE_ACCESS);
2508 break;
2509 }
2510 case AMDGPU::S_SENDMSG:
2511 case AMDGPU::S_SENDMSGHALT: {
2512 if (ST.hasLegacyGeometry() &&
2513 ((MI.getOperand(0).getImm() & AMDGPU::SendMsg::ID_MASK_PreGFX11_) ==
2515 // Resolve vm waits before gs-done.
2516 Wait.set(AMDGPU::LOAD_CNT, 0);
2517 break;
2518 }
2519 [[fallthrough]];
2520 }
2521 default: {
2522
2523 // Export & GDS instructions do not read the EXEC mask until after the
2524 // export is granted (which can occur well after the instruction is issued).
2525 // The shader program must flush all EXP operations on the export-count
2526 // before overwriting the EXEC mask.
2527 if (MI.modifiesRegister(AMDGPU::EXEC, &TRI)) {
2528 // Export and GDS are tracked individually, either may trigger a waitcnt
2529 // for EXEC.
2530 if (ScoreBrackets.hasPendingEvent(EXP_GPR_LOCK) ||
2531 ScoreBrackets.hasPendingEvent(EXP_PARAM_ACCESS) ||
2532 ScoreBrackets.hasPendingEvent(EXP_POS_ACCESS) ||
2533 ScoreBrackets.hasPendingEvent(GDS_GPR_LOCK)) {
2534 Wait.set(AMDGPU::EXP_CNT, 0);
2535 }
2536 }
2537
2538 // Wait for any pending GDS instruction to complete before any
2539 // "Always GDS" instruction.
2540 if (TII.isAlwaysGDS(Opc) && ScoreBrackets.hasPendingGDS())
2541 addWait(Wait, AMDGPU::DS_CNT, ScoreBrackets.getPendingGDSWait());
2542
2543 if (MI.isCall()) {
2544 // The function is going to insert a wait on everything in its prolog.
2545 // This still needs to be careful if the call target is a load (e.g. a GOT
2546 // load). We also need to check WAW dependency with saved PC.
2547 CallInsts.insert(&MI);
2548 Wait = AMDGPU::Waitcnt();
2549
2550 const MachineOperand &CallAddrOp = TII.getCalleeOperand(MI);
2551 if (CallAddrOp.isReg()) {
2552 ScoreBrackets.determineWaitForPhysReg(
2553 SmemAccessCounter, CallAddrOp.getReg().asMCReg(), Wait);
2554
2555 if (const auto *RtnAddrOp =
2556 TII.getNamedOperand(MI, AMDGPU::OpName::dst)) {
2557 ScoreBrackets.determineWaitForPhysReg(
2558 SmemAccessCounter, RtnAddrOp->getReg().asMCReg(), Wait);
2559 }
2560 }
2561 } else if (Opc == AMDGPU::S_BARRIER_WAIT) {
2562 ScoreBrackets.tryClearSCCWriteEvent(&MI);
2563 } else {
2564 // FIXME: Should not be relying on memoperands.
2565 // Look at the source operands of every instruction to see if
2566 // any of them results from a previous memory operation that affects
2567 // its current usage. If so, an s_waitcnt instruction needs to be
2568 // emitted.
2569 // If the source operand was defined by a load, add the s_waitcnt
2570 // instruction.
2571 //
2572 // Two cases are handled for destination operands:
2573 // 1) If the destination operand was defined by a load, add the s_waitcnt
2574 // instruction to guarantee the right WAW order.
2575 // 2) If a destination operand that was used by a recent export/store ins,
2576 // add s_waitcnt on exp_cnt to guarantee the WAR order.
2577
2578 for (const MachineMemOperand *Memop : MI.memoperands()) {
2579 const Value *Ptr = Memop->getValue();
2580 if (Memop->isStore()) {
2581 if (auto It = SLoadAddresses.find(Ptr); It != SLoadAddresses.end()) {
2582 addWait(Wait, SmemAccessCounter, 0);
2583 if (PDT.dominates(MI.getParent(), It->second))
2584 SLoadAddresses.erase(It);
2585 }
2586 }
2587 unsigned AS = Memop->getAddrSpace();
2589 continue;
2590 // No need to wait before load from VMEM to LDS.
2591 if (TII.mayWriteLDSThroughDMA(MI))
2592 continue;
2593
2594 // LOAD_CNT is only relevant to vgpr or LDS.
2595 unsigned TID = LDSDMA_BEGIN;
2596 if (Ptr && Memop->getAAInfo()) {
2597 const auto &LDSDMAStores = ScoreBrackets.getLDSDMAStores();
2598 for (unsigned I = 0, E = LDSDMAStores.size(); I != E; ++I) {
2599 if (MI.mayAlias(AA, *LDSDMAStores[I], true)) {
2600 if ((I + 1) >= NUM_LDSDMA) {
2601 // We didn't have enough slot to track this LDS DMA store, it
2602 // has been tracked using the common RegNo (FIRST_LDS_VGPR).
2603 ScoreBrackets.determineWaitForLDSDMA(AMDGPU::LOAD_CNT, TID,
2604 Wait);
2605 break;
2606 }
2607
2608 ScoreBrackets.determineWaitForLDSDMA(AMDGPU::LOAD_CNT,
2609 TID + I + 1, Wait);
2610 }
2611 }
2612 } else {
2613 ScoreBrackets.determineWaitForLDSDMA(AMDGPU::LOAD_CNT, TID, Wait);
2614 }
2615 if (Memop->isStore()) {
2616 ScoreBrackets.determineWaitForLDSDMA(AMDGPU::EXP_CNT, TID, Wait);
2617 }
2618 }
2619
2620 // Loop over use and def operands.
2621 for (const MachineOperand &Op : MI.operands()) {
2622 if (!Op.isReg())
2623 continue;
2624
2625 // If the instruction does not read tied source, skip the operand.
2626 if (Op.isTied() && Op.isUse() && TII.doesNotReadTiedSource(MI))
2627 continue;
2628
2629 MCPhysReg Reg = Op.getReg().asMCReg();
2630
2631 const bool IsVGPR = TRI.isVectorRegister(MRI, Op.getReg());
2632 if (IsVGPR) {
2633 // Implicit VGPR defs and uses are never a part of the memory
2634 // instructions description and usually present to account for
2635 // super-register liveness.
2636 // TODO: Most of the other instructions also have implicit uses
2637 // for the liveness accounting only.
2638 if (Op.isImplicit() && MI.mayLoadOrStore())
2639 continue;
2640
2641 ScoreBrackets.determineWaitForPhysReg(AMDGPU::VA_VDST, Reg, Wait);
2642 if (Op.isDef())
2643 ScoreBrackets.determineWaitForPhysReg(AMDGPU::VM_VSRC, Reg, Wait);
2644 // RAW always needs an s_waitcnt. WAW needs an s_waitcnt unless the
2645 // previous write and this write are the same type of VMEM
2646 // instruction, in which case they are (in some architectures)
2647 // guaranteed to write their results in order anyway.
2648 // Additionally check instructions where Point Sample Acceleration
2649 // might be applied.
2650 if (Op.isUse() || !updateVMCntOnly(MI) ||
2651 ScoreBrackets.hasOtherPendingVmemTypes(Reg, getVmemType(MI)) ||
2652 ScoreBrackets.hasPointSamplePendingVmemTypes(MI, Reg) ||
2653 !ST.hasVmemWriteVgprInOrder()) {
2654 ScoreBrackets.determineWaitForPhysReg(AMDGPU::LOAD_CNT, Reg, Wait);
2655 ScoreBrackets.determineWaitForPhysReg(AMDGPU::SAMPLE_CNT, Reg,
2656 Wait);
2657 ScoreBrackets.determineWaitForPhysReg(AMDGPU::BVH_CNT, Reg, Wait);
2658 ScoreBrackets.clearVgprVmemTypes(Reg);
2659 }
2660
2661 if (Op.isDef() || ScoreBrackets.hasPendingEvent(EXP_LDS_ACCESS)) {
2662 ScoreBrackets.determineWaitForPhysReg(AMDGPU::EXP_CNT, Reg, Wait);
2663 }
2664 ScoreBrackets.determineWaitForPhysReg(AMDGPU::DS_CNT, Reg, Wait);
2665 } else if (Op.getReg() == AMDGPU::SCC) {
2666 ScoreBrackets.determineWaitForPhysReg(AMDGPU::KM_CNT, Reg, Wait);
2667 } else {
2668 ScoreBrackets.determineWaitForPhysReg(SmemAccessCounter, Reg, Wait);
2669 }
2670
2671 if (ST.hasWaitXcnt() && Op.isDef())
2672 ScoreBrackets.determineWaitForPhysReg(AMDGPU::X_CNT, Reg, Wait);
2673 }
2674 }
2675 }
2676 }
2677
2678 // Ensure safety against exceptions from outstanding memory operations while
2679 // waiting for a barrier:
2680 //
2681 // * Some subtargets safely handle backing off the barrier in hardware
2682 // when an exception occurs.
2683 // * Some subtargets have an implicit S_WAITCNT 0 before barriers, so that
2684 // there can be no outstanding memory operations during the wait.
2685 // * Subtargets with split barriers don't need to back off the barrier; it
2686 // is up to the trap handler to preserve the user barrier state correctly.
2687 //
2688 // In all other cases, ensure safety by ensuring that there are no outstanding
2689 // memory operations.
2690 if (Opc == AMDGPU::S_BARRIER && !ST.hasAutoWaitcntBeforeBarrier() &&
2691 !ST.hasBackOffBarrier()) {
2692 Wait = Wait.combined(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/true));
2693 }
2694
2695 // TODO: Remove this work-around, enable the assert for Bug 457939
2696 // after fixing the scheduler. Also, the Shader Compiler code is
2697 // independent of target.
2698 if (SIInstrInfo::isCBranchVCCZRead(MI) && ST.hasReadVCCZBug() &&
2699 ScoreBrackets.hasPendingEvent(SMEM_ACCESS)) {
2700 Wait.set(AMDGPU::DS_CNT, 0);
2701 }
2702
2703 // Verify that the wait is actually needed.
2704 ScoreBrackets.simplifyWaitcnt(Wait);
2705
2706 // It is only necessary to insert an S_WAITCNT_DEPCTR instruction that
2707 // waits on VA_VDST if the instruction it would precede is not a VALU
2708 // instruction, since hardware handles VALU->VGPR->VALU hazards in
2709 // expert scheduling mode.
2710 if (TII.isVALU(MI))
2711 Wait.set(AMDGPU::VA_VDST, ~0u);
2712
2713 // Since the translation for VMEM addresses occur in-order, we can apply the
2714 // XCnt if the current instruction is of VMEM type and has a memory
2715 // dependency with another VMEM instruction in flight.
2716 if (Wait.get(AMDGPU::X_CNT) != ~0u && isVmemAccess(MI)) {
2717 ScoreBrackets.applyWaitcnt(Wait, AMDGPU::X_CNT);
2718 Wait.set(AMDGPU::X_CNT, ~0u);
2719 }
2720
2721 // When forcing emit, we need to skip terminators because that would break the
2722 // terminators of the MBB if we emit a waitcnt between terminators.
2723 if (ForceEmitZeroFlag && !MI.isTerminator())
2724 Wait = WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false);
2725
2726 // If we force waitcnt then update Wait accordingly.
2728 if (!ForceEmitWaitcnt[T])
2729 continue;
2730 Wait.set(T, 0);
2731 }
2732
2733 if (FlushFlags.FlushVmCnt) {
2736 Wait.set(T, 0);
2737 }
2738
2739 if (FlushFlags.FlushDsCnt && ScoreBrackets.hasPendingEvent(AMDGPU::DS_CNT))
2740 Wait.set(AMDGPU::DS_CNT, 0);
2741
2742 if (ForceEmitZeroLoadFlag && Wait.get(AMDGPU::LOAD_CNT) != ~0u)
2743 Wait.set(AMDGPU::LOAD_CNT, 0);
2744
2745 return generateWaitcnt(Wait, MI.getIterator(), *MI.getParent(), ScoreBrackets,
2746 OldWaitcntInstr);
2747}
2748
2749bool SIInsertWaitcnts::generateWaitcnt(AMDGPU::Waitcnt Wait,
2751 MachineBasicBlock &Block,
2752 WaitcntBrackets &ScoreBrackets,
2753 MachineInstr *OldWaitcntInstr) {
2754 bool Modified = false;
2755
2756 if (OldWaitcntInstr)
2757 // Try to merge the required wait with preexisting waitcnt instructions.
2758 // Also erase redundant waitcnt.
2759 Modified =
2760 WCG->applyPreexistingWaitcnt(ScoreBrackets, *OldWaitcntInstr, Wait, It);
2761
2762 // ExpCnt can be merged into VINTERP.
2763 if (Wait.get(AMDGPU::EXP_CNT) != ~0u && It != Block.instr_end() &&
2765 MachineOperand *WaitExp = TII.getNamedOperand(*It, AMDGPU::OpName::waitexp);
2766 if (Wait.get(AMDGPU::EXP_CNT) < WaitExp->getImm()) {
2767 WaitExp->setImm(Wait.get(AMDGPU::EXP_CNT));
2768 Modified = true;
2769 }
2770 // Apply ExpCnt before resetting it, so applyWaitcnt below sees all counts.
2771 ScoreBrackets.applyWaitcnt(Wait, AMDGPU::EXP_CNT);
2772 Wait.set(AMDGPU::EXP_CNT, ~0u);
2773
2774 LLVM_DEBUG(dbgs() << "generateWaitcnt\n"
2775 << "Update Instr: " << *It);
2776 }
2777
2778 if (WCG->createNewWaitcnt(Block, It, Wait, ScoreBrackets))
2779 Modified = true;
2780
2781 // Any counts that could have been applied to any existing waitcnt
2782 // instructions will have been done so, now deal with any remaining.
2783 ScoreBrackets.applyWaitcnt(Wait);
2784
2785 return Modified;
2786}
2787
2788std::optional<WaitEventType>
2789SIInsertWaitcnts::getExpertSchedulingEventType(const MachineInstr &Inst) const {
2790 if (TII.isVALU(Inst)) {
2791 // Core/Side-, DP-, XDL- and TRANS-MACC VALU instructions complete
2792 // out-of-order with respect to each other, so each of these classes
2793 // has its own event.
2794
2795 if (TII.isXDL(Inst))
2796 return VGPR_XDL_WRITE;
2797
2798 if (TII.isTRANS(Inst))
2799 return VGPR_TRANS_WRITE;
2800
2802 return VGPR_DPMACC_WRITE;
2803
2804 return VGPR_CSMACC_WRITE;
2805 }
2806
2807 // FLAT and LDS instructions may read their VGPR sources out-of-order
2808 // with respect to each other and all other VMEM instructions, so
2809 // each of these also has a separate event.
2810
2811 if (TII.isFLAT(Inst))
2812 return VGPR_FLAT_READ;
2813
2814 if (TII.isDS(Inst))
2815 return VGPR_LDS_READ;
2816
2817 if (TII.isVMEM(Inst) || TII.isVIMAGE(Inst) || TII.isVSAMPLE(Inst))
2818 return VGPR_VMEM_READ;
2819
2820 // Otherwise, no hazard.
2821
2822 return {};
2823}
2824
2825bool SIInsertWaitcnts::isVmemAccess(const MachineInstr &MI) const {
2826 return (TII.isFLAT(MI) && TII.mayAccessVMEMThroughFlat(MI)) ||
2827 (TII.isVMEM(MI) && !AMDGPU::getMUBUFIsBufferInv(MI.getOpcode()));
2828}
2829
2830// Return true if the next instruction is S_ENDPGM, following fallthrough
2831// blocks if necessary.
2832bool SIInsertWaitcnts::isNextENDPGM(MachineBasicBlock::instr_iterator It,
2833 MachineBasicBlock *Block) const {
2834 auto BlockEnd = Block->getParent()->end();
2835 auto BlockIter = Block->getIterator();
2836
2837 while (true) {
2838 if (It.isEnd()) {
2839 if (++BlockIter != BlockEnd) {
2840 It = BlockIter->instr_begin();
2841 continue;
2842 }
2843
2844 return false;
2845 }
2846
2847 if (!It->isMetaInstruction())
2848 break;
2849
2850 It++;
2851 }
2852
2853 assert(!It.isEnd());
2854
2855 return It->getOpcode() == AMDGPU::S_ENDPGM;
2856}
2857
2858// Add a wait after an instruction if architecture requirements mandate one.
2859bool SIInsertWaitcnts::insertForcedWaitAfter(MachineInstr &Inst,
2860 MachineBasicBlock &Block,
2861 WaitcntBrackets &ScoreBrackets) {
2862 AMDGPU::Waitcnt Wait;
2863 bool NeedsEndPGMCheck = false;
2864
2865 if (ST.isPreciseMemoryEnabled() && Inst.mayLoadOrStore())
2866 Wait = WCG->getAllZeroWaitcnt(Inst.mayStore() &&
2868
2869 if (TII.isAlwaysGDS(Inst.getOpcode())) {
2870 Wait.set(AMDGPU::DS_CNT, 0);
2871 NeedsEndPGMCheck = true;
2872 }
2873
2874 ScoreBrackets.simplifyWaitcnt(Wait);
2875
2876 auto SuccessorIt = std::next(Inst.getIterator());
2877 bool Result = generateWaitcnt(Wait, SuccessorIt, Block, ScoreBrackets,
2878 /*OldWaitcntInstr=*/nullptr);
2879
2880 if (Result && NeedsEndPGMCheck && isNextENDPGM(SuccessorIt, &Block)) {
2881 BuildMI(Block, SuccessorIt, Inst.getDebugLoc(), TII.get(AMDGPU::S_NOP))
2882 .addImm(0);
2883 }
2884
2885 return Result;
2886}
2887
2888WaitEventSet SIInsertWaitcnts::getEventsFor(const MachineInstr &Inst) const {
2889 WaitEventSet Events;
2890 if (IsExpertMode) {
2891 if (const auto ET = getExpertSchedulingEventType(Inst))
2892 Events.insert(*ET);
2893 }
2894
2895 if (TII.isDS(Inst) && TII.usesLGKM_CNT(Inst)) {
2896 if (TII.isAlwaysGDS(Inst.getOpcode()) ||
2897 TII.hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2898 Events.insert(GDS_ACCESS);
2899 Events.insert(GDS_GPR_LOCK);
2900 } else {
2901 Events.insert(LDS_ACCESS);
2902 }
2903 } else if (TII.isFLAT(Inst)) {
2905 Events.insert(getVmemWaitEventType(Inst));
2906 } else {
2907 assert(Inst.mayLoadOrStore());
2908 if (TII.mayAccessVMEMThroughFlat(Inst)) {
2909 if (ST.hasWaitXcnt())
2910 Events.insert(VMEM_GROUP);
2911 Events.insert(getVmemWaitEventType(Inst));
2912 }
2913 if (TII.mayAccessLDSThroughFlat(Inst))
2914 Events.insert(LDS_ACCESS);
2915 }
2916 } else if (SIInstrInfo::isVMEM(Inst) &&
2918 Inst.getOpcode() == AMDGPU::BUFFER_WBL2)) {
2919 // BUFFER_WBL2 is included here because unlike invalidates, has to be
2920 // followed "S_WAITCNT vmcnt(0)" is needed after to ensure the writeback has
2921 // completed.
2922 if (ST.hasWaitXcnt())
2923 Events.insert(VMEM_GROUP);
2924 Events.insert(getVmemWaitEventType(Inst));
2925 if (ST.vmemWriteNeedsExpWaitcnt() &&
2926 (Inst.mayStore() || SIInstrInfo::isAtomicRet(Inst))) {
2927 Events.insert(VMW_GPR_LOCK);
2928 }
2929 } else if (TII.isSMRD(Inst)) {
2930 if (ST.hasWaitXcnt())
2931 Events.insert(SMEM_GROUP);
2932 Events.insert(SMEM_ACCESS);
2933 } else if (SIInstrInfo::isLDSDIR(Inst)) {
2934 Events.insert(EXP_LDS_ACCESS);
2935 } else if (SIInstrInfo::isEXP(Inst)) {
2936 unsigned Imm = TII.getNamedOperand(Inst, AMDGPU::OpName::tgt)->getImm();
2938 Events.insert(EXP_PARAM_ACCESS);
2939 else if (Imm >= AMDGPU::Exp::ET_POS0 && Imm <= AMDGPU::Exp::ET_POS_LAST)
2940 Events.insert(EXP_POS_ACCESS);
2941 else
2942 Events.insert(EXP_GPR_LOCK);
2943 } else if (SIInstrInfo::isSBarrierSCCWrite(Inst.getOpcode())) {
2944 Events.insert(SCC_WRITE);
2945 } else {
2946 switch (Inst.getOpcode()) {
2947 case AMDGPU::S_SENDMSG:
2948 case AMDGPU::S_SENDMSG_RTN_B32:
2949 case AMDGPU::S_SENDMSG_RTN_B64:
2950 case AMDGPU::S_SENDMSGHALT:
2951 Events.insert(SQ_MESSAGE);
2952 break;
2953 case AMDGPU::S_MEMTIME:
2954 case AMDGPU::S_MEMREALTIME:
2955 case AMDGPU::S_GET_BARRIER_STATE_M0:
2956 case AMDGPU::S_GET_BARRIER_STATE_IMM:
2957 Events.insert(SMEM_ACCESS);
2958 break;
2959 }
2960 }
2961 return Events;
2962}
2963
2964void SIInsertWaitcnts::updateEventWaitcntAfter(MachineInstr &Inst,
2965 WaitcntBrackets *ScoreBrackets) {
2966
2967 WaitEventSet InstEvents = getEventsFor(Inst);
2968 for (WaitEventType E : wait_events()) {
2969 if (InstEvents.contains(E))
2970 ScoreBrackets->updateByEvent(E, Inst);
2971 }
2972
2973 if (TII.isDS(Inst) && TII.usesLGKM_CNT(Inst)) {
2974 if (TII.isAlwaysGDS(Inst.getOpcode()) ||
2975 TII.hasModifiersSet(Inst, AMDGPU::OpName::gds)) {
2976 ScoreBrackets->setPendingGDS();
2977 }
2978 } else if (TII.isFLAT(Inst)) {
2979 if (Inst.mayLoadOrStore() && TII.mayAccessVMEMThroughFlat(Inst) &&
2980 TII.mayAccessLDSThroughFlat(Inst) && !SIInstrInfo::isLDSDMA(Inst)) {
2981 // Async/LDSDMA operations have FLAT encoding but do not actually use flat
2982 // pointers. They do have two operands that each access global and LDS,
2983 // thus making it appear at this point that they are using a flat pointer.
2984 // Filter them out, and for the rest, generate a dependency on flat
2985 // pointers so that both VM and LGKM counters are flushed.
2986 ScoreBrackets->setPendingFlat();
2987 }
2988 if (SIInstrInfo::usesASYNC_CNT(Inst)) {
2989 ScoreBrackets->updateByEvent(ASYNC_ACCESS, Inst);
2990 }
2991 } else if (Inst.isCall()) {
2992 // Act as a wait on everything, but AsyncCnt is never included in such
2993 // blanket waits.
2994 ScoreBrackets->applyWaitcnt(WCG->getAllZeroWaitcnt(/*IncludeVSCnt=*/false));
2995 ScoreBrackets->setStateOnFunctionEntryOrReturn();
2996 } else if (TII.isVINTERP(Inst)) {
2997 int64_t Imm = TII.getNamedOperand(Inst, AMDGPU::OpName::waitexp)->getImm();
2998 ScoreBrackets->applyWaitcnt(AMDGPU::EXP_CNT, Imm);
2999 }
3000}
3001
3002bool WaitcntBrackets::mergeScore(const MergeInfo &M, unsigned &Score,
3003 unsigned OtherScore) {
3004 unsigned MyShifted = Score <= M.OldLB ? 0 : Score + M.MyShift;
3005 unsigned OtherShifted =
3006 OtherScore <= M.OtherLB ? 0 : OtherScore + M.OtherShift;
3007 Score = std::max(MyShifted, OtherShifted);
3008 return OtherShifted > MyShifted;
3009}
3010
3011bool WaitcntBrackets::mergeAsyncMarks(ArrayRef<MergeInfo> MergeInfos,
3012 ArrayRef<CounterValueArray> OtherMarks) {
3013 bool StrictDom = false;
3014
3015 LLVM_DEBUG(dbgs() << "Merging async marks ...");
3016 // Early exit: both empty
3017 if (AsyncMarks.empty() && OtherMarks.empty()) {
3018 LLVM_DEBUG(dbgs() << " nothing to merge\n");
3019 return false;
3020 }
3021 LLVM_DEBUG(dbgs() << '\n');
3022
3023 // Determine maximum length needed after merging
3024 auto MaxSize = (unsigned)std::max(AsyncMarks.size(), OtherMarks.size());
3025 MaxSize = std::min(MaxSize, MaxAsyncMarks);
3026
3027 // Keep only the most recent marks within our limit.
3028 if (AsyncMarks.size() > MaxSize)
3029 AsyncMarks.erase(AsyncMarks.begin(),
3030 AsyncMarks.begin() + (AsyncMarks.size() - MaxSize));
3031
3032 // Pad with zero-filled marks if our list is shorter. Zero represents "no
3033 // pending async operations at this checkpoint" and acts as the identity
3034 // element for max() during merging. We pad at the beginning since the marks
3035 // need to be aligned in most-recent order.
3036 constexpr CounterValueArray ZeroMark{};
3037 AsyncMarks.insert(AsyncMarks.begin(), MaxSize - AsyncMarks.size(), ZeroMark);
3038
3039 LLVM_DEBUG({
3040 dbgs() << "Before merge:\n";
3041 for (const auto &Mark : AsyncMarks) {
3042 llvm::interleaveComma(Mark, dbgs());
3043 dbgs() << '\n';
3044 }
3045 dbgs() << "Other marks:\n";
3046 for (const auto &Mark : OtherMarks) {
3047 llvm::interleaveComma(Mark, dbgs());
3048 dbgs() << '\n';
3049 }
3050 });
3051
3052 // Merge element-wise using the existing mergeScore function and the
3053 // appropriate MergeInfo for each counter type. Iterate only while we have
3054 // elements in both vectors.
3055 unsigned OtherSize = OtherMarks.size();
3056 unsigned OurSize = AsyncMarks.size();
3057 unsigned MergeCount = std::min(OtherSize, OurSize);
3058 for (auto Idx : seq_inclusive<unsigned>(1, MergeCount)) {
3059 for (auto T : inst_counter_types(Context->MaxCounter)) {
3060 StrictDom |= mergeScore(MergeInfos[T], AsyncMarks[OurSize - Idx][T],
3061 OtherMarks[OtherSize - Idx][T]);
3062 }
3063 }
3064
3065 LLVM_DEBUG({
3066 dbgs() << "After merge:\n";
3067 for (const auto &Mark : AsyncMarks) {
3068 llvm::interleaveComma(Mark, dbgs());
3069 dbgs() << '\n';
3070 }
3071 });
3072
3073 return StrictDom;
3074}
3075
3076/// Merge the pending events and associater score brackets of \p Other into
3077/// this brackets status.
3078///
3079/// Returns whether the merge resulted in a change that requires tighter waits
3080/// (i.e. the merged brackets strictly dominate the original brackets).
3081bool WaitcntBrackets::merge(const WaitcntBrackets &Other) {
3082 bool StrictDom = false;
3083
3084 // Check if "other" has keys we don't have, and create default entries for
3085 // those. If they remain empty after merging, we will clean it up after.
3086 for (auto K : Other.VMem.keys())
3087 VMem.try_emplace(K);
3088 for (auto K : Other.SGPRs.keys())
3089 SGPRs.try_emplace(K);
3090
3091 // Array to store MergeInfo for each counter type
3092 MergeInfo MergeInfos[AMDGPU::NUM_INST_CNTS];
3093
3094 for (auto T : inst_counter_types(Context->MaxCounter)) {
3095 // Merge event flags for this counter
3096 const WaitEventSet &EventsForT = Context->getWaitEvents(T);
3097 const WaitEventSet OldEvents = PendingEvents & EventsForT;
3098 const WaitEventSet OtherEvents = Other.PendingEvents & EventsForT;
3099 if (!OldEvents.contains(OtherEvents))
3100 StrictDom = true;
3101 PendingEvents |= OtherEvents;
3102
3103 // Merge scores for this counter
3104 const unsigned MyPending = ScoreUBs[T] - ScoreLBs[T];
3105 const unsigned OtherPending = Other.ScoreUBs[T] - Other.ScoreLBs[T];
3106 const unsigned NewUB = ScoreLBs[T] + std::max(MyPending, OtherPending);
3107 if (NewUB < ScoreLBs[T])
3108 report_fatal_error("waitcnt score overflow");
3109
3110 MergeInfo &M = MergeInfos[T];
3111 M.OldLB = ScoreLBs[T];
3112 M.OtherLB = Other.ScoreLBs[T];
3113 M.MyShift = NewUB - ScoreUBs[T];
3114 M.OtherShift = NewUB - Other.ScoreUBs[T];
3115
3116 ScoreUBs[T] = NewUB;
3117
3118 if (T == AMDGPU::LOAD_CNT)
3119 StrictDom |= mergeScore(M, LastFlatLoadCnt, Other.LastFlatLoadCnt);
3120
3121 if (T == AMDGPU::DS_CNT) {
3122 StrictDom |= mergeScore(M, LastFlatDsCnt, Other.LastFlatDsCnt);
3123 StrictDom |= mergeScore(M, LastGDS, Other.LastGDS);
3124 }
3125
3126 if (T == AMDGPU::KM_CNT) {
3127 StrictDom |= mergeScore(M, SCCScore, Other.SCCScore);
3128 if (Other.hasPendingEvent(SCC_WRITE)) {
3129 if (!OldEvents.contains(SCC_WRITE)) {
3130 PendingSCCWrite = Other.PendingSCCWrite;
3131 } else if (PendingSCCWrite != Other.PendingSCCWrite) {
3132 PendingSCCWrite = nullptr;
3133 }
3134 }
3135 }
3136
3137 for (auto &[RegID, Info] : VMem)
3138 StrictDom |= mergeScore(M, Info.Scores[T], Other.getVMemScore(RegID, T));
3139
3140 if (isSmemCounter(T)) {
3141 for (auto &[RegID, Info] : SGPRs) {
3142 auto It = Other.SGPRs.find(RegID);
3143 unsigned OtherScore = (It != Other.SGPRs.end()) ? It->second.get(T) : 0;
3144 StrictDom |= mergeScore(M, Info.get(T), OtherScore);
3145 }
3146 }
3147 }
3148
3149 for (auto &[TID, Info] : VMem) {
3150 if (auto It = Other.VMem.find(TID); It != Other.VMem.end()) {
3151 unsigned char NewVmemTypes = Info.VMEMTypes | It->second.VMEMTypes;
3152 StrictDom |= NewVmemTypes != Info.VMEMTypes;
3153 Info.VMEMTypes = NewVmemTypes;
3154 }
3155 }
3156
3157 StrictDom |= mergeAsyncMarks(MergeInfos, Other.AsyncMarks);
3158 for (auto T : inst_counter_types(Context->MaxCounter))
3159 StrictDom |= mergeScore(MergeInfos[T], AsyncScore[T], Other.AsyncScore[T]);
3160
3161 purgeEmptyTrackingData();
3162 return StrictDom;
3163}
3164
3165static bool isWaitInstr(MachineInstr &Inst) {
3166 unsigned Opcode = SIInstrInfo::getNonSoftWaitcntOpcode(Inst.getOpcode());
3167 return Opcode == AMDGPU::S_WAITCNT ||
3168 (Opcode == AMDGPU::S_WAITCNT_VSCNT && Inst.getOperand(0).isReg() &&
3169 Inst.getOperand(0).getReg() == AMDGPU::SGPR_NULL) ||
3170 Opcode == AMDGPU::S_WAIT_LOADCNT_DSCNT ||
3171 Opcode == AMDGPU::S_WAIT_STORECNT_DSCNT ||
3172 Opcode == AMDGPU::S_WAITCNT_lds_direct ||
3173 Opcode == AMDGPU::WAIT_ASYNCMARK ||
3174 counterTypeForInstr(Opcode).has_value();
3175}
3176
3177void SIInsertWaitcnts::setSchedulingMode(MachineBasicBlock &MBB,
3179 bool ExpertMode) const {
3180 const unsigned EncodedReg = AMDGPU::Hwreg::HwregEncoding::encode(
3182 BuildMI(MBB, I, DebugLoc(), TII.get(AMDGPU::S_SETREG_IMM32_B32))
3183 .addImm(ExpertMode ? 2 : 0)
3184 .addImm(EncodedReg);
3185}
3186
3187namespace {
3188// TODO: Remove this work-around after fixing the scheduler.
3189// There are two reasons why vccz might be incorrect; see ST.hasReadVCCZBug()
3190// and ST.partialVCCWritesUpdateVCCZ().
3191// i. VCCZBug: There is a hardware bug on CI/SI where SMRD instruction may
3192// corrupt vccz bit, so when we detect that an instruction may read from
3193// a corrupt vccz bit, we need to:
3194// 1. Insert s_waitcnt lgkm(0) to wait for all outstanding SMRD
3195// operations to complete.
3196// 2. Recompute the correct value of vccz by writing the current value
3197// of vcc back to vcc.
3198// ii. Partial writes to vcc don't update vccz, so we need to recompute the
3199// correct value of vccz by reading vcc and writing it back to vcc.
3200// No waitcnt is needed in this case.
3201class VCCZWorkaround {
3202 const WaitcntBrackets &ScoreBrackets;
3203 const GCNSubtarget &ST;
3204 const SIInstrInfo &TII;
3205 const SIRegisterInfo &TRI;
3206 bool VCCZCorruptionBug = false;
3207 bool VCCZNotUpdatedByPartialWrites = false;
3208 /// vccz could be incorrect at a basic block boundary if a predecessor wrote
3209 /// to vcc and then issued an smem load, so initialize to true.
3210 bool MustRecomputeVCCZ = true;
3211
3212public:
3213 VCCZWorkaround(const WaitcntBrackets &ScoreBrackets, const GCNSubtarget &ST,
3214 const SIInstrInfo &TII, const SIRegisterInfo &TRI)
3215 : ScoreBrackets(ScoreBrackets), ST(ST), TII(TII), TRI(TRI) {
3216 VCCZCorruptionBug = ST.hasReadVCCZBug();
3217 VCCZNotUpdatedByPartialWrites = !ST.partialVCCWritesUpdateVCCZ();
3218 }
3219 /// If \p MI reads vccz and we must recompute it based on MustRecomputeVCCZ,
3220 /// then emit a vccz recompute instruction before \p MI. This needs to be
3221 /// called on every instruction in the basic block because it also tracks the
3222 /// state and updates MustRecomputeVCCZ accordingly. Returns true if it
3223 /// modified the IR.
3224 bool tryRecomputeVCCZ(MachineInstr &MI) {
3225 // No need to run this if neither bug is present.
3226 if (!VCCZCorruptionBug && !VCCZNotUpdatedByPartialWrites)
3227 return false;
3228
3229 // If MI is an SMEM and it can corrupt vccz on this target, then we need
3230 // both to emit a waitcnt and to recompute vccz.
3231 // But we don't actually emit a waitcnt here. This is done in
3232 // generateWaitcntInstBefore() because it tracks all the necessary waitcnt
3233 // state, and can either skip emitting a waitcnt if there is already one in
3234 // the IR, or emit an "optimized" combined waitcnt.
3235 // If this is an smem read, it could complete and clobber vccz at any time.
3236 MustRecomputeVCCZ |= VCCZCorruptionBug && TII.isSMRD(MI);
3237
3238 // If the target partial vcc writes don't update vccz, and MI is such an
3239 // instruction then we must recompute vccz.
3240 // Note: We are using PartiallyWritesToVCCOpt optional to avoid calling
3241 // `definesRegister()` more than needed, because it's not very cheap.
3242 std::optional<bool> PartiallyWritesToVCCOpt;
3243 auto PartiallyWritesToVCC = [](MachineInstr &MI) {
3244 return MI.definesRegister(AMDGPU::VCC_LO, /*TRI=*/nullptr) ||
3245 MI.definesRegister(AMDGPU::VCC_HI, /*TRI=*/nullptr);
3246 };
3247 if (VCCZNotUpdatedByPartialWrites) {
3248 PartiallyWritesToVCCOpt = PartiallyWritesToVCC(MI);
3249 // If this is a partial VCC write but won't update vccz, then we must
3250 // recompute vccz.
3251 MustRecomputeVCCZ |= *PartiallyWritesToVCCOpt;
3252 }
3253
3254 // If MI is a vcc write with no pending smem, or there is a pending smem
3255 // but the target does not suffer from the vccz corruption bug, then we
3256 // don't need to recompute vccz as this write will recompute it anyway.
3257 if (!ScoreBrackets.hasPendingEvent(SMEM_ACCESS) || !VCCZCorruptionBug) {
3258 // Compute PartiallyWritesToVCCOpt if we haven't done so already.
3259 if (!PartiallyWritesToVCCOpt)
3260 PartiallyWritesToVCCOpt = PartiallyWritesToVCC(MI);
3261 bool FullyWritesToVCC = !*PartiallyWritesToVCCOpt &&
3262 MI.definesRegister(AMDGPU::VCC, /*TRI=*/nullptr);
3263 // If we write to the full vcc or we write partially and the target
3264 // updates vccz on partial writes, then vccz will be updated correctly.
3265 bool UpdatesVCCZ = FullyWritesToVCC || (!VCCZNotUpdatedByPartialWrites &&
3266 *PartiallyWritesToVCCOpt);
3267 if (UpdatesVCCZ)
3268 MustRecomputeVCCZ = false;
3269 }
3270
3271 // If MI is a branch that reads VCCZ then emit a waitcnt and a vccz
3272 // restore instruction if either is needed.
3273 if (SIInstrInfo::isCBranchVCCZRead(MI) && MustRecomputeVCCZ) {
3274 // Recompute the vccz bit. Any time a value is written to vcc, the vccz
3275 // bit is updated, so we can restore the bit by reading the value of vcc
3276 // and then writing it back to the register.
3277 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
3278 TII.get(ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64),
3279 TRI.getVCC())
3280 .addReg(TRI.getVCC());
3281 MustRecomputeVCCZ = false;
3282 return true;
3283 }
3284 return false;
3285 }
3286};
3287
3288} // namespace
3289
3290// Generate s_waitcnt instructions where needed.
3291bool SIInsertWaitcnts::insertWaitcntInBlock(MachineFunction &MF,
3292 MachineBasicBlock &Block,
3293 WaitcntBrackets &ScoreBrackets) {
3294 bool Modified = false;
3295
3296 LLVM_DEBUG({
3297 dbgs() << "*** Begin Block: ";
3298 Block.printName(dbgs());
3299 ScoreBrackets.dump();
3300 });
3301 VCCZWorkaround VCCZW(ScoreBrackets, ST, TII, TRI);
3302
3303 // Walk over the instructions.
3304 MachineInstr *OldWaitcntInstr = nullptr;
3305
3306 // NOTE: We may append instrs after Inst while iterating.
3307 for (MachineBasicBlock::instr_iterator Iter = Block.instr_begin(),
3308 E = Block.instr_end();
3309 Iter != E; ++Iter) {
3310 MachineInstr &Inst = *Iter;
3311 if (Inst.isMetaInstruction())
3312 continue;
3313 // Track pre-existing waitcnts that were added in earlier iterations or by
3314 // the memory legalizer.
3315 if (isWaitInstr(Inst) ||
3316 (IsExpertMode && Inst.getOpcode() == AMDGPU::S_WAITCNT_DEPCTR)) {
3317 if (!OldWaitcntInstr)
3318 OldWaitcntInstr = &Inst;
3319 continue;
3320 }
3321
3322 PreheaderFlushFlags FlushFlags;
3323 if (Block.getFirstTerminator() == Inst)
3324 FlushFlags = isPreheaderToFlush(Block, ScoreBrackets);
3325
3326 // Generate an s_waitcnt instruction to be placed before Inst, if needed.
3327 Modified |= generateWaitcntInstBefore(Inst, ScoreBrackets, OldWaitcntInstr,
3328 FlushFlags);
3329 OldWaitcntInstr = nullptr;
3330
3331 if (Inst.getOpcode() == AMDGPU::ASYNCMARK) {
3332 // Asyncmarks record the current wait state and so should not allow
3333 // waitcnts that occur after them to be merged into waitcnts that occur
3334 // before.
3335 ScoreBrackets.recordAsyncMark(Inst);
3336 continue;
3337 }
3338
3339 if (TII.isSMRD(Inst)) {
3340 for (const MachineMemOperand *Memop : Inst.memoperands()) {
3341 // No need to handle invariant loads when avoiding WAR conflicts, as
3342 // there cannot be a vector store to the same memory location.
3343 if (!Memop->isInvariant()) {
3344 const Value *Ptr = Memop->getValue();
3345 SLoadAddresses.insert(std::pair(Ptr, Inst.getParent()));
3346 }
3347 }
3348 }
3349
3350 updateEventWaitcntAfter(Inst, &ScoreBrackets);
3351
3352 // Note: insertForcedWaitAfter() may add instrs after Iter that need to be
3353 // visited by the loop.
3354 Modified |= insertForcedWaitAfter(Inst, Block, ScoreBrackets);
3355
3356 LLVM_DEBUG({
3357 Inst.print(dbgs());
3358 ScoreBrackets.dump();
3359 });
3360
3361 // If the target suffers from the vccz bugs, this may emit the necessary
3362 // vccz recompute instruction before \p Inst if needed.
3363 Modified |= VCCZW.tryRecomputeVCCZ(Inst);
3364 }
3365
3366 // Flush counters at the end of the block if needed (for preheaders with no
3367 // terminator).
3368 AMDGPU::Waitcnt Wait;
3369 if (Block.getFirstTerminator() == Block.end()) {
3370 PreheaderFlushFlags FlushFlags = isPreheaderToFlush(Block, ScoreBrackets);
3371 if (FlushFlags.FlushVmCnt) {
3372 if (ScoreBrackets.hasPendingEvent(AMDGPU::LOAD_CNT))
3373 Wait.set(AMDGPU::LOAD_CNT, 0);
3374 if (ScoreBrackets.hasPendingEvent(AMDGPU::SAMPLE_CNT))
3375 Wait.set(AMDGPU::SAMPLE_CNT, 0);
3376 if (ScoreBrackets.hasPendingEvent(AMDGPU::BVH_CNT))
3377 Wait.set(AMDGPU::BVH_CNT, 0);
3378 }
3379 if (FlushFlags.FlushDsCnt && ScoreBrackets.hasPendingEvent(AMDGPU::DS_CNT))
3380 Wait.set(AMDGPU::DS_CNT, 0);
3381 }
3382
3383 // Combine or remove any redundant waitcnts at the end of the block.
3384 Modified |= generateWaitcnt(Wait, Block.instr_end(), Block, ScoreBrackets,
3385 OldWaitcntInstr);
3386
3387 LLVM_DEBUG({
3388 dbgs() << "*** End Block: ";
3389 Block.printName(dbgs());
3390 ScoreBrackets.dump();
3391 });
3392
3393 return Modified;
3394}
3395
3396bool SIInsertWaitcnts::removeRedundantSoftXcnts(MachineBasicBlock &Block) {
3397 if (Block.size() <= 1)
3398 return false;
3399 // The Memory Legalizer conservatively inserts a soft xcnt before each
3400 // atomic RMW operation. However, for sequences of back-to-back atomic
3401 // RMWs, only the first s_wait_xcnt insertion is necessary. Optimize away
3402 // the redundant soft xcnts.
3403 bool Modified = false;
3404 // Remember the last atomic with a soft xcnt right before it.
3405 MachineInstr *LastAtomicWithSoftXcnt = nullptr;
3406
3407 for (MachineInstr &MI : drop_begin(Block)) {
3408 // Ignore last atomic if non-LDS VMEM and SMEM.
3409 bool IsLDS =
3410 TII.isDS(MI) || (TII.isFLAT(MI) && TII.mayAccessLDSThroughFlat(MI));
3411 if (!IsLDS && (MI.mayLoad() ^ MI.mayStore()))
3412 LastAtomicWithSoftXcnt = nullptr;
3413
3414 bool IsAtomicRMW = (MI.getDesc().TSFlags & SIInstrFlags::maybeAtomic) &&
3415 MI.mayLoad() && MI.mayStore();
3416 MachineInstr &PrevMI = *MI.getPrevNode();
3417 // This is an atomic with a soft xcnt.
3418 if (PrevMI.getOpcode() == AMDGPU::S_WAIT_XCNT_soft && IsAtomicRMW) {
3419 // If we have already found an atomic with a soft xcnt, remove this soft
3420 // xcnt as it's redundant.
3421 if (LastAtomicWithSoftXcnt) {
3422 PrevMI.eraseFromParent();
3423 Modified = true;
3424 }
3425 LastAtomicWithSoftXcnt = &MI;
3426 }
3427 }
3428 return Modified;
3429}
3430
3431// Return flags indicating which counters should be flushed in the preheader.
3432PreheaderFlushFlags
3433SIInsertWaitcnts::isPreheaderToFlush(MachineBasicBlock &MBB,
3434 const WaitcntBrackets &ScoreBrackets) {
3435 auto [Iterator, IsInserted] =
3436 PreheadersToFlush.try_emplace(&MBB, PreheaderFlushFlags());
3437 if (!IsInserted)
3438 return Iterator->second;
3439
3440 MachineBasicBlock *Succ = MBB.getSingleSuccessor();
3441 if (!Succ)
3442 return PreheaderFlushFlags();
3443
3444 MachineLoop *Loop = MLI.getLoopFor(Succ);
3445 if (!Loop)
3446 return PreheaderFlushFlags();
3447
3448 if (Loop->getLoopPreheader() == &MBB) {
3449 Iterator->second = getPreheaderFlushFlags(Loop, ScoreBrackets);
3450 return Iterator->second;
3451 }
3452
3453 return PreheaderFlushFlags();
3454}
3455
3456bool SIInsertWaitcnts::isVMEMOrFlatVMEM(const MachineInstr &MI) const {
3458 return TII.mayAccessVMEMThroughFlat(MI);
3459 return SIInstrInfo::isVMEM(MI);
3460}
3461
3462bool SIInsertWaitcnts::isDSRead(const MachineInstr &MI) const {
3463 return SIInstrInfo::isDS(MI) && MI.mayLoad() && !MI.mayStore();
3464}
3465
3466// Check if instruction is a store to LDS that is counted via DSCNT
3467// (where that counter exists).
3468bool SIInsertWaitcnts::mayStoreIncrementingDSCNT(const MachineInstr &MI) const {
3469 return MI.mayStore() && SIInstrInfo::isDS(MI);
3470}
3471
3472// Return flags indicating which counters should be flushed in the preheader of
3473// the given loop. We currently decide to flush in the following situations:
3474// For VMEM (FlushVmCnt):
3475// 1. The loop contains vmem store(s), no vmem load and at least one use of a
3476// vgpr containing a value that is loaded outside of the loop. (Only on
3477// targets with no vscnt counter).
3478// 2. The loop contains vmem load(s), but the loaded values are not used in the
3479// loop, and at least one use of a vgpr containing a value that is loaded
3480// outside of the loop.
3481// For DS (FlushDsCnt, GFX12+ only):
3482// 3. The loop contains no DS reads, and at least one use of a vgpr containing
3483// a value that is DS read outside of the loop.
3484// 4. The loop contains DS read(s), loaded values are not used in the same
3485// iteration but in the next iteration (prefetch pattern), and at least one
3486// use of a vgpr containing a value that is DS read outside of the loop.
3487// Flushing in preheader reduces wait overhead if the wait requirement in
3488// iteration 1 would otherwise be more strict (but unfortunately preheader
3489// flush decision is taken before knowing that).
3490// 5. (Single-block loops only) The loop has DS prefetch reads with flush point
3491// tracking. Some DS reads may be used in the same iteration (creating
3492// "flush points"), but others remain unflushed at the backedge. When a DS
3493// read is consumed in the same iteration, it and all prior reads are
3494// "flushed" (FIFO order). No DS writes are allowed in the loop.
3495// TODO: Find a way to extend to multi-block loops.
3496PreheaderFlushFlags
3497SIInsertWaitcnts::getPreheaderFlushFlags(MachineLoop *ML,
3498 const WaitcntBrackets &Brackets) {
3499 PreheaderFlushFlags Flags;
3500 bool HasVMemLoad = false;
3501 bool HasVMemStore = false;
3502 bool UsesVgprVMEMLoadedOutside = false;
3503 bool UsesVgprDSReadOutside = false;
3504 bool VMemInvalidated = false;
3505 // DS optimization only applies to GFX12+ where DS_CNT is separate.
3506 // Tracking status for "no DS read in loop" or "pure DS prefetch
3507 // (use only in next iteration)".
3508 bool TrackSimpleDSOpt = ST.hasExtendedWaitCounts();
3509 DenseSet<MCRegUnit> VgprUse;
3510 DenseSet<MCRegUnit> VgprDefVMEM;
3511 DenseSet<MCRegUnit> VgprDefDS;
3512
3513 // Track DS reads for prefetch pattern with flush points (single-block only).
3514 // Keeps track of the last DS read (position counted from the top of the loop)
3515 // to each VGPR. Read is considered consumed (and thus needs flushing) if
3516 // the dest register has a use or is overwritten (by any later opertions).
3517 DenseMap<MCRegUnit, unsigned> LastDSReadPositionMap;
3518 unsigned DSReadPosition = 0;
3519 bool IsSingleBlock = ML->getNumBlocks() == 1;
3520 bool TrackDSFlushPoint = ST.hasExtendedWaitCounts() && IsSingleBlock;
3521 unsigned LastDSFlushPosition = 0;
3522
3523 for (MachineBasicBlock *MBB : ML->blocks()) {
3524 for (MachineInstr &MI : *MBB) {
3525 if (isVMEMOrFlatVMEM(MI)) {
3526 HasVMemLoad |= MI.mayLoad();
3527 HasVMemStore |= MI.mayStore();
3528 }
3529 // TODO: Can we relax DSStore check? There may be cases where
3530 // these DS stores are drained prior to the end of MBB (or loop).
3531 if (mayStoreIncrementingDSCNT(MI)) {
3532 // Early exit if none of the optimizations are feasible.
3533 // Otherwise, set tracking status appropriately and continue.
3534 if (VMemInvalidated)
3535 return Flags;
3536 TrackSimpleDSOpt = false;
3537 TrackDSFlushPoint = false;
3538 }
3539 bool IsDSRead = isDSRead(MI);
3540 if (IsDSRead)
3541 ++DSReadPosition;
3542
3543 // Helper: if RU has a pending DS read, update LastDSFlushPosition
3544 auto updateDSReadFlushTracking = [&](MCRegUnit RU) {
3545 if (!TrackDSFlushPoint)
3546 return;
3547 if (auto It = LastDSReadPositionMap.find(RU);
3548 It != LastDSReadPositionMap.end()) {
3549 // RU defined by DSRead is used or overwritten. Need to complete
3550 // the read, if not already implied by a later DSRead (to any RU)
3551 // needing to complete in FIFO order.
3552 LastDSFlushPosition = std::max(LastDSFlushPosition, It->second);
3553 }
3554 };
3555
3556 for (const MachineOperand &Op : MI.all_uses()) {
3557 if (Op.isDebug() || !TRI.isVectorRegister(MRI, Op.getReg()))
3558 continue;
3559 // Vgpr use
3560 for (MCRegUnit RU : TRI.regunits(Op.getReg().asMCReg())) {
3561 // If we find a register that is loaded inside the loop, 1. and 2.
3562 // are invalidated.
3563 if (VgprDefVMEM.contains(RU))
3564 VMemInvalidated = true;
3565
3566 // Check for DS reads used inside the loop
3567 if (VgprDefDS.contains(RU))
3568 TrackSimpleDSOpt = false;
3569
3570 // Early exit if all optimizations are invalidated
3571 if (VMemInvalidated && !TrackSimpleDSOpt && !TrackDSFlushPoint)
3572 return Flags;
3573
3574 // Check for flush points (DS read used in same iteration)
3575 updateDSReadFlushTracking(RU);
3576
3577 VgprUse.insert(RU);
3578 // Check if this register has a pending VMEM load from outside the
3579 // loop (value loaded outside and used inside).
3580 VMEMID ID = toVMEMID(RU);
3581 if (Brackets.hasPendingVMEM(ID, AMDGPU::LOAD_CNT) ||
3582 Brackets.hasPendingVMEM(ID, AMDGPU::SAMPLE_CNT) ||
3583 Brackets.hasPendingVMEM(ID, AMDGPU::BVH_CNT))
3584 UsesVgprVMEMLoadedOutside = true;
3585 // Check if loaded outside the loop via DS (not VMEM/FLAT).
3586 // Only consider it a DS read if there's no pending VMEM load for
3587 // this register, since FLAT can set both counters.
3588 else if (Brackets.hasPendingVMEM(ID, AMDGPU::DS_CNT))
3589 UsesVgprDSReadOutside = true;
3590 }
3591 }
3592
3593 // VMem load vgpr def
3594 if (isVMEMOrFlatVMEM(MI) && MI.mayLoad()) {
3595 for (const MachineOperand &Op : MI.all_defs()) {
3596 for (MCRegUnit RU : TRI.regunits(Op.getReg().asMCReg())) {
3597 // If we find a register that is loaded inside the loop, 1. and 2.
3598 // are invalidated.
3599 if (VgprUse.contains(RU))
3600 VMemInvalidated = true;
3601 VgprDefVMEM.insert(RU);
3602 }
3603 }
3604 // Early exit if all optimizations are invalidated
3605 if (VMemInvalidated && !TrackSimpleDSOpt && !TrackDSFlushPoint)
3606 return Flags;
3607 }
3608
3609 // DS read vgpr def
3610 // Note: Unlike VMEM, we DON'T invalidate when VgprUse.contains(RegNo).
3611 // If USE comes before DEF, it's the prefetch pattern (use value from
3612 // previous iteration, read for next iteration). We should still flush
3613 // in preheader so iteration 1 doesn't need to wait inside the loop.
3614 // Only invalidate when DEF comes before USE (same-iteration consumption,
3615 // checked above when processing uses).
3616 if (IsDSRead || TrackDSFlushPoint) {
3617 for (const MachineOperand &Op : MI.all_defs()) {
3618 if (!TRI.isVectorRegister(MRI, Op.getReg()))
3619 continue;
3620 for (MCRegUnit RU : TRI.regunits(Op.getReg().asMCReg())) {
3621 // Check for overwrite of pending DS read (flush point) by any
3622 // instruction
3623 updateDSReadFlushTracking(RU);
3624 if (IsDSRead) {
3625 VgprDefDS.insert(RU);
3626 if (TrackDSFlushPoint)
3627 LastDSReadPositionMap[RU] = DSReadPosition;
3628 }
3629 }
3630 }
3631 }
3632 }
3633 }
3634
3635 // VMEM flush decision
3636 if (!VMemInvalidated && UsesVgprVMEMLoadedOutside &&
3637 ((!ST.hasVscnt() && HasVMemStore && !HasVMemLoad) ||
3638 (HasVMemLoad && ST.hasVmemWriteVgprInOrder())))
3639 Flags.FlushVmCnt = true;
3640
3641 // DS flush decision:
3642 // Simple DS Opt: flush if loop uses DS read values from outside
3643 // and either has no DS reads in the loop, or DS reads whose results
3644 // are not used in the loop.
3645 bool SimpleDSOpt = TrackSimpleDSOpt && UsesVgprDSReadOutside;
3646 // Prefetch with flush points: some DS reads used in same iteration,
3647 // but unflushed reads remain at backedge
3648 bool HasUnflushedDSReads = DSReadPosition > LastDSFlushPosition;
3649 bool DSFlushPointPrefetch =
3650 TrackDSFlushPoint && UsesVgprDSReadOutside && HasUnflushedDSReads;
3651
3652 if (SimpleDSOpt || DSFlushPointPrefetch)
3653 Flags.FlushDsCnt = true;
3654
3655 return Flags;
3656}
3657
3658bool SIInsertWaitcntsLegacy::runOnMachineFunction(MachineFunction &MF) {
3659 auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
3660 auto &PDT =
3661 getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
3662 AliasAnalysis *AA = nullptr;
3663 if (auto *AAR = getAnalysisIfAvailable<AAResultsWrapperPass>())
3664 AA = &AAR->getAAResults();
3665
3666 return SIInsertWaitcnts(MLI, PDT, AA, MF).run();
3667}
3668
3669PreservedAnalyses
3672 auto &MLI = MFAM.getResult<MachineLoopAnalysis>(MF);
3673 auto &PDT = MFAM.getResult<MachinePostDominatorTreeAnalysis>(MF);
3675 .getManager()
3676 .getCachedResult<AAManager>(MF.getFunction());
3677
3678 if (!SIInsertWaitcnts(MLI, PDT, AA, MF).run())
3679 return PreservedAnalyses::all();
3680
3683 .preserve<AAManager>();
3684}
3685
3686bool SIInsertWaitcnts::run() {
3688
3690
3691 // Initialize hardware limits first, as they're needed by the generators.
3692 Limits = AMDGPU::HardwareLimits(IV);
3693
3694 if (ST.hasExtendedWaitCounts()) {
3695 IsExpertMode = ST.hasExpertSchedulingMode() &&
3696 (ExpertSchedulingModeFlag.getNumOccurrences()
3698 : MF.getFunction()
3699 .getFnAttribute("amdgpu-expert-scheduling-mode")
3700 .getValueAsBool());
3701 MaxCounter = IsExpertMode ? AMDGPU::NUM_EXPERT_INST_CNTS
3703 // Initialize WCG per MF. It contains state that depends on MF attributes.
3704 WCG = std::make_unique<WaitcntGeneratorGFX12Plus>(MF, MaxCounter, Limits,
3705 IsExpertMode);
3706 } else {
3707 MaxCounter = AMDGPU::NUM_NORMAL_INST_CNTS;
3708 // Initialize WCG per MF. It contains state that depends on MF attributes.
3709 WCG = std::make_unique<WaitcntGeneratorPreGFX12>(
3710 MF, AMDGPU::NUM_NORMAL_INST_CNTS, Limits);
3711 }
3712
3713 SmemAccessCounter = getCounterFromEvent(SMEM_ACCESS);
3714
3715 bool Modified = false;
3716
3717 MachineBasicBlock &EntryBB = MF.front();
3718
3719 if (!MFI->isEntryFunction() &&
3720 !MF.getFunction().hasFnAttribute(Attribute::Naked)) {
3721 // Wait for any outstanding memory operations that the input registers may
3722 // depend on. We can't track them and it's better to do the wait after the
3723 // costly call sequence.
3724
3725 // TODO: Could insert earlier and schedule more liberally with operations
3726 // that only use caller preserved registers.
3728 while (I != EntryBB.end() && I->isMetaInstruction())
3729 ++I;
3730
3731 if (ST.hasExtendedWaitCounts()) {
3732 BuildMI(EntryBB, I, DebugLoc(), TII.get(AMDGPU::S_WAIT_LOADCNT_DSCNT))
3733 .addImm(0);
3735 if (CT == AMDGPU::LOAD_CNT || CT == AMDGPU::DS_CNT ||
3736 CT == AMDGPU::STORE_CNT || CT == AMDGPU::X_CNT ||
3737 CT == AMDGPU::ASYNC_CNT)
3738 continue;
3739
3740 if (!ST.hasImageInsts() &&
3741 (CT == AMDGPU::EXP_CNT || CT == AMDGPU::SAMPLE_CNT ||
3742 CT == AMDGPU::BVH_CNT))
3743 continue;
3744
3745 BuildMI(EntryBB, I, DebugLoc(),
3746 TII.get(instrsForExtendedCounterTypes[CT]))
3747 .addImm(0);
3748 }
3749 if (IsExpertMode) {
3750 unsigned Enc = AMDGPU::DepCtr::encodeFieldVaVdst(0, ST);
3752 BuildMI(EntryBB, I, DebugLoc(), TII.get(AMDGPU::S_WAITCNT_DEPCTR))
3753 .addImm(Enc);
3754 }
3755 } else {
3756 BuildMI(EntryBB, I, DebugLoc(), TII.get(AMDGPU::S_WAITCNT)).addImm(0);
3757 }
3758
3759 auto NonKernelInitialState = std::make_unique<WaitcntBrackets>(this);
3760 NonKernelInitialState->setStateOnFunctionEntryOrReturn();
3761 BlockInfos[&EntryBB].Incoming = std::move(NonKernelInitialState);
3762
3763 Modified = true;
3764 }
3765
3766 // Keep iterating over the blocks in reverse post order, inserting and
3767 // updating s_waitcnt where needed, until a fix point is reached.
3768 for (auto *MBB : ReversePostOrderTraversal<MachineFunction *>(&MF))
3769 BlockInfos.try_emplace(MBB);
3770
3771 std::unique_ptr<WaitcntBrackets> Brackets;
3772 bool Repeat;
3773 do {
3774 Repeat = false;
3775
3776 for (auto BII = BlockInfos.begin(), BIE = BlockInfos.end(); BII != BIE;
3777 ++BII) {
3778 MachineBasicBlock *MBB = BII->first;
3779 BlockInfo &BI = BII->second;
3780 if (!BI.Dirty)
3781 continue;
3782
3783 if (BI.Incoming) {
3784 if (!Brackets)
3785 Brackets = std::make_unique<WaitcntBrackets>(*BI.Incoming);
3786 else
3787 *Brackets = *BI.Incoming;
3788 } else {
3789 if (!Brackets) {
3790 Brackets = std::make_unique<WaitcntBrackets>(this);
3791 } else {
3792 // Reinitialize in-place. N.B. do not do this by assigning from a
3793 // temporary because the WaitcntBrackets class is large and it could
3794 // cause this function to use an unreasonable amount of stack space.
3795 Brackets->~WaitcntBrackets();
3796 new (Brackets.get()) WaitcntBrackets(this);
3797 }
3798 }
3799
3800 if (ST.hasWaitXcnt())
3801 Modified |= removeRedundantSoftXcnts(*MBB);
3802 Modified |= insertWaitcntInBlock(MF, *MBB, *Brackets);
3803 BI.Dirty = false;
3804
3805 if (Brackets->hasPendingEvent()) {
3806 BlockInfo *MoveBracketsToSucc = nullptr;
3807 for (MachineBasicBlock *Succ : MBB->successors()) {
3808 auto *SuccBII = BlockInfos.find(Succ);
3809 BlockInfo &SuccBI = SuccBII->second;
3810 if (!SuccBI.Incoming) {
3811 SuccBI.Dirty = true;
3812 if (SuccBII <= BII) {
3813 LLVM_DEBUG(dbgs() << "Repeat on backedge without merge\n");
3814 Repeat = true;
3815 }
3816 if (!MoveBracketsToSucc) {
3817 MoveBracketsToSucc = &SuccBI;
3818 } else {
3819 SuccBI.Incoming = std::make_unique<WaitcntBrackets>(*Brackets);
3820 }
3821 } else {
3822 LLVM_DEBUG({
3823 dbgs() << "Try to merge ";
3824 MBB->printName(dbgs());
3825 dbgs() << " into ";
3826 Succ->printName(dbgs());
3827 dbgs() << '\n';
3828 });
3829 if (SuccBI.Incoming->merge(*Brackets)) {
3830 SuccBI.Dirty = true;
3831 if (SuccBII <= BII) {
3832 LLVM_DEBUG(dbgs() << "Repeat on backedge with merge\n");
3833 Repeat = true;
3834 }
3835 }
3836 }
3837 }
3838 if (MoveBracketsToSucc)
3839 MoveBracketsToSucc->Incoming = std::move(Brackets);
3840 }
3841 }
3842 } while (Repeat);
3843
3844 if (ST.hasScalarStores()) {
3845 SmallVector<MachineBasicBlock *, 4> EndPgmBlocks;
3846 bool HaveScalarStores = false;
3847
3848 for (MachineBasicBlock &MBB : MF) {
3849 for (MachineInstr &MI : MBB) {
3850 if (!HaveScalarStores && TII.isScalarStore(MI))
3851 HaveScalarStores = true;
3852
3853 if (MI.getOpcode() == AMDGPU::S_ENDPGM ||
3854 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG)
3855 EndPgmBlocks.push_back(&MBB);
3856 }
3857 }
3858
3859 if (HaveScalarStores) {
3860 // If scalar writes are used, the cache must be flushed or else the next
3861 // wave to reuse the same scratch memory can be clobbered.
3862 //
3863 // Insert s_dcache_wb at wave termination points if there were any scalar
3864 // stores, and only if the cache hasn't already been flushed. This could
3865 // be improved by looking across blocks for flushes in postdominating
3866 // blocks from the stores but an explicitly requested flush is probably
3867 // very rare.
3868 for (MachineBasicBlock *MBB : EndPgmBlocks) {
3869 bool SeenDCacheWB = false;
3870
3871 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
3872 I != E; ++I) {
3873 if (I->getOpcode() == AMDGPU::S_DCACHE_WB)
3874 SeenDCacheWB = true;
3875 else if (TII.isScalarStore(*I))
3876 SeenDCacheWB = false;
3877
3878 // FIXME: It would be better to insert this before a waitcnt if any.
3879 if ((I->getOpcode() == AMDGPU::S_ENDPGM ||
3880 I->getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG) &&
3881 !SeenDCacheWB) {
3882 Modified = true;
3883 BuildMI(*MBB, I, I->getDebugLoc(), TII.get(AMDGPU::S_DCACHE_WB));
3884 }
3885 }
3886 }
3887 }
3888 }
3889
3890 if (IsExpertMode) {
3891 // Enable expert scheduling on function entry. To satisfy ABI requirements
3892 // and to allow calls between function with different expert scheduling
3893 // settings, disable it around calls and before returns.
3894
3896 while (I != EntryBB.end() && I->isMetaInstruction())
3897 ++I;
3898 setSchedulingMode(EntryBB, I, true);
3899
3900 for (MachineInstr *MI : CallInsts) {
3901 MachineBasicBlock &MBB = *MI->getParent();
3902 setSchedulingMode(MBB, MI, false);
3903 setSchedulingMode(MBB, std::next(MI->getIterator()), true);
3904 }
3905
3906 for (MachineInstr *MI : ReturnInsts)
3907 setSchedulingMode(*MI->getParent(), MI, false);
3908
3909 Modified = true;
3910 }
3911
3912 // Deallocate the VGPRs before previously identified S_ENDPGM instructions.
3913 // This is done in different ways depending on how the VGPRs were allocated
3914 // (i.e. whether we're in dynamic VGPR mode or not).
3915 // Skip deallocation if kernel is waveslot limited vs VGPR limited. A short
3916 // waveslot limited kernel runs slower with the deallocation.
3917 if (!WCG->isOptNone() && MFI->isDynamicVGPREnabled()) {
3918 for (auto [MI, _] : EndPgmInsts) {
3919 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
3920 TII.get(AMDGPU::S_ALLOC_VGPR))
3921 .addImm(0);
3922 Modified = true;
3923 }
3924 } else if (!WCG->isOptNone() &&
3925 ST.getGeneration() >= AMDGPUSubtarget::GFX11 &&
3926 (MF.getFrameInfo().hasCalls() ||
3927 ST.getOccupancyWithNumVGPRs(
3928 TRI.getNumUsedPhysRegs(MRI, AMDGPU::VGPR_32RegClass),
3929 /*IsDynamicVGPR=*/false) <
3931 for (auto [MI, Flag] : EndPgmInsts) {
3932 if (Flag) {
3933 if (ST.requiresNopBeforeDeallocVGPRs()) {
3934 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
3935 TII.get(AMDGPU::S_NOP))
3936 .addImm(0);
3937 }
3938 BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
3939 TII.get(AMDGPU::S_SENDMSG))
3941 Modified = true;
3942 }
3943 }
3944 }
3945
3946 return Modified;
3947}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
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)
#define _
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 std::optional< AMDGPU::InstCounterType > counterTypeForInstr(unsigned Opcode)
Determine if MI is a gfx12+ single-counter S_WAIT_*CNT instruction, and if so, which counter it is wa...
static bool isWaitInstr(MachineInstr &Inst)
static cl::opt< bool > ExpertSchedulingModeFlag("amdgpu-expert-scheduling-mode", cl::desc("Enable expert scheduling mode 2 for all functions (GFX12+ only)"), cl::init(false), cl::Hidden)
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)
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:483
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.
Represents the counter values to wait for in an s_waitcnt instruction.
unsigned get(InstCounterType T) const
void set(InstCounterType T, unsigned Val)
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
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
LLVM_ABI bool getValueAsBool() const
Return the attribute's value as a boolean.
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
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:763
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:728
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()
LLVM_ABI void printName(raw_ostream &os, unsigned printNameFlags=PrintNameIr, ModuleSlotTracker *moduleSlotTracker=nullptr) const
Print the basic block's name as:
MachineInstrBundleIterator< MachineInstr > iterator
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
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 & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate 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.
mop_range operands()
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.
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
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
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
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition Pass.cpp:140
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 isDS(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 usesASYNC_CNT(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:882
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 encodeFieldVaVdst(unsigned Encoded, unsigned VaVdst)
unsigned encodeFieldVmVsrc(unsigned Encoded, unsigned VmVsrc)
unsigned decodeFieldVaVdst(unsigned Encoded)
int getDefaultDepCtrEncoding(const MCSubtargetInfo &STI)
unsigned decodeFieldVmVsrc(unsigned Encoded)
unsigned getMaxWavesPerEU(const MCSubtargetInfo *STI)
LLVM_READONLY const MIMGInfo * getMIMGInfo(unsigned Opc)
bool isDPMACCInstruction(unsigned Opc)
iota_range< InstCounterType > inst_counter_types(InstCounterType MaxCounter)
unsigned encodeLoadcntDscnt(const IsaVersion &Version, const Waitcnt &Decoded)
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
Waitcnt decodeWaitcnt(const IsaVersion &Version, unsigned Encoded)
unsigned encodeWaitcnt(const IsaVersion &Version, const Waitcnt &Decoded)
Waitcnt decodeStorecntDscnt(const IsaVersion &Version, unsigned StorecntDscnt)
Waitcnt decodeLoadcntDscnt(const IsaVersion &Version, unsigned LoadcntDscnt)
unsigned encodeStorecntDscnt(const IsaVersion &Version, const Waitcnt &Decoded)
bool getMUBUFIsBufferInv(unsigned Opc)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
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
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto seq_inclusive(T Begin, T End)
Iterate over an integral type from Begin to End inclusive.
Definition Sequence.h:325
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:1739
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.
APInt operator&(APInt a, const APInt &b)
Definition APInt.h:2141
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.
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2131
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2313
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:634
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2173
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
char & SIInsertWaitcntsID
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:157
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
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:163
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
bool operator&=(SparseBitVector< ElementSize > *LHS, const SparseBitVector< ElementSize > &RHS)
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
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool operator|=(SparseBitVector< ElementSize > &LHS, const SparseBitVector< ElementSize > *RHS)
APInt operator|(APInt a, const APInt &b)
Definition APInt.h:2161
FunctionPass * createSIInsertWaitcntsPass()
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
#define N
static constexpr ValueType Default
static constexpr uint64_t encode(Fields... Values)
Represents the hardware counter limits for different wait count types.
Instruction set architecture version.