blob: 9fc12ac89e12e371d9d08a91585c5faca47e3658 [file] [log] [blame]
Evan Cheng00b1a3c2012-01-07 03:02:36 +00001//===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Evan Cheng00b1a3c2012-01-07 03:02:36 +00006//
7//===----------------------------------------------------------------------===//
8//
Geoff Berryfabedba2017-10-03 16:59:13 +00009// This is an extremely simple MachineInstr-level copy propagation pass.
Evan Cheng00b1a3c2012-01-07 03:02:36 +000010//
Geoff Berrya2b90112018-02-27 16:59:10 +000011// This pass forwards the source of COPYs to the users of their destinations
12// when doing so is legal. For example:
13//
14// %reg1 = COPY %reg0
15// ...
16// ... = OP %reg1
17//
18// If
19// - %reg0 has not been clobbered by the time of the use of %reg1
20// - the register class constraints are satisfied
21// - the COPY def is the only value that reaches OP
22// then this pass replaces the above with:
23//
24// %reg1 = COPY %reg0
25// ...
26// ... = OP %reg0
27//
28// This pass also removes some redundant COPYs. For example:
29//
30// %R1 = COPY %R0
31// ... // No clobber of %R1
32// %R0 = COPY %R1 <<< Removed
33//
34// or
35//
36// %R1 = COPY %R0
37// ... // No clobber of %R0
38// %R1 = COPY %R0 <<< Removed
39//
Evan Cheng00b1a3c2012-01-07 03:02:36 +000040//===----------------------------------------------------------------------===//
41
Evan Cheng00b1a3c2012-01-07 03:02:36 +000042#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000043#include "llvm/ADT/STLExtras.h"
Evan Cheng00b1a3c2012-01-07 03:02:36 +000044#include "llvm/ADT/SetVector.h"
45#include "llvm/ADT/SmallVector.h"
46#include "llvm/ADT/Statistic.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000047#include "llvm/ADT/iterator_range.h"
48#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000049#include "llvm/CodeGen/MachineFunction.h"
50#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000051#include "llvm/CodeGen/MachineInstr.h"
52#include "llvm/CodeGen/MachineOperand.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000053#include "llvm/CodeGen/MachineRegisterInfo.h"
Geoff Berrya2b90112018-02-27 16:59:10 +000054#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000055#include "llvm/CodeGen/TargetRegisterInfo.h"
56#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000057#include "llvm/MC/MCRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include "llvm/Pass.h"
59#include "llvm/Support/Debug.h"
Geoff Berrya2b90112018-02-27 16:59:10 +000060#include "llvm/Support/DebugCounter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000061#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000062#include <cassert>
63#include <iterator>
64
Evan Cheng00b1a3c2012-01-07 03:02:36 +000065using namespace llvm;
66
Matthias Braun1527baa2017-05-25 21:26:32 +000067#define DEBUG_TYPE "machine-cp"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000068
Evan Cheng00b1a3c2012-01-07 03:02:36 +000069STATISTIC(NumDeletes, "Number of dead copies deleted");
Geoff Berrya2b90112018-02-27 16:59:10 +000070STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
71DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
72 "Controls which register COPYs are forwarded");
Evan Cheng00b1a3c2012-01-07 03:02:36 +000073
74namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +000075
Justin Bogner45b3ddc2018-09-21 00:51:04 +000076class CopyTracker {
Justin Bogner912adfb2018-10-22 19:51:31 +000077 struct CopyInfo {
78 MachineInstr *MI;
79 SmallVector<unsigned, 4> DefRegs;
80 bool Avail;
81 };
Justin Bogner45b3ddc2018-09-21 00:51:04 +000082
Justin Bogner912adfb2018-10-22 19:51:31 +000083 DenseMap<unsigned, CopyInfo> Copies;
Justin Bogner45b3ddc2018-09-21 00:51:04 +000084
85public:
86 /// Mark all of the given registers and their subregisters as unavailable for
87 /// copying.
Justin Bogner912adfb2018-10-22 19:51:31 +000088 void markRegsUnavailable(ArrayRef<unsigned> Regs,
89 const TargetRegisterInfo &TRI) {
Justin Bogner45b3ddc2018-09-21 00:51:04 +000090 for (unsigned Reg : Regs) {
91 // Source of copy is no longer available for propagation.
Justin Bogner912adfb2018-10-22 19:51:31 +000092 for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
93 auto CI = Copies.find(*RUI);
94 if (CI != Copies.end())
95 CI->second.Avail = false;
96 }
Justin Bogner45b3ddc2018-09-21 00:51:04 +000097 }
98 }
99
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000100 /// Clobber a single register, removing it from the tracker's copy maps.
101 void clobberRegister(unsigned Reg, const TargetRegisterInfo &TRI) {
Justin Bogner912adfb2018-10-22 19:51:31 +0000102 for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
103 auto I = Copies.find(*RUI);
104 if (I != Copies.end()) {
105 // When we clobber the source of a copy, we need to clobber everything
106 // it defined.
107 markRegsUnavailable(I->second.DefRegs, TRI);
108 // When we clobber the destination of a copy, we need to clobber the
109 // whole register it defined.
110 if (MachineInstr *MI = I->second.MI)
111 markRegsUnavailable({MI->getOperand(0).getReg()}, TRI);
112 // Now we can erase the copy.
113 Copies.erase(I);
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000114 }
115 }
116 }
117
118 /// Add this copy's registers into the tracker's copy maps.
Justin Bogner912adfb2018-10-22 19:51:31 +0000119 void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI) {
120 assert(MI->isCopy() && "Tracking non-copy?");
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000121
Justin Bogner912adfb2018-10-22 19:51:31 +0000122 unsigned Def = MI->getOperand(0).getReg();
123 unsigned Src = MI->getOperand(1).getReg();
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000124
125 // Remember Def is defined by the copy.
Justin Bogner912adfb2018-10-22 19:51:31 +0000126 for (MCRegUnitIterator RUI(Def, &TRI); RUI.isValid(); ++RUI)
127 Copies[*RUI] = {MI, {}, true};
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000128
129 // Remember source that's copied to Def. Once it's clobbered, then
130 // it's no longer available for copy propagation.
Justin Bogner912adfb2018-10-22 19:51:31 +0000131 for (MCRegUnitIterator RUI(Src, &TRI); RUI.isValid(); ++RUI) {
132 auto I = Copies.insert({*RUI, {nullptr, {}, false}});
133 auto &Copy = I.first->second;
134 if (!is_contained(Copy.DefRegs, Def))
135 Copy.DefRegs.push_back(Def);
136 }
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000137 }
138
Justin Bogner912adfb2018-10-22 19:51:31 +0000139 bool hasAnyCopies() {
140 return !Copies.empty();
141 }
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000142
Justin Bogner912adfb2018-10-22 19:51:31 +0000143 MachineInstr *findCopyForUnit(unsigned RegUnit, const TargetRegisterInfo &TRI,
144 bool MustBeAvailable = false) {
145 auto CI = Copies.find(RegUnit);
146 if (CI == Copies.end())
Justin Bognerdb02d3d2018-09-25 04:45:25 +0000147 return nullptr;
Justin Bogner912adfb2018-10-22 19:51:31 +0000148 if (MustBeAvailable && !CI->second.Avail)
149 return nullptr;
150 return CI->second.MI;
151 }
152
153 MachineInstr *findAvailCopy(MachineInstr &DestCopy, unsigned Reg,
154 const TargetRegisterInfo &TRI) {
155 // We check the first RegUnit here, since we'll only be interested in the
156 // copy if it copies the entire register anyway.
157 MCRegUnitIterator RUI(Reg, &TRI);
158 MachineInstr *AvailCopy =
159 findCopyForUnit(*RUI, TRI, /*MustBeAvailable=*/true);
160 if (!AvailCopy ||
161 !TRI.isSubRegisterEq(AvailCopy->getOperand(0).getReg(), Reg))
162 return nullptr;
Justin Bognerdb02d3d2018-09-25 04:45:25 +0000163
164 // Check that the available copy isn't clobbered by any regmasks between
165 // itself and the destination.
Justin Bogner912adfb2018-10-22 19:51:31 +0000166 unsigned AvailSrc = AvailCopy->getOperand(1).getReg();
167 unsigned AvailDef = AvailCopy->getOperand(0).getReg();
Justin Bognerdb02d3d2018-09-25 04:45:25 +0000168 for (const MachineInstr &MI :
Justin Bogner912adfb2018-10-22 19:51:31 +0000169 make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
Justin Bognerdb02d3d2018-09-25 04:45:25 +0000170 for (const MachineOperand &MO : MI.operands())
171 if (MO.isRegMask())
172 if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
173 return nullptr;
174
Justin Bogner912adfb2018-10-22 19:51:31 +0000175 return AvailCopy;
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000176 }
177
178 void clear() {
Justin Bogner912adfb2018-10-22 19:51:31 +0000179 Copies.clear();
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000180 }
181};
Matthias Braune39ff702016-02-26 03:18:50 +0000182
Justin Bogner927b75d2018-09-21 00:08:33 +0000183class MachineCopyPropagation : public MachineFunctionPass {
184 const TargetRegisterInfo *TRI;
185 const TargetInstrInfo *TII;
186 const MachineRegisterInfo *MRI;
Andrew Trick9e761992012-02-08 21:22:43 +0000187
Justin Bogner927b75d2018-09-21 00:08:33 +0000188public:
189 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000190
Justin Bogner927b75d2018-09-21 00:08:33 +0000191 MachineCopyPropagation() : MachineFunctionPass(ID) {
192 initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
193 }
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000194
Justin Bogner927b75d2018-09-21 00:08:33 +0000195 void getAnalysisUsage(AnalysisUsage &AU) const override {
196 AU.setPreservesCFG();
197 MachineFunctionPass::getAnalysisUsage(AU);
198 }
Matt Arsenault8f4d43a2016-06-02 00:04:26 +0000199
Justin Bogner927b75d2018-09-21 00:08:33 +0000200 bool runOnMachineFunction(MachineFunction &MF) override;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000201
Justin Bogner927b75d2018-09-21 00:08:33 +0000202 MachineFunctionProperties getRequiredProperties() const override {
203 return MachineFunctionProperties().set(
204 MachineFunctionProperties::Property::NoVRegs);
205 }
Derek Schuffad154c82016-03-28 17:05:30 +0000206
Justin Bogner927b75d2018-09-21 00:08:33 +0000207private:
208 void ClobberRegister(unsigned Reg);
209 void ReadRegister(unsigned Reg);
210 void CopyPropagateBlock(MachineBasicBlock &MBB);
211 bool eraseIfRedundant(MachineInstr &Copy, unsigned Src, unsigned Def);
212 void forwardUses(MachineInstr &MI);
213 bool isForwardableRegClassCopy(const MachineInstr &Copy,
214 const MachineInstr &UseI, unsigned UseIdx);
215 bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
Matthias Braunbd18d752016-02-20 03:56:39 +0000216
Justin Bogner927b75d2018-09-21 00:08:33 +0000217 /// Candidates for deletion.
218 SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000219
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000220 CopyTracker Tracker;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000221
Justin Bogner927b75d2018-09-21 00:08:33 +0000222 bool Changed;
223};
Eugene Zelenko900b6332017-08-29 22:32:07 +0000224
225} // end anonymous namespace
226
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000227char MachineCopyPropagation::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000228
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000229char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000230
Matthias Braun1527baa2017-05-25 21:26:32 +0000231INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000232 "Machine Copy Propagation Pass", false, false)
233
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000234void MachineCopyPropagation::ReadRegister(unsigned Reg) {
235 // If 'Reg' is defined by a copy, the copy is no longer a candidate
236 // for elimination.
Justin Bogner912adfb2018-10-22 19:51:31 +0000237 for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) {
238 if (MachineInstr *Copy = Tracker.findCopyForUnit(*RUI, *TRI)) {
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000239 LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
240 MaybeDeadCopies.remove(Copy);
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000241 }
242 }
243}
244
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000245/// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
246/// This fact may have been obscured by sub register usage or may not be true at
247/// all even though Src and Def are subregisters of the registers used in
248/// PreviousCopy. e.g.
249/// isNopCopy("ecx = COPY eax", AX, CX) == true
250/// isNopCopy("ecx = COPY eax", AH, CL) == false
251static bool isNopCopy(const MachineInstr &PreviousCopy, unsigned Src,
252 unsigned Def, const TargetRegisterInfo *TRI) {
253 unsigned PreviousSrc = PreviousCopy.getOperand(1).getReg();
254 unsigned PreviousDef = PreviousCopy.getOperand(0).getReg();
255 if (Src == PreviousSrc) {
256 assert(Def == PreviousDef);
Evan Cheng63618f92012-02-20 23:28:17 +0000257 return true;
Evan Cheng63618f92012-02-20 23:28:17 +0000258 }
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000259 if (!TRI->isSubRegister(PreviousSrc, Src))
260 return false;
261 unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
262 return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
263}
Evan Cheng63618f92012-02-20 23:28:17 +0000264
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000265/// Remove instruction \p Copy if there exists a previous copy that copies the
266/// register \p Src to the register \p Def; This may happen indirectly by
267/// copying the super registers.
268bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy, unsigned Src,
269 unsigned Def) {
270 // Avoid eliminating a copy from/to a reserved registers as we cannot predict
271 // the value (Example: The sparc zero register is writable but stays zero).
272 if (MRI->isReserved(Src) || MRI->isReserved(Def))
273 return false;
274
275 // Search for an existing copy.
Justin Bogner912adfb2018-10-22 19:51:31 +0000276 MachineInstr *PrevCopy = Tracker.findAvailCopy(Copy, Def, *TRI);
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000277 if (!PrevCopy)
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000278 return false;
279
280 // Check that the existing copy uses the correct sub registers.
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000281 if (PrevCopy->getOperand(0).isDead())
Alexander Timofeev28da0672017-11-10 12:21:10 +0000282 return false;
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000283 if (!isNopCopy(*PrevCopy, Src, Def, TRI))
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000284 return false;
285
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000286 LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000287
288 // Copy was redundantly redefining either Src or Def. Remove earlier kill
289 // flags between Copy and PrevCopy because the value will be reused now.
290 assert(Copy.isCopy());
291 unsigned CopyDef = Copy.getOperand(0).getReg();
292 assert(CopyDef == Src || CopyDef == Def);
293 for (MachineInstr &MI :
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000294 make_range(PrevCopy->getIterator(), Copy.getIterator()))
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000295 MI.clearRegisterKills(CopyDef, TRI);
296
297 Copy.eraseFromParent();
298 Changed = true;
299 ++NumDeletes;
300 return true;
Evan Cheng63618f92012-02-20 23:28:17 +0000301}
302
Geoff Berrya2b90112018-02-27 16:59:10 +0000303/// Decide whether we should forward the source of \param Copy to its use in
304/// \param UseI based on the physical register class constraints of the opcode
305/// and avoiding introducing more cross-class COPYs.
306bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
307 const MachineInstr &UseI,
308 unsigned UseIdx) {
309
310 unsigned CopySrcReg = Copy.getOperand(1).getReg();
311
312 // If the new register meets the opcode register constraints, then allow
313 // forwarding.
314 if (const TargetRegisterClass *URC =
315 UseI.getRegClassConstraint(UseIdx, TII, TRI))
316 return URC->contains(CopySrcReg);
317
318 if (!UseI.isCopy())
319 return false;
320
321 /// COPYs don't have register class constraints, so if the user instruction
322 /// is a COPY, we just try to avoid introducing additional cross-class
323 /// COPYs. For example:
324 ///
325 /// RegClassA = COPY RegClassB // Copy parameter
326 /// ...
327 /// RegClassB = COPY RegClassA // UseI parameter
328 ///
329 /// which after forwarding becomes
330 ///
331 /// RegClassA = COPY RegClassB
332 /// ...
333 /// RegClassB = COPY RegClassB
334 ///
335 /// so we have reduced the number of cross-class COPYs and potentially
336 /// introduced a nop COPY that can be removed.
337 const TargetRegisterClass *UseDstRC =
338 TRI->getMinimalPhysRegClass(UseI.getOperand(0).getReg());
339
340 const TargetRegisterClass *SuperRC = UseDstRC;
341 for (TargetRegisterClass::sc_iterator SuperRCI = UseDstRC->getSuperClasses();
342 SuperRC; SuperRC = *SuperRCI++)
343 if (SuperRC->contains(CopySrcReg))
344 return true;
345
346 return false;
347}
348
349/// Check that \p MI does not have implicit uses that overlap with it's \p Use
350/// operand (the register being replaced), since these can sometimes be
351/// implicitly tied to other operands. For example, on AMDGPU:
352///
353/// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
354///
355/// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
356/// way of knowing we need to update the latter when updating the former.
357bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
358 const MachineOperand &Use) {
359 for (const MachineOperand &MIUse : MI.uses())
360 if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
361 MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
362 return true;
363
364 return false;
365}
366
367/// Look for available copies whose destination register is used by \p MI and
368/// replace the use in \p MI with the copy's source register.
369void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
Justin Bogner912adfb2018-10-22 19:51:31 +0000370 if (!Tracker.hasAnyCopies())
Geoff Berrya2b90112018-02-27 16:59:10 +0000371 return;
372
373 // Look for non-tied explicit vreg uses that have an active COPY
374 // instruction that defines the physical register allocated to them.
375 // Replace the vreg with the source of the active COPY.
376 for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
377 ++OpIdx) {
378 MachineOperand &MOUse = MI.getOperand(OpIdx);
379 // Don't forward into undef use operands since doing so can cause problems
380 // with the machine verifier, since it doesn't treat undef reads as reads,
381 // so we can end up with a live range that ends on an undef read, leading to
382 // an error that the live range doesn't end on a read of the live range
383 // register.
384 if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
385 MOUse.isImplicit())
386 continue;
387
388 if (!MOUse.getReg())
389 continue;
390
391 // Check that the register is marked 'renamable' so we know it is safe to
392 // rename it without violating any constraints that aren't expressed in the
393 // IR (e.g. ABI or opcode requirements).
394 if (!MOUse.isRenamable())
395 continue;
396
Justin Bogner912adfb2018-10-22 19:51:31 +0000397 MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg(), *TRI);
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000398 if (!Copy)
Geoff Berrya2b90112018-02-27 16:59:10 +0000399 continue;
400
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000401 unsigned CopyDstReg = Copy->getOperand(0).getReg();
402 const MachineOperand &CopySrc = Copy->getOperand(1);
Geoff Berrya2b90112018-02-27 16:59:10 +0000403 unsigned CopySrcReg = CopySrc.getReg();
404
405 // FIXME: Don't handle partial uses of wider COPYs yet.
406 if (MOUse.getReg() != CopyDstReg) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000407 LLVM_DEBUG(
408 dbgs() << "MCP: FIXME! Not forwarding COPY to sub-register use:\n "
409 << MI);
Geoff Berrya2b90112018-02-27 16:59:10 +0000410 continue;
411 }
412
413 // Don't forward COPYs of reserved regs unless they are constant.
414 if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
415 continue;
416
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000417 if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
Geoff Berrya2b90112018-02-27 16:59:10 +0000418 continue;
419
420 if (hasImplicitOverlap(MI, MOUse))
421 continue;
422
423 if (!DebugCounter::shouldExecute(FwdCounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000424 LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n "
425 << MI);
Geoff Berrya2b90112018-02-27 16:59:10 +0000426 continue;
427 }
428
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000429 LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
430 << "\n with " << printReg(CopySrcReg, TRI)
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000431 << "\n in " << MI << " from " << *Copy);
Geoff Berrya2b90112018-02-27 16:59:10 +0000432
433 MOUse.setReg(CopySrcReg);
434 if (!CopySrc.isRenamable())
435 MOUse.setIsRenamable(false);
436
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000437 LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
Geoff Berrya2b90112018-02-27 16:59:10 +0000438
439 // Clear kill markers that may have been invalidated.
440 for (MachineInstr &KMI :
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000441 make_range(Copy->getIterator(), std::next(MI.getIterator())))
Geoff Berrya2b90112018-02-27 16:59:10 +0000442 KMI.clearRegisterKills(CopySrcReg, TRI);
443
444 ++NumCopyForwards;
445 Changed = true;
446 }
447}
448
Matthias Braunbd18d752016-02-20 03:56:39 +0000449void MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000450 LLVM_DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
James Molloyd787d3e2014-01-22 09:12:27 +0000451
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000452 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
453 MachineInstr *MI = &*I;
454 ++I;
455
Eli Friedman208fe672018-03-30 00:56:03 +0000456 // Analyze copies (which don't overlap themselves).
457 if (MI->isCopy() && !TRI->regsOverlap(MI->getOperand(0).getReg(),
458 MI->getOperand(1).getReg())) {
Geoff Berryfabedba2017-10-03 16:59:13 +0000459 unsigned Def = MI->getOperand(0).getReg();
460 unsigned Src = MI->getOperand(1).getReg();
461
462 assert(!TargetRegisterInfo::isVirtualRegister(Def) &&
463 !TargetRegisterInfo::isVirtualRegister(Src) &&
464 "MachineCopyPropagation should be run after register allocation!");
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000465
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000466 // The two copies cancel out and the source of the first copy
467 // hasn't been overridden, eliminate the second one. e.g.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000468 // %ecx = COPY %eax
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000469 // ... nothing clobbered eax.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000470 // %eax = COPY %ecx
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000471 // =>
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000472 // %ecx = COPY %eax
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000473 //
474 // or
475 //
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000476 // %ecx = COPY %eax
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +0000477 // ... nothing clobbered eax.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000478 // %ecx = COPY %eax
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000479 // =>
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000480 // %ecx = COPY %eax
Geoff Berryfabedba2017-10-03 16:59:13 +0000481 if (eraseIfRedundant(*MI, Def, Src) || eraseIfRedundant(*MI, Src, Def))
482 continue;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000483
Geoff Berrya2b90112018-02-27 16:59:10 +0000484 forwardUses(*MI);
485
486 // Src may have been changed by forwardUses()
487 Src = MI->getOperand(1).getReg();
488
Jun Bum Lim59df5e82016-02-03 15:56:27 +0000489 // If Src is defined by a previous copy, the previous copy cannot be
490 // eliminated.
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000491 ReadRegister(Src);
492 for (const MachineOperand &MO : MI->implicit_operands()) {
493 if (!MO.isReg() || !MO.readsReg())
494 continue;
495 unsigned Reg = MO.getReg();
496 if (!Reg)
497 continue;
498 ReadRegister(Reg);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000499 }
500
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000501 LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
James Molloyd787d3e2014-01-22 09:12:27 +0000502
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000503 // Copy is now a candidate for deletion.
Geoff Berryfabedba2017-10-03 16:59:13 +0000504 if (!MRI->isReserved(Def))
Matthias Braun273575d2016-02-20 03:56:36 +0000505 MaybeDeadCopies.insert(MI);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000506
Jun Bum Lim59df5e82016-02-03 15:56:27 +0000507 // If 'Def' is previously source of another copy, then this earlier copy's
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000508 // source is no longer available. e.g.
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000509 // %xmm9 = copy %xmm2
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000510 // ...
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000511 // %xmm2 = copy %xmm0
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000512 // ...
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000513 // %xmm2 = copy %xmm9
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000514 Tracker.clobberRegister(Def, *TRI);
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000515 for (const MachineOperand &MO : MI->implicit_operands()) {
516 if (!MO.isReg() || !MO.isDef())
517 continue;
Geoff Berryfabedba2017-10-03 16:59:13 +0000518 unsigned Reg = MO.getReg();
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000519 if (!Reg)
520 continue;
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000521 Tracker.clobberRegister(Reg, *TRI);
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000522 }
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000523
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000524 Tracker.trackCopy(MI, *TRI);
Alexander Timofeev9dff31c2017-10-16 16:57:37 +0000525
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000526 continue;
527 }
528
Geoff Berrya2b90112018-02-27 16:59:10 +0000529 // Clobber any earlyclobber regs first.
530 for (const MachineOperand &MO : MI->operands())
531 if (MO.isReg() && MO.isEarlyClobber()) {
532 unsigned Reg = MO.getReg();
533 // If we have a tied earlyclobber, that means it is also read by this
534 // instruction, so we need to make sure we don't remove it as dead
535 // later.
536 if (MO.isTied())
537 ReadRegister(Reg);
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000538 Tracker.clobberRegister(Reg, *TRI);
Geoff Berrya2b90112018-02-27 16:59:10 +0000539 }
540
541 forwardUses(*MI);
542
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000543 // Not a copy.
544 SmallVector<unsigned, 2> Defs;
Matthias Braun273575d2016-02-20 03:56:36 +0000545 const MachineOperand *RegMask = nullptr;
546 for (const MachineOperand &MO : MI->operands()) {
Jakob Stoklund Olesen8610a592012-02-08 22:37:35 +0000547 if (MO.isRegMask())
Matthias Braun273575d2016-02-20 03:56:36 +0000548 RegMask = &MO;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000549 if (!MO.isReg())
550 continue;
Geoff Berryfabedba2017-10-03 16:59:13 +0000551 unsigned Reg = MO.getReg();
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000552 if (!Reg)
553 continue;
554
Geoff Berryfabedba2017-10-03 16:59:13 +0000555 assert(!TargetRegisterInfo::isVirtualRegister(Reg) &&
556 "MachineCopyPropagation should be run after register allocation!");
557
Geoff Berrya2b90112018-02-27 16:59:10 +0000558 if (MO.isDef() && !MO.isEarlyClobber()) {
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000559 Defs.push_back(Reg);
560 continue;
Krzysztof Parzyszek0b492f72018-07-11 13:30:27 +0000561 } else if (!MO.isDebug() && MO.readsReg())
Matthias Braun82e7f4d2017-02-04 02:27:20 +0000562 ReadRegister(Reg);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000563 }
564
Jakob Stoklund Olesen8610a592012-02-08 22:37:35 +0000565 // The instruction has a register mask operand which means that it clobbers
Matthias Braune39ff702016-02-26 03:18:50 +0000566 // a large set of registers. Treat clobbered registers the same way as
567 // defined registers.
Matthias Braun273575d2016-02-20 03:56:36 +0000568 if (RegMask) {
Jakob Stoklund Olesen938b4d22012-02-09 00:19:08 +0000569 // Erase any MaybeDeadCopies whose destination register is clobbered.
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000570 for (SmallSetVector<MachineInstr *, 8>::iterator DI =
571 MaybeDeadCopies.begin();
572 DI != MaybeDeadCopies.end();) {
573 MachineInstr *MaybeDead = *DI;
Matthias Braun273575d2016-02-20 03:56:36 +0000574 unsigned Reg = MaybeDead->getOperand(0).getReg();
575 assert(!MRI->isReserved(Reg));
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000576
577 if (!RegMask->clobbersPhysReg(Reg)) {
578 ++DI;
Jakob Stoklund Olesen938b4d22012-02-09 00:19:08 +0000579 continue;
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000580 }
581
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000582 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
583 MaybeDead->dump());
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000584
Justin Bognerdb02d3d2018-09-25 04:45:25 +0000585 // Make sure we invalidate any entries in the copy maps before erasing
586 // the instruction.
587 Tracker.clobberRegister(Reg, *TRI);
588
Jun Bum Lim36c53fe2016-03-25 21:15:35 +0000589 // erase() will return the next valid iterator pointing to the next
590 // element after the erased one.
591 DI = MaybeDeadCopies.erase(DI);
Matthias Braun273575d2016-02-20 03:56:36 +0000592 MaybeDead->eraseFromParent();
Jakob Stoklund Olesen938b4d22012-02-09 00:19:08 +0000593 Changed = true;
594 ++NumDeletes;
595 }
Jakob Stoklund Olesen8610a592012-02-08 22:37:35 +0000596 }
597
Matthias Braune39ff702016-02-26 03:18:50 +0000598 // Any previous copy definition or reading the Defs is no longer available.
Matthias Braun9dcd65f2016-02-26 03:18:55 +0000599 for (unsigned Reg : Defs)
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000600 Tracker.clobberRegister(Reg, *TRI);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000601 }
602
603 // If MBB doesn't have successors, delete the copies whose defs are not used.
604 // If MBB does have successors, then conservative assume the defs are live-out
605 // since we don't want to trust live-in lists.
606 if (MBB.succ_empty()) {
Matthias Braun273575d2016-02-20 03:56:36 +0000607 for (MachineInstr *MaybeDead : MaybeDeadCopies) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000608 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
609 MaybeDead->dump());
Matthias Braun273575d2016-02-20 03:56:36 +0000610 assert(!MRI->isReserved(MaybeDead->getOperand(0).getReg()));
Carlos Alberto Enciso81d8ef22018-10-01 08:14:44 +0000611
612 // Update matching debug values.
613 assert(MaybeDead->isCopy());
614 MaybeDead->changeDebugValuesDefReg(MaybeDead->getOperand(1).getReg());
615
Matthias Braun273575d2016-02-20 03:56:36 +0000616 MaybeDead->eraseFromParent();
617 Changed = true;
618 ++NumDeletes;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000619 }
620 }
621
Matthias Braunbd18d752016-02-20 03:56:39 +0000622 MaybeDeadCopies.clear();
Justin Bogner45b3ddc2018-09-21 00:51:04 +0000623 Tracker.clear();
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000624}
625
626bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000627 if (skipFunction(MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000628 return false;
629
Matthias Braunbd18d752016-02-20 03:56:39 +0000630 Changed = false;
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000631
Eric Christopherfc6de422014-08-05 02:39:49 +0000632 TRI = MF.getSubtarget().getRegisterInfo();
633 TII = MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesenc30a9af2012-10-15 21:57:41 +0000634 MRI = &MF.getRegInfo();
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000635
Matthias Braun273575d2016-02-20 03:56:36 +0000636 for (MachineBasicBlock &MBB : MF)
Matthias Braunbd18d752016-02-20 03:56:39 +0000637 CopyPropagateBlock(MBB);
Evan Cheng00b1a3c2012-01-07 03:02:36 +0000638
639 return Changed;
640}