LLVM  5.0.0
AArch64RedundantCopyElimination.cpp
Go to the documentation of this file.
1 //=- AArch64RedundantCopyElimination.cpp - Remove useless copy for AArch64 -=//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 // This pass removes unnecessary zero copies in BBs that are targets of
9 // cbz/cbnz instructions. For instance, the copy instruction in the code below
10 // can be removed because the CBZW jumps to BB#2 when W0 is zero.
11 // BB#1:
12 // CBZW %W0, <BB#2>
13 // BB#2:
14 // %W0 = COPY %WZR
15 // Similarly, this pass also handles non-zero copies.
16 // BB#0:
17 // cmp x0, #1
18 // b.eq .LBB0_1
19 // .LBB0_1:
20 // orr x0, xzr, #0x1
21 //
22 // This pass should be run after register allocation.
23 //
24 // FIXME: This could also be extended to check the whole dominance subtree below
25 // the comparison if the compile time regression is acceptable.
26 //
27 //===----------------------------------------------------------------------===//
28 
29 #include "AArch64.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Support/Debug.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "aarch64-copyelim"
41 
42 STATISTIC(NumCopiesRemoved, "Number of copies removed.");
43 
44 namespace {
45 class AArch64RedundantCopyElimination : public MachineFunctionPass {
46  const MachineRegisterInfo *MRI;
47  const TargetRegisterInfo *TRI;
49 
50 public:
51  static char ID;
52  AArch64RedundantCopyElimination() : MachineFunctionPass(ID) {
55  }
56 
57  struct RegImm {
58  MCPhysReg Reg;
59  int32_t Imm;
60  RegImm(MCPhysReg Reg, int32_t Imm) : Reg(Reg), Imm(Imm) {}
61  };
62 
63  Optional<RegImm> knownRegValInBlock(MachineInstr &CondBr,
64  MachineBasicBlock *MBB,
65  MachineBasicBlock::iterator &FirstUse);
66  bool optimizeCopy(MachineBasicBlock *MBB);
67  bool runOnMachineFunction(MachineFunction &MF) override;
68  MachineFunctionProperties getRequiredProperties() const override {
71  }
72  StringRef getPassName() const override {
73  return "AArch64 Redundant Copy Elimination";
74  }
75 };
77 }
78 
79 INITIALIZE_PASS(AArch64RedundantCopyElimination, "aarch64-copyelim",
80  "AArch64 redundant copy elimination pass", false, false)
81 
82 /// Remember what registers the specified instruction modifies.
83 static void trackRegDefs(const MachineInstr &MI, BitVector &ClobberedRegs,
85  for (const MachineOperand &MO : MI.operands()) {
86  if (MO.isRegMask()) {
87  ClobberedRegs.setBitsNotInMask(MO.getRegMask());
88  continue;
89  }
90 
91  if (!MO.isReg())
92  continue;
93  unsigned Reg = MO.getReg();
94  if (!Reg)
95  continue;
96  if (!MO.isDef())
97  continue;
98 
99  for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
100  ClobberedRegs.set(*AI);
101  }
102 }
103 
104 /// It's possible to determine the value of a register based on a dominating
105 /// condition. To do so, this function checks to see if the basic block \p MBB
106 /// is the target to which a conditional branch \p CondBr jumps and whose
107 /// equality comparison is against a constant. If so, return a known physical
108 /// register and constant value pair. Otherwise, return None.
110 AArch64RedundantCopyElimination::knownRegValInBlock(
111  MachineInstr &CondBr, MachineBasicBlock *MBB,
112  MachineBasicBlock::iterator &FirstUse) {
113  unsigned Opc = CondBr.getOpcode();
114 
115  // Check if the current basic block is the target block to which the
116  // CBZ/CBNZ instruction jumps when its Wt/Xt is zero.
117  if (((Opc == AArch64::CBZW || Opc == AArch64::CBZX) &&
118  MBB == CondBr.getOperand(1).getMBB()) ||
119  ((Opc == AArch64::CBNZW || Opc == AArch64::CBNZX) &&
120  MBB != CondBr.getOperand(1).getMBB())) {
121  FirstUse = CondBr;
122  return RegImm(CondBr.getOperand(0).getReg(), 0);
123  }
124 
125  // Otherwise, must be a conditional branch.
126  if (Opc != AArch64::Bcc)
127  return None;
128 
129  // Must be an equality check (i.e., == or !=).
131  if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
132  return None;
133 
134  MachineBasicBlock *BrTarget = CondBr.getOperand(1).getMBB();
135  if ((CC == AArch64CC::EQ && BrTarget != MBB) ||
136  (CC == AArch64CC::NE && BrTarget == MBB))
137  return None;
138 
139  // Stop if we get to the beginning of PredMBB.
140  MachineBasicBlock *PredMBB = *MBB->pred_begin();
141  assert(PredMBB == CondBr.getParent() &&
142  "Conditional branch not in predecessor block!");
143  if (CondBr == PredMBB->begin())
144  return None;
145 
146  // Registers clobbered in PredMBB between CondBr instruction and current
147  // instruction being checked in loop.
149 
150  // Find compare instruction that sets NZCV used by CondBr.
152  for (MachineInstr &PredI : make_range(std::next(RIt), PredMBB->rend())) {
153 
154  // Track clobbered registers.
155  trackRegDefs(PredI, ClobberedRegs, TRI);
156 
157  bool IsCMN = false;
158  switch (PredI.getOpcode()) {
159  default:
160  break;
161 
162  // CMN is an alias for ADDS with a dead destination register.
163  case AArch64::ADDSWri:
164  case AArch64::ADDSXri:
165  IsCMN = true;
167  // CMP is an alias for SUBS with a dead destination register.
168  case AArch64::SUBSWri:
169  case AArch64::SUBSXri: {
170  MCPhysReg SrcReg = PredI.getOperand(1).getReg();
171 
172  // Must not be a symbolic immediate.
173  if (!PredI.getOperand(2).isImm())
174  return None;
175 
176  // The src register must not be modified between the cmp and conditional
177  // branch. This includes a self-clobbering compare.
178  if (ClobberedRegs[SrcReg])
179  return None;
180 
181  // We've found the Cmp that sets NZCV.
182  int32_t KnownImm = PredI.getOperand(2).getImm();
183  int32_t Shift = PredI.getOperand(3).getImm();
184  KnownImm <<= Shift;
185  if (IsCMN)
186  KnownImm = -KnownImm;
187  FirstUse = PredI;
188  return RegImm(SrcReg, KnownImm);
189  }
190  }
191 
192  // Bail if we see an instruction that defines NZCV that we don't handle.
193  if (PredI.definesRegister(AArch64::NZCV))
194  return None;
195  }
196  return None;
197 }
198 
199 bool AArch64RedundantCopyElimination::optimizeCopy(MachineBasicBlock *MBB) {
200  // Check if the current basic block has a single predecessor.
201  if (MBB->pred_size() != 1)
202  return false;
203 
204  // Check if the predecessor has two successors, implying the block ends in a
205  // conditional branch.
206  MachineBasicBlock *PredMBB = *MBB->pred_begin();
207  if (PredMBB->succ_size() != 2)
208  return false;
209 
211  if (CondBr == PredMBB->end())
212  return false;
213 
214  // Keep track of the earliest point in the PredMBB block where kill markers
215  // need to be removed if a COPY is removed.
217  // After calling knownRegValInBlock, FirstUse will either point to a CBZ/CBNZ
218  // or a compare (i.e., SUBS). In the latter case, we must take care when
219  // updating FirstUse when scanning for COPY instructions. In particular, if
220  // there's a COPY in between the compare and branch the COPY should not
221  // update FirstUse.
222  bool SeenFirstUse = false;
223  // Registers that contain a known value at the start of MBB.
224  SmallVector<RegImm, 4> KnownRegs;
225 
226  MachineBasicBlock::iterator Itr = std::next(CondBr);
227  do {
228  --Itr;
229 
230  Optional<RegImm> KnownRegImm = knownRegValInBlock(*Itr, MBB, FirstUse);
231  if (KnownRegImm == None)
232  continue;
233 
234  KnownRegs.push_back(*KnownRegImm);
235 
236  // Reset the clobber list, which is used by knownRegValInBlock.
238 
239  // Look backward in PredMBB for COPYs from the known reg to find other
240  // registers that are known to be a constant value.
241  for (auto PredI = Itr;; --PredI) {
242  if (FirstUse == PredI)
243  SeenFirstUse = true;
244 
245  if (PredI->isCopy()) {
246  MCPhysReg CopyDstReg = PredI->getOperand(0).getReg();
247  MCPhysReg CopySrcReg = PredI->getOperand(1).getReg();
248  for (auto &KnownReg : KnownRegs) {
249  if (ClobberedRegs[KnownReg.Reg])
250  continue;
251  // If we have X = COPY Y, and Y is known to be zero, then now X is
252  // known to be zero.
253  if (CopySrcReg == KnownReg.Reg && !ClobberedRegs[CopyDstReg]) {
254  KnownRegs.push_back(RegImm(CopyDstReg, KnownReg.Imm));
255  if (SeenFirstUse)
256  FirstUse = PredI;
257  break;
258  }
259  // If we have X = COPY Y, and X is known to be zero, then now Y is
260  // known to be zero.
261  if (CopyDstReg == KnownReg.Reg && !ClobberedRegs[CopySrcReg]) {
262  KnownRegs.push_back(RegImm(CopySrcReg, KnownReg.Imm));
263  if (SeenFirstUse)
264  FirstUse = PredI;
265  break;
266  }
267  }
268  }
269 
270  // Stop if we get to the beginning of PredMBB.
271  if (PredI == PredMBB->begin())
272  break;
273 
274  trackRegDefs(*PredI, ClobberedRegs, TRI);
275  // Stop if all of the known-zero regs have been clobbered.
276  if (all_of(KnownRegs, [&](RegImm KnownReg) {
277  return ClobberedRegs[KnownReg.Reg];
278  }))
279  break;
280  }
281  break;
282 
283  } while (Itr != PredMBB->begin() && Itr->isTerminator());
284 
285  // We've not found a registers with a known value, time to bail out.
286  if (KnownRegs.empty())
287  return false;
288 
289  bool Changed = false;
290  // UsedKnownRegs is the set of KnownRegs that have had uses added to MBB.
291  SmallSetVector<unsigned, 4> UsedKnownRegs;
292  MachineBasicBlock::iterator LastChange = MBB->begin();
293  // Remove redundant Copy instructions unless KnownReg is modified.
294  for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;) {
295  MachineInstr *MI = &*I;
296  ++I;
297  bool RemovedMI = false;
298  bool IsCopy = MI->isCopy();
299  bool IsMoveImm = MI->isMoveImmediate();
300  if (IsCopy || IsMoveImm) {
301  MCPhysReg DefReg = MI->getOperand(0).getReg();
302  MCPhysReg SrcReg = IsCopy ? MI->getOperand(1).getReg() : 0;
303  int64_t SrcImm = IsMoveImm ? MI->getOperand(1).getImm() : 0;
304  if (!MRI->isReserved(DefReg) &&
305  ((IsCopy && (SrcReg == AArch64::XZR || SrcReg == AArch64::WZR)) ||
306  IsMoveImm)) {
307  for (RegImm &KnownReg : KnownRegs) {
308  if (KnownReg.Reg != DefReg &&
309  !TRI->isSuperRegister(DefReg, KnownReg.Reg))
310  continue;
311 
312  // For a copy, the known value must be a zero.
313  if (IsCopy && KnownReg.Imm != 0)
314  continue;
315 
316  if (IsMoveImm) {
317  // For a move immediate, the known immediate must match the source
318  // immediate.
319  if (KnownReg.Imm != SrcImm)
320  continue;
321 
322  // Don't remove a move immediate that implicitly defines the upper
323  // bits when only the lower 32 bits are known.
324  MCPhysReg CmpReg = KnownReg.Reg;
325  if (any_of(MI->implicit_operands(), [CmpReg](MachineOperand &O) {
326  return !O.isDead() && O.isReg() && O.isDef() &&
327  O.getReg() != CmpReg;
328  }))
329  continue;
330  }
331 
332  if (IsCopy)
333  DEBUG(dbgs() << "Remove redundant Copy : " << *MI);
334  else
335  DEBUG(dbgs() << "Remove redundant Move : " << *MI);
336 
337  MI->eraseFromParent();
338  Changed = true;
339  LastChange = I;
340  NumCopiesRemoved++;
341  UsedKnownRegs.insert(KnownReg.Reg);
342  RemovedMI = true;
343  break;
344  }
345  }
346  }
347 
348  // Skip to the next instruction if we removed the COPY/MovImm.
349  if (RemovedMI)
350  continue;
351 
352  // Remove any regs the MI clobbers from the KnownConstRegs set.
353  for (unsigned RI = 0; RI < KnownRegs.size();)
354  if (MI->modifiesRegister(KnownRegs[RI].Reg, TRI)) {
355  std::swap(KnownRegs[RI], KnownRegs[KnownRegs.size() - 1]);
356  KnownRegs.pop_back();
357  // Don't increment RI since we need to now check the swapped-in
358  // KnownRegs[RI].
359  } else {
360  ++RI;
361  }
362 
363  // Continue until the KnownRegs set is empty.
364  if (KnownRegs.empty())
365  break;
366  }
367 
368  if (!Changed)
369  return false;
370 
371  // Add newly used regs to the block's live-in list if they aren't there
372  // already.
373  for (MCPhysReg KnownReg : UsedKnownRegs)
374  if (!MBB->isLiveIn(KnownReg))
375  MBB->addLiveIn(KnownReg);
376 
377  // Clear kills in the range where changes were made. This is conservative,
378  // but should be okay since kill markers are being phased out.
379  DEBUG(dbgs() << "Clearing kill flags.\n\tFirstUse: " << *FirstUse
380  << "\tLastChange: " << *LastChange);
381  for (MachineInstr &MMI : make_range(FirstUse, PredMBB->end()))
382  MMI.clearKillInfo();
383  for (MachineInstr &MMI : make_range(MBB->begin(), LastChange))
384  MMI.clearKillInfo();
385 
386  return true;
387 }
388 
389 bool AArch64RedundantCopyElimination::runOnMachineFunction(
390  MachineFunction &MF) {
391  if (skipFunction(*MF.getFunction()))
392  return false;
393  TRI = MF.getSubtarget().getRegisterInfo();
394  MRI = &MF.getRegInfo();
395 
396  // Resize the clobber register bitfield tracker. We do this once per
397  // function and then clear the bitfield each time we optimize a copy.
398  ClobberedRegs.resize(TRI->getNumRegs());
399 
400  bool Changed = false;
401  for (MachineBasicBlock &MBB : MF)
402  Changed |= optimizeCopy(&MBB);
403  return Changed;
404 }
405 
407  return new AArch64RedundantCopyElimination();
408 }
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
Definition: BitVector.h:372
const NoneType None
Definition: None.h:24
unsigned succ_size() const
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
STATISTIC(NumFunctions,"Total number of functions")
MachineBasicBlock * getMBB() const
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:818
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
void initializeAArch64RedundantCopyEliminationPass(PassRegistry &)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Reg
All possible values of the reg field in the ModR/M byte.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:142
iterator getLastNonDebugInstr()
Returns an iterator to the last non-debug instruction in the basic block, or end().
int64_t getImm() const
reverse_iterator rend()
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:279
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:139
INITIALIZE_PASS(AArch64RedundantCopyElimination,"aarch64-copyelim","AArch64 redundant copy elimination pass", false, false) static void trackRegDefs(const MachineInstr &MI
Remember what registers the specified instruction modifies.
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
unsigned const MachineRegisterInfo * MRI
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:284
bool isCopy() const
Definition: MachineInstr.h:823
MCRegAliasIterator enumerates all registers aliasing Reg.
BitVector & reset()
Definition: BitVector.h:439
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:825
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
FunctionPass * createAArch64RedundantCopyEliminationPass()
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
BitVector & ClobberedRegs
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:298
#define E
Definition: LargeTest.cpp:27
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
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:923
iterator_range< mop_iterator > implicit_operands()
Definition: MachineInstr.h:320
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:59
reverse_self_iterator getReverseIterator()
Definition: ilist_node.h:85
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
#define I(x, y, z)
Definition: MD5.cpp:58
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
aarch64 promote const
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:235
#define DEBUG(X)
Definition: Debug.h:118
IRTranslator LLVM IR MI
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
bool isMoveImmediate(QueryType Type=IgnoreBundle) const
Return true if this instruction is a move immediate (including conditional moves) instruction...
Definition: MachineInstr.h:499
unsigned pred_size() const
bool modifiesRegister(unsigned Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr modifies (fully define or partially define) the specified register...
Definition: MachineInstr.h:930
Properties which a MachineFunction may have at a given point in time.