xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/SIOptimizeExecMaskingPreRA.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
10b57cec5SDimitry Andric //===-- SIOptimizeExecMaskingPreRA.cpp ------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric /// \file
105ffd83dbSDimitry Andric /// This pass performs exec mask handling peephole optimizations which needs
115ffd83dbSDimitry Andric /// to be done before register allocation to reduce register pressure.
120b57cec5SDimitry Andric ///
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "AMDGPU.h"
16e8d8bef9SDimitry Andric #include "GCNSubtarget.h"
170b57cec5SDimitry Andric #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
180b57cec5SDimitry Andric #include "llvm/CodeGen/LiveIntervals.h"
190b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
20480093f4SDimitry Andric #include "llvm/InitializePasses.h"
210b57cec5SDimitry Andric 
220b57cec5SDimitry Andric using namespace llvm;
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric #define DEBUG_TYPE "si-optimize-exec-masking-pre-ra"
250b57cec5SDimitry Andric 
260b57cec5SDimitry Andric namespace {
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric class SIOptimizeExecMaskingPreRA : public MachineFunctionPass {
290b57cec5SDimitry Andric private:
300b57cec5SDimitry Andric   const SIRegisterInfo *TRI;
310b57cec5SDimitry Andric   const SIInstrInfo *TII;
320b57cec5SDimitry Andric   MachineRegisterInfo *MRI;
33e8d8bef9SDimitry Andric   LiveIntervals *LIS;
34e8d8bef9SDimitry Andric 
35e8d8bef9SDimitry Andric   unsigned AndOpc;
36e8d8bef9SDimitry Andric   unsigned Andn2Opc;
37e8d8bef9SDimitry Andric   unsigned OrSaveExecOpc;
38e8d8bef9SDimitry Andric   unsigned XorTermrOpc;
39e8d8bef9SDimitry Andric   MCRegister CondReg;
40e8d8bef9SDimitry Andric   MCRegister ExecReg;
41e8d8bef9SDimitry Andric 
42*81ad6265SDimitry Andric   bool optimizeVcndVcmpPair(MachineBasicBlock &MBB);
43e8d8bef9SDimitry Andric   bool optimizeElseBranch(MachineBasicBlock &MBB);
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric public:
460b57cec5SDimitry Andric   static char ID;
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric   SIOptimizeExecMaskingPreRA() : MachineFunctionPass(ID) {
490b57cec5SDimitry Andric     initializeSIOptimizeExecMaskingPreRAPass(*PassRegistry::getPassRegistry());
500b57cec5SDimitry Andric   }
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
530b57cec5SDimitry Andric 
540b57cec5SDimitry Andric   StringRef getPassName() const override {
550b57cec5SDimitry Andric     return "SI optimize exec mask operations pre-RA";
560b57cec5SDimitry Andric   }
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
590b57cec5SDimitry Andric     AU.addRequired<LiveIntervals>();
600b57cec5SDimitry Andric     AU.setPreservesAll();
610b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
620b57cec5SDimitry Andric   }
630b57cec5SDimitry Andric };
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric } // End anonymous namespace.
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,
680b57cec5SDimitry Andric                       "SI optimize exec mask operations pre-RA", false, false)
690b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
700b57cec5SDimitry Andric INITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,
710b57cec5SDimitry Andric                     "SI optimize exec mask operations pre-RA", false, false)
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric char SIOptimizeExecMaskingPreRA::ID = 0;
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric char &llvm::SIOptimizeExecMaskingPreRAID = SIOptimizeExecMaskingPreRA::ID;
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric FunctionPass *llvm::createSIOptimizeExecMaskingPreRAPass() {
780b57cec5SDimitry Andric   return new SIOptimizeExecMaskingPreRA();
790b57cec5SDimitry Andric }
800b57cec5SDimitry Andric 
81e8d8bef9SDimitry Andric // See if there is a def between \p AndIdx and \p SelIdx that needs to live
82e8d8bef9SDimitry Andric // beyond \p AndIdx.
83e8d8bef9SDimitry Andric static bool isDefBetween(const LiveRange &LR, SlotIndex AndIdx,
84e8d8bef9SDimitry Andric                          SlotIndex SelIdx) {
85e8d8bef9SDimitry Andric   LiveQueryResult AndLRQ = LR.Query(AndIdx);
86e8d8bef9SDimitry Andric   return (!AndLRQ.isKill() && AndLRQ.valueIn() != LR.Query(SelIdx).valueOut());
87e8d8bef9SDimitry Andric }
880b57cec5SDimitry Andric 
89e8d8bef9SDimitry Andric // FIXME: Why do we bother trying to handle physical registers here?
90e8d8bef9SDimitry Andric static bool isDefBetween(const SIRegisterInfo &TRI,
91e8d8bef9SDimitry Andric                          LiveIntervals *LIS, Register Reg,
92e8d8bef9SDimitry Andric                          const MachineInstr &Sel, const MachineInstr &And) {
93*81ad6265SDimitry Andric   SlotIndex AndIdx = LIS->getInstructionIndex(And).getRegSlot();
94*81ad6265SDimitry Andric   SlotIndex SelIdx = LIS->getInstructionIndex(Sel).getRegSlot();
95e8d8bef9SDimitry Andric 
96e8d8bef9SDimitry Andric   if (Reg.isVirtual())
97e8d8bef9SDimitry Andric     return isDefBetween(LIS->getInterval(Reg), AndIdx, SelIdx);
98e8d8bef9SDimitry Andric 
99e8d8bef9SDimitry Andric   for (MCRegUnitIterator UI(Reg.asMCReg(), &TRI); UI.isValid(); ++UI) {
100e8d8bef9SDimitry Andric     if (isDefBetween(LIS->getRegUnit(*UI), AndIdx, SelIdx))
1010b57cec5SDimitry Andric       return true;
102e8d8bef9SDimitry Andric   }
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric   return false;
1050b57cec5SDimitry Andric }
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric // Optimize sequence
1080b57cec5SDimitry Andric //    %sel = V_CNDMASK_B32_e64 0, 1, %cc
1090b57cec5SDimitry Andric //    %cmp = V_CMP_NE_U32 1, %1
1100b57cec5SDimitry Andric //    $vcc = S_AND_B64 $exec, %cmp
1110b57cec5SDimitry Andric //    S_CBRANCH_VCC[N]Z
1120b57cec5SDimitry Andric // =>
1130b57cec5SDimitry Andric //    $vcc = S_ANDN2_B64 $exec, %cc
1140b57cec5SDimitry Andric //    S_CBRANCH_VCC[N]Z
1150b57cec5SDimitry Andric //
1160b57cec5SDimitry Andric // It is the negation pattern inserted by DAGCombiner::visitBRCOND() in the
1170b57cec5SDimitry Andric // rebuildSetCC(). We start with S_CBRANCH to avoid exhaustive search, but
1180b57cec5SDimitry Andric // only 3 first instructions are really needed. S_AND_B64 with exec is a
1190b57cec5SDimitry Andric // required part of the pattern since V_CNDMASK_B32 writes zeroes for inactive
1200b57cec5SDimitry Andric // lanes.
1210b57cec5SDimitry Andric //
122*81ad6265SDimitry Andric // Returns true on success.
123*81ad6265SDimitry Andric bool SIOptimizeExecMaskingPreRA::optimizeVcndVcmpPair(MachineBasicBlock &MBB) {
1240b57cec5SDimitry Andric   auto I = llvm::find_if(MBB.terminators(), [](const MachineInstr &MI) {
1250b57cec5SDimitry Andric                            unsigned Opc = MI.getOpcode();
1260b57cec5SDimitry Andric                            return Opc == AMDGPU::S_CBRANCH_VCCZ ||
1270b57cec5SDimitry Andric                                   Opc == AMDGPU::S_CBRANCH_VCCNZ; });
1280b57cec5SDimitry Andric   if (I == MBB.terminators().end())
129*81ad6265SDimitry Andric     return false;
1300b57cec5SDimitry Andric 
131e8d8bef9SDimitry Andric   auto *And =
132e8d8bef9SDimitry Andric       TRI->findReachingDef(CondReg, AMDGPU::NoSubRegister, *I, *MRI, LIS);
1330b57cec5SDimitry Andric   if (!And || And->getOpcode() != AndOpc ||
1340b57cec5SDimitry Andric       !And->getOperand(1).isReg() || !And->getOperand(2).isReg())
135*81ad6265SDimitry Andric     return false;
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   MachineOperand *AndCC = &And->getOperand(1);
1388bcb0991SDimitry Andric   Register CmpReg = AndCC->getReg();
1390b57cec5SDimitry Andric   unsigned CmpSubReg = AndCC->getSubReg();
140e8d8bef9SDimitry Andric   if (CmpReg == Register(ExecReg)) {
1410b57cec5SDimitry Andric     AndCC = &And->getOperand(2);
1420b57cec5SDimitry Andric     CmpReg = AndCC->getReg();
1430b57cec5SDimitry Andric     CmpSubReg = AndCC->getSubReg();
144e8d8bef9SDimitry Andric   } else if (And->getOperand(2).getReg() != Register(ExecReg)) {
145*81ad6265SDimitry Andric     return false;
1460b57cec5SDimitry Andric   }
1470b57cec5SDimitry Andric 
148e8d8bef9SDimitry Andric   auto *Cmp = TRI->findReachingDef(CmpReg, CmpSubReg, *And, *MRI, LIS);
1490b57cec5SDimitry Andric   if (!Cmp || !(Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e32 ||
1500b57cec5SDimitry Andric                 Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e64) ||
1510b57cec5SDimitry Andric       Cmp->getParent() != And->getParent())
152*81ad6265SDimitry Andric     return false;
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   MachineOperand *Op1 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src0);
1550b57cec5SDimitry Andric   MachineOperand *Op2 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src1);
1560b57cec5SDimitry Andric   if (Op1->isImm() && Op2->isReg())
1570b57cec5SDimitry Andric     std::swap(Op1, Op2);
1580b57cec5SDimitry Andric   if (!Op1->isReg() || !Op2->isImm() || Op2->getImm() != 1)
159*81ad6265SDimitry Andric     return false;
1600b57cec5SDimitry Andric 
1618bcb0991SDimitry Andric   Register SelReg = Op1->getReg();
162e8d8bef9SDimitry Andric   auto *Sel = TRI->findReachingDef(SelReg, Op1->getSubReg(), *Cmp, *MRI, LIS);
1630b57cec5SDimitry Andric   if (!Sel || Sel->getOpcode() != AMDGPU::V_CNDMASK_B32_e64)
164*81ad6265SDimitry Andric     return false;
1650b57cec5SDimitry Andric 
1660b57cec5SDimitry Andric   if (TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers) ||
1670b57cec5SDimitry Andric       TII->hasModifiersSet(*Sel, AMDGPU::OpName::src1_modifiers))
168*81ad6265SDimitry Andric     return false;
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   Op1 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src0);
1710b57cec5SDimitry Andric   Op2 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src1);
1720b57cec5SDimitry Andric   MachineOperand *CC = TII->getNamedOperand(*Sel, AMDGPU::OpName::src2);
1730b57cec5SDimitry Andric   if (!Op1->isImm() || !Op2->isImm() || !CC->isReg() ||
1740b57cec5SDimitry Andric       Op1->getImm() != 0 || Op2->getImm() != 1)
175*81ad6265SDimitry Andric     return false;
176e8d8bef9SDimitry Andric 
177e8d8bef9SDimitry Andric   Register CCReg = CC->getReg();
178e8d8bef9SDimitry Andric 
179e8d8bef9SDimitry Andric   // If there was a def between the select and the and, we would need to move it
180e8d8bef9SDimitry Andric   // to fold this.
181e8d8bef9SDimitry Andric   if (isDefBetween(*TRI, LIS, CCReg, *Sel, *And))
182*81ad6265SDimitry Andric     return false;
1830b57cec5SDimitry Andric 
184*81ad6265SDimitry Andric   // TODO: Guard against implicit def operands?
1858bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << "Folding sequence:\n\t" << *Sel << '\t' << *Cmp << '\t'
1868bcb0991SDimitry Andric                     << *And);
1870b57cec5SDimitry Andric 
1888bcb0991SDimitry Andric   MachineInstr *Andn2 =
1898bcb0991SDimitry Andric       BuildMI(MBB, *And, And->getDebugLoc(), TII->get(Andn2Opc),
1908bcb0991SDimitry Andric               And->getOperand(0).getReg())
1910b57cec5SDimitry Andric           .addReg(ExecReg)
1928bcb0991SDimitry Andric           .addReg(CCReg, getUndefRegState(CC->isUndef()), CC->getSubReg());
1935ffd83dbSDimitry Andric   MachineOperand &AndSCC = And->getOperand(3);
1945ffd83dbSDimitry Andric   assert(AndSCC.getReg() == AMDGPU::SCC);
1955ffd83dbSDimitry Andric   MachineOperand &Andn2SCC = Andn2->getOperand(3);
1965ffd83dbSDimitry Andric   assert(Andn2SCC.getReg() == AMDGPU::SCC);
1975ffd83dbSDimitry Andric   Andn2SCC.setIsDead(AndSCC.isDead());
198*81ad6265SDimitry Andric 
199*81ad6265SDimitry Andric   SlotIndex AndIdx = LIS->ReplaceMachineInstrInMaps(*And, *Andn2);
2000b57cec5SDimitry Andric   And->eraseFromParent();
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "=>\n\t" << *Andn2 << '\n');
2030b57cec5SDimitry Andric 
204*81ad6265SDimitry Andric   SlotIndex CmpIdx = LIS->getInstructionIndex(*Cmp);
205*81ad6265SDimitry Andric   SlotIndex SelIdx = LIS->getInstructionIndex(*Sel);
206*81ad6265SDimitry Andric 
207*81ad6265SDimitry Andric   LiveInterval *CmpLI =
208*81ad6265SDimitry Andric       CmpReg.isVirtual() ? &LIS->getInterval(CmpReg) : nullptr;
209*81ad6265SDimitry Andric   LiveInterval *SelLI =
210*81ad6265SDimitry Andric       SelReg.isVirtual() ? &LIS->getInterval(SelReg) : nullptr;
211*81ad6265SDimitry Andric 
212*81ad6265SDimitry Andric   // Update live intervals for CCReg before potentially removing CmpReg/SelReg,
213*81ad6265SDimitry Andric   // and their associated liveness information.
214*81ad6265SDimitry Andric   if (CCReg.isVirtual()) {
215*81ad6265SDimitry Andric     // Note: this ignores that SelLI might have multiple internal values
216*81ad6265SDimitry Andric     // or splits and simply extends the live range to cover all cases
217*81ad6265SDimitry Andric     // where the result of the v_cndmask_b32 was live (e.g. loops).
218*81ad6265SDimitry Andric     // This could yield worse register allocation in rare edge cases.
219*81ad6265SDimitry Andric     SlotIndex EndIdx = AndIdx.getRegSlot();
220*81ad6265SDimitry Andric     if (SelLI && SelLI->endIndex() > EndIdx && SelLI->endIndex().isBlock())
221*81ad6265SDimitry Andric       EndIdx = SelLI->endIndex();
222*81ad6265SDimitry Andric 
223*81ad6265SDimitry Andric     LiveInterval &CCLI = LIS->getInterval(CCReg);
224*81ad6265SDimitry Andric     auto CCQ = CCLI.Query(SelIdx.getRegSlot());
225*81ad6265SDimitry Andric     if (CCQ.valueIn()) {
226*81ad6265SDimitry Andric       CCLI.addSegment(LiveRange::Segment(SelIdx.getRegSlot(),
227*81ad6265SDimitry Andric                                          EndIdx, CCQ.valueIn()));
228*81ad6265SDimitry Andric     }
229*81ad6265SDimitry Andric 
230*81ad6265SDimitry Andric     if (CC->getSubReg()) {
231*81ad6265SDimitry Andric       LaneBitmask Mask = TRI->getSubRegIndexLaneMask(CC->getSubReg());
232*81ad6265SDimitry Andric       BumpPtrAllocator &Allocator = LIS->getVNInfoAllocator();
233*81ad6265SDimitry Andric       CCLI.refineSubRanges(
234*81ad6265SDimitry Andric           Allocator, Mask,
235*81ad6265SDimitry Andric           [=](LiveInterval::SubRange &SR) {
236*81ad6265SDimitry Andric             auto CCQS = SR.Query(SelIdx.getRegSlot());
237*81ad6265SDimitry Andric             if (CCQS.valueIn()) {
238*81ad6265SDimitry Andric               SR.addSegment(LiveRange::Segment(
239*81ad6265SDimitry Andric                   SelIdx.getRegSlot(), EndIdx, CCQS.valueIn()));
240*81ad6265SDimitry Andric             }
241*81ad6265SDimitry Andric           },
242*81ad6265SDimitry Andric           *LIS->getSlotIndexes(), *TRI);
243*81ad6265SDimitry Andric       CCLI.removeEmptySubRanges();
244*81ad6265SDimitry Andric 
245*81ad6265SDimitry Andric       SmallVector<LiveInterval *> SplitLIs;
246*81ad6265SDimitry Andric       LIS->splitSeparateComponents(CCLI, SplitLIs);
247*81ad6265SDimitry Andric     }
248*81ad6265SDimitry Andric   } else
249*81ad6265SDimitry Andric     LIS->removeAllRegUnitsForPhysReg(CCReg);
250*81ad6265SDimitry Andric 
2510b57cec5SDimitry Andric   // Try to remove compare. Cmp value should not used in between of cmp
2520b57cec5SDimitry Andric   // and s_and_b64 if VCC or just unused if any other register.
253*81ad6265SDimitry Andric   if ((CmpReg.isVirtual() && CmpLI && CmpLI->Query(AndIdx.getRegSlot()).isKill()) ||
254e8d8bef9SDimitry Andric       (CmpReg == Register(CondReg) &&
2550b57cec5SDimitry Andric        std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(),
2560b57cec5SDimitry Andric                     [&](const MachineInstr &MI) {
2578bcb0991SDimitry Andric                       return MI.readsRegister(CondReg, TRI);
2588bcb0991SDimitry Andric                     }))) {
2590b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Erasing: " << *Cmp << '\n');
260*81ad6265SDimitry Andric     if (CmpLI)
261*81ad6265SDimitry Andric       LIS->removeVRegDefAt(*CmpLI, CmpIdx.getRegSlot());
2620b57cec5SDimitry Andric     LIS->RemoveMachineInstrFromMaps(*Cmp);
2630b57cec5SDimitry Andric     Cmp->eraseFromParent();
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric     // Try to remove v_cndmask_b32.
266*81ad6265SDimitry Andric     if (SelLI) {
267*81ad6265SDimitry Andric       bool CanRemoveSel = SelLI->Query(CmpIdx.getRegSlot()).isKill();
268*81ad6265SDimitry Andric       if (!CanRemoveSel) {
269*81ad6265SDimitry Andric         // Try to shrink the live interval and check for dead def instead.
270*81ad6265SDimitry Andric         LIS->shrinkToUses(SelLI, nullptr);
271*81ad6265SDimitry Andric         CanRemoveSel = SelLI->Query(SelIdx.getRegSlot()).isDeadDef();
272*81ad6265SDimitry Andric       }
273*81ad6265SDimitry Andric       if (CanRemoveSel) {
2740b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Erasing: " << *Sel << '\n');
2750b57cec5SDimitry Andric 
276*81ad6265SDimitry Andric         LIS->removeVRegDefAt(*SelLI, SelIdx.getRegSlot());
2770b57cec5SDimitry Andric         LIS->RemoveMachineInstrFromMaps(*Sel);
2780b57cec5SDimitry Andric         Sel->eraseFromParent();
2790b57cec5SDimitry Andric       }
2800b57cec5SDimitry Andric     }
281*81ad6265SDimitry Andric   }
2820b57cec5SDimitry Andric 
283*81ad6265SDimitry Andric   return true;
2840b57cec5SDimitry Andric }
2850b57cec5SDimitry Andric 
286e8d8bef9SDimitry Andric // Optimize sequence
287e8d8bef9SDimitry Andric //    %dst = S_OR_SAVEEXEC %src
288e8d8bef9SDimitry Andric //    ... instructions not modifying exec ...
289e8d8bef9SDimitry Andric //    %tmp = S_AND $exec, %dst
290e8d8bef9SDimitry Andric //    $exec = S_XOR_term $exec, %tmp
291e8d8bef9SDimitry Andric // =>
292e8d8bef9SDimitry Andric //    %dst = S_OR_SAVEEXEC %src
293e8d8bef9SDimitry Andric //    ... instructions not modifying exec ...
294e8d8bef9SDimitry Andric //    $exec = S_XOR_term $exec, %dst
295e8d8bef9SDimitry Andric //
296e8d8bef9SDimitry Andric // Clean up potentially unnecessary code added for safety during
297e8d8bef9SDimitry Andric // control flow lowering.
298e8d8bef9SDimitry Andric //
299e8d8bef9SDimitry Andric // Return whether any changes were made to MBB.
300e8d8bef9SDimitry Andric bool SIOptimizeExecMaskingPreRA::optimizeElseBranch(MachineBasicBlock &MBB) {
301e8d8bef9SDimitry Andric   if (MBB.empty())
302e8d8bef9SDimitry Andric     return false;
303e8d8bef9SDimitry Andric 
304e8d8bef9SDimitry Andric   // Check this is an else block.
305e8d8bef9SDimitry Andric   auto First = MBB.begin();
306e8d8bef9SDimitry Andric   MachineInstr &SaveExecMI = *First;
307e8d8bef9SDimitry Andric   if (SaveExecMI.getOpcode() != OrSaveExecOpc)
308e8d8bef9SDimitry Andric     return false;
309e8d8bef9SDimitry Andric 
310e8d8bef9SDimitry Andric   auto I = llvm::find_if(MBB.terminators(), [this](const MachineInstr &MI) {
311e8d8bef9SDimitry Andric     return MI.getOpcode() == XorTermrOpc;
312e8d8bef9SDimitry Andric   });
313e8d8bef9SDimitry Andric   if (I == MBB.terminators().end())
314e8d8bef9SDimitry Andric     return false;
315e8d8bef9SDimitry Andric 
316e8d8bef9SDimitry Andric   MachineInstr &XorTermMI = *I;
317e8d8bef9SDimitry Andric   if (XorTermMI.getOperand(1).getReg() != Register(ExecReg))
318e8d8bef9SDimitry Andric     return false;
319e8d8bef9SDimitry Andric 
320e8d8bef9SDimitry Andric   Register SavedExecReg = SaveExecMI.getOperand(0).getReg();
321e8d8bef9SDimitry Andric   Register DstReg = XorTermMI.getOperand(2).getReg();
322e8d8bef9SDimitry Andric 
323e8d8bef9SDimitry Andric   // Find potentially unnecessary S_AND
324e8d8bef9SDimitry Andric   MachineInstr *AndExecMI = nullptr;
325e8d8bef9SDimitry Andric   I--;
326e8d8bef9SDimitry Andric   while (I != First && !AndExecMI) {
327e8d8bef9SDimitry Andric     if (I->getOpcode() == AndOpc && I->getOperand(0).getReg() == DstReg &&
328e8d8bef9SDimitry Andric         I->getOperand(1).getReg() == Register(ExecReg))
329e8d8bef9SDimitry Andric       AndExecMI = &*I;
330e8d8bef9SDimitry Andric     I--;
331e8d8bef9SDimitry Andric   }
332e8d8bef9SDimitry Andric   if (!AndExecMI)
333e8d8bef9SDimitry Andric     return false;
334e8d8bef9SDimitry Andric 
335e8d8bef9SDimitry Andric   // Check for exec modifying instructions.
336e8d8bef9SDimitry Andric   // Note: exec defs do not create live ranges beyond the
337e8d8bef9SDimitry Andric   // instruction so isDefBetween cannot be used.
338e8d8bef9SDimitry Andric   // Instead just check that the def segments are adjacent.
339e8d8bef9SDimitry Andric   SlotIndex StartIdx = LIS->getInstructionIndex(SaveExecMI);
340e8d8bef9SDimitry Andric   SlotIndex EndIdx = LIS->getInstructionIndex(*AndExecMI);
341e8d8bef9SDimitry Andric   for (MCRegUnitIterator UI(ExecReg, TRI); UI.isValid(); ++UI) {
342e8d8bef9SDimitry Andric     LiveRange &RegUnit = LIS->getRegUnit(*UI);
343e8d8bef9SDimitry Andric     if (RegUnit.find(StartIdx) != std::prev(RegUnit.find(EndIdx)))
344e8d8bef9SDimitry Andric       return false;
345e8d8bef9SDimitry Andric   }
346e8d8bef9SDimitry Andric 
347e8d8bef9SDimitry Andric   // Remove unnecessary S_AND
348e8d8bef9SDimitry Andric   LIS->removeInterval(SavedExecReg);
349e8d8bef9SDimitry Andric   LIS->removeInterval(DstReg);
350e8d8bef9SDimitry Andric 
351e8d8bef9SDimitry Andric   SaveExecMI.getOperand(0).setReg(DstReg);
352e8d8bef9SDimitry Andric 
353e8d8bef9SDimitry Andric   LIS->RemoveMachineInstrFromMaps(*AndExecMI);
354e8d8bef9SDimitry Andric   AndExecMI->eraseFromParent();
355e8d8bef9SDimitry Andric 
356e8d8bef9SDimitry Andric   LIS->createAndComputeVirtRegInterval(DstReg);
357e8d8bef9SDimitry Andric 
358e8d8bef9SDimitry Andric   return true;
359e8d8bef9SDimitry Andric }
360e8d8bef9SDimitry Andric 
3610b57cec5SDimitry Andric bool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) {
3620b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
3630b57cec5SDimitry Andric     return false;
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3660b57cec5SDimitry Andric   TRI = ST.getRegisterInfo();
3670b57cec5SDimitry Andric   TII = ST.getInstrInfo();
3680b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
369e8d8bef9SDimitry Andric   LIS = &getAnalysis<LiveIntervals>();
3700b57cec5SDimitry Andric 
371e8d8bef9SDimitry Andric   const bool Wave32 = ST.isWave32();
372e8d8bef9SDimitry Andric   AndOpc = Wave32 ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
373e8d8bef9SDimitry Andric   Andn2Opc = Wave32 ? AMDGPU::S_ANDN2_B32 : AMDGPU::S_ANDN2_B64;
374e8d8bef9SDimitry Andric   OrSaveExecOpc =
375e8d8bef9SDimitry Andric       Wave32 ? AMDGPU::S_OR_SAVEEXEC_B32 : AMDGPU::S_OR_SAVEEXEC_B64;
376e8d8bef9SDimitry Andric   XorTermrOpc = Wave32 ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
377e8d8bef9SDimitry Andric   CondReg = MCRegister::from(Wave32 ? AMDGPU::VCC_LO : AMDGPU::VCC);
378e8d8bef9SDimitry Andric   ExecReg = MCRegister::from(Wave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC);
379e8d8bef9SDimitry Andric 
380e8d8bef9SDimitry Andric   DenseSet<Register> RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI});
3810b57cec5SDimitry Andric   bool Changed = false;
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
3840b57cec5SDimitry Andric 
385e8d8bef9SDimitry Andric     if (optimizeElseBranch(MBB)) {
386e8d8bef9SDimitry Andric       RecalcRegs.insert(AMDGPU::SCC);
387e8d8bef9SDimitry Andric       Changed = true;
388e8d8bef9SDimitry Andric     }
389e8d8bef9SDimitry Andric 
390*81ad6265SDimitry Andric     if (optimizeVcndVcmpPair(MBB)) {
3910b57cec5SDimitry Andric       RecalcRegs.insert(AMDGPU::VCC_LO);
3920b57cec5SDimitry Andric       RecalcRegs.insert(AMDGPU::VCC_HI);
3930b57cec5SDimitry Andric       RecalcRegs.insert(AMDGPU::SCC);
3940b57cec5SDimitry Andric       Changed = true;
3950b57cec5SDimitry Andric     }
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric     // Try to remove unneeded instructions before s_endpgm.
3980b57cec5SDimitry Andric     if (MBB.succ_empty()) {
3990b57cec5SDimitry Andric       if (MBB.empty())
4000b57cec5SDimitry Andric         continue;
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric       // Skip this if the endpgm has any implicit uses, otherwise we would need
4030b57cec5SDimitry Andric       // to be careful to update / remove them.
4040b57cec5SDimitry Andric       // S_ENDPGM always has a single imm operand that is not used other than to
4050b57cec5SDimitry Andric       // end up in the encoding
4060b57cec5SDimitry Andric       MachineInstr &Term = MBB.back();
4070b57cec5SDimitry Andric       if (Term.getOpcode() != AMDGPU::S_ENDPGM || Term.getNumOperands() != 1)
4080b57cec5SDimitry Andric         continue;
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric       SmallVector<MachineBasicBlock*, 4> Blocks({&MBB});
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric       while (!Blocks.empty()) {
4130b57cec5SDimitry Andric         auto CurBB = Blocks.pop_back_val();
4140b57cec5SDimitry Andric         auto I = CurBB->rbegin(), E = CurBB->rend();
4150b57cec5SDimitry Andric         if (I != E) {
4160b57cec5SDimitry Andric           if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM)
4170b57cec5SDimitry Andric             ++I;
4180b57cec5SDimitry Andric           else if (I->isBranch())
4190b57cec5SDimitry Andric             continue;
4200b57cec5SDimitry Andric         }
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric         while (I != E) {
4230b57cec5SDimitry Andric           if (I->isDebugInstr()) {
4240b57cec5SDimitry Andric             I = std::next(I);
4250b57cec5SDimitry Andric             continue;
4260b57cec5SDimitry Andric           }
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric           if (I->mayStore() || I->isBarrier() || I->isCall() ||
4290b57cec5SDimitry Andric               I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef())
4300b57cec5SDimitry Andric             break;
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric           LLVM_DEBUG(dbgs()
4330b57cec5SDimitry Andric                      << "Removing no effect instruction: " << *I << '\n');
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric           for (auto &Op : I->operands()) {
4360b57cec5SDimitry Andric             if (Op.isReg())
4370b57cec5SDimitry Andric               RecalcRegs.insert(Op.getReg());
4380b57cec5SDimitry Andric           }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric           auto Next = std::next(I);
4410b57cec5SDimitry Andric           LIS->RemoveMachineInstrFromMaps(*I);
4420b57cec5SDimitry Andric           I->eraseFromParent();
4430b57cec5SDimitry Andric           I = Next;
4440b57cec5SDimitry Andric 
4450b57cec5SDimitry Andric           Changed = true;
4460b57cec5SDimitry Andric         }
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric         if (I != E)
4490b57cec5SDimitry Andric           continue;
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric         // Try to ascend predecessors.
4520b57cec5SDimitry Andric         for (auto *Pred : CurBB->predecessors()) {
4530b57cec5SDimitry Andric           if (Pred->succ_size() == 1)
4540b57cec5SDimitry Andric             Blocks.push_back(Pred);
4550b57cec5SDimitry Andric         }
4560b57cec5SDimitry Andric       }
4570b57cec5SDimitry Andric       continue;
4580b57cec5SDimitry Andric     }
4590b57cec5SDimitry Andric 
4605ffd83dbSDimitry Andric     // If the only user of a logical operation is move to exec, fold it now
461*81ad6265SDimitry Andric     // to prevent forming of saveexec. I.e.:
4625ffd83dbSDimitry Andric     //
4635ffd83dbSDimitry Andric     //    %0:sreg_64 = COPY $exec
4645ffd83dbSDimitry Andric     //    %1:sreg_64 = S_AND_B64 %0:sreg_64, %2:sreg_64
4655ffd83dbSDimitry Andric     // =>
4665ffd83dbSDimitry Andric     //    %1 = S_AND_B64 $exec, %2:sreg_64
4675ffd83dbSDimitry Andric     unsigned ScanThreshold = 10;
4685ffd83dbSDimitry Andric     for (auto I = MBB.rbegin(), E = MBB.rend(); I != E
4695ffd83dbSDimitry Andric          && ScanThreshold--; ++I) {
470e8d8bef9SDimitry Andric       // Continue scanning if this is not a full exec copy
471e8d8bef9SDimitry Andric       if (!(I->isFullCopy() && I->getOperand(1).getReg() == Register(ExecReg)))
4720b57cec5SDimitry Andric         continue;
4730b57cec5SDimitry Andric 
4745ffd83dbSDimitry Andric       Register SavedExec = I->getOperand(0).getReg();
475fe6060f1SDimitry Andric       if (SavedExec.isVirtual() && MRI->hasOneNonDBGUse(SavedExec)) {
476fe6060f1SDimitry Andric         MachineInstr *SingleExecUser = &*MRI->use_instr_nodbg_begin(SavedExec);
477fe6060f1SDimitry Andric         int Idx = SingleExecUser->findRegisterUseOperandIdx(SavedExec);
478fe6060f1SDimitry Andric         assert(Idx != -1);
479fe6060f1SDimitry Andric         if (SingleExecUser->getParent() == I->getParent() &&
480fe6060f1SDimitry Andric             !SingleExecUser->getOperand(Idx).isImplicit() &&
481fe6060f1SDimitry Andric             TII->isOperandLegal(*SingleExecUser, Idx, &I->getOperand(1))) {
4825ffd83dbSDimitry Andric           LLVM_DEBUG(dbgs() << "Redundant EXEC COPY: " << *I << '\n');
4835ffd83dbSDimitry Andric           LIS->RemoveMachineInstrFromMaps(*I);
4845ffd83dbSDimitry Andric           I->eraseFromParent();
485e8d8bef9SDimitry Andric           MRI->replaceRegWith(SavedExec, ExecReg);
4860b57cec5SDimitry Andric           LIS->removeInterval(SavedExec);
4875ffd83dbSDimitry Andric           Changed = true;
4885ffd83dbSDimitry Andric         }
489fe6060f1SDimitry Andric       }
4905ffd83dbSDimitry Andric       break;
4910b57cec5SDimitry Andric     }
4920b57cec5SDimitry Andric   }
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   if (Changed) {
4950b57cec5SDimitry Andric     for (auto Reg : RecalcRegs) {
496e8d8bef9SDimitry Andric       if (Reg.isVirtual()) {
4970b57cec5SDimitry Andric         LIS->removeInterval(Reg);
498e8d8bef9SDimitry Andric         if (!MRI->reg_empty(Reg))
4990b57cec5SDimitry Andric           LIS->createAndComputeVirtRegInterval(Reg);
5000b57cec5SDimitry Andric       } else {
5010b57cec5SDimitry Andric         LIS->removeAllRegUnitsForPhysReg(Reg);
5020b57cec5SDimitry Andric       }
5030b57cec5SDimitry Andric     }
5040b57cec5SDimitry Andric   }
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric   return Changed;
5070b57cec5SDimitry Andric }
508