xref: /llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeExecMaskingPreRA.cpp (revision b03d902b61099cc5bfe7d17bbca59fccc1fd064a)
1 //===-- SIOptimizeExecMaskingPreRA.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 exec mask handling peephole optimizations which needs
11 /// to be done before register allocation to reduce register pressure.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPU.h"
16 #include "GCNSubtarget.h"
17 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
18 #include "llvm/CodeGen/LiveIntervals.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/InitializePasses.h"
21 
22 using namespace llvm;
23 
24 #define DEBUG_TYPE "si-optimize-exec-masking-pre-ra"
25 
26 namespace {
27 
28 class SIOptimizeExecMaskingPreRA : public MachineFunctionPass {
29 private:
30   const SIRegisterInfo *TRI;
31   const SIInstrInfo *TII;
32   MachineRegisterInfo *MRI;
33   LiveIntervals *LIS;
34 
35   unsigned AndOpc;
36   unsigned Andn2Opc;
37   unsigned OrSaveExecOpc;
38   unsigned XorTermrOpc;
39   MCRegister CondReg;
40   MCRegister ExecReg;
41 
42   bool optimizeVcndVcmpPair(MachineBasicBlock &MBB);
43   bool optimizeElseBranch(MachineBasicBlock &MBB);
44 
45 public:
46   static char ID;
47 
48   SIOptimizeExecMaskingPreRA() : MachineFunctionPass(ID) {
49     initializeSIOptimizeExecMaskingPreRAPass(*PassRegistry::getPassRegistry());
50   }
51 
52   bool runOnMachineFunction(MachineFunction &MF) override;
53 
54   StringRef getPassName() const override {
55     return "SI optimize exec mask operations pre-RA";
56   }
57 
58   void getAnalysisUsage(AnalysisUsage &AU) const override {
59     AU.addRequired<LiveIntervals>();
60     AU.setPreservesAll();
61     MachineFunctionPass::getAnalysisUsage(AU);
62   }
63 };
64 
65 } // End anonymous namespace.
66 
67 INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,
68                       "SI optimize exec mask operations pre-RA", false, false)
69 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
70 INITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,
71                     "SI optimize exec mask operations pre-RA", false, false)
72 
73 char SIOptimizeExecMaskingPreRA::ID = 0;
74 
75 char &llvm::SIOptimizeExecMaskingPreRAID = SIOptimizeExecMaskingPreRA::ID;
76 
77 FunctionPass *llvm::createSIOptimizeExecMaskingPreRAPass() {
78   return new SIOptimizeExecMaskingPreRA();
79 }
80 
81 // See if there is a def between \p AndIdx and \p SelIdx that needs to live
82 // beyond \p AndIdx.
83 static bool isDefBetween(const LiveRange &LR, SlotIndex AndIdx,
84                          SlotIndex SelIdx) {
85   LiveQueryResult AndLRQ = LR.Query(AndIdx);
86   return (!AndLRQ.isKill() && AndLRQ.valueIn() != LR.Query(SelIdx).valueOut());
87 }
88 
89 // FIXME: Why do we bother trying to handle physical registers here?
90 static bool isDefBetween(const SIRegisterInfo &TRI,
91                          LiveIntervals *LIS, Register Reg,
92                          const MachineInstr &Sel, const MachineInstr &And) {
93   SlotIndex AndIdx = LIS->getInstructionIndex(And).getRegSlot();
94   SlotIndex SelIdx = LIS->getInstructionIndex(Sel).getRegSlot();
95 
96   if (Reg.isVirtual())
97     return isDefBetween(LIS->getInterval(Reg), AndIdx, SelIdx);
98 
99   for (MCRegUnitIterator UI(Reg.asMCReg(), &TRI); UI.isValid(); ++UI) {
100     if (isDefBetween(LIS->getRegUnit(*UI), AndIdx, SelIdx))
101       return true;
102   }
103 
104   return false;
105 }
106 
107 // Optimize sequence
108 //    %sel = V_CNDMASK_B32_e64 0, 1, %cc
109 //    %cmp = V_CMP_NE_U32 1, %1
110 //    $vcc = S_AND_B64 $exec, %cmp
111 //    S_CBRANCH_VCC[N]Z
112 // =>
113 //    $vcc = S_ANDN2_B64 $exec, %cc
114 //    S_CBRANCH_VCC[N]Z
115 //
116 // It is the negation pattern inserted by DAGCombiner::visitBRCOND() in the
117 // rebuildSetCC(). We start with S_CBRANCH to avoid exhaustive search, but
118 // only 3 first instructions are really needed. S_AND_B64 with exec is a
119 // required part of the pattern since V_CNDMASK_B32 writes zeroes for inactive
120 // lanes.
121 //
122 // Returns true on success.
123 bool SIOptimizeExecMaskingPreRA::optimizeVcndVcmpPair(MachineBasicBlock &MBB) {
124   auto I = llvm::find_if(MBB.terminators(), [](const MachineInstr &MI) {
125                            unsigned Opc = MI.getOpcode();
126                            return Opc == AMDGPU::S_CBRANCH_VCCZ ||
127                                   Opc == AMDGPU::S_CBRANCH_VCCNZ; });
128   if (I == MBB.terminators().end())
129     return false;
130 
131   auto *And =
132       TRI->findReachingDef(CondReg, AMDGPU::NoSubRegister, *I, *MRI, LIS);
133   if (!And || And->getOpcode() != AndOpc ||
134       !And->getOperand(1).isReg() || !And->getOperand(2).isReg())
135     return false;
136 
137   MachineOperand *AndCC = &And->getOperand(1);
138   Register CmpReg = AndCC->getReg();
139   unsigned CmpSubReg = AndCC->getSubReg();
140   if (CmpReg == Register(ExecReg)) {
141     AndCC = &And->getOperand(2);
142     CmpReg = AndCC->getReg();
143     CmpSubReg = AndCC->getSubReg();
144   } else if (And->getOperand(2).getReg() != Register(ExecReg)) {
145     return false;
146   }
147 
148   auto *Cmp = TRI->findReachingDef(CmpReg, CmpSubReg, *And, *MRI, LIS);
149   if (!Cmp || !(Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e32 ||
150                 Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e64) ||
151       Cmp->getParent() != And->getParent())
152     return false;
153 
154   MachineOperand *Op1 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src0);
155   MachineOperand *Op2 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src1);
156   if (Op1->isImm() && Op2->isReg())
157     std::swap(Op1, Op2);
158   if (!Op1->isReg() || !Op2->isImm() || Op2->getImm() != 1)
159     return false;
160 
161   Register SelReg = Op1->getReg();
162   auto *Sel = TRI->findReachingDef(SelReg, Op1->getSubReg(), *Cmp, *MRI, LIS);
163   if (!Sel || Sel->getOpcode() != AMDGPU::V_CNDMASK_B32_e64)
164     return false;
165 
166   if (TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers) ||
167       TII->hasModifiersSet(*Sel, AMDGPU::OpName::src1_modifiers))
168     return false;
169 
170   Op1 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src0);
171   Op2 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src1);
172   MachineOperand *CC = TII->getNamedOperand(*Sel, AMDGPU::OpName::src2);
173   if (!Op1->isImm() || !Op2->isImm() || !CC->isReg() ||
174       Op1->getImm() != 0 || Op2->getImm() != 1)
175     return false;
176 
177   Register CCReg = CC->getReg();
178 
179   // If there was a def between the select and the and, we would need to move it
180   // to fold this.
181   if (isDefBetween(*TRI, LIS, CCReg, *Sel, *And))
182     return false;
183 
184   // TODO: Guard against implicit def operands?
185   LLVM_DEBUG(dbgs() << "Folding sequence:\n\t" << *Sel << '\t' << *Cmp << '\t'
186                     << *And);
187 
188   MachineInstr *Andn2 =
189       BuildMI(MBB, *And, And->getDebugLoc(), TII->get(Andn2Opc),
190               And->getOperand(0).getReg())
191           .addReg(ExecReg)
192           .addReg(CCReg, getUndefRegState(CC->isUndef()), CC->getSubReg());
193   MachineOperand &AndSCC = And->getOperand(3);
194   assert(AndSCC.getReg() == AMDGPU::SCC);
195   MachineOperand &Andn2SCC = Andn2->getOperand(3);
196   assert(Andn2SCC.getReg() == AMDGPU::SCC);
197   Andn2SCC.setIsDead(AndSCC.isDead());
198 
199   SlotIndex AndIdx = LIS->ReplaceMachineInstrInMaps(*And, *Andn2);
200   And->eraseFromParent();
201 
202   LLVM_DEBUG(dbgs() << "=>\n\t" << *Andn2 << '\n');
203 
204   SlotIndex CmpIdx = LIS->getInstructionIndex(*Cmp);
205   SlotIndex SelIdx = LIS->getInstructionIndex(*Sel);
206 
207   LiveInterval *CmpLI =
208       CmpReg.isVirtual() ? &LIS->getInterval(CmpReg) : nullptr;
209 
210   // Try to remove compare. Cmp value should not used in between of cmp
211   // and s_and_b64 if VCC or just unused if any other register.
212   if ((CmpReg.isVirtual() && CmpLI->Query(AndIdx.getRegSlot()).isKill()) ||
213       (CmpReg == Register(CondReg) &&
214        std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(),
215                     [&](const MachineInstr &MI) {
216                       return MI.readsRegister(CondReg, TRI);
217                     }))) {
218     LLVM_DEBUG(dbgs() << "Erasing: " << *Cmp << '\n');
219     if (CmpLI)
220       LIS->removeVRegDefAt(*CmpLI, CmpIdx.getRegSlot());
221     LIS->RemoveMachineInstrFromMaps(*Cmp);
222     Cmp->eraseFromParent();
223 
224     LiveInterval *SelLI =
225         SelReg.isVirtual() ? &LIS->getInterval(SelReg) : nullptr;
226     // Try to remove v_cndmask_b32.
227     if (SelLI && SelLI->Query(CmpIdx.getRegSlot()).isKill()) {
228       LLVM_DEBUG(dbgs() << "Erasing: " << *Sel << '\n');
229 
230       if (SelLI)
231         LIS->removeVRegDefAt(*SelLI, SelIdx.getRegSlot());
232       LIS->RemoveMachineInstrFromMaps(*Sel);
233       Sel->eraseFromParent();
234     }
235   }
236 
237   if (CCReg.isVirtual()) {
238     LiveInterval &CCLI = LIS->getInterval(CCReg);
239     auto CCQ = CCLI.Query(SelIdx.getRegSlot());
240     if (CCQ.valueIn()) {
241       CCLI.addSegment(LiveRange::Segment(SelIdx.getRegSlot(),
242                                          AndIdx.getRegSlot(), CCQ.valueIn()));
243     }
244 
245     if (CC->getSubReg()) {
246       LaneBitmask Mask = TRI->getSubRegIndexLaneMask(CC->getSubReg());
247       BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
248       CCLI.refineSubRanges(
249           Allocator, Mask,
250           [=](LiveInterval::SubRange &SR) {
251             auto CCQS = SR.Query(SelIdx.getRegSlot());
252             if (CCQS.valueIn()) {
253               SR.addSegment(LiveRange::Segment(
254                   SelIdx.getRegSlot(), AndIdx.getRegSlot(), CCQS.valueIn()));
255             }
256           },
257           *LIS->getSlotIndexes(), *TRI);
258       CCLI.removeEmptySubRanges();
259 
260       SmallVector<LiveInterval *> SplitLIs;
261       LIS->splitSeparateComponents(CCLI, SplitLIs);
262     }
263   } else
264     LIS->removeAllRegUnitsForPhysReg(CCReg);
265 
266   return true;
267 }
268 
269 // Optimize sequence
270 //    %dst = S_OR_SAVEEXEC %src
271 //    ... instructions not modifying exec ...
272 //    %tmp = S_AND $exec, %dst
273 //    $exec = S_XOR_term $exec, %tmp
274 // =>
275 //    %dst = S_OR_SAVEEXEC %src
276 //    ... instructions not modifying exec ...
277 //    $exec = S_XOR_term $exec, %dst
278 //
279 // Clean up potentially unnecessary code added for safety during
280 // control flow lowering.
281 //
282 // Return whether any changes were made to MBB.
283 bool SIOptimizeExecMaskingPreRA::optimizeElseBranch(MachineBasicBlock &MBB) {
284   if (MBB.empty())
285     return false;
286 
287   // Check this is an else block.
288   auto First = MBB.begin();
289   MachineInstr &SaveExecMI = *First;
290   if (SaveExecMI.getOpcode() != OrSaveExecOpc)
291     return false;
292 
293   auto I = llvm::find_if(MBB.terminators(), [this](const MachineInstr &MI) {
294     return MI.getOpcode() == XorTermrOpc;
295   });
296   if (I == MBB.terminators().end())
297     return false;
298 
299   MachineInstr &XorTermMI = *I;
300   if (XorTermMI.getOperand(1).getReg() != Register(ExecReg))
301     return false;
302 
303   Register SavedExecReg = SaveExecMI.getOperand(0).getReg();
304   Register DstReg = XorTermMI.getOperand(2).getReg();
305 
306   // Find potentially unnecessary S_AND
307   MachineInstr *AndExecMI = nullptr;
308   I--;
309   while (I != First && !AndExecMI) {
310     if (I->getOpcode() == AndOpc && I->getOperand(0).getReg() == DstReg &&
311         I->getOperand(1).getReg() == Register(ExecReg))
312       AndExecMI = &*I;
313     I--;
314   }
315   if (!AndExecMI)
316     return false;
317 
318   // Check for exec modifying instructions.
319   // Note: exec defs do not create live ranges beyond the
320   // instruction so isDefBetween cannot be used.
321   // Instead just check that the def segments are adjacent.
322   SlotIndex StartIdx = LIS->getInstructionIndex(SaveExecMI);
323   SlotIndex EndIdx = LIS->getInstructionIndex(*AndExecMI);
324   for (MCRegUnitIterator UI(ExecReg, TRI); UI.isValid(); ++UI) {
325     LiveRange &RegUnit = LIS->getRegUnit(*UI);
326     if (RegUnit.find(StartIdx) != std::prev(RegUnit.find(EndIdx)))
327       return false;
328   }
329 
330   // Remove unnecessary S_AND
331   LIS->removeInterval(SavedExecReg);
332   LIS->removeInterval(DstReg);
333 
334   SaveExecMI.getOperand(0).setReg(DstReg);
335 
336   LIS->RemoveMachineInstrFromMaps(*AndExecMI);
337   AndExecMI->eraseFromParent();
338 
339   LIS->createAndComputeVirtRegInterval(DstReg);
340 
341   return true;
342 }
343 
344 bool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) {
345   if (skipFunction(MF.getFunction()))
346     return false;
347 
348   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
349   TRI = ST.getRegisterInfo();
350   TII = ST.getInstrInfo();
351   MRI = &MF.getRegInfo();
352   LIS = &getAnalysis<LiveIntervals>();
353 
354   const bool Wave32 = ST.isWave32();
355   AndOpc = Wave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
356   Andn2Opc = Wave32 ? AMDGPU::S_ANDN2_B32 : AMDGPU::S_ANDN2_B64;
357   OrSaveExecOpc =
358       Wave32 ? AMDGPU::S_OR_SAVEEXEC_B32 : AMDGPU::S_OR_SAVEEXEC_B64;
359   XorTermrOpc = Wave32 ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
360   CondReg = MCRegister::from(Wave32 ? AMDGPU::VCC_LO : AMDGPU::VCC);
361   ExecReg = MCRegister::from(Wave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC);
362 
363   DenseSet<Register> RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI});
364   bool Changed = false;
365 
366   for (MachineBasicBlock &MBB : MF) {
367 
368     if (optimizeElseBranch(MBB)) {
369       RecalcRegs.insert(AMDGPU::SCC);
370       Changed = true;
371     }
372 
373     if (optimizeVcndVcmpPair(MBB)) {
374       RecalcRegs.insert(AMDGPU::VCC_LO);
375       RecalcRegs.insert(AMDGPU::VCC_HI);
376       RecalcRegs.insert(AMDGPU::SCC);
377       Changed = true;
378     }
379 
380     // Try to remove unneeded instructions before s_endpgm.
381     if (MBB.succ_empty()) {
382       if (MBB.empty())
383         continue;
384 
385       // Skip this if the endpgm has any implicit uses, otherwise we would need
386       // to be careful to update / remove them.
387       // S_ENDPGM always has a single imm operand that is not used other than to
388       // end up in the encoding
389       MachineInstr &Term = MBB.back();
390       if (Term.getOpcode() != AMDGPU::S_ENDPGM || Term.getNumOperands() != 1)
391         continue;
392 
393       SmallVector<MachineBasicBlock*, 4> Blocks({&MBB});
394 
395       while (!Blocks.empty()) {
396         auto CurBB = Blocks.pop_back_val();
397         auto I = CurBB->rbegin(), E = CurBB->rend();
398         if (I != E) {
399           if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM)
400             ++I;
401           else if (I->isBranch())
402             continue;
403         }
404 
405         while (I != E) {
406           if (I->isDebugInstr()) {
407             I = std::next(I);
408             continue;
409           }
410 
411           if (I->mayStore() || I->isBarrier() || I->isCall() ||
412               I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef())
413             break;
414 
415           LLVM_DEBUG(dbgs()
416                      << "Removing no effect instruction: " << *I << '\n');
417 
418           for (auto &Op : I->operands()) {
419             if (Op.isReg())
420               RecalcRegs.insert(Op.getReg());
421           }
422 
423           auto Next = std::next(I);
424           LIS->RemoveMachineInstrFromMaps(*I);
425           I->eraseFromParent();
426           I = Next;
427 
428           Changed = true;
429         }
430 
431         if (I != E)
432           continue;
433 
434         // Try to ascend predecessors.
435         for (auto *Pred : CurBB->predecessors()) {
436           if (Pred->succ_size() == 1)
437             Blocks.push_back(Pred);
438         }
439       }
440       continue;
441     }
442 
443     // If the only user of a logical operation is move to exec, fold it now
444     // to prevent forming of saveexec. I.e.:
445     //
446     //    %0:sreg_64 = COPY $exec
447     //    %1:sreg_64 = S_AND_B64 %0:sreg_64, %2:sreg_64
448     // =>
449     //    %1 = S_AND_B64 $exec, %2:sreg_64
450     unsigned ScanThreshold = 10;
451     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E
452          && ScanThreshold--; ++I) {
453       // Continue scanning if this is not a full exec copy
454       if (!(I->isFullCopy() && I->getOperand(1).getReg() == Register(ExecReg)))
455         continue;
456 
457       Register SavedExec = I->getOperand(0).getReg();
458       if (SavedExec.isVirtual() && MRI->hasOneNonDBGUse(SavedExec)) {
459         MachineInstr *SingleExecUser = &*MRI->use_instr_nodbg_begin(SavedExec);
460         int Idx = SingleExecUser->findRegisterUseOperandIdx(SavedExec);
461         assert(Idx != -1);
462         if (SingleExecUser->getParent() == I->getParent() &&
463             !SingleExecUser->getOperand(Idx).isImplicit() &&
464             TII->isOperandLegal(*SingleExecUser, Idx, &I->getOperand(1))) {
465           LLVM_DEBUG(dbgs() << "Redundant EXEC COPY: " << *I << '\n');
466           LIS->RemoveMachineInstrFromMaps(*I);
467           I->eraseFromParent();
468           MRI->replaceRegWith(SavedExec, ExecReg);
469           LIS->removeInterval(SavedExec);
470           Changed = true;
471         }
472       }
473       break;
474     }
475   }
476 
477   if (Changed) {
478     for (auto Reg : RecalcRegs) {
479       if (Reg.isVirtual()) {
480         LIS->removeInterval(Reg);
481         if (!MRI->reg_empty(Reg))
482           LIS->createAndComputeVirtRegInterval(Reg);
483       } else {
484         LIS->removeAllRegUnitsForPhysReg(Reg);
485       }
486     }
487   }
488 
489   return Changed;
490 }
491