LLVM  9.0.0svn
SIOptimizeExecMaskingPreRA.cpp
Go to the documentation of this file.
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"
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 public:
37  static char ID;
38 
39 public:
40  SIOptimizeExecMaskingPreRA() : MachineFunctionPass(ID) {
42  }
43 
44  bool runOnMachineFunction(MachineFunction &MF) override;
45 
46  StringRef getPassName() const override {
47  return "SI optimize exec mask operations pre-RA";
48  }
49 
50  void getAnalysisUsage(AnalysisUsage &AU) const override {
52  AU.setPreservesAll();
54  }
55 };
56 
57 } // End anonymous namespace.
58 
59 INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,
60  "SI optimize exec mask operations pre-RA", false, false)
62 INITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,
63  "SI optimize exec mask operations pre-RA", false, false)
64 
65 char SIOptimizeExecMaskingPreRA::ID = 0;
66 
67 char &llvm::SIOptimizeExecMaskingPreRAID = SIOptimizeExecMaskingPreRA::ID;
68 
70  return new SIOptimizeExecMaskingPreRA();
71 }
72 
73 static bool isEndCF(const MachineInstr& MI, const SIRegisterInfo* TRI) {
74  return MI.getOpcode() == AMDGPU::S_OR_B64 &&
75  MI.modifiesRegister(AMDGPU::EXEC, TRI);
76 }
77 
78 static bool isFullExecCopy(const MachineInstr& MI) {
79  return MI.isFullCopy() && MI.getOperand(1).getReg() == AMDGPU::EXEC;
80 }
81 
82 static unsigned getOrNonExecReg(const MachineInstr &MI,
83  const SIInstrInfo &TII) {
84  auto Op = TII.getNamedOperand(MI, AMDGPU::OpName::src1);
85  if (Op->isReg() && Op->getReg() != AMDGPU::EXEC)
86  return Op->getReg();
87  Op = TII.getNamedOperand(MI, AMDGPU::OpName::src0);
88  if (Op->isReg() && Op->getReg() != AMDGPU::EXEC)
89  return Op->getReg();
90  return AMDGPU::NoRegister;
91 }
92 
94  const SIInstrInfo &TII,
95  const MachineRegisterInfo &MRI) {
96  auto SavedExec = getOrNonExecReg(MI, TII);
97  if (SavedExec == AMDGPU::NoRegister)
98  return nullptr;
99  auto SaveExecInst = MRI.getUniqueVRegDef(SavedExec);
100  if (!SaveExecInst || !isFullExecCopy(*SaveExecInst))
101  return nullptr;
102  return SaveExecInst;
103 }
104 
105 // Optimize sequence
106 // %sel = V_CNDMASK_B32_e64 0, 1, %cc
107 // %cmp = V_CMP_NE_U32 1, %1
108 // $vcc = S_AND_B64 $exec, %cmp
109 // S_CBRANCH_VCC[N]Z
110 // =>
111 // $vcc = S_ANDN2_B64 $exec, %cc
112 // S_CBRANCH_VCC[N]Z
113 //
114 // It is the negation pattern inserted by DAGCombiner::visitBRCOND() in the
115 // rebuildSetCC(). We start with S_CBRANCH to avoid exhaustive search, but
116 // only 3 first instructions are really needed. S_AND_B64 with exec is a
117 // required part of the pattern since V_CNDMASK_B32 writes zeroes for inactive
118 // lanes.
119 //
120 // Returns %cc register on success.
122  const GCNSubtarget &ST,
124  LiveIntervals *LIS) {
125  const SIRegisterInfo *TRI = ST.getRegisterInfo();
126  const SIInstrInfo *TII = ST.getInstrInfo();
127  const unsigned AndOpc = AMDGPU::S_AND_B64;
128  const unsigned Andn2Opc = AMDGPU::S_ANDN2_B64;
129  const unsigned CondReg = AMDGPU::VCC;
130  const unsigned ExecReg = AMDGPU::EXEC;
131 
132  auto I = llvm::find_if(MBB.terminators(), [](const MachineInstr &MI) {
133  unsigned Opc = MI.getOpcode();
134  return Opc == AMDGPU::S_CBRANCH_VCCZ ||
135  Opc == AMDGPU::S_CBRANCH_VCCNZ; });
136  if (I == MBB.terminators().end())
137  return AMDGPU::NoRegister;
138 
139  auto *And = TRI->findReachingDef(CondReg, AMDGPU::NoSubRegister,
140  *I, MRI, LIS);
141  if (!And || And->getOpcode() != AndOpc ||
142  !And->getOperand(1).isReg() || !And->getOperand(2).isReg())
143  return AMDGPU::NoRegister;
144 
145  MachineOperand *AndCC = &And->getOperand(1);
146  unsigned CmpReg = AndCC->getReg();
147  unsigned CmpSubReg = AndCC->getSubReg();
148  if (CmpReg == ExecReg) {
149  AndCC = &And->getOperand(2);
150  CmpReg = AndCC->getReg();
151  CmpSubReg = AndCC->getSubReg();
152  } else if (And->getOperand(2).getReg() != ExecReg) {
153  return AMDGPU::NoRegister;
154  }
155 
156  auto *Cmp = TRI->findReachingDef(CmpReg, CmpSubReg, *And, MRI, LIS);
157  if (!Cmp || !(Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e32 ||
158  Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e64) ||
159  Cmp->getParent() != And->getParent())
160  return AMDGPU::NoRegister;
161 
162  MachineOperand *Op1 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src0);
163  MachineOperand *Op2 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src1);
164  if (Op1->isImm() && Op2->isReg())
165  std::swap(Op1, Op2);
166  if (!Op1->isReg() || !Op2->isImm() || Op2->getImm() != 1)
167  return AMDGPU::NoRegister;
168 
169  unsigned SelReg = Op1->getReg();
170  auto *Sel = TRI->findReachingDef(SelReg, Op1->getSubReg(), *Cmp, MRI, LIS);
171  if (!Sel || Sel->getOpcode() != AMDGPU::V_CNDMASK_B32_e64)
172  return AMDGPU::NoRegister;
173 
174  if (TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers) ||
175  TII->hasModifiersSet(*Sel, AMDGPU::OpName::src0_modifiers))
176  return AMDGPU::NoRegister;
177 
178  Op1 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src0);
179  Op2 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src1);
180  MachineOperand *CC = TII->getNamedOperand(*Sel, AMDGPU::OpName::src2);
181  if (!Op1->isImm() || !Op2->isImm() || !CC->isReg() ||
182  Op1->getImm() != 0 || Op2->getImm() != 1)
183  return AMDGPU::NoRegister;
184 
185  LLVM_DEBUG(dbgs() << "Folding sequence:\n\t" << *Sel << '\t'
186  << *Cmp << '\t' << *And);
187 
188  unsigned CCReg = CC->getReg();
189  LIS->RemoveMachineInstrFromMaps(*And);
190  MachineInstr *Andn2 = BuildMI(MBB, *And, And->getDebugLoc(),
191  TII->get(Andn2Opc), And->getOperand(0).getReg())
192  .addReg(ExecReg)
193  .addReg(CCReg, CC->getSubReg());
194  And->eraseFromParent();
195  LIS->InsertMachineInstrInMaps(*Andn2);
196 
197  LLVM_DEBUG(dbgs() << "=>\n\t" << *Andn2 << '\n');
198 
199  // Try to remove compare. Cmp value should not used in between of cmp
200  // and s_and_b64 if VCC or just unused if any other register.
202  MRI.use_nodbg_empty(CmpReg)) ||
203  (CmpReg == CondReg &&
204  std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(),
205  [&](const MachineInstr &MI) {
206  return MI.readsRegister(CondReg, TRI); }))) {
207  LLVM_DEBUG(dbgs() << "Erasing: " << *Cmp << '\n');
208 
209  LIS->RemoveMachineInstrFromMaps(*Cmp);
210  Cmp->eraseFromParent();
211 
212  // Try to remove v_cndmask_b32.
214  MRI.use_nodbg_empty(SelReg)) {
215  LLVM_DEBUG(dbgs() << "Erasing: " << *Sel << '\n');
216 
217  LIS->RemoveMachineInstrFromMaps(*Sel);
218  Sel->eraseFromParent();
219  }
220  }
221 
222  return CCReg;
223 }
224 
225 bool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) {
226  if (skipFunction(MF.getFunction()))
227  return false;
228 
229  const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
230  const SIRegisterInfo *TRI = ST.getRegisterInfo();
231  const SIInstrInfo *TII = ST.getInstrInfo();
233  LiveIntervals *LIS = &getAnalysis<LiveIntervals>();
234  DenseSet<unsigned> RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI});
235  bool Changed = false;
236 
237  for (MachineBasicBlock &MBB : MF) {
238 
239  if (unsigned Reg = optimizeVcndVcmpPair(MBB, ST, MRI, LIS)) {
240  RecalcRegs.insert(Reg);
241  RecalcRegs.insert(AMDGPU::VCC_LO);
242  RecalcRegs.insert(AMDGPU::VCC_HI);
243  RecalcRegs.insert(AMDGPU::SCC);
244  Changed = true;
245  }
246 
247  // Try to remove unneeded instructions before s_endpgm.
248  if (MBB.succ_empty()) {
249  if (MBB.empty())
250  continue;
251 
252  // Skip this if the endpgm has any implicit uses, otherwise we would need
253  // to be careful to update / remove them.
254  // S_ENDPGM always has a single imm operand that is not used other than to
255  // end up in the encoding
256  MachineInstr &Term = MBB.back();
257  if (Term.getOpcode() != AMDGPU::S_ENDPGM || Term.getNumOperands() != 1)
258  continue;
259 
260  SmallVector<MachineBasicBlock*, 4> Blocks({&MBB});
261 
262  while (!Blocks.empty()) {
263  auto CurBB = Blocks.pop_back_val();
264  auto I = CurBB->rbegin(), E = CurBB->rend();
265  if (I != E) {
266  if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM)
267  ++I;
268  else if (I->isBranch())
269  continue;
270  }
271 
272  while (I != E) {
273  if (I->isDebugInstr()) {
274  I = std::next(I);
275  continue;
276  }
277 
278  if (I->mayStore() || I->isBarrier() || I->isCall() ||
279  I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef())
280  break;
281 
282  LLVM_DEBUG(dbgs()
283  << "Removing no effect instruction: " << *I << '\n');
284 
285  for (auto &Op : I->operands()) {
286  if (Op.isReg())
287  RecalcRegs.insert(Op.getReg());
288  }
289 
290  auto Next = std::next(I);
292  I->eraseFromParent();
293  I = Next;
294 
295  Changed = true;
296  }
297 
298  if (I != E)
299  continue;
300 
301  // Try to ascend predecessors.
302  for (auto *Pred : CurBB->predecessors()) {
303  if (Pred->succ_size() == 1)
304  Blocks.push_back(Pred);
305  }
306  }
307  continue;
308  }
309 
310  // Try to collapse adjacent endifs.
311  auto Lead = MBB.begin(), E = MBB.end();
312  if (MBB.succ_size() != 1 || Lead == E || !isEndCF(*Lead, TRI))
313  continue;
314 
315  const MachineBasicBlock* Succ = *MBB.succ_begin();
316  if (!MBB.isLayoutSuccessor(Succ))
317  continue;
318 
319  auto I = std::next(Lead);
320 
321  for ( ; I != E; ++I)
322  if (!TII->isSALU(*I) || I->readsRegister(AMDGPU::EXEC, TRI))
323  break;
324 
325  if (I != E)
326  continue;
327 
328  const auto NextLead = Succ->begin();
329  if (NextLead == Succ->end() || !isEndCF(*NextLead, TRI) ||
330  !getOrExecSource(*NextLead, *TII, MRI))
331  continue;
332 
333  LLVM_DEBUG(dbgs() << "Redundant EXEC = S_OR_B64 found: " << *Lead << '\n');
334 
335  auto SaveExec = getOrExecSource(*Lead, *TII, MRI);
336  unsigned SaveExecReg = getOrNonExecReg(*Lead, *TII);
337  for (auto &Op : Lead->operands()) {
338  if (Op.isReg())
339  RecalcRegs.insert(Op.getReg());
340  }
341 
342  LIS->RemoveMachineInstrFromMaps(*Lead);
343  Lead->eraseFromParent();
344  if (SaveExecReg) {
345  LIS->removeInterval(SaveExecReg);
346  LIS->createAndComputeVirtRegInterval(SaveExecReg);
347  }
348 
349  Changed = true;
350 
351  // If the only use of saved exec in the removed instruction is S_AND_B64
352  // fold the copy now.
353  if (!SaveExec || !SaveExec->isFullCopy())
354  continue;
355 
356  unsigned SavedExec = SaveExec->getOperand(0).getReg();
357  bool SafeToReplace = true;
358  for (auto& U : MRI.use_nodbg_instructions(SavedExec)) {
359  if (U.getParent() != SaveExec->getParent()) {
360  SafeToReplace = false;
361  break;
362  }
363 
364  LLVM_DEBUG(dbgs() << "Redundant EXEC COPY: " << *SaveExec << '\n');
365  }
366 
367  if (SafeToReplace) {
368  LIS->RemoveMachineInstrFromMaps(*SaveExec);
369  SaveExec->eraseFromParent();
370  MRI.replaceRegWith(SavedExec, AMDGPU::EXEC);
371  LIS->removeInterval(SavedExec);
372  }
373  }
374 
375  if (Changed) {
376  for (auto Reg : RecalcRegs) {
378  LIS->removeInterval(Reg);
379  if (!MRI.reg_empty(Reg))
381  } else {
383  }
384  }
385  }
386 
387  return Changed;
388 }
bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
AMDGPU specific subclass of TargetSubtarget.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool hasModifiersSet(const MachineInstr &MI, unsigned OpName) const
unsigned getReg() const
getReg - Returns the register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
unsigned Reg
unsigned getSubReg() const
const SIInstrInfo * getInstrInfo() const override
unsigned const TargetRegisterInfo * TRI
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
static bool isFullExecCopy(const MachineInstr &MI)
SI optimize exec mask operations pre RA
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
MachineInstr * findReachingDef(unsigned Reg, unsigned SubReg, MachineInstr &Use, MachineRegisterInfo &MRI, LiveIntervals *LIS) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:411
void eraseFromParent()
Unlink &#39;this&#39; from the containing basic block and delete it.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1199
iterator_range< iterator > terminators()
char & SIOptimizeExecMaskingPreRAID
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:408
INITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE, "SI optimize exec mask operations pre-RA", false, false) INITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA
bool isFullCopy() const
LLVM_READONLY MachineOperand * getNamedOperand(MachineInstr &MI, unsigned OperandName) const
Returns the operand named Op.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
void initializeSIOptimizeExecMaskingPreRAPass(PassRegistry &)
static MachineInstr * getOrExecSource(const MachineInstr &MI, const SIInstrInfo &TII, const MachineRegisterInfo &MRI)
SI optimize exec mask operations
static unsigned getOrNonExecReg(const MachineInstr &MI, const SIInstrInfo &TII)
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionPass * createSIOptimizeExecMaskingPreRAPass()
unsigned const MachineRegisterInfo * MRI
void removeAllRegUnitsForPhysReg(unsigned Reg)
Remove associated live ranges for the register units associated with Reg.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void removeInterval(unsigned Reg)
Interval removal.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:187
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
self_iterator getIterator()
Definition: ilist_node.h:81
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1213
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
static unsigned optimizeVcndVcmpPair(MachineBasicBlock &MBB, const GCNSubtarget &ST, MachineRegisterInfo &MRI, LiveIntervals *LIS)
static bool isSALU(const MachineInstr &MI)
Definition: SIInstrInfo.h:314
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
static bool isEndCF(const MachineInstr &MI, const SIRegisterInfo *TRI)
int64_t getImm() const
MachineInstr * getUniqueVRegDef(unsigned Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
void setPreservesAll()
Set by analyses that do not transform their input at all.
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Provides AMDGPU specific target descriptions.
Representation of each machine instruction.
Definition: MachineInstr.h:63
Interface definition for SIInstrInfo.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
#define I(x, y, z)
Definition: MD5.cpp:58
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
#define DEBUG_TYPE
bool reg_empty(unsigned RegNo) const
reg_empty - Return true if there are no instructions using or defining the specified register (it may...
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(unsigned Reg) const
LiveInterval & createAndComputeVirtRegInterval(unsigned Reg)
const SIRegisterInfo * getRegisterInfo() const override