xref: /llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeExecMaskingPreRA.cpp (revision a353fd572abbbf00f5ccd496bc2571fb23c517e3)
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 removes redundant S_OR_B64 instructions enabling lanes in
11 /// the exec. If two SI_END_CF (lowered as S_OR_B64) come together without any
12 /// vector instructions between them we can only keep outer SI_END_CF, given
13 /// that CFG is structured and exec bits of the outer end statement are always
14 /// not less than exec bit of the inner one.
15 ///
16 /// This needs to be done before the RA to eliminate saved exec bits registers
17 /// but after register coalescer to have no vector registers copies in between
18 /// of different end cf statements.
19 ///
20 //===----------------------------------------------------------------------===//
21 
22 #include "AMDGPU.h"
23 #include "AMDGPUSubtarget.h"
24 #include "SIInstrInfo.h"
25 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
26 #include "llvm/CodeGen/LiveIntervals.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 
29 using namespace llvm;
30 
31 #define DEBUG_TYPE "si-optimize-exec-masking-pre-ra"
32 
33 namespace {
34 
35 class SIOptimizeExecMaskingPreRA : public MachineFunctionPass {
36 private:
37   const SIRegisterInfo *TRI;
38   const SIInstrInfo *TII;
39   MachineRegisterInfo *MRI;
40 
41 public:
42   MachineBasicBlock::iterator skipIgnoreExecInsts(
43     MachineBasicBlock::iterator I, MachineBasicBlock::iterator E) const;
44 
45     MachineBasicBlock::iterator skipIgnoreExecInstsTrivialSucc(
46       MachineBasicBlock *&MBB,
47       MachineBasicBlock::iterator It) const;
48 
49 public:
50   static char ID;
51 
52   SIOptimizeExecMaskingPreRA() : MachineFunctionPass(ID) {
53     initializeSIOptimizeExecMaskingPreRAPass(*PassRegistry::getPassRegistry());
54   }
55 
56   bool runOnMachineFunction(MachineFunction &MF) override;
57 
58   StringRef getPassName() const override {
59     return "SI optimize exec mask operations pre-RA";
60   }
61 
62   void getAnalysisUsage(AnalysisUsage &AU) const override {
63     AU.addRequired<LiveIntervals>();
64     AU.setPreservesAll();
65     MachineFunctionPass::getAnalysisUsage(AU);
66   }
67 };
68 
69 } // End anonymous namespace.
70 
71 INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,
72                       "SI optimize exec mask operations pre-RA", false, false)
73 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
74 INITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,
75                     "SI optimize exec mask operations pre-RA", false, false)
76 
77 char SIOptimizeExecMaskingPreRA::ID = 0;
78 
79 char &llvm::SIOptimizeExecMaskingPreRAID = SIOptimizeExecMaskingPreRA::ID;
80 
81 FunctionPass *llvm::createSIOptimizeExecMaskingPreRAPass() {
82   return new SIOptimizeExecMaskingPreRA();
83 }
84 
85 static bool isEndCF(const MachineInstr& MI, const SIRegisterInfo* TRI) {
86   return MI.getOpcode() == AMDGPU::S_OR_B64 &&
87          MI.modifiesRegister(AMDGPU::EXEC, TRI);
88 }
89 
90 static bool isFullExecCopy(const MachineInstr& MI) {
91   return MI.getOperand(1).getReg() == AMDGPU::EXEC;
92 }
93 
94 static unsigned getOrNonExecReg(const MachineInstr &MI,
95                                 const SIInstrInfo &TII) {
96   auto Op = TII.getNamedOperand(MI, AMDGPU::OpName::src1);
97   if (Op->isReg() && Op->getReg() != AMDGPU::EXEC)
98      return Op->getReg();
99   Op = TII.getNamedOperand(MI, AMDGPU::OpName::src0);
100   if (Op->isReg() && Op->getReg() != AMDGPU::EXEC)
101      return Op->getReg();
102   return AMDGPU::NoRegister;
103 }
104 
105 static MachineInstr* getOrExecSource(const MachineInstr &MI,
106                                      const SIInstrInfo &TII,
107                                      const MachineRegisterInfo &MRI) {
108   auto SavedExec = getOrNonExecReg(MI, TII);
109   if (SavedExec == AMDGPU::NoRegister)
110     return nullptr;
111   auto SaveExecInst = MRI.getUniqueVRegDef(SavedExec);
112   if (!SaveExecInst || !isFullExecCopy(*SaveExecInst))
113     return nullptr;
114   return SaveExecInst;
115 }
116 
117 /// Skip over instructions that don't care about the exec mask.
118 MachineBasicBlock::iterator SIOptimizeExecMaskingPreRA::skipIgnoreExecInsts(
119   MachineBasicBlock::iterator I, MachineBasicBlock::iterator E) const {
120   for ( ; I != E; ++I) {
121     if (TII->mayReadEXEC(*MRI, *I))
122       break;
123   }
124 
125   return I;
126 }
127 
128 // Skip to the next instruction, ignoring debug instructions, and trivial block
129 // boundaries (blocks that have one (typically fallthrough) successor, and the
130 // successor has one predecessor.
131 MachineBasicBlock::iterator
132 SIOptimizeExecMaskingPreRA::skipIgnoreExecInstsTrivialSucc(
133   MachineBasicBlock *&MBB,
134   MachineBasicBlock::iterator It) const {
135 
136   do {
137     It = skipIgnoreExecInsts(It, MBB->end());
138     if (It != MBB->end() || MBB->succ_size() != 1)
139       break;
140 
141     // If there is one trivial successor, advance to the next block.
142     MachineBasicBlock *Succ = *MBB->succ_begin();
143 
144     // TODO: Is this really necessary?
145     if (!MBB->isLayoutSuccessor(Succ))
146       break;
147 
148     It = Succ->begin();
149     MBB = Succ;
150   } while (true);
151 
152   return It;
153 }
154 
155 
156 // Optimize sequence
157 //    %sel = V_CNDMASK_B32_e64 0, 1, %cc
158 //    %cmp = V_CMP_NE_U32 1, %1
159 //    $vcc = S_AND_B64 $exec, %cmp
160 //    S_CBRANCH_VCC[N]Z
161 // =>
162 //    $vcc = S_ANDN2_B64 $exec, %cc
163 //    S_CBRANCH_VCC[N]Z
164 //
165 // It is the negation pattern inserted by DAGCombiner::visitBRCOND() in the
166 // rebuildSetCC(). We start with S_CBRANCH to avoid exhaustive search, but
167 // only 3 first instructions are really needed. S_AND_B64 with exec is a
168 // required part of the pattern since V_CNDMASK_B32 writes zeroes for inactive
169 // lanes.
170 //
171 // Returns %cc register on success.
172 static unsigned optimizeVcndVcmpPair(MachineBasicBlock &MBB,
173                                      const GCNSubtarget &ST,
174                                      MachineRegisterInfo &MRI,
175                                      LiveIntervals *LIS) {
176   const SIRegisterInfo *TRI = ST.getRegisterInfo();
177   const SIInstrInfo *TII = ST.getInstrInfo();
178   const unsigned AndOpc = AMDGPU::S_AND_B64;
179   const unsigned Andn2Opc = AMDGPU::S_ANDN2_B64;
180   const unsigned CondReg = AMDGPU::VCC;
181   const unsigned ExecReg = AMDGPU::EXEC;
182 
183   auto I = llvm::find_if(MBB.terminators(), [](const MachineInstr &MI) {
184                            unsigned Opc = MI.getOpcode();
185                            return Opc == AMDGPU::S_CBRANCH_VCCZ ||
186                                   Opc == AMDGPU::S_CBRANCH_VCCNZ; });
187   if (I == MBB.terminators().end())
188     return AMDGPU::NoRegister;
189 
190   auto *And = TRI->findReachingDef(CondReg, AMDGPU::NoSubRegister,
191                                    *I, MRI, LIS);
192   if (!And || And->getOpcode() != AndOpc ||
193       !And->getOperand(1).isReg() || !And->getOperand(2).isReg())
194     return AMDGPU::NoRegister;
195 
196   MachineOperand *AndCC = &And->getOperand(1);
197   unsigned CmpReg = AndCC->getReg();
198   unsigned CmpSubReg = AndCC->getSubReg();
199   if (CmpReg == ExecReg) {
200     AndCC = &And->getOperand(2);
201     CmpReg = AndCC->getReg();
202     CmpSubReg = AndCC->getSubReg();
203   } else if (And->getOperand(2).getReg() != ExecReg) {
204     return AMDGPU::NoRegister;
205   }
206 
207   auto *Cmp = TRI->findReachingDef(CmpReg, CmpSubReg, *And, MRI, LIS);
208   if (!Cmp || !(Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e32 ||
209                 Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e64) ||
210       Cmp->getParent() != And->getParent())
211     return AMDGPU::NoRegister;
212 
213   MachineOperand *Op1 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src0);
214   MachineOperand *Op2 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src1);
215   if (Op1->isImm() && Op2->isReg())
216     std::swap(Op1, Op2);
217   if (!Op1->isReg() || !Op2->isImm() || Op2->getImm() != 1)
218     return AMDGPU::NoRegister;
219 
220   unsigned SelReg = Op1->getReg();
221   auto *Sel = TRI->findReachingDef(SelReg, Op1->getSubReg(), *Cmp, MRI, LIS);
222   if (!Sel || Sel->getOpcode() != AMDGPU::V_CNDMASK_B32_e64)
223     return AMDGPU::NoRegister;
224 
225   if (TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers) ||
226       TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers))
227     return AMDGPU::NoRegister;
228 
229   Op1 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src0);
230   Op2 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src1);
231   MachineOperand *CC = TII->getNamedOperand(*Sel, AMDGPU::OpName::src2);
232   if (!Op1->isImm() || !Op2->isImm() || !CC->isReg() ||
233       Op1->getImm() != 0 || Op2->getImm() != 1)
234     return AMDGPU::NoRegister;
235 
236   LLVM_DEBUG(dbgs() << "Folding sequence:\n\t" << *Sel << '\t'
237                     << *Cmp << '\t' << *And);
238 
239   unsigned CCReg = CC->getReg();
240   LIS->RemoveMachineInstrFromMaps(*And);
241   MachineInstr *Andn2 = BuildMI(MBB, *And, And->getDebugLoc(),
242                                 TII->get(Andn2Opc), And->getOperand(0).getReg())
243                             .addReg(ExecReg)
244                             .addReg(CCReg, CC->getSubReg());
245   And->eraseFromParent();
246   LIS->InsertMachineInstrInMaps(*Andn2);
247 
248   LLVM_DEBUG(dbgs() << "=>\n\t" << *Andn2 << '\n');
249 
250   // Try to remove compare. Cmp value should not used in between of cmp
251   // and s_and_b64 if VCC or just unused if any other register.
252   if ((TargetRegisterInfo::isVirtualRegister(CmpReg) &&
253        MRI.use_nodbg_empty(CmpReg)) ||
254       (CmpReg == CondReg &&
255        std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(),
256                     [&](const MachineInstr &MI) {
257                       return MI.readsRegister(CondReg, TRI); }))) {
258     LLVM_DEBUG(dbgs() << "Erasing: " << *Cmp << '\n');
259 
260     LIS->RemoveMachineInstrFromMaps(*Cmp);
261     Cmp->eraseFromParent();
262 
263     // Try to remove v_cndmask_b32.
264     if (TargetRegisterInfo::isVirtualRegister(SelReg) &&
265         MRI.use_nodbg_empty(SelReg)) {
266       LLVM_DEBUG(dbgs() << "Erasing: " << *Sel << '\n');
267 
268       LIS->RemoveMachineInstrFromMaps(*Sel);
269       Sel->eraseFromParent();
270     }
271   }
272 
273   return CCReg;
274 }
275 
276 bool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) {
277   if (skipFunction(MF.getFunction()))
278     return false;
279 
280   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
281   TRI = ST.getRegisterInfo();
282   TII = ST.getInstrInfo();
283   MRI = &MF.getRegInfo();
284 
285   MachineRegisterInfo &MRI = MF.getRegInfo();
286   LiveIntervals *LIS = &getAnalysis<LiveIntervals>();
287   DenseSet<unsigned> RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI});
288   bool Changed = false;
289 
290   for (MachineBasicBlock &MBB : MF) {
291 
292     if (unsigned Reg = optimizeVcndVcmpPair(MBB, ST, MRI, LIS)) {
293       RecalcRegs.insert(Reg);
294       RecalcRegs.insert(AMDGPU::VCC_LO);
295       RecalcRegs.insert(AMDGPU::VCC_HI);
296       RecalcRegs.insert(AMDGPU::SCC);
297       Changed = true;
298     }
299 
300     // Try to remove unneeded instructions before s_endpgm.
301     if (MBB.succ_empty()) {
302       if (MBB.empty())
303         continue;
304 
305       // Skip this if the endpgm has any implicit uses, otherwise we would need
306       // to be careful to update / remove them.
307       // S_ENDPGM always has a single imm operand that is not used other than to
308       // end up in the encoding
309       MachineInstr &Term = MBB.back();
310       if (Term.getOpcode() != AMDGPU::S_ENDPGM || Term.getNumOperands() != 1)
311         continue;
312 
313       SmallVector<MachineBasicBlock*, 4> Blocks({&MBB});
314 
315       while (!Blocks.empty()) {
316         auto CurBB = Blocks.pop_back_val();
317         auto I = CurBB->rbegin(), E = CurBB->rend();
318         if (I != E) {
319           if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM)
320             ++I;
321           else if (I->isBranch())
322             continue;
323         }
324 
325         while (I != E) {
326           if (I->isDebugInstr()) {
327             I = std::next(I);
328             continue;
329           }
330 
331           if (I->mayStore() || I->isBarrier() || I->isCall() ||
332               I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef())
333             break;
334 
335           LLVM_DEBUG(dbgs()
336                      << "Removing no effect instruction: " << *I << '\n');
337 
338           for (auto &Op : I->operands()) {
339             if (Op.isReg())
340               RecalcRegs.insert(Op.getReg());
341           }
342 
343           auto Next = std::next(I);
344           LIS->RemoveMachineInstrFromMaps(*I);
345           I->eraseFromParent();
346           I = Next;
347 
348           Changed = true;
349         }
350 
351         if (I != E)
352           continue;
353 
354         // Try to ascend predecessors.
355         for (auto *Pred : CurBB->predecessors()) {
356           if (Pred->succ_size() == 1)
357             Blocks.push_back(Pred);
358         }
359       }
360       continue;
361     }
362 
363     // Try to collapse adjacent endifs.
364     auto E = MBB.end();
365     auto Lead = skipDebugInstructionsForward(MBB.begin(), E);
366     if (MBB.succ_size() != 1 || Lead == E || !isEndCF(*Lead, TRI))
367       continue;
368 
369     MachineBasicBlock *TmpMBB = &MBB;
370     auto NextLead = skipIgnoreExecInstsTrivialSucc(TmpMBB, std::next(Lead));
371     if (NextLead == TmpMBB->end() || !isEndCF(*NextLead, TRI) ||
372         !getOrExecSource(*NextLead, *TII, MRI))
373       continue;
374 
375     LLVM_DEBUG(dbgs() << "Redundant EXEC = S_OR_B64 found: " << *Lead << '\n');
376 
377     auto SaveExec = getOrExecSource(*Lead, *TII, MRI);
378     unsigned SaveExecReg = getOrNonExecReg(*Lead, *TII);
379     for (auto &Op : Lead->operands()) {
380       if (Op.isReg())
381         RecalcRegs.insert(Op.getReg());
382     }
383 
384     LIS->RemoveMachineInstrFromMaps(*Lead);
385     Lead->eraseFromParent();
386     if (SaveExecReg) {
387       LIS->removeInterval(SaveExecReg);
388       LIS->createAndComputeVirtRegInterval(SaveExecReg);
389     }
390 
391     Changed = true;
392 
393     // If the only use of saved exec in the removed instruction is S_AND_B64
394     // fold the copy now.
395     if (!SaveExec || !SaveExec->isFullCopy())
396       continue;
397 
398     unsigned SavedExec = SaveExec->getOperand(0).getReg();
399     bool SafeToReplace = true;
400     for (auto& U : MRI.use_nodbg_instructions(SavedExec)) {
401       if (U.getParent() != SaveExec->getParent()) {
402         SafeToReplace = false;
403         break;
404       }
405 
406       LLVM_DEBUG(dbgs() << "Redundant EXEC COPY: " << *SaveExec << '\n');
407     }
408 
409     if (SafeToReplace) {
410       LIS->RemoveMachineInstrFromMaps(*SaveExec);
411       SaveExec->eraseFromParent();
412       MRI.replaceRegWith(SavedExec, AMDGPU::EXEC);
413       LIS->removeInterval(SavedExec);
414     }
415   }
416 
417   if (Changed) {
418     for (auto Reg : RecalcRegs) {
419       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
420         LIS->removeInterval(Reg);
421         if (!MRI.reg_empty(Reg))
422           LIS->createAndComputeVirtRegInterval(Reg);
423       } else {
424         LIS->removeAllRegUnitsForPhysReg(Reg);
425       }
426     }
427   }
428 
429   return Changed;
430 }
431