1 //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is an extremely simple MachineInstr-level copy propagation pass.
12 // This pass forwards the source of COPYs to the users of their destinations
13 // when doing so is legal. For example:
20 // - %reg0 has not been clobbered by the time of the use of %reg1
21 // - the register class constraints are satisfied
22 // - the COPY def is the only value that reaches OP
23 // then this pass replaces the above with:
29 // This pass also removes some redundant COPYs. For example:
32 // ... // No clobber of %R1
33 // %R0 = COPY %R1 <<< Removed
38 // ... // No clobber of %R0
39 // %R1 = COPY %R0 <<< Removed
41 //===----------------------------------------------------------------------===//
43 #include "llvm/ADT/DenseMap.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/SetVector.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/ADT/iterator_range.h"
49 #include "llvm/CodeGen/MachineBasicBlock.h"
50 #include "llvm/CodeGen/MachineFunction.h"
51 #include "llvm/CodeGen/MachineFunctionPass.h"
52 #include "llvm/CodeGen/MachineInstr.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/TargetInstrInfo.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/TargetSubtargetInfo.h"
58 #include "llvm/MC/MCRegisterInfo.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/DebugCounter.h"
62 #include "llvm/Support/raw_ostream.h"
68 #define DEBUG_TYPE "machine-cp"
70 STATISTIC(NumDeletes
, "Number of dead copies deleted");
71 STATISTIC(NumCopyForwards
, "Number of copy uses forwarded");
72 DEBUG_COUNTER(FwdCounter
, "machine-cp-fwd",
73 "Controls which register COPYs are forwarded");
78 using RegList
= SmallVector
<unsigned, 4>;
79 using SourceMap
= DenseMap
<unsigned, RegList
>;
80 using Reg2MIMap
= DenseMap
<unsigned, MachineInstr
*>;
82 /// Def -> available copies map.
83 Reg2MIMap AvailCopyMap
;
85 /// Def -> copies map.
92 /// Mark all of the given registers and their subregisters as unavailable for
94 void markRegsUnavailable(const RegList
&Regs
, const TargetRegisterInfo
&TRI
) {
95 for (unsigned Reg
: Regs
) {
96 // Source of copy is no longer available for propagation.
97 for (MCSubRegIterator
SR(Reg
, &TRI
, true); SR
.isValid(); ++SR
)
98 AvailCopyMap
.erase(*SR
);
102 /// Clobber a single register, removing it from the tracker's copy maps.
103 void clobberRegister(unsigned Reg
, const TargetRegisterInfo
&TRI
) {
104 for (MCRegAliasIterator
AI(Reg
, &TRI
, true); AI
.isValid(); ++AI
) {
106 AvailCopyMap
.erase(*AI
);
108 SourceMap::iterator SI
= SrcMap
.find(*AI
);
109 if (SI
!= SrcMap
.end()) {
110 markRegsUnavailable(SI
->second
, TRI
);
116 /// Add this copy's registers into the tracker's copy maps.
117 void trackCopy(MachineInstr
*Copy
, const TargetRegisterInfo
&TRI
) {
118 assert(Copy
->isCopy() && "Tracking non-copy?");
120 unsigned Def
= Copy
->getOperand(0).getReg();
121 unsigned Src
= Copy
->getOperand(1).getReg();
123 // Remember Def is defined by the copy.
124 for (MCSubRegIterator
SR(Def
, &TRI
, /*IncludeSelf=*/true); SR
.isValid();
127 AvailCopyMap
[*SR
] = Copy
;
130 // Remember source that's copied to Def. Once it's clobbered, then
131 // it's no longer available for copy propagation.
132 RegList
&DestList
= SrcMap
[Src
];
133 if (!is_contained(DestList
, Def
))
134 DestList
.push_back(Def
);
137 bool hasAvailableCopies() { return !AvailCopyMap
.empty(); }
139 MachineInstr
*findAvailCopy(MachineInstr
&DestCopy
, unsigned Reg
) {
140 auto CI
= AvailCopyMap
.find(Reg
);
141 if (CI
== AvailCopyMap
.end())
143 MachineInstr
&AvailCopy
= *CI
->second
;
145 // Check that the available copy isn't clobbered by any regmasks between
146 // itself and the destination.
147 unsigned AvailSrc
= AvailCopy
.getOperand(1).getReg();
148 unsigned AvailDef
= AvailCopy
.getOperand(0).getReg();
149 for (const MachineInstr
&MI
:
150 make_range(AvailCopy
.getIterator(), DestCopy
.getIterator()))
151 for (const MachineOperand
&MO
: MI
.operands())
153 if (MO
.clobbersPhysReg(AvailSrc
) || MO
.clobbersPhysReg(AvailDef
))
159 MachineInstr
*findCopy(unsigned Reg
) {
160 auto CI
= CopyMap
.find(Reg
);
161 if (CI
!= CopyMap
.end())
167 AvailCopyMap
.clear();
173 class MachineCopyPropagation
: public MachineFunctionPass
{
174 const TargetRegisterInfo
*TRI
;
175 const TargetInstrInfo
*TII
;
176 const MachineRegisterInfo
*MRI
;
179 static char ID
; // Pass identification, replacement for typeid
181 MachineCopyPropagation() : MachineFunctionPass(ID
) {
182 initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
185 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
186 AU
.setPreservesCFG();
187 MachineFunctionPass::getAnalysisUsage(AU
);
190 bool runOnMachineFunction(MachineFunction
&MF
) override
;
192 MachineFunctionProperties
getRequiredProperties() const override
{
193 return MachineFunctionProperties().set(
194 MachineFunctionProperties::Property::NoVRegs
);
198 void ClobberRegister(unsigned Reg
);
199 void ReadRegister(unsigned Reg
);
200 void CopyPropagateBlock(MachineBasicBlock
&MBB
);
201 bool eraseIfRedundant(MachineInstr
&Copy
, unsigned Src
, unsigned Def
);
202 void forwardUses(MachineInstr
&MI
);
203 bool isForwardableRegClassCopy(const MachineInstr
&Copy
,
204 const MachineInstr
&UseI
, unsigned UseIdx
);
205 bool hasImplicitOverlap(const MachineInstr
&MI
, const MachineOperand
&Use
);
207 /// Candidates for deletion.
208 SmallSetVector
<MachineInstr
*, 8> MaybeDeadCopies
;
215 } // end anonymous namespace
217 char MachineCopyPropagation::ID
= 0;
219 char &llvm::MachineCopyPropagationID
= MachineCopyPropagation::ID
;
221 INITIALIZE_PASS(MachineCopyPropagation
, DEBUG_TYPE
,
222 "Machine Copy Propagation Pass", false, false)
224 void MachineCopyPropagation::ReadRegister(unsigned Reg
) {
225 // If 'Reg' is defined by a copy, the copy is no longer a candidate
227 for (MCRegAliasIterator
AI(Reg
, TRI
, true); AI
.isValid(); ++AI
) {
228 if (MachineInstr
*Copy
= Tracker
.findCopy(*AI
)) {
229 LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy
->dump());
230 MaybeDeadCopies
.remove(Copy
);
235 /// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
236 /// This fact may have been obscured by sub register usage or may not be true at
237 /// all even though Src and Def are subregisters of the registers used in
238 /// PreviousCopy. e.g.
239 /// isNopCopy("ecx = COPY eax", AX, CX) == true
240 /// isNopCopy("ecx = COPY eax", AH, CL) == false
241 static bool isNopCopy(const MachineInstr
&PreviousCopy
, unsigned Src
,
242 unsigned Def
, const TargetRegisterInfo
*TRI
) {
243 unsigned PreviousSrc
= PreviousCopy
.getOperand(1).getReg();
244 unsigned PreviousDef
= PreviousCopy
.getOperand(0).getReg();
245 if (Src
== PreviousSrc
) {
246 assert(Def
== PreviousDef
);
249 if (!TRI
->isSubRegister(PreviousSrc
, Src
))
251 unsigned SubIdx
= TRI
->getSubRegIndex(PreviousSrc
, Src
);
252 return SubIdx
== TRI
->getSubRegIndex(PreviousDef
, Def
);
255 /// Remove instruction \p Copy if there exists a previous copy that copies the
256 /// register \p Src to the register \p Def; This may happen indirectly by
257 /// copying the super registers.
258 bool MachineCopyPropagation::eraseIfRedundant(MachineInstr
&Copy
, unsigned Src
,
260 // Avoid eliminating a copy from/to a reserved registers as we cannot predict
261 // the value (Example: The sparc zero register is writable but stays zero).
262 if (MRI
->isReserved(Src
) || MRI
->isReserved(Def
))
265 // Search for an existing copy.
266 MachineInstr
*PrevCopy
= Tracker
.findAvailCopy(Copy
, Def
);
270 // Check that the existing copy uses the correct sub registers.
271 if (PrevCopy
->getOperand(0).isDead())
273 if (!isNopCopy(*PrevCopy
, Src
, Def
, TRI
))
276 LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy
.dump());
278 // Copy was redundantly redefining either Src or Def. Remove earlier kill
279 // flags between Copy and PrevCopy because the value will be reused now.
280 assert(Copy
.isCopy());
281 unsigned CopyDef
= Copy
.getOperand(0).getReg();
282 assert(CopyDef
== Src
|| CopyDef
== Def
);
283 for (MachineInstr
&MI
:
284 make_range(PrevCopy
->getIterator(), Copy
.getIterator()))
285 MI
.clearRegisterKills(CopyDef
, TRI
);
287 Copy
.eraseFromParent();
293 /// Decide whether we should forward the source of \param Copy to its use in
294 /// \param UseI based on the physical register class constraints of the opcode
295 /// and avoiding introducing more cross-class COPYs.
296 bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr
&Copy
,
297 const MachineInstr
&UseI
,
300 unsigned CopySrcReg
= Copy
.getOperand(1).getReg();
302 // If the new register meets the opcode register constraints, then allow
304 if (const TargetRegisterClass
*URC
=
305 UseI
.getRegClassConstraint(UseIdx
, TII
, TRI
))
306 return URC
->contains(CopySrcReg
);
311 /// COPYs don't have register class constraints, so if the user instruction
312 /// is a COPY, we just try to avoid introducing additional cross-class
313 /// COPYs. For example:
315 /// RegClassA = COPY RegClassB // Copy parameter
317 /// RegClassB = COPY RegClassA // UseI parameter
319 /// which after forwarding becomes
321 /// RegClassA = COPY RegClassB
323 /// RegClassB = COPY RegClassB
325 /// so we have reduced the number of cross-class COPYs and potentially
326 /// introduced a nop COPY that can be removed.
327 const TargetRegisterClass
*UseDstRC
=
328 TRI
->getMinimalPhysRegClass(UseI
.getOperand(0).getReg());
330 const TargetRegisterClass
*SuperRC
= UseDstRC
;
331 for (TargetRegisterClass::sc_iterator SuperRCI
= UseDstRC
->getSuperClasses();
332 SuperRC
; SuperRC
= *SuperRCI
++)
333 if (SuperRC
->contains(CopySrcReg
))
339 /// Check that \p MI does not have implicit uses that overlap with it's \p Use
340 /// operand (the register being replaced), since these can sometimes be
341 /// implicitly tied to other operands. For example, on AMDGPU:
343 /// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
345 /// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
346 /// way of knowing we need to update the latter when updating the former.
347 bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr
&MI
,
348 const MachineOperand
&Use
) {
349 for (const MachineOperand
&MIUse
: MI
.uses())
350 if (&MIUse
!= &Use
&& MIUse
.isReg() && MIUse
.isImplicit() &&
351 MIUse
.isUse() && TRI
->regsOverlap(Use
.getReg(), MIUse
.getReg()))
357 /// Look for available copies whose destination register is used by \p MI and
358 /// replace the use in \p MI with the copy's source register.
359 void MachineCopyPropagation::forwardUses(MachineInstr
&MI
) {
360 if (!Tracker
.hasAvailableCopies())
363 // Look for non-tied explicit vreg uses that have an active COPY
364 // instruction that defines the physical register allocated to them.
365 // Replace the vreg with the source of the active COPY.
366 for (unsigned OpIdx
= 0, OpEnd
= MI
.getNumOperands(); OpIdx
< OpEnd
;
368 MachineOperand
&MOUse
= MI
.getOperand(OpIdx
);
369 // Don't forward into undef use operands since doing so can cause problems
370 // with the machine verifier, since it doesn't treat undef reads as reads,
371 // so we can end up with a live range that ends on an undef read, leading to
372 // an error that the live range doesn't end on a read of the live range
374 if (!MOUse
.isReg() || MOUse
.isTied() || MOUse
.isUndef() || MOUse
.isDef() ||
381 // Check that the register is marked 'renamable' so we know it is safe to
382 // rename it without violating any constraints that aren't expressed in the
383 // IR (e.g. ABI or opcode requirements).
384 if (!MOUse
.isRenamable())
387 MachineInstr
*Copy
= Tracker
.findAvailCopy(MI
, MOUse
.getReg());
391 unsigned CopyDstReg
= Copy
->getOperand(0).getReg();
392 const MachineOperand
&CopySrc
= Copy
->getOperand(1);
393 unsigned CopySrcReg
= CopySrc
.getReg();
395 // FIXME: Don't handle partial uses of wider COPYs yet.
396 if (MOUse
.getReg() != CopyDstReg
) {
398 dbgs() << "MCP: FIXME! Not forwarding COPY to sub-register use:\n "
403 // Don't forward COPYs of reserved regs unless they are constant.
404 if (MRI
->isReserved(CopySrcReg
) && !MRI
->isConstantPhysReg(CopySrcReg
))
407 if (!isForwardableRegClassCopy(*Copy
, MI
, OpIdx
))
410 if (hasImplicitOverlap(MI
, MOUse
))
413 if (!DebugCounter::shouldExecute(FwdCounter
)) {
414 LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n "
419 LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse
.getReg(), TRI
)
420 << "\n with " << printReg(CopySrcReg
, TRI
)
421 << "\n in " << MI
<< " from " << *Copy
);
423 MOUse
.setReg(CopySrcReg
);
424 if (!CopySrc
.isRenamable())
425 MOUse
.setIsRenamable(false);
427 LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI
<< "\n");
429 // Clear kill markers that may have been invalidated.
430 for (MachineInstr
&KMI
:
431 make_range(Copy
->getIterator(), std::next(MI
.getIterator())))
432 KMI
.clearRegisterKills(CopySrcReg
, TRI
);
439 void MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock
&MBB
) {
440 LLVM_DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB
.getName() << "\n");
442 for (MachineBasicBlock::iterator I
= MBB
.begin(), E
= MBB
.end(); I
!= E
; ) {
443 MachineInstr
*MI
= &*I
;
446 // Analyze copies (which don't overlap themselves).
447 if (MI
->isCopy() && !TRI
->regsOverlap(MI
->getOperand(0).getReg(),
448 MI
->getOperand(1).getReg())) {
449 unsigned Def
= MI
->getOperand(0).getReg();
450 unsigned Src
= MI
->getOperand(1).getReg();
452 assert(!TargetRegisterInfo::isVirtualRegister(Def
) &&
453 !TargetRegisterInfo::isVirtualRegister(Src
) &&
454 "MachineCopyPropagation should be run after register allocation!");
456 // The two copies cancel out and the source of the first copy
457 // hasn't been overridden, eliminate the second one. e.g.
459 // ... nothing clobbered eax.
467 // ... nothing clobbered eax.
471 if (eraseIfRedundant(*MI
, Def
, Src
) || eraseIfRedundant(*MI
, Src
, Def
))
476 // Src may have been changed by forwardUses()
477 Src
= MI
->getOperand(1).getReg();
479 // If Src is defined by a previous copy, the previous copy cannot be
482 for (const MachineOperand
&MO
: MI
->implicit_operands()) {
483 if (!MO
.isReg() || !MO
.readsReg())
485 unsigned Reg
= MO
.getReg();
491 LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI
->dump());
493 // Copy is now a candidate for deletion.
494 if (!MRI
->isReserved(Def
))
495 MaybeDeadCopies
.insert(MI
);
497 // If 'Def' is previously source of another copy, then this earlier copy's
498 // source is no longer available. e.g.
499 // %xmm9 = copy %xmm2
501 // %xmm2 = copy %xmm0
503 // %xmm2 = copy %xmm9
504 Tracker
.clobberRegister(Def
, *TRI
);
505 for (const MachineOperand
&MO
: MI
->implicit_operands()) {
506 if (!MO
.isReg() || !MO
.isDef())
508 unsigned Reg
= MO
.getReg();
511 Tracker
.clobberRegister(Reg
, *TRI
);
514 Tracker
.trackCopy(MI
, *TRI
);
519 // Clobber any earlyclobber regs first.
520 for (const MachineOperand
&MO
: MI
->operands())
521 if (MO
.isReg() && MO
.isEarlyClobber()) {
522 unsigned Reg
= MO
.getReg();
523 // If we have a tied earlyclobber, that means it is also read by this
524 // instruction, so we need to make sure we don't remove it as dead
528 Tracker
.clobberRegister(Reg
, *TRI
);
534 SmallVector
<unsigned, 2> Defs
;
535 const MachineOperand
*RegMask
= nullptr;
536 for (const MachineOperand
&MO
: MI
->operands()) {
541 unsigned Reg
= MO
.getReg();
545 assert(!TargetRegisterInfo::isVirtualRegister(Reg
) &&
546 "MachineCopyPropagation should be run after register allocation!");
548 if (MO
.isDef() && !MO
.isEarlyClobber()) {
551 } else if (!MO
.isDebug() && MO
.readsReg())
555 // The instruction has a register mask operand which means that it clobbers
556 // a large set of registers. Treat clobbered registers the same way as
557 // defined registers.
559 // Erase any MaybeDeadCopies whose destination register is clobbered.
560 for (SmallSetVector
<MachineInstr
*, 8>::iterator DI
=
561 MaybeDeadCopies
.begin();
562 DI
!= MaybeDeadCopies
.end();) {
563 MachineInstr
*MaybeDead
= *DI
;
564 unsigned Reg
= MaybeDead
->getOperand(0).getReg();
565 assert(!MRI
->isReserved(Reg
));
567 if (!RegMask
->clobbersPhysReg(Reg
)) {
572 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
575 // Make sure we invalidate any entries in the copy maps before erasing
577 Tracker
.clobberRegister(Reg
, *TRI
);
579 // erase() will return the next valid iterator pointing to the next
580 // element after the erased one.
581 DI
= MaybeDeadCopies
.erase(DI
);
582 MaybeDead
->eraseFromParent();
588 // Any previous copy definition or reading the Defs is no longer available.
589 for (unsigned Reg
: Defs
)
590 Tracker
.clobberRegister(Reg
, *TRI
);
593 // If MBB doesn't have successors, delete the copies whose defs are not used.
594 // If MBB does have successors, then conservative assume the defs are live-out
595 // since we don't want to trust live-in lists.
596 if (MBB
.succ_empty()) {
597 for (MachineInstr
*MaybeDead
: MaybeDeadCopies
) {
598 LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
600 assert(!MRI
->isReserved(MaybeDead
->getOperand(0).getReg()));
602 // Update matching debug values.
603 assert(MaybeDead
->isCopy());
604 MaybeDead
->changeDebugValuesDefReg(MaybeDead
->getOperand(1).getReg());
606 MaybeDead
->eraseFromParent();
612 MaybeDeadCopies
.clear();
616 bool MachineCopyPropagation::runOnMachineFunction(MachineFunction
&MF
) {
617 if (skipFunction(MF
.getFunction()))
622 TRI
= MF
.getSubtarget().getRegisterInfo();
623 TII
= MF
.getSubtarget().getInstrInfo();
624 MRI
= &MF
.getRegInfo();
626 for (MachineBasicBlock
&MBB
: MF
)
627 CopyPropagateBlock(MBB
);