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 "GCNSubtarget.h"
24#include "llvm/ADT/SetVector.h"
31using namespace llvm;
32
33#define DEBUG_TYPE "si-pre-emit-peephole"
34
35namespace {
36
37class SIPreEmitPeephole {
38private:
39 const SIInstrInfo *TII = nullptr;
40 const SIRegisterInfo *TRI = nullptr;
41 MachineLoopInfo *MLI = nullptr;
42
43 bool optimizeVccBranch(MachineInstr &MI) const;
44 void updateMLIBeforeRemovingEdge(MachineBasicBlock *From,
45 MachineBasicBlock *To) const;
46 bool optimizeSetGPR(MachineInstr &First, MachineInstr &MI) const;
47 bool getBlockDestinations(MachineBasicBlock &SrcMBB,
48 MachineBasicBlock *&TrueMBB,
49 MachineBasicBlock *&FalseMBB,
51 bool mustRetainExeczBranch(const MachineInstr &Branch,
52 const MachineBasicBlock &From,
53 const MachineBasicBlock &To) const;
54 bool removeExeczBranch(MachineInstr &MI, MachineBasicBlock &SrcMBB);
55 // Creates a list of packed instructions following an MFMA that are suitable
56 // for unpacking.
57 void collectUnpackingCandidates(MachineInstr &BeginMI,
58 SetVector<MachineInstr *> &InstrsToUnpack,
59 uint16_t NumMFMACycles);
60 // v_pk_fma_f32 v[0:1], v[0:1], v[2:3], v[2:3] op_sel:[1,1,1]
61 // op_sel_hi:[0,0,0]
62 // ==>
63 // v_fma_f32 v0, v1, v3, v3
64 // v_fma_f32 v1, v0, v2, v2
65 // Here, we have overwritten v0 before we use it. This function checks if
66 // unpacking can lead to such a situation.
67 bool canUnpackingClobberRegister(const MachineInstr &MI);
68 // Unpack and insert F32 packed instructions, such as V_PK_MUL, V_PK_ADD, and
69 // V_PK_FMA. Currently, only V_PK_MUL, V_PK_ADD, V_PK_FMA are supported for
70 // this transformation.
71 void performF32Unpacking(MachineInstr &I);
72 // Select corresponding unpacked instruction
73 uint32_t mapToUnpackedOpcode(MachineInstr &I);
74 // Creates the unpacked instruction to be inserted. Adds source modifiers to
75 // the unpacked instructions based on the source modifiers in the packed
76 // instruction.
77 MachineInstrBuilder createUnpackedMI(MachineInstr &I, uint32_t UnpackedOpcode,
78 bool IsHiBits);
79 // Process operands/source modifiers from packed instructions and insert the
80 // appropriate source modifers and operands into the unpacked instructions.
81 void addOperandAndMods(MachineInstrBuilder &NewMI, unsigned SrcMods,
82 bool IsHiBits, const MachineOperand &SrcMO);
83
84public:
85 bool run(MachineFunction &MF, MachineLoopInfo *MLI);
86};
87
88class SIPreEmitPeepholeLegacy : public MachineFunctionPass {
89public:
90 static char ID;
91
92 SIPreEmitPeepholeLegacy() : MachineFunctionPass(ID) {}
93
94 void getAnalysisUsage(AnalysisUsage &AU) const override {
98 }
99
100 bool runOnMachineFunction(MachineFunction &MF) override {
101 auto *MLIWrapper = getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
102 MachineLoopInfo *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
103 return SIPreEmitPeephole().run(MF, MLI);
104 }
105};
106
107} // End anonymous namespace.
108
109INITIALIZE_PASS(SIPreEmitPeepholeLegacy, DEBUG_TYPE,
110 "SI peephole optimizations", false, false)
111
112char SIPreEmitPeepholeLegacy::ID = 0;
113
114char &llvm::SIPreEmitPeepholeID = SIPreEmitPeepholeLegacy::ID;
115
116void SIPreEmitPeephole::updateMLIBeforeRemovingEdge(
117 MachineBasicBlock *From, MachineBasicBlock *To) const {
118 if (!MLI)
119 return;
120
121 // Only handle back-edges: To must be a loop header with From inside the loop.
122 MachineLoop *Loop = MLI->getLoopFor(To);
123 if (!Loop || Loop->getHeader() != To || !Loop->contains(From))
124 return;
125
126 // Count back-edges
127 unsigned BackEdgeCount = 0;
128 for (MachineBasicBlock *Pred : To->predecessors()) {
129 if (Loop->contains(Pred))
130 BackEdgeCount++;
131 }
132
133 if (BackEdgeCount > 1)
134 return;
135
136 MachineLoop *ParentLoop = Loop->getParentLoop();
137
138 // Re-map blocks directly owned by this loop to the parent.
139 for (MachineBasicBlock *BB : Loop->blocks()) {
140 if (MLI->getLoopFor(BB) == Loop)
141 MLI->changeLoopFor(BB, ParentLoop);
142 }
143
144 // Reparent all child loops.
145 while (!Loop->isInnermost()) {
146 MachineLoop *Child = Loop->removeChildLoop(std::prev(Loop->end()));
147 if (ParentLoop)
148 ParentLoop->addChildLoop(Child);
149 else
150 MLI->addTopLevelLoop(Child);
151 }
152
153 if (ParentLoop)
154 ParentLoop->removeChildLoop(Loop);
155 else
156 MLI->removeLoop(llvm::find(*MLI, Loop));
157
158 MLI->destroy(Loop);
159}
160
161bool SIPreEmitPeephole::optimizeVccBranch(MachineInstr &MI) const {
162 // Match:
163 // sreg = -1 or 0
164 // vcc = S_AND_B64 exec, sreg or S_ANDN2_B64 exec, sreg
165 // S_CBRANCH_VCC[N]Z
166 // =>
167 // S_CBRANCH_EXEC[N]Z
168 // We end up with this pattern sometimes after basic block placement.
169 // It happens while combining a block which assigns -1 or 0 to a saved mask
170 // and another block which consumes that saved mask and then a branch.
171 //
172 // While searching this also performs the following substitution:
173 // vcc = V_CMP
174 // vcc = S_AND exec, vcc
175 // S_CBRANCH_VCC[N]Z
176 // =>
177 // vcc = V_CMP
178 // S_CBRANCH_VCC[N]Z
179
180 bool Changed = false;
181 MachineBasicBlock &MBB = *MI.getParent();
182 const GCNSubtarget &ST = MBB.getParent()->getSubtarget<GCNSubtarget>();
183 const bool IsWave32 = ST.isWave32();
184 const unsigned CondReg = TRI->getVCC();
185 const unsigned ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
186 const unsigned And = IsWave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
187 const unsigned AndN2 = IsWave32 ? AMDGPU::S_ANDN2_B32 : AMDGPU::S_ANDN2_B64;
188 const unsigned Mov = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
189
190 MachineBasicBlock::reverse_iterator A = MI.getReverseIterator(),
191 E = MBB.rend();
192 bool ReadsCond = false;
193 unsigned Threshold = 5;
194 for (++A; A != E; ++A) {
195 if (!--Threshold)
196 return false;
197 if (A->modifiesRegister(ExecReg, TRI))
198 return false;
199 if (A->modifiesRegister(CondReg, TRI)) {
200 if (!A->definesRegister(CondReg, TRI) ||
201 (A->getOpcode() != And && A->getOpcode() != AndN2))
202 return false;
203 break;
204 }
205 ReadsCond |= A->readsRegister(CondReg, TRI);
206 }
207 if (A == E)
208 return false;
209
210 MachineOperand &Op1 = A->getOperand(1);
211 MachineOperand &Op2 = A->getOperand(2);
212 if ((!Op1.isReg() || Op1.getReg() != ExecReg) && Op2.isReg() &&
213 Op2.getReg() == ExecReg) {
214 TII->commuteInstruction(*A);
215 Changed = true;
216 }
217 if (!Op1.isReg() || Op1.getReg() != ExecReg)
218 return Changed;
219 if (Op2.isImm() && !(Op2.getImm() == -1 || Op2.getImm() == 0))
220 return Changed;
221
222 int64_t MaskValue = 0;
224 if (Op2.isReg()) {
225 SReg = Op2.getReg();
226 auto M = std::next(A);
227 bool ReadsSreg = false;
228 bool ModifiesExec = false;
229 for (; M != E; ++M) {
230 if (M->definesRegister(SReg, TRI))
231 break;
232 if (M->modifiesRegister(SReg, TRI))
233 return Changed;
234 ReadsSreg |= M->readsRegister(SReg, TRI);
235 ModifiesExec |= M->modifiesRegister(ExecReg, TRI);
236 }
237 if (M == E)
238 return Changed;
239 // If SReg is VCC and SReg definition is a VALU comparison.
240 // This means S_AND with EXEC is not required, unless
241 // the implicit def of SCC is alive.
242 // Erase the S_AND and return.
243 // Note: isVOPC is used instead of isCompare to catch V_CMP_CLASS
244 if (A->getOpcode() == And && SReg == CondReg && !ModifiesExec &&
245 TII->isVOPC(*M) && A->allImplicitDefsAreDead()) {
246 A->eraseFromParent();
247 return true;
248 }
249
250 if (!M->isMoveImmediate() || !M->getOperand(1).isImm() ||
251 (M->getOperand(1).getImm() != -1 && M->getOperand(1).getImm() != 0))
252 return Changed;
253 MaskValue = M->getOperand(1).getImm();
254 // First if sreg is only used in the AND instruction fold the immediate
255 // into the AND.
256 if (!ReadsSreg && Op2.isKill()) {
257 A->getOperand(2).ChangeToImmediate(MaskValue);
258 M->eraseFromParent();
259 }
260 } else if (Op2.isImm()) {
261 MaskValue = Op2.getImm();
262 } else {
263 llvm_unreachable("Op2 must be register or immediate");
264 }
265
266 // Invert mask for s_andn2
267 assert(MaskValue == 0 || MaskValue == -1);
268 if (A->getOpcode() == AndN2)
269 MaskValue = ~MaskValue;
270
271 if (!ReadsCond && A->registerDefIsDead(AMDGPU::SCC, /*TRI=*/nullptr)) {
272 if (!MI.killsRegister(CondReg, TRI)) {
273 // Replace AND with MOV
274 if (MaskValue == 0) {
275 BuildMI(*A->getParent(), *A, A->getDebugLoc(), TII->get(Mov), CondReg)
276 .addImm(0);
277 } else {
278 BuildMI(*A->getParent(), *A, A->getDebugLoc(), TII->get(Mov), CondReg)
279 .addReg(ExecReg);
280 }
281 }
282 // Remove AND instruction
283 A->eraseFromParent();
284 }
285
286 bool IsVCCZ = MI.getOpcode() == AMDGPU::S_CBRANCH_VCCZ;
287 if (SReg == ExecReg) {
288 // EXEC is updated directly
289 if (IsVCCZ) {
290 MI.eraseFromParent();
291 return true;
292 }
293 MI.setDesc(TII->get(AMDGPU::S_BRANCH));
294 } else if (IsVCCZ && MaskValue == 0) {
295 // Will always branch
296 // Remove all successors shadowed by new unconditional branch
297 MachineBasicBlock *Parent = MI.getParent();
298 SmallVector<MachineInstr *, 4> ToRemove;
299 bool Found = false;
300 for (MachineInstr &Term : Parent->terminators()) {
301 if (Found) {
302 if (Term.isBranch())
303 ToRemove.push_back(&Term);
304 } else {
305 Found = Term.isIdenticalTo(MI);
306 }
307 }
308 assert(Found && "conditional branch is not terminator");
309 for (auto *BranchMI : ToRemove) {
310 MachineOperand &Dst = BranchMI->getOperand(0);
311 assert(Dst.isMBB() && "destination is not basic block");
312 updateMLIBeforeRemovingEdge(Parent, Dst.getMBB());
313 Parent->removeSuccessor(Dst.getMBB());
314 BranchMI->eraseFromParent();
315 }
316
317 if (MachineBasicBlock *Succ = Parent->getFallThrough()) {
318 updateMLIBeforeRemovingEdge(Parent, Succ);
319 Parent->removeSuccessor(Succ);
320 }
321
322 // Rewrite to unconditional branch
323 MI.setDesc(TII->get(AMDGPU::S_BRANCH));
324 } else if (!IsVCCZ && MaskValue == 0) {
325 // Will never branch
326 MachineOperand &Dst = MI.getOperand(0);
327 assert(Dst.isMBB() && "destination is not basic block");
328 MachineBasicBlock *Parent = MI.getParent();
329 updateMLIBeforeRemovingEdge(Parent, Dst.getMBB());
330 Parent->removeSuccessor(Dst.getMBB());
331 MI.eraseFromParent();
332 return true;
333 } else if (MaskValue == -1) {
334 // Depends only on EXEC
335 MI.setDesc(
336 TII->get(IsVCCZ ? AMDGPU::S_CBRANCH_EXECZ : AMDGPU::S_CBRANCH_EXECNZ));
337 }
338
339 MI.removeOperand(MI.findRegisterUseOperandIdx(CondReg, TRI, false /*Kill*/));
340 MI.addImplicitDefUseOperands(*MBB.getParent());
341
342 return true;
343}
344
345bool SIPreEmitPeephole::optimizeSetGPR(MachineInstr &First,
346 MachineInstr &MI) const {
347 MachineBasicBlock &MBB = *MI.getParent();
348 const MachineFunction &MF = *MBB.getParent();
349 const MachineRegisterInfo &MRI = MF.getRegInfo();
350 MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
351 Register IdxReg = Idx->isReg() ? Idx->getReg() : Register();
352 SmallVector<MachineInstr *, 4> ToRemove;
353 bool IdxOn = true;
354
355 if (!MI.isIdenticalTo(First))
356 return false;
357
358 // Scan back to find an identical S_SET_GPR_IDX_ON
359 for (MachineBasicBlock::instr_iterator I = std::next(First.getIterator()),
360 E = MI.getIterator();
361 I != E; ++I) {
362 if (I->isBundle() || I->isDebugInstr())
363 continue;
364 switch (I->getOpcode()) {
365 case AMDGPU::S_SET_GPR_IDX_MODE:
366 return false;
367 case AMDGPU::S_SET_GPR_IDX_OFF:
368 IdxOn = false;
369 ToRemove.push_back(&*I);
370 break;
371 default:
372 if (I->modifiesRegister(AMDGPU::M0, TRI))
373 return false;
374 if (IdxReg && I->modifiesRegister(IdxReg, TRI))
375 return false;
376 if (llvm::any_of(I->operands(), [&MRI, this](const MachineOperand &MO) {
377 return MO.isReg() && TRI->isVectorRegister(MRI, MO.getReg());
378 })) {
379 // The only exception allowed here is another indirect vector move
380 // with the same mode.
381 if (!IdxOn || !(I->getOpcode() == AMDGPU::V_MOV_B32_indirect_write ||
382 I->getOpcode() == AMDGPU::V_MOV_B32_indirect_read))
383 return false;
384 }
385 }
386 }
387
388 MI.eraseFromBundle();
389 for (MachineInstr *RI : ToRemove)
390 RI->eraseFromBundle();
391 return true;
392}
393
394bool SIPreEmitPeephole::getBlockDestinations(
395 MachineBasicBlock &SrcMBB, MachineBasicBlock *&TrueMBB,
396 MachineBasicBlock *&FalseMBB, SmallVectorImpl<MachineOperand> &Cond) {
397 if (TII->analyzeBranch(SrcMBB, TrueMBB, FalseMBB, Cond))
398 return false;
399
400 if (!FalseMBB)
401 FalseMBB = SrcMBB.getNextNode();
402
403 return true;
404}
405
406namespace {
407class BranchWeightCostModel {
408 const SIInstrInfo &TII;
409 const TargetSchedModel &SchedModel;
410 BranchProbability BranchProb;
411 static constexpr uint64_t BranchNotTakenCost = 1;
412 uint64_t BranchTakenCost;
413 uint64_t ThenCyclesCost = 0;
414
415public:
416 BranchWeightCostModel(const SIInstrInfo &TII, const MachineInstr &Branch,
417 const MachineBasicBlock &Succ)
418 : TII(TII), SchedModel(TII.getSchedModel()) {
419 const MachineBasicBlock &Head = *Branch.getParent();
420 const auto *FromIt = find(Head.successors(), &Succ);
421 assert(FromIt != Head.succ_end());
422
423 BranchProb = Head.getSuccProbability(FromIt);
424 if (BranchProb.isUnknown())
425 BranchProb = BranchProbability::getZero();
426 BranchTakenCost = SchedModel.computeInstrLatency(&Branch);
427 }
428
429 bool isProfitable(const MachineInstr &MI) {
430 if (TII.isWaitcnt(MI.getOpcode()))
431 return false;
432
433 ThenCyclesCost += SchedModel.computeInstrLatency(&MI);
434
435 // Consider `P = N/D` to be the probability of execz being false (skipping
436 // the then-block) The transformation is profitable if always executing the
437 // 'then' block is cheaper than executing sometimes 'then' and always
438 // executing s_cbranch_execz:
439 // * ThenCost <= P*ThenCost + (1-P)*BranchTakenCost + P*BranchNotTakenCost
440 // * (1-P) * ThenCost <= (1-P)*BranchTakenCost + P*BranchNotTakenCost
441 // * (D-N)/D * ThenCost <= (D-N)/D * BranchTakenCost + N/D *
442 // BranchNotTakenCost
443 uint64_t Numerator = BranchProb.getNumerator();
444 uint64_t Denominator = BranchProb.getDenominator();
445 return (Denominator - Numerator) * ThenCyclesCost <=
446 ((Denominator - Numerator) * BranchTakenCost +
447 Numerator * BranchNotTakenCost);
448 }
449};
450
451bool SIPreEmitPeephole::mustRetainExeczBranch(
452 const MachineInstr &Branch, const MachineBasicBlock &From,
453 const MachineBasicBlock &To) const {
454 assert(is_contained(Branch.getParent()->successors(), &From));
455 BranchWeightCostModel CostModel{*TII, Branch, From};
456
457 const MachineFunction *MF = From.getParent();
458 for (MachineFunction::const_iterator MBBI(&From), ToI(&To), End = MF->end();
459 MBBI != End && MBBI != ToI; ++MBBI) {
460 const MachineBasicBlock &MBB = *MBBI;
461
462 for (const MachineInstr &MI : MBB) {
463 // When a uniform loop is inside non-uniform control flow, the branch
464 // leaving the loop might never be taken when EXEC = 0.
465 // Hence we should retain cbranch out of the loop lest it become infinite.
466 if (MI.isConditionalBranch())
467 return true;
468
469 if (MI.isUnconditionalBranch() &&
470 TII->getBranchDestBlock(MI) != MBB.getNextNode())
471 return true;
472
473 if (MI.isMetaInstruction())
474 continue;
475
476 if (TII->hasUnwantedEffectsWhenEXECEmpty(MI))
477 return true;
478
479 if (!CostModel.isProfitable(MI))
480 return true;
481 }
482 }
483
484 return false;
485}
486} // namespace
487
488// Returns true if the skip branch instruction is removed.
489bool SIPreEmitPeephole::removeExeczBranch(MachineInstr &MI,
490 MachineBasicBlock &SrcMBB) {
491
492 if (!TII->getSchedModel().hasInstrSchedModel())
493 return false;
494
495 MachineBasicBlock *TrueMBB = nullptr;
496 MachineBasicBlock *FalseMBB = nullptr;
498
499 if (!getBlockDestinations(SrcMBB, TrueMBB, FalseMBB, Cond))
500 return false;
501
502 // Consider only the forward branches.
503 if (SrcMBB.getNumber() >= TrueMBB->getNumber())
504 return false;
505
506 // Consider only when it is legal and profitable
507 if (mustRetainExeczBranch(MI, *FalseMBB, *TrueMBB))
508 return false;
509
510 LLVM_DEBUG(dbgs() << "Removing the execz branch: " << MI);
511 MI.eraseFromParent();
512 SrcMBB.removeSuccessor(TrueMBB);
513
514 return true;
515}
516
517bool SIPreEmitPeephole::canUnpackingClobberRegister(const MachineInstr &MI) {
518 unsigned OpCode = MI.getOpcode();
519 Register DstReg = MI.getOperand(0).getReg();
520 // Only the first register in the register pair needs to be checked due to the
521 // unpacking order. Packed instructions are unpacked such that the lower 32
522 // bits (i.e., the first register in the pair) are written first. This can
523 // introduce dependencies if the first register is written in one instruction
524 // and then read as part of the higher 32 bits in the subsequent instruction.
525 // Such scenarios can arise due to specific combinations of op_sel and
526 // op_sel_hi modifiers.
527 Register UnpackedDstReg = TRI->getSubReg(DstReg, AMDGPU::sub0);
528
529 const MachineOperand *Src0MO = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
530 if (Src0MO && Src0MO->isReg()) {
531 Register SrcReg0 = Src0MO->getReg();
532 unsigned Src0Mods =
533 TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
534 Register HiSrc0Reg = (Src0Mods & SISrcMods::OP_SEL_1)
535 ? TRI->getSubReg(SrcReg0, AMDGPU::sub1)
536 : TRI->getSubReg(SrcReg0, AMDGPU::sub0);
537 // Check if the register selected by op_sel_hi is the same as the first
538 // register in the destination register pair.
539 if (TRI->regsOverlap(UnpackedDstReg, HiSrc0Reg))
540 return true;
541 }
542
543 const MachineOperand *Src1MO = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
544 if (Src1MO && Src1MO->isReg()) {
545 Register SrcReg1 = Src1MO->getReg();
546 unsigned Src1Mods =
547 TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
548 Register HiSrc1Reg = (Src1Mods & SISrcMods::OP_SEL_1)
549 ? TRI->getSubReg(SrcReg1, AMDGPU::sub1)
550 : TRI->getSubReg(SrcReg1, AMDGPU::sub0);
551 if (TRI->regsOverlap(UnpackedDstReg, HiSrc1Reg))
552 return true;
553 }
554
555 // Applicable for packed instructions with 3 source operands, such as
556 // V_PK_FMA.
557 if (AMDGPU::hasNamedOperand(OpCode, AMDGPU::OpName::src2)) {
558 const MachineOperand *Src2MO =
559 TII->getNamedOperand(MI, AMDGPU::OpName::src2);
560 if (Src2MO && Src2MO->isReg()) {
561 Register SrcReg2 = Src2MO->getReg();
562 unsigned Src2Mods =
563 TII->getNamedOperand(MI, AMDGPU::OpName::src2_modifiers)->getImm();
564 Register HiSrc2Reg = (Src2Mods & SISrcMods::OP_SEL_1)
565 ? TRI->getSubReg(SrcReg2, AMDGPU::sub1)
566 : TRI->getSubReg(SrcReg2, AMDGPU::sub0);
567 if (TRI->regsOverlap(UnpackedDstReg, HiSrc2Reg))
568 return true;
569 }
570 }
571 return false;
572}
573
574uint32_t SIPreEmitPeephole::mapToUnpackedOpcode(MachineInstr &I) {
575 unsigned Opcode = I.getOpcode();
576 // Use 64 bit encoding to allow use of VOP3 instructions.
577 // VOP3 e64 instructions allow source modifiers
578 // e32 instructions don't allow source modifiers.
579 switch (Opcode) {
580 case AMDGPU::V_PK_ADD_F32:
581 case AMDGPU::V_PK_ADD_F32_gfx1250:
582 return AMDGPU::V_ADD_F32_e64;
583 case AMDGPU::V_PK_MUL_F32:
584 case AMDGPU::V_PK_MUL_F32_gfx1250:
585 return AMDGPU::V_MUL_F32_e64;
586 case AMDGPU::V_PK_FMA_F32:
587 case AMDGPU::V_PK_FMA_F32_gfx1250:
588 return AMDGPU::V_FMA_F32_e64;
589 default:
590 return std::numeric_limits<uint32_t>::max();
591 }
592 llvm_unreachable("Fully covered switch");
593}
594
595void SIPreEmitPeephole::addOperandAndMods(MachineInstrBuilder &NewMI,
596 unsigned SrcMods, bool IsHiBits,
597 const MachineOperand &SrcMO) {
598 unsigned NewSrcMods = 0;
599 unsigned NegModifier = IsHiBits ? SISrcMods::NEG_HI : SISrcMods::NEG;
600 unsigned OpSelModifier = IsHiBits ? SISrcMods::OP_SEL_1 : SISrcMods::OP_SEL_0;
601 // Packed instructions (VOP3P) do not support ABS. Hence, no checks are done
602 // for ABS modifiers.
603 // If NEG or NEG_HI is true, we need to negate the corresponding 32 bit
604 // lane.
605 // NEG_HI shares the same bit position with ABS. But packed instructions do
606 // not support ABS. Therefore, NEG_HI must be translated to NEG source
607 // modifier for the higher 32 bits. Unpacked VOP3 instructions support
608 // ABS, but do not support NEG_HI. Therefore we need to explicitly add the
609 // NEG modifier if present in the packed instruction.
610 if (SrcMods & NegModifier)
611 NewSrcMods |= SISrcMods::NEG;
612 // Src modifiers. Only negative modifiers are added if needed. Unpacked
613 // operations do not have op_sel, therefore it must be handled explicitly as
614 // done below.
615 NewMI.addImm(NewSrcMods);
616 if (SrcMO.isImm()) {
617 NewMI.addImm(SrcMO.getImm());
618 return;
619 }
620 // If op_sel == 0, select register 0 of reg:sub0_sub1.
621 Register UnpackedSrcReg = (SrcMods & OpSelModifier)
622 ? TRI->getSubReg(SrcMO.getReg(), AMDGPU::sub1)
623 : TRI->getSubReg(SrcMO.getReg(), AMDGPU::sub0);
624
625 MachineOperand UnpackedSrcMO =
626 MachineOperand::CreateReg(UnpackedSrcReg, /*isDef=*/false);
627 if (SrcMO.isKill()) {
628 // For each unpacked instruction, mark its source registers as killed if the
629 // corresponding source register in the original packed instruction was
630 // marked as killed.
631 //
632 // Exception:
633 // If the op_sel and op_sel_hi modifiers require both unpacked instructions
634 // to use the same register (e.g., due to overlapping access to low/high
635 // bits of the same packed register), then only the *second* (latter)
636 // instruction should mark the register as killed. This is because the
637 // second instruction handles the higher bits and is effectively the last
638 // user of the full register pair.
639
640 bool OpSel = SrcMods & SISrcMods::OP_SEL_0;
641 bool OpSelHi = SrcMods & SISrcMods::OP_SEL_1;
642 bool KillState = true;
643 if ((OpSel == OpSelHi) && !IsHiBits)
644 KillState = false;
645 UnpackedSrcMO.setIsKill(KillState);
646 }
647 NewMI.add(UnpackedSrcMO);
648}
649
650void SIPreEmitPeephole::collectUnpackingCandidates(
651 MachineInstr &BeginMI, SetVector<MachineInstr *> &InstrsToUnpack,
652 uint16_t NumMFMACycles) {
653 auto *BB = BeginMI.getParent();
654 auto E = BB->end();
655 int TotalCyclesBetweenCandidates = 0;
656 auto SchedModel = TII->getSchedModel();
657 Register MFMADef = BeginMI.getOperand(0).getReg();
658
659 for (auto I = std::next(BeginMI.getIterator()); I != E; ++I) {
660 MachineInstr &Instr = *I;
661 uint32_t UnpackedOpCode = mapToUnpackedOpcode(Instr);
662 bool IsUnpackable =
663 !(UnpackedOpCode == std::numeric_limits<uint32_t>::max());
664 if (Instr.isMetaInstruction())
665 continue;
666 if ((Instr.isTerminator()) ||
667 (TII->isNeverCoissue(Instr) && !IsUnpackable) ||
669 Instr.modifiesRegister(AMDGPU::EXEC, TRI)))
670 return;
671
672 const MCSchedClassDesc *InstrSchedClassDesc =
673 SchedModel.resolveSchedClass(&Instr);
674 uint16_t Latency =
675 SchedModel.getWriteProcResBegin(InstrSchedClassDesc)->ReleaseAtCycle;
676 TotalCyclesBetweenCandidates += Latency;
677
678 if (TotalCyclesBetweenCandidates >= NumMFMACycles - 1)
679 return;
680 // Identify register dependencies between those used by the MFMA
681 // instruction and the following packed instructions. Also checks for
682 // transitive dependencies between the MFMA def and candidate instruction
683 // def and uses. Conservatively ensures that we do not incorrectly
684 // read/write registers.
685 for (const MachineOperand &InstrMO : Instr.operands()) {
686 if (!InstrMO.isReg() || !InstrMO.getReg().isValid())
687 continue;
688 if (TRI->regsOverlap(MFMADef, InstrMO.getReg()))
689 return;
690 }
691 if (!IsUnpackable)
692 continue;
693
694 if (canUnpackingClobberRegister(Instr))
695 return;
696 // If it's a packed instruction, adjust latency: remove the packed
697 // latency, add latency of two unpacked instructions (currently estimated
698 // as 2 cycles).
699 TotalCyclesBetweenCandidates -= Latency;
700 // TODO: improve latency handling based on instruction modeling.
701 TotalCyclesBetweenCandidates += 2;
702 // Subtract 1 to account for MFMA issue latency.
703 if (TotalCyclesBetweenCandidates < NumMFMACycles - 1)
704 InstrsToUnpack.insert(&Instr);
705 }
706}
707
708void SIPreEmitPeephole::performF32Unpacking(MachineInstr &I) {
709 const MachineOperand &DstOp = I.getOperand(0);
710
711 uint32_t UnpackedOpcode = mapToUnpackedOpcode(I);
712 assert(UnpackedOpcode != std::numeric_limits<uint32_t>::max() &&
713 "Unsupported Opcode");
714
715 MachineInstrBuilder Op0LOp1L =
716 createUnpackedMI(I, UnpackedOpcode, /*IsHiBits=*/false);
717 MachineOperand LoDstOp = Op0LOp1L->getOperand(0);
718
719 LoDstOp.setIsUndef(DstOp.isUndef());
720
721 MachineInstrBuilder Op0HOp1H =
722 createUnpackedMI(I, UnpackedOpcode, /*IsHiBits=*/true);
723 MachineOperand HiDstOp = Op0HOp1H->getOperand(0);
724
725 uint32_t IFlags = I.getFlags();
726 Op0LOp1L->setFlags(IFlags);
727 Op0HOp1H->setFlags(IFlags);
728 LoDstOp.setIsRenamable(DstOp.isRenamable());
729 HiDstOp.setIsRenamable(DstOp.isRenamable());
730
731 I.eraseFromParent();
732}
733
734MachineInstrBuilder SIPreEmitPeephole::createUnpackedMI(MachineInstr &I,
735 uint32_t UnpackedOpcode,
736 bool IsHiBits) {
737 MachineBasicBlock &MBB = *I.getParent();
738 const DebugLoc &DL = I.getDebugLoc();
739 const MachineOperand *SrcMO0 = TII->getNamedOperand(I, AMDGPU::OpName::src0);
740 const MachineOperand *SrcMO1 = TII->getNamedOperand(I, AMDGPU::OpName::src1);
741 Register DstReg = I.getOperand(0).getReg();
742 unsigned OpCode = I.getOpcode();
743 Register UnpackedDstReg = IsHiBits ? TRI->getSubReg(DstReg, AMDGPU::sub1)
744 : TRI->getSubReg(DstReg, AMDGPU::sub0);
745
746 int64_t ClampVal = TII->getNamedOperand(I, AMDGPU::OpName::clamp)->getImm();
747 unsigned Src0Mods =
748 TII->getNamedOperand(I, AMDGPU::OpName::src0_modifiers)->getImm();
749 unsigned Src1Mods =
750 TII->getNamedOperand(I, AMDGPU::OpName::src1_modifiers)->getImm();
751
752 MachineInstrBuilder NewMI = BuildMI(MBB, I, DL, TII->get(UnpackedOpcode));
753 NewMI.addDef(UnpackedDstReg); // vdst
754 addOperandAndMods(NewMI, Src0Mods, IsHiBits, *SrcMO0);
755 addOperandAndMods(NewMI, Src1Mods, IsHiBits, *SrcMO1);
756
757 if (AMDGPU::hasNamedOperand(OpCode, AMDGPU::OpName::src2)) {
758 const MachineOperand *SrcMO2 =
759 TII->getNamedOperand(I, AMDGPU::OpName::src2);
760 unsigned Src2Mods =
761 TII->getNamedOperand(I, AMDGPU::OpName::src2_modifiers)->getImm();
762 addOperandAndMods(NewMI, Src2Mods, IsHiBits, *SrcMO2);
763 }
764 NewMI.addImm(ClampVal); // clamp
765 // Packed instructions do not support output modifiers. safe to assign them 0
766 // for this use case
767 NewMI.addImm(0); // omod
768 return NewMI;
769}
770
771PreservedAnalyses
774 auto *MLI = MFAM.getCachedResult<MachineLoopAnalysis>(MF);
775 SIPreEmitPeephole Impl;
776
777 if (Impl.run(MF, MLI)) {
779 PA.preserve<MachineLoopAnalysis>();
780 return PA;
781 }
782
783 return PreservedAnalyses::all();
784}
785
786bool SIPreEmitPeephole::run(MachineFunction &MF, MachineLoopInfo *LoopInfo) {
787 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
788 TII = ST.getInstrInfo();
789 TRI = &TII->getRegisterInfo();
790 MLI = LoopInfo;
791 bool Changed = false;
792
793 MF.RenumberBlocks();
794
795 for (MachineBasicBlock &MBB : MF) {
796 MachineBasicBlock::iterator TermI = MBB.getFirstTerminator();
797 // Check first terminator for branches to optimize
798 if (TermI != MBB.end()) {
799 MachineInstr &MI = *TermI;
800 switch (MI.getOpcode()) {
801 case AMDGPU::S_CBRANCH_VCCZ:
802 case AMDGPU::S_CBRANCH_VCCNZ:
803 Changed |= optimizeVccBranch(MI);
804 break;
805 case AMDGPU::S_CBRANCH_EXECZ:
806 Changed |= removeExeczBranch(MI, MBB);
807 break;
808 }
809 }
810
811 if (!ST.hasVGPRIndexMode())
812 continue;
813
814 MachineInstr *SetGPRMI = nullptr;
815 const unsigned Threshold = 20;
816 unsigned Count = 0;
817 // Scan the block for two S_SET_GPR_IDX_ON instructions to see if a
818 // second is not needed. Do expensive checks in the optimizeSetGPR()
819 // and limit the distance to 20 instructions for compile time purposes.
820 // Note: this needs to work on bundles as S_SET_GPR_IDX* instructions
821 // may be bundled with the instructions they modify.
822 for (auto &MI : make_early_inc_range(MBB.instrs())) {
823 if (Count == Threshold)
824 SetGPRMI = nullptr;
825 else
826 ++Count;
827
828 if (MI.getOpcode() != AMDGPU::S_SET_GPR_IDX_ON)
829 continue;
830
831 Count = 0;
832 if (!SetGPRMI) {
833 SetGPRMI = &MI;
834 continue;
835 }
836
837 if (optimizeSetGPR(*SetGPRMI, MI))
838 Changed = true;
839 else
840 SetGPRMI = &MI;
841 }
842 }
843
844 // TODO: Fold this into previous block, if possible. Evaluate and handle any
845 // side effects.
846
847 // Perform the extra MF scans only for supported archs
848 if (!ST.hasGFX940Insts())
849 return Changed;
850 for (MachineBasicBlock &MBB : MF) {
851 // Unpack packed instructions overlapped by MFMAs. This allows the
852 // compiler to co-issue unpacked instructions with MFMA
853 auto SchedModel = TII->getSchedModel();
854 SetVector<MachineInstr *> InstrsToUnpack;
855 for (auto &MI : make_early_inc_range(MBB.instrs())) {
857 continue;
858 const MCSchedClassDesc *SchedClassDesc =
859 SchedModel.resolveSchedClass(&MI);
860 uint16_t NumMFMACycles =
861 SchedModel.getWriteProcResBegin(SchedClassDesc)->ReleaseAtCycle;
862 collectUnpackingCandidates(MI, InstrsToUnpack, NumMFMACycles);
863 }
864 for (MachineInstr *MI : InstrsToUnpack) {
865 performF32Unpacking(*MI);
866 }
867 }
868
869 return Changed;
870}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Provides AMDGPU specific target descriptions.
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
const SmallVectorImpl< MachineOperand > & Cond
This file implements a set that has insertion order iteration characteristics.
static bool isProfitable(const StableFunctionMap::StableFunctionEntries &SFS)
#define LLVM_DEBUG(...)
Definition Debug.h:119
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
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
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
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.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
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 void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
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.
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)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
static bool isMFMA(const MachineInstr &MI)
static bool modifiesModeRegister(const MachineInstr &MI)
Return true if the instruction modifies the mode register.q.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
A vector that has set insertion semantics.
Definition SetVector.h:57
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
LLVM_ABI const MCSchedClassDesc * resolveSchedClass(const MachineInstr *MI) const
Return the MCSchedClassDesc for this instruction.
ProcResIter getWriteProcResBegin(const MCSchedClassDesc *SC) const
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
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_READONLY bool hasNamedOperand(uint64_t Opcode, OpName NamedIdx)
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
This is an optimization pass for GlobalISel generic memory operations.
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:1765
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:633
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:1746
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.
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:1947
uint16_t ReleaseAtCycle
Cycle at which the resource will be released by an instruction, relatively to the cycle in which the ...
Definition MCSchedule.h:79