LLVM 24.0.0git
SIPreEmitPeephole.cpp
Go to the documentation of this file.
1//===-- SIPreEmitPeephole.cpp ------------------------------------===//
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/// This pass performs the peephole optimizations before code emission.
11///
12/// Additionally, this pass also unpacks packed instructions (V_PK_MUL_F32/F16,
13/// V_PK_ADD_F32/F16, V_PK_FMA_F32) adjacent to MFMAs such that they can be
14/// co-issued. This helps with overlapping MFMA and certain vector instructions
15/// in machine schedules and is expected to improve performance. Only those
16/// packed instructions are unpacked that are overlapped by the MFMA latency.
17/// Rest should remain untouched.
18/// TODO: Add support for F16 packed instructions
19//===----------------------------------------------------------------------===//
20
21#include "AMDGPU.h"
22#include "GCNHazardRecognizer.h"
23#include "GCNSubtarget.h"
26#include "llvm/ADT/Statistic.h"
32using namespace llvm;
33
34#define DEBUG_TYPE "si-pre-emit-peephole"
35
36STATISTIC(NumModeWritesRemoved,
37 "Number of redundant mode register writes removed");
38
39namespace {
40
41/// The state of one independent field of the MODE register, as tracked by
42/// removeRedundantModeWrites.
43struct ModeFieldState {
44 std::optional<int64_t> Value;
45 std::optional<int64_t> ValueBeforePendingWrite;
46 MachineInstr *PendingWrite = nullptr;
47
48 bool isTracked() const { return PendingWrite || Value; }
49};
50
51class SIPreEmitPeephole {
52private:
53 const SIInstrInfo *TII = nullptr;
54 const SIRegisterInfo *TRI = nullptr;
55 MachineLoopInfo *MLI = nullptr;
56
57 std::optional<int64_t> matchVccMask(MachineInstr &A, Register &SReg,
58 bool &Changed) const;
59 bool optimizeVccBranch(MachineInstr &MI) const;
60 void updateMLIBeforeRemovingEdge(MachineBasicBlock *From,
61 MachineBasicBlock *To) const;
62 bool optimizeSetGPR(MachineInstr &First, MachineInstr &MI) const;
63 bool getBlockDestinations(MachineBasicBlock &SrcMBB,
64 MachineBasicBlock *&TrueMBB,
65 MachineBasicBlock *&FalseMBB,
66 SmallVectorImpl<MachineOperand> &Cond);
67 bool hasPendingWMMACoexecutionHazard(const MachineInstr &Branch) const;
68 bool mustRetainExeczBranch(const MachineInstr &Branch,
69 const MachineBasicBlock &From,
70 const MachineBasicBlock &To) const;
71 bool removeExeczBranch(MachineInstr &MI, MachineBasicBlock &SrcMBB);
72 bool removeRedundantModeWrites(MachineBasicBlock &SrcMBB) const;
73 bool optimizeCrossWaveVALUCoexec(MachineFunction &MF) const;
74 // Creates a list of packed instructions following an MFMA that are suitable
75 // for unpacking.
76 void collectUnpackingCandidates(MachineInstr &BeginMI,
77 SetVector<MachineInstr *> &InstrsToUnpack,
78 uint16_t NumMFMACycles);
79 // v_pk_fma_f32 v[0:1], v[0:1], v[2:3], v[2:3] op_sel:[1,1,1]
80 // op_sel_hi:[0,0,0]
81 // ==>
82 // v_fma_f32 v0, v1, v3, v3
83 // v_fma_f32 v1, v0, v2, v2
84 // Here, we have overwritten v0 before we use it. This function checks if
85 // unpacking can lead to such a situation.
86 bool canUnpackingClobberRegister(const MachineInstr &MI);
87 // Unpack and insert F32 packed instructions, such as V_PK_MUL, V_PK_ADD, and
88 // V_PK_FMA. Currently, only V_PK_MUL, V_PK_ADD, V_PK_FMA are supported for
89 // this transformation.
90 void performF32Unpacking(MachineInstr &I);
91 // Select corresponding unpacked instruction
92 uint32_t mapToUnpackedOpcode(MachineInstr &I);
93 // Creates the unpacked instruction to be inserted. Adds source modifiers to
94 // the unpacked instructions based on the source modifiers in the packed
95 // instruction.
96 MachineInstrBuilder createUnpackedMI(MachineInstr &I, uint32_t UnpackedOpcode,
97 bool IsHiBits);
98 // Process operands/source modifiers from packed instructions and insert the
99 // appropriate source modifers and operands into the unpacked instructions.
100 void addOperandAndMods(MachineInstrBuilder &NewMI, unsigned SrcMods,
101 bool IsHiBits, const MachineOperand &SrcMO);
102
103public:
104 bool run(MachineFunction &MF, MachineLoopInfo *MLI);
105};
106
107class SIPreEmitPeepholeLegacy : public MachineFunctionPass {
108public:
109 static char ID;
110
111 SIPreEmitPeepholeLegacy() : MachineFunctionPass(ID) {}
112
113 void getAnalysisUsage(AnalysisUsage &AU) const override {
114 AU.addUsedIfAvailable<MachineLoopInfoWrapperPass>();
115 AU.addPreserved<MachineLoopInfoWrapperPass>();
117 }
118
119 bool runOnMachineFunction(MachineFunction &MF) override {
120 auto *MLIWrapper = getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
121 MachineLoopInfo *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
122 return SIPreEmitPeephole().run(MF, MLI);
123 }
124};
125
126} // End anonymous namespace.
127
128INITIALIZE_PASS(SIPreEmitPeepholeLegacy, DEBUG_TYPE,
129 "SI peephole optimizations", false, false)
130
131char SIPreEmitPeepholeLegacy::ID = 0;
132
133char &llvm::SIPreEmitPeepholeID = SIPreEmitPeepholeLegacy::ID;
134
135void SIPreEmitPeephole::updateMLIBeforeRemovingEdge(
136 MachineBasicBlock *From, MachineBasicBlock *To) const {
137 if (!MLI)
138 return;
139
140 // Only handle back-edges: To must be a loop header with From inside the loop.
141 MachineLoop *Loop = MLI->getLoopFor(To);
142 if (!Loop || Loop->getHeader() != To || !Loop->contains(From))
143 return;
144
145 // Count back-edges
146 unsigned BackEdgeCount = 0;
147 for (MachineBasicBlock *Pred : To->predecessors()) {
148 if (Loop->contains(Pred))
149 BackEdgeCount++;
150 }
151
152 if (BackEdgeCount > 1)
153 return;
154
155 MachineLoop *ParentLoop = Loop->getParentLoop();
156
157 // Re-map blocks directly owned by this loop to the parent.
158 for (MachineBasicBlock *BB : Loop->blocks()) {
159 if (MLI->getLoopFor(BB) == Loop)
160 MLI->changeLoopFor(BB, ParentLoop);
161 }
162
163 // Reparent all child loops.
164 while (!Loop->isInnermost()) {
165 MachineLoop *Child = Loop->removeChildLoop(std::prev(Loop->end()));
166 if (ParentLoop)
167 ParentLoop->addChildLoop(Child);
168 else
169 MLI->addTopLevelLoop(Child);
170 }
171
172 if (ParentLoop)
173 ParentLoop->removeChildLoop(Loop);
174 else
175 MLI->removeLoop(llvm::find(*MLI, Loop));
176
177 MLI->destroy(Loop);
178}
179
180// Match the instruction A that defines vcc for optimizeVccBranch. Returns 0 if
181// vcc == 0, -1 if vcc == exec, or std::nullopt otherwise. SReg is set to the
182// mask register when A is an S_AND/S_ANDN2 of exec with a register.
183std::optional<int64_t> SIPreEmitPeephole::matchVccMask(MachineInstr &A,
184 Register &SReg,
185 bool &Changed) const {
186 const GCNSubtarget &ST = A.getMF()->getSubtarget<GCNSubtarget>();
187 const bool IsWave32 = ST.isWave32();
188 const unsigned ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
189 const unsigned AndN2 = IsWave32 ? AMDGPU::S_ANDN2_B32 : AMDGPU::S_ANDN2_B64;
190 const unsigned Mov = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
191
192 const unsigned Opc = A.getOpcode();
193 if (Opc == Mov || Opc == AMDGPU::COPY) {
194 const MachineOperand &Src = A.getOperand(1);
195 if (Src.isImm() && Src.getImm() == 0)
196 return 0;
197 if (Src.isReg() && Src.getReg() == ExecReg)
198 return -1;
199 return std::nullopt;
200 }
201
202 MachineOperand &Op1 = A.getOperand(1);
203 MachineOperand &Op2 = A.getOperand(2);
204 if ((!Op1.isReg() || Op1.getReg() != ExecReg) && Op2.isReg() &&
205 Op2.getReg() == ExecReg) {
206 TII->commuteInstruction(A);
207 Changed = true;
208 }
209 if (!Op1.isReg() || Op1.getReg() != ExecReg)
210 return std::nullopt;
211 if (Op2.isImm() && !(Op2.getImm() == -1 || Op2.getImm() == 0))
212 return std::nullopt;
213
214 int64_t MaskValue = 0;
215 if (Op2.isReg()) {
216 SReg = Op2.getReg();
219 MachineBasicBlock::reverse_iterator E = A.getParent()->rend();
220 bool ReadsSreg = false;
221 for (; M != E; ++M) {
222 if (M->definesRegister(SReg, TRI))
223 break;
224 if (M->modifiesRegister(SReg, TRI))
225 return std::nullopt;
226 ReadsSreg |= M->readsRegister(SReg, TRI);
227 }
228 if (M == E)
229 return std::nullopt;
230
231 if (!M->isMoveImmediate() || !M->getOperand(1).isImm() ||
232 (M->getOperand(1).getImm() != -1 && M->getOperand(1).getImm() != 0))
233 return std::nullopt;
234 MaskValue = M->getOperand(1).getImm();
235 // First if sreg is only used in the AND instruction fold the immediate
236 // into the AND.
237 if (!ReadsSreg && Op2.isKill()) {
238 A.getOperand(2).ChangeToImmediate(MaskValue);
239 M->eraseFromParent();
240 }
241 } else if (Op2.isImm()) {
242 MaskValue = Op2.getImm();
243 } else {
244 llvm_unreachable("Op2 must be register or immediate");
245 }
246
247 // Invert mask for s_andn2
248 assert(MaskValue == 0 || MaskValue == -1);
249 if (Opc == AndN2)
250 MaskValue = ~MaskValue;
251 return MaskValue;
252}
253
254bool SIPreEmitPeephole::optimizeVccBranch(MachineInstr &MI) const {
255 // Match:
256 // vcc = S_AND exec, 0/-1 (or S_ANDN2) / S_MOV 0 / S_MOV|COPY exec
257 // S_CBRANCH_VCC[N]Z
258 // =>
259 // S_CBRANCH_EXEC[N]Z
260
261 bool Changed = false;
262 MachineBasicBlock &MBB = *MI.getParent();
263 const GCNSubtarget &ST = MBB.getParent()->getSubtarget<GCNSubtarget>();
264 const bool IsWave32 = ST.isWave32();
265 const unsigned CondReg = TRI->getVCC();
266 const unsigned ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
267 const unsigned And = IsWave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
268 const unsigned AndN2 = IsWave32 ? AMDGPU::S_ANDN2_B32 : AMDGPU::S_ANDN2_B64;
269 const unsigned Mov = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
270
271 MachineBasicBlock::reverse_iterator A = MI.getReverseIterator(),
272 E = MBB.rend();
273 bool ReadsCond = false;
274 unsigned Threshold = 5;
275 for (++A; A != E; ++A) {
276 if (!--Threshold)
277 return false;
278 if (A->modifiesRegister(ExecReg, TRI))
279 return false;
280 if (A->modifiesRegister(CondReg, TRI)) {
281 unsigned Opc = A->getOpcode();
282 if (!A->definesRegister(CondReg, TRI) ||
283 (Opc != And && Opc != AndN2 && Opc != Mov && Opc != AMDGPU::COPY))
284 return false;
285 break;
286 }
287 ReadsCond |= A->readsRegister(CondReg, TRI);
288 }
289 if (A == E)
290 return false;
291
293 std::optional<int64_t> Match = matchVccMask(*A, SReg, Changed);
294 if (!Match)
295 return Changed;
296 int64_t MaskValue = *Match;
297
298 const bool IsAnd = A->getOpcode() == And || A->getOpcode() == AndN2;
299 if (!ReadsCond &&
300 (!IsAnd || A->registerDefIsDead(AMDGPU::SCC, /*TRI=*/nullptr))) {
301 const bool KillsCond = MI.killsRegister(CondReg, TRI);
302 if (IsAnd && !KillsCond) {
303 // Replace AND with MOV
304 if (MaskValue == 0) {
305 BuildMI(*A->getParent(), *A, A->getDebugLoc(), TII->get(Mov), CondReg)
306 .addImm(0);
307 } else {
308 BuildMI(*A->getParent(), *A, A->getDebugLoc(), TII->get(Mov), CondReg)
309 .addReg(ExecReg);
310 }
311 }
312 if (IsAnd || KillsCond)
313 A->eraseFromParent();
314 }
315
316 bool IsVCCZ = MI.getOpcode() == AMDGPU::S_CBRANCH_VCCZ;
317 if (SReg == ExecReg) {
318 // EXEC is updated directly
319 if (IsVCCZ) {
320 MI.eraseFromParent();
321 return true;
322 }
323 MI.setDesc(TII->get(AMDGPU::S_BRANCH));
324 } else if (IsVCCZ && MaskValue == 0) {
325 // Will always branch
326 // Remove all successors shadowed by new unconditional branch
327 MachineBasicBlock *Parent = MI.getParent();
328 SmallVector<MachineInstr *, 4> ToRemove;
329 bool Found = false;
330 for (MachineInstr &Term : Parent->terminators()) {
331 if (Found) {
332 if (Term.isBranch())
333 ToRemove.push_back(&Term);
334 } else {
335 Found = Term.isIdenticalTo(MI);
336 }
337 }
338 assert(Found && "conditional branch is not terminator");
339 for (auto *BranchMI : ToRemove) {
340 MachineOperand &Dst = BranchMI->getOperand(0);
341 assert(Dst.isMBB() && "destination is not basic block");
342 updateMLIBeforeRemovingEdge(Parent, Dst.getMBB());
343 Parent->removeSuccessor(Dst.getMBB());
344 BranchMI->eraseFromParent();
345 }
346
347 if (MachineBasicBlock *Succ = Parent->getFallThrough()) {
348 updateMLIBeforeRemovingEdge(Parent, Succ);
349 Parent->removeSuccessor(Succ);
350 }
351
352 // Rewrite to unconditional branch
353 MI.setDesc(TII->get(AMDGPU::S_BRANCH));
354 } else if (!IsVCCZ && MaskValue == 0) {
355 // Will never branch
356 MachineOperand &Dst = MI.getOperand(0);
357 assert(Dst.isMBB() && "destination is not basic block");
358 MachineBasicBlock *Parent = MI.getParent();
359 updateMLIBeforeRemovingEdge(Parent, Dst.getMBB());
360 Parent->removeSuccessor(Dst.getMBB());
361 MI.eraseFromParent();
362 return true;
363 } else if (MaskValue == -1) {
364 // Depends only on EXEC
365 MI.setDesc(
366 TII->get(IsVCCZ ? AMDGPU::S_CBRANCH_EXECZ : AMDGPU::S_CBRANCH_EXECNZ));
367 }
368
369 MI.removeOperand(MI.findRegisterUseOperandIdx(CondReg, TRI, false /*Kill*/));
370 MI.addImplicitDefUseOperands(*MBB.getParent());
371
372 return true;
373}
374
375bool SIPreEmitPeephole::optimizeSetGPR(MachineInstr &First,
376 MachineInstr &MI) const {
377 MachineBasicBlock &MBB = *MI.getParent();
378 const MachineFunction &MF = *MBB.getParent();
379 const MachineRegisterInfo &MRI = MF.getRegInfo();
380 MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
381 Register IdxReg = Idx->isReg() ? Idx->getReg() : Register();
382 SmallVector<MachineInstr *, 4> ToRemove;
383 bool IdxOn = true;
384
385 if (!MI.isIdenticalTo(First))
386 return false;
387
388 // Scan back to find an identical S_SET_GPR_IDX_ON
389 for (MachineBasicBlock::instr_iterator I = std::next(First.getIterator()),
390 E = MI.getIterator();
391 I != E; ++I) {
392 if (I->isBundle() || I->isDebugInstr())
393 continue;
394 switch (I->getOpcode()) {
395 case AMDGPU::S_SET_GPR_IDX_MODE:
396 return false;
397 case AMDGPU::S_SET_GPR_IDX_OFF:
398 IdxOn = false;
399 ToRemove.push_back(&*I);
400 break;
401 default:
402 if (I->modifiesRegister(AMDGPU::M0, TRI))
403 return false;
404 if (IdxReg && I->modifiesRegister(IdxReg, TRI))
405 return false;
406 if (llvm::any_of(I->operands(), [&MRI, this](const MachineOperand &MO) {
407 return MO.isReg() && TRI->isVectorRegister(MRI, MO.getReg());
408 })) {
409 // The only exception allowed here is another indirect vector move
410 // with the same mode.
411 if (!IdxOn || !(I->getOpcode() == AMDGPU::V_MOV_B32_indirect_write ||
412 I->getOpcode() == AMDGPU::V_MOV_B32_indirect_read))
413 return false;
414 }
415 }
416 }
417
418 MI.eraseFromBundle();
419 for (MachineInstr *RI : ToRemove)
420 RI->eraseFromBundle();
421 return true;
422}
423
424bool SIPreEmitPeephole::getBlockDestinations(
425 MachineBasicBlock &SrcMBB, MachineBasicBlock *&TrueMBB,
426 MachineBasicBlock *&FalseMBB, SmallVectorImpl<MachineOperand> &Cond) {
427 if (TII->analyzeBranch(SrcMBB, TrueMBB, FalseMBB, Cond))
428 return false;
429
430 if (!FalseMBB)
431 FalseMBB = SrcMBB.getNextNode();
432
433 return true;
434}
435
436namespace {
437class BranchWeightCostModel {
438 const SIInstrInfo &TII;
439 const TargetSchedModel &SchedModel;
440 BranchProbability BranchProb;
441 static constexpr uint64_t BranchNotTakenCost = 1;
442 uint64_t BranchTakenCost;
443 uint64_t ThenCyclesCost = 0;
444
445public:
446 BranchWeightCostModel(const SIInstrInfo &TII, const MachineInstr &Branch,
447 const MachineBasicBlock &Succ)
448 : TII(TII), SchedModel(TII.getSchedModel()) {
449 const MachineBasicBlock &Head = *Branch.getParent();
450 const auto *FromIt = find(Head.successors(), &Succ);
451 assert(FromIt != Head.succ_end());
452
453 BranchProb = Head.getSuccProbability(FromIt);
454 if (BranchProb.isUnknown())
455 BranchProb = BranchProbability::getZero();
456 BranchTakenCost = SchedModel.computeInstrLatency(&Branch);
457 }
458
459 bool isProfitable(const MachineInstr &MI) {
460 if (TII.isWaitcnt(MI.getOpcode()))
461 return false;
462
463 ThenCyclesCost += SchedModel.computeInstrLatency(&MI);
464
465 // Consider `P = N/D` to be the probability of execz being false (skipping
466 // the then-block) The transformation is profitable if always executing the
467 // 'then' block is cheaper than executing sometimes 'then' and always
468 // executing s_cbranch_execz:
469 // * ThenCost <= P*ThenCost + (1-P)*BranchTakenCost + P*BranchNotTakenCost
470 // * (1-P) * ThenCost <= (1-P)*BranchTakenCost + P*BranchNotTakenCost
471 // * (D-N)/D * ThenCost <= (D-N)/D * BranchTakenCost + N/D *
472 // BranchNotTakenCost
473 uint64_t Numerator = BranchProb.getNumerator();
474 uint64_t Denominator = BranchProb.getDenominator();
475 return (Denominator - Numerator) * ThenCyclesCost <=
476 ((Denominator - Numerator) * BranchTakenCost +
477 Numerator * BranchNotTakenCost);
478 }
479};
480
481// Returns true if an XDL WMMA co-execution hazard may still be unresolved when
482// \p Branch is reached. VALUs skipped because EXEC = 0 do not issue, so they
483// must not count toward resolving it.
484bool SIPreEmitPeephole::hasPendingWMMACoexecutionHazard(
485 const MachineInstr &Branch) const {
487 Branch.getMF()->getSubtarget<GCNSubtarget>());
488
489 // Scans backwards, counting VALUs into \p VALUs. Returns true on reaching an
490 // XDL WMMA whose window is not yet covered.
493 unsigned &VALUs) {
494 for (; I != E && VALUs < Window; ++I) {
495 if (I->isBundle() || I->isMetaInstruction())
496 continue;
497 if (TII->isXDLWMMA(*I))
498 return true;
499 if (SIInstrInfo::isVALU(*I, /*AllowLDSDMA=*/true))
500 ++VALUs;
501 }
502 return false;
503 };
504
505 const MachineBasicBlock *MBB = Branch.getParent();
506 unsigned VALUs = 0;
507 if (Scan(std::next(Branch.getReverseIterator()), MBB->instr_rend(), VALUs))
508 return true;
509 if (VALUs >= Window)
510 return false;
511
512 // Fewest VALUs between the end of each visited block and Branch.
513 DenseMap<const MachineBasicBlock *, unsigned> MinVALUsAtEnd;
515 for (const MachineBasicBlock *Pred : MBB->predecessors())
516 Worklist.emplace_back(Pred, VALUs);
517
518 while (!Worklist.empty()) {
519 auto [Block, Count] = Worklist.pop_back_val();
520 auto [It, Inserted] = MinVALUsAtEnd.try_emplace(Block, Count);
521 if (!Inserted) {
522 if (It->second <= Count)
523 continue;
524 It->second = Count;
525 }
526 if (Scan(Block->instr_rbegin(), Block->instr_rend(), Count))
527 return true;
528 if (Count >= Window)
529 continue;
530 for (const MachineBasicBlock *Pred : Block->predecessors())
531 Worklist.emplace_back(Pred, Count);
532 }
533 return false;
534}
535
536bool SIPreEmitPeephole::mustRetainExeczBranch(
537 const MachineInstr &Branch, const MachineBasicBlock &From,
538 const MachineBasicBlock &To) const {
539 assert(is_contained(Branch.getParent()->successors(), &From));
540 BranchWeightCostModel CostModel{*TII, Branch, From};
541 bool HasVALU = false;
542
543 const MachineFunction *MF = From.getParent();
544 const bool CheckWMMA =
545 MF->getSubtarget<GCNSubtarget>().hasWMMACoexecutionHazards();
546 for (MachineFunction::const_iterator MBBI(&From), ToI(&To), End = MF->end();
547 MBBI != End && MBBI != ToI; ++MBBI) {
548 const MachineBasicBlock &MBB = *MBBI;
549
550 for (const MachineInstr &MI : MBB) {
551 // When a uniform loop is inside non-uniform control flow, the branch
552 // leaving the loop might never be taken when EXEC = 0.
553 // Hence we should retain cbranch out of the loop lest it become infinite.
554 if (MI.isConditionalBranch())
555 return true;
556
557 if (MI.isUnconditionalBranch() &&
559 return true;
560
561 if (MI.isMetaInstruction())
562 continue;
563
564 if (TII->hasUnwantedEffectsWhenEXECEmpty(MI))
565 return true;
566
567 // An XDL WMMA is not skipped when EXEC = 0, but the VALUs after it are,
568 // so they cannot cover its hazard window.
569 if (CheckWMMA && TII->isXDLWMMA(MI))
570 return true;
571
572 if (!CostModel.isProfitable(MI))
573 return true;
574
575 HasVALU |= SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/true);
576 }
577 }
578
579 // Keep the skip so the hazard recognizer pads the path around the region
580 // instead of counting VALUs that may be skipped as spacing.
581 return CheckWMMA && HasVALU && hasPendingWMMACoexecutionHazard(Branch);
582}
583} // namespace
584
585// Returns true if the skip branch instruction is removed.
586bool SIPreEmitPeephole::removeExeczBranch(MachineInstr &MI,
587 MachineBasicBlock &SrcMBB) {
588
589 if (!TII->getSchedModel().hasInstrSchedModel())
590 return false;
591
592 MachineBasicBlock *TrueMBB = nullptr;
593 MachineBasicBlock *FalseMBB = nullptr;
595
596 if (!getBlockDestinations(SrcMBB, TrueMBB, FalseMBB, Cond))
597 return false;
598
599 // Consider only the forward branches.
600 if (SrcMBB.getNumber() >= TrueMBB->getNumber())
601 return false;
602
603 // Consider only when it is legal and profitable
604 if (mustRetainExeczBranch(MI, *FalseMBB, *TrueMBB))
605 return false;
606
607 LLVM_DEBUG(dbgs() << "Removing the execz branch: " << MI);
608 MI.eraseFromParent();
609 SrcMBB.removeSuccessor(TrueMBB);
610
611 return true;
612}
613
614/// Remove writes to the FP round mode and FP denorm mode that can never be
615/// observed: either the value written is already live in MODE, or a mode write
616/// replaces the whole mode field before anything reads it.
617///
618/// s_round_mode and s_denorm_mode each assign one field of MODE and preserve
619/// the rest of the register, so the two fields are tracked independently and a
620/// write to one is transparent to the other.
621///
622/// This is a purely intra-block analysis: the mode on entry to \p SrcMBB is
623/// unknown, and a write that is still live at the end of the block is kept for
624/// the benefit of the successors.
625bool SIPreEmitPeephole::removeRedundantModeWrites(
626 MachineBasicBlock &SrcMBB) const {
627 bool Changed = false;
628 ModeFieldState DenormMode;
629 ModeFieldState RoundMode;
630
631 for (MachineInstr &MI : make_early_inc_range(SrcMBB)) {
632 if (MI.isDebugInstr())
633 continue;
634
635 unsigned Opc = MI.getOpcode();
636 if (Opc == AMDGPU::S_DENORM_MODE || Opc == AMDGPU::S_ROUND_MODE) {
637 ModeFieldState &Field =
638 Opc == AMDGPU::S_DENORM_MODE ? DenormMode : RoundMode;
639 int64_t NewValue = MI.getOperand(0).getImm();
640
641 if (Field.PendingWrite) {
642 LLVM_DEBUG(dbgs() << "Removing dead mode write: "
643 << *Field.PendingWrite);
644 Field.PendingWrite->eraseFromParent();
645 ++NumModeWritesRemoved;
646 Changed = true;
647 Field.PendingWrite = nullptr;
648 Field.Value = Field.ValueBeforePendingWrite;
649 }
650
651 if (Field.Value == NewValue) {
652 LLVM_DEBUG(dbgs() << "Removing redundant mode write: " << MI);
653 MI.eraseFromParent();
654 ++NumModeWritesRemoved;
655 Changed = true;
656 continue;
657 }
658
659 Field.ValueBeforePendingWrite = Field.Value;
660 Field.PendingWrite = &MI;
661 Field.Value = NewValue;
662 continue;
663 }
664
665 // Nothing tracked yet; skip register checks below.
666 if (!DenormMode.isTracked() && !RoundMode.isTracked())
667 continue;
668
669 // Inline asm cannot declare a MODE clobber, so assume it writes both.
670 if (MI.isInlineAsm() || MI.modifiesRegister(AMDGPU::MODE, TRI)) {
671 DenormMode = ModeFieldState();
672 RoundMode = ModeFieldState();
673 continue;
674 }
675
676 if (MI.readsRegister(AMDGPU::MODE, TRI) || MI.hasUnmodeledSideEffects()) {
677 DenormMode.PendingWrite = nullptr;
678 RoundMode.PendingWrite = nullptr;
679 }
680 }
681 return Changed;
682}
683
684bool SIPreEmitPeephole::canUnpackingClobberRegister(const MachineInstr &MI) {
685 unsigned OpCode = MI.getOpcode();
686 Register DstReg = MI.getOperand(0).getReg();
687 // Only the first register in the register pair needs to be checked due to the
688 // unpacking order. Packed instructions are unpacked such that the lower 32
689 // bits (i.e., the first register in the pair) are written first. This can
690 // introduce dependencies if the first register is written in one instruction
691 // and then read as part of the higher 32 bits in the subsequent instruction.
692 // Such scenarios can arise due to specific combinations of op_sel and
693 // op_sel_hi modifiers.
694 Register UnpackedDstReg = TRI->getSubReg(DstReg, AMDGPU::sub0);
695
696 const MachineOperand *Src0MO = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
697 if (Src0MO && Src0MO->isReg()) {
698 Register SrcReg0 = Src0MO->getReg();
699 unsigned Src0Mods =
700 TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
701 Register HiSrc0Reg = (Src0Mods & SISrcMods::OP_SEL_1)
702 ? TRI->getSubReg(SrcReg0, AMDGPU::sub1)
703 : TRI->getSubReg(SrcReg0, AMDGPU::sub0);
704 // Check if the register selected by op_sel_hi is the same as the first
705 // register in the destination register pair.
706 if (TRI->regsOverlap(UnpackedDstReg, HiSrc0Reg))
707 return true;
708 }
709
710 const MachineOperand *Src1MO = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
711 if (Src1MO && Src1MO->isReg()) {
712 Register SrcReg1 = Src1MO->getReg();
713 unsigned Src1Mods =
714 TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
715 Register HiSrc1Reg = (Src1Mods & SISrcMods::OP_SEL_1)
716 ? TRI->getSubReg(SrcReg1, AMDGPU::sub1)
717 : TRI->getSubReg(SrcReg1, AMDGPU::sub0);
718 if (TRI->regsOverlap(UnpackedDstReg, HiSrc1Reg))
719 return true;
720 }
721
722 // Applicable for packed instructions with 3 source operands, such as
723 // V_PK_FMA.
724 if (AMDGPU::hasNamedOperand(OpCode, AMDGPU::OpName::src2)) {
725 const MachineOperand *Src2MO =
726 TII->getNamedOperand(MI, AMDGPU::OpName::src2);
727 if (Src2MO && Src2MO->isReg()) {
728 Register SrcReg2 = Src2MO->getReg();
729 unsigned Src2Mods =
730 TII->getNamedOperand(MI, AMDGPU::OpName::src2_modifiers)->getImm();
731 Register HiSrc2Reg = (Src2Mods & SISrcMods::OP_SEL_1)
732 ? TRI->getSubReg(SrcReg2, AMDGPU::sub1)
733 : TRI->getSubReg(SrcReg2, AMDGPU::sub0);
734 if (TRI->regsOverlap(UnpackedDstReg, HiSrc2Reg))
735 return true;
736 }
737 }
738 return false;
739}
740
741uint32_t SIPreEmitPeephole::mapToUnpackedOpcode(MachineInstr &I) {
742 unsigned Opcode = I.getOpcode();
743 // Use 64 bit encoding to allow use of VOP3 instructions.
744 // VOP3 e64 instructions allow source modifiers
745 // e32 instructions don't allow source modifiers.
746 switch (Opcode) {
747 case AMDGPU::V_PK_ADD_F32:
748 case AMDGPU::V_PK_ADD_F32_gfx1250:
749 return AMDGPU::V_ADD_F32_e64;
750 case AMDGPU::V_PK_MUL_F32:
751 case AMDGPU::V_PK_MUL_F32_gfx1250:
752 return AMDGPU::V_MUL_F32_e64;
753 case AMDGPU::V_PK_FMA_F32:
754 case AMDGPU::V_PK_FMA_F32_gfx1250:
755 return AMDGPU::V_FMA_F32_e64;
756 default:
757 return std::numeric_limits<uint32_t>::max();
758 }
759 llvm_unreachable("Fully covered switch");
760}
761
762void SIPreEmitPeephole::addOperandAndMods(MachineInstrBuilder &NewMI,
763 unsigned SrcMods, bool IsHiBits,
764 const MachineOperand &SrcMO) {
765 unsigned NewSrcMods = 0;
766 unsigned NegModifier = IsHiBits ? SISrcMods::NEG_HI : SISrcMods::NEG;
767 unsigned OpSelModifier = IsHiBits ? SISrcMods::OP_SEL_1 : SISrcMods::OP_SEL_0;
768 // Packed instructions (VOP3P) do not support ABS. Hence, no checks are done
769 // for ABS modifiers.
770 // If NEG or NEG_HI is true, we need to negate the corresponding 32 bit
771 // lane.
772 // NEG_HI shares the same bit position with ABS. But packed instructions do
773 // not support ABS. Therefore, NEG_HI must be translated to NEG source
774 // modifier for the higher 32 bits. Unpacked VOP3 instructions support
775 // ABS, but do not support NEG_HI. Therefore we need to explicitly add the
776 // NEG modifier if present in the packed instruction.
777 if (SrcMods & NegModifier)
778 NewSrcMods |= SISrcMods::NEG;
779 // Src modifiers. Only negative modifiers are added if needed. Unpacked
780 // operations do not have op_sel, therefore it must be handled explicitly as
781 // done below.
782 NewMI.addImm(NewSrcMods);
783 if (SrcMO.isImm()) {
784 NewMI.addImm(SrcMO.getImm());
785 return;
786 }
787 // If op_sel == 0, select register 0 of reg:sub0_sub1.
788 Register UnpackedSrcReg = (SrcMods & OpSelModifier)
789 ? TRI->getSubReg(SrcMO.getReg(), AMDGPU::sub1)
790 : TRI->getSubReg(SrcMO.getReg(), AMDGPU::sub0);
791
792 MachineOperand UnpackedSrcMO =
793 MachineOperand::CreateReg(UnpackedSrcReg, /*isDef=*/false);
794 if (SrcMO.isKill()) {
795 // For each unpacked instruction, mark its source registers as killed if the
796 // corresponding source register in the original packed instruction was
797 // marked as killed.
798 //
799 // Exception:
800 // If the op_sel and op_sel_hi modifiers require both unpacked instructions
801 // to use the same register (e.g., due to overlapping access to low/high
802 // bits of the same packed register), then only the *second* (latter)
803 // instruction should mark the register as killed. This is because the
804 // second instruction handles the higher bits and is effectively the last
805 // user of the full register pair.
806
807 bool OpSel = SrcMods & SISrcMods::OP_SEL_0;
808 bool OpSelHi = SrcMods & SISrcMods::OP_SEL_1;
809 bool KillState = true;
810 if ((OpSel == OpSelHi) && !IsHiBits)
811 KillState = false;
812 UnpackedSrcMO.setIsKill(KillState);
813 }
814 NewMI.add(UnpackedSrcMO);
815}
816
817void SIPreEmitPeephole::collectUnpackingCandidates(
818 MachineInstr &BeginMI, SetVector<MachineInstr *> &InstrsToUnpack,
819 uint16_t NumMFMACycles) {
820 auto *BB = BeginMI.getParent();
821 auto E = BB->end();
822 int TotalCyclesBetweenCandidates = 0;
823 const TargetSchedModel &SchedModel = TII->getSchedModel();
824 Register MFMADef = BeginMI.getOperand(0).getReg();
825
826 for (auto I = std::next(BeginMI.getIterator()); I != E; ++I) {
827 MachineInstr &Instr = *I;
828 uint32_t UnpackedOpCode = mapToUnpackedOpcode(Instr);
829 bool IsUnpackable =
830 !(UnpackedOpCode == std::numeric_limits<uint32_t>::max());
831 if (Instr.isMetaInstruction())
832 continue;
833 if ((Instr.isTerminator()) ||
834 (TII->isNeverCoissue(Instr) && !IsUnpackable) ||
836 Instr.modifiesRegister(AMDGPU::EXEC, TRI)))
837 return;
838
839 const MCSchedClassDesc *InstrSchedClassDesc =
840 SchedModel.resolveSchedClass(&Instr);
841 uint16_t Latency =
842 SchedModel.getWriteProcResBegin(InstrSchedClassDesc)->ReleaseAtCycle;
843 TotalCyclesBetweenCandidates += Latency;
844
845 if (TotalCyclesBetweenCandidates >= NumMFMACycles - 1)
846 return;
847 // Identify register dependencies between those used by the MFMA
848 // instruction and the following packed instructions. Also checks for
849 // transitive dependencies between the MFMA def and candidate instruction
850 // def and uses. Conservatively ensures that we do not incorrectly
851 // read/write registers.
852 for (const MachineOperand &InstrMO : Instr.operands()) {
853 if (!InstrMO.isReg() || !InstrMO.getReg().isValid())
854 continue;
855 if (TRI->regsOverlap(MFMADef, InstrMO.getReg()))
856 return;
857 }
858 if (!IsUnpackable)
859 continue;
860
861 if (canUnpackingClobberRegister(Instr))
862 return;
863 // If it's a packed instruction, adjust latency: remove the packed
864 // latency, add latency of two unpacked instructions (currently estimated
865 // as 2 cycles).
866 TotalCyclesBetweenCandidates -= Latency;
867 // TODO: improve latency handling based on instruction modeling.
868 TotalCyclesBetweenCandidates += 2;
869 // Subtract 1 to account for MFMA issue latency.
870 if (TotalCyclesBetweenCandidates < NumMFMACycles - 1)
871 InstrsToUnpack.insert(&Instr);
872 }
873}
874
875void SIPreEmitPeephole::performF32Unpacking(MachineInstr &I) {
876 const MachineOperand &DstOp = I.getOperand(0);
877
878 uint32_t UnpackedOpcode = mapToUnpackedOpcode(I);
879 assert(UnpackedOpcode != std::numeric_limits<uint32_t>::max() &&
880 "Unsupported Opcode");
881
882 MachineInstrBuilder Op0LOp1L =
883 createUnpackedMI(I, UnpackedOpcode, /*IsHiBits=*/false);
884 MachineOperand &LoDstOp = Op0LOp1L->getOperand(0);
885
886 LoDstOp.setIsUndef(DstOp.isUndef());
887
888 MachineInstrBuilder Op0HOp1H =
889 createUnpackedMI(I, UnpackedOpcode, /*IsHiBits=*/true);
890 MachineOperand &HiDstOp = Op0HOp1H->getOperand(0);
891
892 uint32_t IFlags = I.getFlags();
893 Op0LOp1L->setFlags(IFlags);
894 Op0HOp1H->setFlags(IFlags);
895 LoDstOp.setIsRenamable(DstOp.isRenamable());
896 HiDstOp.setIsRenamable(DstOp.isRenamable());
897
898 I.eraseFromParent();
899}
900
901MachineInstrBuilder SIPreEmitPeephole::createUnpackedMI(MachineInstr &I,
902 uint32_t UnpackedOpcode,
903 bool IsHiBits) {
904 MachineBasicBlock &MBB = *I.getParent();
905 const DebugLoc &DL = I.getDebugLoc();
906 const MachineOperand *SrcMO0 = TII->getNamedOperand(I, AMDGPU::OpName::src0);
907 const MachineOperand *SrcMO1 = TII->getNamedOperand(I, AMDGPU::OpName::src1);
908 Register DstReg = I.getOperand(0).getReg();
909 unsigned OpCode = I.getOpcode();
910 Register UnpackedDstReg = IsHiBits ? TRI->getSubReg(DstReg, AMDGPU::sub1)
911 : TRI->getSubReg(DstReg, AMDGPU::sub0);
912
913 int64_t ClampVal = TII->getNamedOperand(I, AMDGPU::OpName::clamp)->getImm();
914 unsigned Src0Mods =
915 TII->getNamedOperand(I, AMDGPU::OpName::src0_modifiers)->getImm();
916 unsigned Src1Mods =
917 TII->getNamedOperand(I, AMDGPU::OpName::src1_modifiers)->getImm();
918
919 MachineInstrBuilder NewMI = BuildMI(MBB, I, DL, TII->get(UnpackedOpcode));
920 NewMI.addDef(UnpackedDstReg); // vdst
921 addOperandAndMods(NewMI, Src0Mods, IsHiBits, *SrcMO0);
922 addOperandAndMods(NewMI, Src1Mods, IsHiBits, *SrcMO1);
923
924 if (AMDGPU::hasNamedOperand(OpCode, AMDGPU::OpName::src2)) {
925 const MachineOperand *SrcMO2 =
926 TII->getNamedOperand(I, AMDGPU::OpName::src2);
927 unsigned Src2Mods =
928 TII->getNamedOperand(I, AMDGPU::OpName::src2_modifiers)->getImm();
929 addOperandAndMods(NewMI, Src2Mods, IsHiBits, *SrcMO2);
930 }
931 NewMI.addImm(ClampVal); // clamp
932 // Packed instructions do not support output modifiers. safe to assign them 0
933 // for this use case
934 NewMI.addImm(0); // omod
935 return NewMI;
936}
937
938PreservedAnalyses
941 auto *MLI = MFAM.getCachedResult<MachineLoopAnalysis>(MF);
942 SIPreEmitPeephole Impl;
943
944 if (Impl.run(MF, MLI)) {
946 PA.preserve<MachineLoopAnalysis>();
947 return PA;
948 }
949
950 return PreservedAnalyses::all();
951}
952
953namespace {
954
955// How well a VALU can be co-issued with a VALU of another wave on the same
956// SIMD, from A (best) to C (never). A SIMD co-issues VALUs of two waves: the
957// oldest wave with a VALU ready to issue (the older wave) and a younger wave. A
958// VALU of the younger wave, of class Y as given by getYoungerVALUClass, can
959// be co-issued next to a VALU of the older wave, of class O as given by
960// getOlderVALUClass, iff Y + O <= 1.
961enum class VALUCoexecClass { A = 0, B = 1, C = 2 };
962
963} // end anonymous namespace
964
965static bool canCoissueVALUs(VALUCoexecClass Younger, VALUCoexecClass Older) {
966 return static_cast<unsigned>(Younger) + static_cast<unsigned>(Older) <= 1;
967}
968
970 return any_of(MI.explicit_operands(), [](const MachineOperand &MO) {
971 return MO.isReg() && AMDGPU::AV_64RegClass.contains(MO.getReg());
972 });
973}
974
975// The class from the co-execution fields of the VOP pseudo, or B if the VALU
976// has none.
977static VALUCoexecClass getVALUCoexecClass(const MachineInstr &MI,
978 const GCNSubtarget &ST,
979 bool Younger) {
980 const AMDGPU::VOPCoexecClassInfo *Info =
981 AMDGPU::getVOPCoexecClassInfo(MI.getOpcode());
982 if (!Info)
983 return VALUCoexecClass::B;
984 const bool Has64BitAndMul32 = ST.hasCrossWaveVALUCoexec64BitAndMul32();
985 return static_cast<VALUCoexecClass>(
986 Younger ? (Has64BitAndMul32 ? Info->CoexecYounger64BitAndMul32
987 : Info->CoexecYounger)
988 : (Has64BitAndMul32 ? Info->CoexecOlder64BitAndMul32
989 : Info->CoexecOlder));
990}
991
992// The class of a VALU of the younger wave.
993static VALUCoexecClass getYoungerVALUClass(const MachineInstr &MI,
994 const GCNSubtarget &ST) {
998 return VALUCoexecClass::C;
999 return getVALUCoexecClass(MI, ST, /*Younger=*/true);
1000}
1001
1002// The class of a VALU of the older wave.
1003static VALUCoexecClass getOlderVALUClass(const MachineInstr &MI,
1004 const GCNSubtarget &ST) {
1005 if (AMDGPU::getVOPCoexecClassInfo(MI.getOpcode()) == nullptr &&
1008 return VALUCoexecClass::C;
1009 VALUCoexecClass Class = getVALUCoexecClass(MI, ST, /*Younger=*/false);
1010 // Without CrossWaveVALUCoexec64BitAndMul32, no VALU can be co-issued next to
1011 // a VALU with a 64-bit operand.
1012 if (Class == VALUCoexecClass::B &&
1013 !ST.hasCrossWaveVALUCoexec64BitAndMul32() && hasVectorOperandOf64Bits(MI))
1014 return VALUCoexecClass::C;
1015 return Class;
1016}
1017
1018// The occupancy, further limited by the VGPRs and AGPRs actually allocated.
1019// The occupancy recorded in SIMachineFunctionInfo is only an estimate made
1020// before register allocation.
1021static unsigned getAllocatedOccupancy(const MachineFunction &MF,
1022 const GCNSubtarget &ST) {
1024 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1025 const MachineRegisterInfo &MRI = MF.getRegInfo();
1026 unsigned NumVGPRs = TRI->getNumUsedPhysRegs(MRI, AMDGPU::VGPR_32RegClass,
1027 /*IncludeCalls=*/false);
1028 unsigned NumAGPRs = TRI->getNumUsedPhysRegs(MRI, AMDGPU::AGPR_32RegClass,
1029 /*IncludeCalls=*/false);
1030 unsigned Total =
1031 AMDGPU::getTotalNumVGPRs(ST.hasGFX90AInsts(), NumAGPRs, NumVGPRs);
1032 return std::min(
1033 MFI->getOccupancy(),
1034 ST.getOccupancyWithNumVGPRs(Total, MFI->getDynamicVGPRBlockSize()));
1035}
1036
1037// Very rough ballpark values that work for the cases measured so far. They can
1038// be adjusted up or down as needed.
1039static constexpr unsigned MinBlockingVALUs = 10;
1040static constexpr unsigned MinOlderABPct = 70;
1041static constexpr unsigned MinYoungerAPct = 50;
1042static constexpr unsigned MaxLoopInstrs = 500;
1043
1044// Returns std::nullopt if L has more than MaxLoopInstrs instructions, otherwise
1045// whether at least MinOlderABPct percent of its instructions are VALUs of older
1046// class A or B and at least MinYoungerAPct percent are VALUs of younger class
1047// A.
1048static std::optional<bool> isCrossWaveVALUCoexecLoop(const MachineLoop &L,
1049 const GCNSubtarget &ST) {
1050 unsigned NumInstrs = 0, NumOlderAB = 0, NumYoungerA = 0;
1051 for (const MachineBasicBlock *MBB : L.blocks()) {
1052 for (const MachineInstr &MI : MBB->instrs()) {
1053 if (MI.isMetaInstruction() || MI.isBundle())
1054 continue;
1055 if (++NumInstrs > MaxLoopInstrs)
1056 return std::nullopt;
1057 if (!SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false) ||
1059 continue;
1060 if (canCoissueVALUs(VALUCoexecClass::A, getOlderVALUClass(MI, ST)))
1061 ++NumOlderAB;
1062 if (getYoungerVALUClass(MI, ST) == VALUCoexecClass::A)
1063 ++NumYoungerA;
1064 }
1065 }
1066 return NumOlderAB * 100 >= NumInstrs * MinOlderABPct &&
1067 NumYoungerA * 100 >= NumInstrs * MinYoungerAPct;
1068}
1069
1070namespace {
1071
1072// Inserts s_nop 0 into the blocks of a loop, scanned one at a time (see
1073// SIPreEmitPeephole::optimizeCrossWaveVALUCoexec).
1074class CrossWaveVALUCoexecScanner {
1075 const GCNSubtarget &ST;
1076 const SIInstrInfo &TII;
1077 // The older class of each VALU in the current VALU sequence.
1079 // Candidate insertion points in the current VALU sequence: the first of at
1080 // least 2 younger class A VALUs immediately following a VALU X of another
1081 // younger class, its index in VALUSeq, and the younger class of X.
1082 struct Candidate {
1083 MachineInstr *MI;
1084 size_t Idx;
1085 VALUCoexecClass XClass;
1086 };
1087 SmallVector<Candidate, 4> Candidates;
1088
1089 unsigned getPasses(const MachineInstr &MI) const;
1090 bool closeVALUSeq();
1091
1092public:
1093 explicit CrossWaveVALUCoexecScanner(const GCNSubtarget &ST)
1094 : ST(ST), TII(*ST.getInstrInfo()) {}
1095
1096 // Returns whether s_nop 0 has been inserted into MBB.
1097 bool scanBlock(MachineBasicBlock &MBB);
1098};
1099
1100} // end anonymous namespace
1101
1102unsigned CrossWaveVALUCoexecScanner::getPasses(const MachineInstr &MI) const {
1103 const TargetSchedModel &SchedModel = TII.getSchedModel();
1104 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
1105 const MCWriteProcResEntry *WPR = SchedModel.getWriteProcResBegin(SC);
1106 return WPR != SchedModel.getWriteProcResEnd(SC) ? WPR->ReleaseAtCycle : 1;
1107}
1108
1109// Inserts s_nop 0 before each candidate in the current VALU sequence that is
1110// followed by at least MinBlockingVALUs VALUs of older class A or B before the
1111// first VALU with which its X can be co-issued. Returns whether any was
1112// inserted.
1113bool CrossWaveVALUCoexecScanner::closeVALUSeq() {
1114 bool Inserted = false;
1115 for (const Candidate &C : Candidates) {
1116 unsigned NumBlocking = 0;
1117 for (VALUCoexecClass OC : drop_begin(VALUSeq, C.Idx)) {
1118 if (NumBlocking >= MinBlockingVALUs || canCoissueVALUs(C.XClass, OC))
1119 break;
1120 if (canCoissueVALUs(VALUCoexecClass::A, OC))
1121 ++NumBlocking;
1122 }
1123 if (NumBlocking >= MinBlockingVALUs) {
1124 BuildMI(*C.MI->getParent(), C.MI, C.MI->getDebugLoc(),
1125 TII.get(AMDGPU::S_NOP))
1126 .addImm(0);
1127 Inserted = true;
1128 }
1129 }
1130 Candidates.clear();
1131 VALUSeq.clear();
1132 return Inserted;
1133}
1134
1135bool CrossWaveVALUCoexecScanner::scanBlock(MachineBasicBlock &MBB) {
1136 bool Inserted = false;
1137 // VALUs issued within the expected duration of an MFMA are not part of a
1138 // VALU sequence, so that the wave's own VALUs that execute alongside the
1139 // MFMA, which is more predictable than cross-wave co-issue, are left
1140 // undisturbed.
1141 unsigned MFMAPassesLeft = 0;
1142 // The younger class of the previous VALU if it is not A.
1143 std::optional<VALUCoexecClass> PrevXClass;
1144 // After a VALU X whose younger class is not A, the first instruction of the
1145 // immediately following sequence of younger class A VALUs, the length of
1146 // that sequence so far, and the younger class of X.
1147 MachineInstr *ASeqStart = nullptr;
1148 unsigned ASeqLen = 0;
1149 VALUCoexecClass ASeqXClass = VALUCoexecClass::B;
1150 for (MachineInstr &MI : MBB.instrs()) {
1151 if (MI.isMetaInstruction() || MI.isBundle())
1152 continue;
1153 bool InMFMAShadow = MFMAPassesLeft > 0;
1154 bool IsMFMA = SIInstrInfo::isMFMA(MI);
1155 if (IsMFMA)
1156 MFMAPassesLeft = std::max(MFMAPassesLeft, getPasses(MI));
1157 else if (InMFMAShadow)
1158 MFMAPassesLeft -= std::min(MFMAPassesLeft, getPasses(MI));
1159 if (!SIInstrInfo::isVALU(MI, /*AllowLDSDMA=*/false) || IsMFMA ||
1160 InMFMAShadow) {
1161 Inserted |= closeVALUSeq();
1162 PrevXClass.reset();
1163 ASeqStart = nullptr;
1164 continue;
1165 }
1166 VALUCoexecClass YC = getYoungerVALUClass(MI, ST);
1167 VALUSeq.push_back(getOlderVALUClass(MI, ST));
1168 if (YC != VALUCoexecClass::A || MI.isInsideBundle()) {
1169 ASeqStart = nullptr;
1170 } else if (PrevXClass) {
1171 ASeqStart = &MI;
1172 ASeqLen = 0;
1173 ASeqXClass = *PrevXClass;
1174 }
1175 if (ASeqStart && ++ASeqLen == 2)
1176 Candidates.push_back({ASeqStart, VALUSeq.size() - 2, ASeqXClass});
1177 if (YC != VALUCoexecClass::A)
1178 PrevXClass = YC;
1179 else
1180 PrevXClass.reset();
1181 }
1182 Inserted |= closeVALUSeq();
1183 return Inserted;
1184}
1185
1186// A SIMD can co-issue VALUs of two waves (see VALUCoexecClass). Assuming
1187// that the waves run the same code, while the older wave issues a sequence S
1188// of VALUs, a younger wave's next VALU X stalls unless X can be co-issued
1189// with S, and so do the VALUs S' that follow X, even if S' could be co-issued
1190// with S, until the older wave issues a VALU next to which X can be co-issued
1191// or a non-VALU instruction. An s_nop 0 in the older wave lets the younger wave
1192// issue X while the older wave issues the s_nop 0. It is inserted between a
1193// VALU X and an immediately following sequence S' of VALUs if 1) X is of
1194// younger class B or C, 2) S' starts with at least 2 VALUs of younger class A,
1195// to amortize the s_nop 0, and 3) S' has at least MinBlockingVALUs VALUs of
1196// older class A or B before the first VALU with which X can be co-issued. It
1197// is inserted only outside MFMA shadows and when the occupancy is not known to
1198// be 1.
1199//
1200// This is applied only to relatively small loops (see MaxLoopInstrs) whose
1201// bodies consist mostly of VALUs that are likely to be co-issued (see
1202// MinOlderABPct and MinYoungerAPct), where unblocking the younger wave's class
1203// B or C VALU pays off on every iteration. Loops are processed from the
1204// innermost outward, and a loop is skipped if s_nop 0 has been inserted into
1205// one of its subloops.
1206bool SIPreEmitPeephole::optimizeCrossWaveVALUCoexec(MachineFunction &MF) const {
1207 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1208 if (!ST.hasCrossWaveVALUCoexecution() || !MLI || MLI->empty() ||
1209 getAllocatedOccupancy(MF, ST) < 2)
1210 return false;
1211
1212 // Subloops come before the loops containing them. The blocks of a loop L that
1213 // are not in a subloop of L are scanned one at a time unless processing of L
1214 // is given up. Processing of the loops containing L is given up if s_nop 0 is
1215 // inserted into L or a subloop of L, or if L is too large.
1216 CrossWaveVALUCoexecScanner Scanner(ST);
1217 bool Changed = false;
1218 SmallPtrSet<const MachineLoop *, 8> GivenUp;
1220 for (MachineLoop *L : reverse(Loops)) {
1221 if (any_of(L->getSubLoops(),
1222 [&](const MachineLoop *Sub) { return GivenUp.contains(Sub); })) {
1223 GivenUp.insert(L);
1224 continue;
1225 }
1226 std::optional<bool> IsCoexec = isCrossWaveVALUCoexecLoop(*L, ST);
1227 if (!IsCoexec) {
1228 GivenUp.insert(L);
1229 continue;
1230 }
1231 if (!*IsCoexec)
1232 continue;
1233 bool Inserted = false;
1234 for (MachineBasicBlock *MBB : L->blocks())
1235 if (MLI->getLoopFor(MBB) == L)
1236 Inserted |= Scanner.scanBlock(*MBB);
1237 if (Inserted) {
1238 GivenUp.insert(L);
1239 Changed = true;
1240 }
1241 }
1242 return Changed;
1243}
1244
1245bool SIPreEmitPeephole::run(MachineFunction &MF, MachineLoopInfo *LoopInfo) {
1246 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1247 TII = ST.getInstrInfo();
1248 TRI = &TII->getRegisterInfo();
1249 MLI = LoopInfo;
1250 bool Changed = false;
1251
1252 MF.RenumberBlocks();
1253
1254 for (MachineBasicBlock &MBB : MF) {
1255 Changed |= removeRedundantModeWrites(MBB);
1256
1258 // Check first terminator for branches to optimize
1259 if (TermI != MBB.end()) {
1260 MachineInstr &MI = *TermI;
1261 switch (MI.getOpcode()) {
1262 case AMDGPU::S_CBRANCH_VCCZ:
1263 case AMDGPU::S_CBRANCH_VCCNZ:
1264 Changed |= optimizeVccBranch(MI);
1265 break;
1266 case AMDGPU::S_CBRANCH_EXECZ:
1267 Changed |= removeExeczBranch(MI, MBB);
1268 break;
1269 }
1270 }
1271
1272 if (!ST.hasVGPRIndexMode())
1273 continue;
1274
1275 MachineInstr *SetGPRMI = nullptr;
1276 const unsigned Threshold = 20;
1277 unsigned Count = 0;
1278 // Scan the block for two S_SET_GPR_IDX_ON instructions to see if a
1279 // second is not needed. Do expensive checks in the optimizeSetGPR()
1280 // and limit the distance to 20 instructions for compile time purposes.
1281 // Note: this needs to work on bundles as S_SET_GPR_IDX* instructions
1282 // may be bundled with the instructions they modify.
1283 for (auto &MI : make_early_inc_range(MBB.instrs())) {
1284 if (Count == Threshold)
1285 SetGPRMI = nullptr;
1286 else
1287 ++Count;
1288
1289 if (MI.getOpcode() != AMDGPU::S_SET_GPR_IDX_ON)
1290 continue;
1291
1292 Count = 0;
1293 if (!SetGPRMI) {
1294 SetGPRMI = &MI;
1295 continue;
1296 }
1297
1298 if (optimizeSetGPR(*SetGPRMI, MI))
1299 Changed = true;
1300 else
1301 SetGPRMI = &MI;
1302 }
1303 }
1304
1305 // TODO: Fold this into previous block, if possible. Evaluate and handle any
1306 // side effects.
1307
1308 // Perform the extra MF scans only for supported archs
1309 if (!ST.hasGFX940Insts())
1310 return Changed;
1311 for (MachineBasicBlock &MBB : MF) {
1312 // Unpack packed instructions overlapped by MFMAs. This allows the
1313 // compiler to co-issue unpacked instructions with MFMA
1314 const TargetSchedModel &SchedModel = TII->getSchedModel();
1315 SetVector<MachineInstr *> InstrsToUnpack;
1316 for (auto &MI : make_early_inc_range(MBB.instrs())) {
1317 if (!SIInstrInfo::isMFMA(MI))
1318 continue;
1319 const MCSchedClassDesc *SchedClassDesc =
1320 SchedModel.resolveSchedClass(&MI);
1321 uint16_t NumMFMACycles =
1322 SchedModel.getWriteProcResBegin(SchedClassDesc)->ReleaseAtCycle;
1323 collectUnpackingCandidates(MI, InstrsToUnpack, NumMFMACycles);
1324 }
1325 for (MachineInstr *MI : InstrsToUnpack) {
1326 performF32Unpacking(*MI);
1327 }
1328 if (!InstrsToUnpack.empty())
1329 Changed = true;
1330 }
1331
1332 Changed |= optimizeCrossWaveVALUCoexec(MF);
1333
1334 return Changed;
1335}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
uint64_t uint64_t
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
Hexagon Hardware Loops
IRTranslator LLVM IR MI
SmallVector< MachineOperand, 4 > Cond
while(!MBB.succ_empty()) MBB.removeSuccessor(MBB.succ_end() - 1)
unsigned Opc
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
OptimizedStructLayoutField Field
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
MachineRegisterInfo & MRI
static VALUCoexecClass getOlderVALUClass(const MachineInstr &MI, const GCNSubtarget &ST)
static bool canCoissueVALUs(VALUCoexecClass Younger, VALUCoexecClass Older)
static constexpr unsigned MinBlockingVALUs
static constexpr unsigned MinYoungerAPct
static VALUCoexecClass getVALUCoexecClass(const MachineInstr &MI, const GCNSubtarget &ST, bool Younger)
static constexpr unsigned MaxLoopInstrs
static std::optional< bool > isCrossWaveVALUCoexecLoop(const MachineLoop &L, const GCNSubtarget &ST)
static unsigned getAllocatedOccupancy(const MachineFunction &MF, const GCNSubtarget &ST)
static constexpr unsigned MinOlderABPct
static bool hasVectorOperandOf64Bits(const MachineInstr &MI)
static VALUCoexecClass getYoungerVALUClass(const MachineInstr &MI, const GCNSubtarget &ST)
This file defines the SmallPtrSet class.
static bool isProfitable(const CGDataOptions &Opts, const StableFunctionMap::StableFunctionEntries &SFS)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
MachineBasicBlock * getBranchDestBlock(const MachineInstr &MI) const override
const AArch64RegisterInfo & getRegisterInfo() const
getRegisterInfo - TargetInstrInfo is a superset of MRegister info.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached 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 & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static uint32_t getDenominator()
static constexpr BranchProbability getZero()
uint32_t getNumerator() const
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
static unsigned getMaxWMMACoexecutionWaitStates(const GCNSubtarget &ST)
Largest number of intervening VALUs checkWMMACoexecutionHazards() can require between an XDL WMMA and...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
BlockT * getHeader() const
iterator_range< block_iterator > blocks() const
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
SmallVector< LoopT *, 4 > getLoopsInPreorder() const
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Instructions::const_reverse_iterator const_reverse_instr_iterator
LLVM_ABI MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
LLVM_ABI BranchProbability getSuccProbability(const_succ_iterator Succ) const
Return probability of the edge from this block to MBB.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
reverse_instr_iterator instr_rend()
Instructions::iterator instr_iterator
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< iterator > terminators()
iterator_range< succ_iterator > successors()
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
BasicBlockListType::const_iterator const_iterator
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.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
const MachineBasicBlock * getParent() const
void setFlags(unsigned flags)
const MachineOperand & getOperand(unsigned i) const
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
LLVM_ABI bool isRenamable() const
isRenamable - Returns true if this register may be renamed, i.e.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
static bool isSDWA(const MachineInstr &MI)
static bool isDOT(const MachineInstr &MI)
static bool isVALU(const MachineInstr &MI, bool AllowLDSDMA)
static bool isTRANS(const MachineInstr &MI)
static bool isDPP(const MachineInstr &MI)
static bool isMFMA(const MachineInstr &MI)
static bool isVOP3P(const MachineInstr &MI)
static bool modifiesModeRegister(const MachineInstr &MI)
Return true if the instruction modifies the mode register.q.
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
reference emplace_back(ArgTypes &&... Args)
ProcResIter getWriteProcResEnd(const MCSchedClassDesc *SC) const
LLVM_ABI const MCSchedClassDesc * resolveSchedClass(const MachineInstr *MI) const
Return the MCSchedClassDesc for this instruction.
ProcResIter getWriteProcResBegin(const MCSchedClassDesc *SC) const
LLVM Value Representation.
Definition Value.h:75
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI unsigned getTotalNumVGPRs(GPUKind AK, bool IsWave32)
LLVM_READONLY bool hasNamedOperand(uint32_t Opcode, OpName NamedIdx)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
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
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
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:649
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
char & SIPreEmitPeepholeID
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
uint16_t ReleaseAtCycle
Cycle at which the resource will be released by an instruction, relatively to the cycle in which the ...
Definition MCSchedule.h:74