xref: /src/contrib/llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
163faed5bSDimitry Andric //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
263faed5bSDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
663faed5bSDimitry Andric //
763faed5bSDimitry Andric //===----------------------------------------------------------------------===//
863faed5bSDimitry Andric //
963faed5bSDimitry Andric // This is an extremely simple MachineInstr-level copy propagation pass.
1063faed5bSDimitry Andric //
11eb11fae6SDimitry Andric // This pass forwards the source of COPYs to the users of their destinations
12eb11fae6SDimitry Andric // when doing so is legal.  For example:
13eb11fae6SDimitry Andric //
14eb11fae6SDimitry Andric //   %reg1 = COPY %reg0
15eb11fae6SDimitry Andric //   ...
16eb11fae6SDimitry Andric //   ... = OP %reg1
17eb11fae6SDimitry Andric //
18eb11fae6SDimitry Andric // If
19eb11fae6SDimitry Andric //   - %reg0 has not been clobbered by the time of the use of %reg1
20eb11fae6SDimitry Andric //   - the register class constraints are satisfied
21eb11fae6SDimitry Andric //   - the COPY def is the only value that reaches OP
22eb11fae6SDimitry Andric // then this pass replaces the above with:
23eb11fae6SDimitry Andric //
24eb11fae6SDimitry Andric //   %reg1 = COPY %reg0
25eb11fae6SDimitry Andric //   ...
26eb11fae6SDimitry Andric //   ... = OP %reg0
27eb11fae6SDimitry Andric //
28eb11fae6SDimitry Andric // This pass also removes some redundant COPYs.  For example:
29eb11fae6SDimitry Andric //
30eb11fae6SDimitry Andric //    %R1 = COPY %R0
31eb11fae6SDimitry Andric //    ... // No clobber of %R1
32eb11fae6SDimitry Andric //    %R0 = COPY %R1 <<< Removed
33eb11fae6SDimitry Andric //
34eb11fae6SDimitry Andric // or
35eb11fae6SDimitry Andric //
36eb11fae6SDimitry Andric //    %R1 = COPY %R0
37eb11fae6SDimitry Andric //    ... // No clobber of %R0
38eb11fae6SDimitry Andric //    %R1 = COPY %R0 <<< Removed
39eb11fae6SDimitry Andric //
40706b4fc4SDimitry Andric // or
41706b4fc4SDimitry Andric //
42706b4fc4SDimitry Andric //    $R0 = OP ...
43706b4fc4SDimitry Andric //    ... // No read/clobber of $R0 and $R1
44706b4fc4SDimitry Andric //    $R1 = COPY $R0 // $R0 is killed
45706b4fc4SDimitry Andric // Replace $R0 with $R1 and remove the COPY
46706b4fc4SDimitry Andric //    $R1 = OP ...
47706b4fc4SDimitry Andric //    ...
48706b4fc4SDimitry Andric //
4963faed5bSDimitry Andric //===----------------------------------------------------------------------===//
5063faed5bSDimitry Andric 
5163faed5bSDimitry Andric #include "llvm/ADT/DenseMap.h"
52044eb2f6SDimitry Andric #include "llvm/ADT/STLExtras.h"
5363faed5bSDimitry Andric #include "llvm/ADT/SetVector.h"
54cfca06d7SDimitry Andric #include "llvm/ADT/SmallSet.h"
5563faed5bSDimitry Andric #include "llvm/ADT/SmallVector.h"
5663faed5bSDimitry Andric #include "llvm/ADT/Statistic.h"
57044eb2f6SDimitry Andric #include "llvm/ADT/iterator_range.h"
58044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
594a16efa3SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
604a16efa3SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
61044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
62044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
634a16efa3SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
64eb11fae6SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
65044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
66044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
67706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
68ac9a064cSDimitry Andric #include "llvm/MC/MCRegister.h"
69044eb2f6SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
704a16efa3SDimitry Andric #include "llvm/Pass.h"
714a16efa3SDimitry Andric #include "llvm/Support/Debug.h"
72eb11fae6SDimitry Andric #include "llvm/Support/DebugCounter.h"
734a16efa3SDimitry Andric #include "llvm/Support/raw_ostream.h"
74044eb2f6SDimitry Andric #include <cassert>
75044eb2f6SDimitry Andric #include <iterator>
76044eb2f6SDimitry Andric 
7763faed5bSDimitry Andric using namespace llvm;
7863faed5bSDimitry Andric 
79ab44ce3dSDimitry Andric #define DEBUG_TYPE "machine-cp"
805ca98fd9SDimitry Andric 
8163faed5bSDimitry Andric STATISTIC(NumDeletes, "Number of dead copies deleted");
82eb11fae6SDimitry Andric STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
83706b4fc4SDimitry Andric STATISTIC(NumCopyBackwardPropagated, "Number of copy defs backward propagated");
847fa27ce4SDimitry Andric STATISTIC(SpillageChainsLength, "Length of spillage chains");
857fa27ce4SDimitry Andric STATISTIC(NumSpillageChains, "Number of spillage chains");
86eb11fae6SDimitry Andric DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
87eb11fae6SDimitry Andric               "Controls which register COPYs are forwarded");
8863faed5bSDimitry Andric 
89145449b1SDimitry Andric static cl::opt<bool> MCPUseCopyInstr("mcp-use-is-copy-instr", cl::init(false),
90145449b1SDimitry Andric                                      cl::Hidden);
917fa27ce4SDimitry Andric static cl::opt<cl::boolOrDefault>
927fa27ce4SDimitry Andric     EnableSpillageCopyElimination("enable-spill-copy-elim", cl::Hidden);
93145449b1SDimitry Andric 
9463faed5bSDimitry Andric namespace {
95044eb2f6SDimitry Andric 
isCopyInstr(const MachineInstr & MI,const TargetInstrInfo & TII,bool UseCopyInstr)96e3b55780SDimitry Andric static std::optional<DestSourcePair> isCopyInstr(const MachineInstr &MI,
97145449b1SDimitry Andric                                                  const TargetInstrInfo &TII,
98145449b1SDimitry Andric                                                  bool UseCopyInstr) {
99145449b1SDimitry Andric   if (UseCopyInstr)
100145449b1SDimitry Andric     return TII.isCopyInstr(MI);
101145449b1SDimitry Andric 
102145449b1SDimitry Andric   if (MI.isCopy())
103e3b55780SDimitry Andric     return std::optional<DestSourcePair>(
104145449b1SDimitry Andric         DestSourcePair{MI.getOperand(0), MI.getOperand(1)});
105145449b1SDimitry Andric 
106e3b55780SDimitry Andric   return std::nullopt;
107145449b1SDimitry Andric }
108145449b1SDimitry Andric 
109d8e91e46SDimitry Andric class CopyTracker {
110d8e91e46SDimitry Andric   struct CopyInfo {
1117fa27ce4SDimitry Andric     MachineInstr *MI, *LastSeenUseInCopy;
112b60736ecSDimitry Andric     SmallVector<MCRegister, 4> DefRegs;
113d8e91e46SDimitry Andric     bool Avail;
114d8e91e46SDimitry Andric   };
115d8e91e46SDimitry Andric 
116ac9a064cSDimitry Andric   DenseMap<MCRegUnit, CopyInfo> Copies;
117d8e91e46SDimitry Andric 
118d8e91e46SDimitry Andric public:
119d8e91e46SDimitry Andric   /// Mark all of the given registers and their subregisters as unavailable for
120d8e91e46SDimitry Andric   /// copying.
markRegsUnavailable(ArrayRef<MCRegister> Regs,const TargetRegisterInfo & TRI)121b60736ecSDimitry Andric   void markRegsUnavailable(ArrayRef<MCRegister> Regs,
122d8e91e46SDimitry Andric                            const TargetRegisterInfo &TRI) {
123b60736ecSDimitry Andric     for (MCRegister Reg : Regs) {
124d8e91e46SDimitry Andric       // Source of copy is no longer available for propagation.
1257fa27ce4SDimitry Andric       for (MCRegUnit Unit : TRI.regunits(Reg)) {
1267fa27ce4SDimitry Andric         auto CI = Copies.find(Unit);
127d8e91e46SDimitry Andric         if (CI != Copies.end())
128d8e91e46SDimitry Andric           CI->second.Avail = false;
129d8e91e46SDimitry Andric       }
130d8e91e46SDimitry Andric     }
131d8e91e46SDimitry Andric   }
132d8e91e46SDimitry Andric 
133706b4fc4SDimitry Andric   /// Remove register from copy maps.
invalidateRegister(MCRegister Reg,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)134145449b1SDimitry Andric   void invalidateRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
135145449b1SDimitry Andric                           const TargetInstrInfo &TII, bool UseCopyInstr) {
136706b4fc4SDimitry Andric     // Since Reg might be a subreg of some registers, only invalidate Reg is not
137706b4fc4SDimitry Andric     // enough. We have to find the COPY defines Reg or registers defined by Reg
138b1c73532SDimitry Andric     // and invalidate all of them. Similarly, we must invalidate all of the
139b1c73532SDimitry Andric     // the subregisters used in the source of the COPY.
140b1c73532SDimitry Andric     SmallSet<MCRegUnit, 8> RegUnitsToInvalidate;
141b1c73532SDimitry Andric     auto InvalidateCopy = [&](MachineInstr *MI) {
142e3b55780SDimitry Andric       std::optional<DestSourcePair> CopyOperands =
143145449b1SDimitry Andric           isCopyInstr(*MI, TII, UseCopyInstr);
144145449b1SDimitry Andric       assert(CopyOperands && "Expect copy");
145145449b1SDimitry Andric 
146b1c73532SDimitry Andric       auto Dest = TRI.regunits(CopyOperands->Destination->getReg().asMCReg());
147b1c73532SDimitry Andric       auto Src = TRI.regunits(CopyOperands->Source->getReg().asMCReg());
148b1c73532SDimitry Andric       RegUnitsToInvalidate.insert(Dest.begin(), Dest.end());
149b1c73532SDimitry Andric       RegUnitsToInvalidate.insert(Src.begin(), Src.end());
150b1c73532SDimitry Andric     };
151b1c73532SDimitry Andric 
152b1c73532SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Reg)) {
153b1c73532SDimitry Andric       auto I = Copies.find(Unit);
154b1c73532SDimitry Andric       if (I != Copies.end()) {
155b1c73532SDimitry Andric         if (MachineInstr *MI = I->second.MI)
156b1c73532SDimitry Andric           InvalidateCopy(MI);
157b1c73532SDimitry Andric         if (MachineInstr *MI = I->second.LastSeenUseInCopy)
158b1c73532SDimitry Andric           InvalidateCopy(MI);
159706b4fc4SDimitry Andric       }
160706b4fc4SDimitry Andric     }
161b1c73532SDimitry Andric     for (MCRegUnit Unit : RegUnitsToInvalidate)
1627fa27ce4SDimitry Andric       Copies.erase(Unit);
163706b4fc4SDimitry Andric   }
164706b4fc4SDimitry Andric 
165d8e91e46SDimitry Andric   /// Clobber a single register, removing it from the tracker's copy maps.
clobberRegister(MCRegister Reg,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)166145449b1SDimitry Andric   void clobberRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
167145449b1SDimitry Andric                        const TargetInstrInfo &TII, bool UseCopyInstr) {
1687fa27ce4SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Reg)) {
1697fa27ce4SDimitry Andric       auto I = Copies.find(Unit);
170d8e91e46SDimitry Andric       if (I != Copies.end()) {
171d8e91e46SDimitry Andric         // When we clobber the source of a copy, we need to clobber everything
172d8e91e46SDimitry Andric         // it defined.
173d8e91e46SDimitry Andric         markRegsUnavailable(I->second.DefRegs, TRI);
174d8e91e46SDimitry Andric         // When we clobber the destination of a copy, we need to clobber the
175d8e91e46SDimitry Andric         // whole register it defined.
176145449b1SDimitry Andric         if (MachineInstr *MI = I->second.MI) {
177e3b55780SDimitry Andric           std::optional<DestSourcePair> CopyOperands =
178145449b1SDimitry Andric               isCopyInstr(*MI, TII, UseCopyInstr);
17977dbea07SDimitry Andric 
18077dbea07SDimitry Andric           MCRegister Def = CopyOperands->Destination->getReg().asMCReg();
18177dbea07SDimitry Andric           MCRegister Src = CopyOperands->Source->getReg().asMCReg();
18277dbea07SDimitry Andric 
18377dbea07SDimitry Andric           markRegsUnavailable(Def, TRI);
18477dbea07SDimitry Andric 
18577dbea07SDimitry Andric           // Since we clobber the destination of a copy, the semantic of Src's
18677dbea07SDimitry Andric           // "DefRegs" to contain Def is no longer effectual. We will also need
18777dbea07SDimitry Andric           // to remove the record from the copy maps that indicates Src defined
18877dbea07SDimitry Andric           // Def. Failing to do so might cause the target to miss some
18977dbea07SDimitry Andric           // opportunities to further eliminate redundant copy instructions.
19077dbea07SDimitry Andric           // Consider the following sequence during the
19177dbea07SDimitry Andric           // ForwardCopyPropagateBlock procedure:
19277dbea07SDimitry Andric           // L1: r0 = COPY r9     <- TrackMI
19377dbea07SDimitry Andric           // L2: r0 = COPY r8     <- TrackMI (Remove r9 defined r0 from tracker)
19477dbea07SDimitry Andric           // L3: use r0           <- Remove L2 from MaybeDeadCopies
19577dbea07SDimitry Andric           // L4: early-clobber r9 <- Clobber r9 (L2 is still valid in tracker)
19677dbea07SDimitry Andric           // L5: r0 = COPY r8     <- Remove NopCopy
19777dbea07SDimitry Andric           for (MCRegUnit SrcUnit : TRI.regunits(Src)) {
19877dbea07SDimitry Andric             auto SrcCopy = Copies.find(SrcUnit);
19977dbea07SDimitry Andric             if (SrcCopy != Copies.end() && SrcCopy->second.LastSeenUseInCopy) {
20077dbea07SDimitry Andric               // If SrcCopy defines multiple values, we only need
20177dbea07SDimitry Andric               // to erase the record for Def in DefRegs.
20277dbea07SDimitry Andric               for (auto itr = SrcCopy->second.DefRegs.begin();
20377dbea07SDimitry Andric                    itr != SrcCopy->second.DefRegs.end(); itr++) {
20477dbea07SDimitry Andric                 if (*itr == Def) {
20577dbea07SDimitry Andric                   SrcCopy->second.DefRegs.erase(itr);
20677dbea07SDimitry Andric                   // If DefReg becomes empty after removal, we can remove the
20777dbea07SDimitry Andric                   // SrcCopy from the tracker's copy maps. We only remove those
20877dbea07SDimitry Andric                   // entries solely record the Def is defined by Src. If an
20977dbea07SDimitry Andric                   // entry also contains the definition record of other Def'
21077dbea07SDimitry Andric                   // registers, it cannot be cleared.
21177dbea07SDimitry Andric                   if (SrcCopy->second.DefRegs.empty() && !SrcCopy->second.MI) {
21277dbea07SDimitry Andric                     Copies.erase(SrcCopy);
21377dbea07SDimitry Andric                   }
21477dbea07SDimitry Andric                   break;
21577dbea07SDimitry Andric                 }
21677dbea07SDimitry Andric               }
21777dbea07SDimitry Andric             }
21877dbea07SDimitry Andric           }
219145449b1SDimitry Andric         }
220d8e91e46SDimitry Andric         // Now we can erase the copy.
221d8e91e46SDimitry Andric         Copies.erase(I);
222d8e91e46SDimitry Andric       }
223d8e91e46SDimitry Andric     }
224d8e91e46SDimitry Andric   }
225d8e91e46SDimitry Andric 
226d8e91e46SDimitry Andric   /// Add this copy's registers into the tracker's copy maps.
trackCopy(MachineInstr * MI,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)227145449b1SDimitry Andric   void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI,
228145449b1SDimitry Andric                  const TargetInstrInfo &TII, bool UseCopyInstr) {
229e3b55780SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
230e3b55780SDimitry Andric         isCopyInstr(*MI, TII, UseCopyInstr);
231145449b1SDimitry Andric     assert(CopyOperands && "Tracking non-copy?");
232d8e91e46SDimitry Andric 
233145449b1SDimitry Andric     MCRegister Src = CopyOperands->Source->getReg().asMCReg();
234145449b1SDimitry Andric     MCRegister Def = CopyOperands->Destination->getReg().asMCReg();
235d8e91e46SDimitry Andric 
236d8e91e46SDimitry Andric     // Remember Def is defined by the copy.
2377fa27ce4SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Def))
2387fa27ce4SDimitry Andric       Copies[Unit] = {MI, nullptr, {}, true};
239d8e91e46SDimitry Andric 
240d8e91e46SDimitry Andric     // Remember source that's copied to Def. Once it's clobbered, then
241d8e91e46SDimitry Andric     // it's no longer available for copy propagation.
2427fa27ce4SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Src)) {
2437fa27ce4SDimitry Andric       auto I = Copies.insert({Unit, {nullptr, nullptr, {}, false}});
244d8e91e46SDimitry Andric       auto &Copy = I.first->second;
245d8e91e46SDimitry Andric       if (!is_contained(Copy.DefRegs, Def))
246d8e91e46SDimitry Andric         Copy.DefRegs.push_back(Def);
2477fa27ce4SDimitry Andric       Copy.LastSeenUseInCopy = MI;
248d8e91e46SDimitry Andric     }
249d8e91e46SDimitry Andric   }
250d8e91e46SDimitry Andric 
hasAnyCopies()251d8e91e46SDimitry Andric   bool hasAnyCopies() {
252d8e91e46SDimitry Andric     return !Copies.empty();
253d8e91e46SDimitry Andric   }
254d8e91e46SDimitry Andric 
findCopyForUnit(MCRegUnit RegUnit,const TargetRegisterInfo & TRI,bool MustBeAvailable=false)255ac9a064cSDimitry Andric   MachineInstr *findCopyForUnit(MCRegUnit RegUnit,
256b60736ecSDimitry Andric                                 const TargetRegisterInfo &TRI,
257d8e91e46SDimitry Andric                                 bool MustBeAvailable = false) {
258d8e91e46SDimitry Andric     auto CI = Copies.find(RegUnit);
259d8e91e46SDimitry Andric     if (CI == Copies.end())
260d8e91e46SDimitry Andric       return nullptr;
261d8e91e46SDimitry Andric     if (MustBeAvailable && !CI->second.Avail)
262d8e91e46SDimitry Andric       return nullptr;
263d8e91e46SDimitry Andric     return CI->second.MI;
264d8e91e46SDimitry Andric   }
265d8e91e46SDimitry Andric 
findCopyDefViaUnit(MCRegUnit RegUnit,const TargetRegisterInfo & TRI)266ac9a064cSDimitry Andric   MachineInstr *findCopyDefViaUnit(MCRegUnit RegUnit,
267706b4fc4SDimitry Andric                                    const TargetRegisterInfo &TRI) {
268706b4fc4SDimitry Andric     auto CI = Copies.find(RegUnit);
269706b4fc4SDimitry Andric     if (CI == Copies.end())
270706b4fc4SDimitry Andric       return nullptr;
271706b4fc4SDimitry Andric     if (CI->second.DefRegs.size() != 1)
272706b4fc4SDimitry Andric       return nullptr;
2737fa27ce4SDimitry Andric     MCRegUnit RU = *TRI.regunits(CI->second.DefRegs[0]).begin();
2747fa27ce4SDimitry Andric     return findCopyForUnit(RU, TRI, true);
275706b4fc4SDimitry Andric   }
276706b4fc4SDimitry Andric 
findAvailBackwardCopy(MachineInstr & I,MCRegister Reg,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)277b60736ecSDimitry Andric   MachineInstr *findAvailBackwardCopy(MachineInstr &I, MCRegister Reg,
278145449b1SDimitry Andric                                       const TargetRegisterInfo &TRI,
279145449b1SDimitry Andric                                       const TargetInstrInfo &TII,
280145449b1SDimitry Andric                                       bool UseCopyInstr) {
2817fa27ce4SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
2827fa27ce4SDimitry Andric     MachineInstr *AvailCopy = findCopyDefViaUnit(RU, TRI);
283145449b1SDimitry Andric 
284145449b1SDimitry Andric     if (!AvailCopy)
285706b4fc4SDimitry Andric       return nullptr;
286706b4fc4SDimitry Andric 
287e3b55780SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
288145449b1SDimitry Andric         isCopyInstr(*AvailCopy, TII, UseCopyInstr);
289145449b1SDimitry Andric     Register AvailSrc = CopyOperands->Source->getReg();
290145449b1SDimitry Andric     Register AvailDef = CopyOperands->Destination->getReg();
291145449b1SDimitry Andric     if (!TRI.isSubRegisterEq(AvailSrc, Reg))
292145449b1SDimitry Andric       return nullptr;
293145449b1SDimitry Andric 
294706b4fc4SDimitry Andric     for (const MachineInstr &MI :
295706b4fc4SDimitry Andric          make_range(AvailCopy->getReverseIterator(), I.getReverseIterator()))
296706b4fc4SDimitry Andric       for (const MachineOperand &MO : MI.operands())
297706b4fc4SDimitry Andric         if (MO.isRegMask())
298706b4fc4SDimitry Andric           // FIXME: Shall we simultaneously invalidate AvailSrc or AvailDef?
299706b4fc4SDimitry Andric           if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
300706b4fc4SDimitry Andric             return nullptr;
301706b4fc4SDimitry Andric 
302706b4fc4SDimitry Andric     return AvailCopy;
303706b4fc4SDimitry Andric   }
304706b4fc4SDimitry Andric 
findAvailCopy(MachineInstr & DestCopy,MCRegister Reg,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)305b60736ecSDimitry Andric   MachineInstr *findAvailCopy(MachineInstr &DestCopy, MCRegister Reg,
306145449b1SDimitry Andric                               const TargetRegisterInfo &TRI,
307145449b1SDimitry Andric                               const TargetInstrInfo &TII, bool UseCopyInstr) {
308d8e91e46SDimitry Andric     // We check the first RegUnit here, since we'll only be interested in the
309d8e91e46SDimitry Andric     // copy if it copies the entire register anyway.
3107fa27ce4SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
311d8e91e46SDimitry Andric     MachineInstr *AvailCopy =
3127fa27ce4SDimitry Andric         findCopyForUnit(RU, TRI, /*MustBeAvailable=*/true);
313145449b1SDimitry Andric 
314145449b1SDimitry Andric     if (!AvailCopy)
315145449b1SDimitry Andric       return nullptr;
316145449b1SDimitry Andric 
317e3b55780SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
318145449b1SDimitry Andric         isCopyInstr(*AvailCopy, TII, UseCopyInstr);
319145449b1SDimitry Andric     Register AvailSrc = CopyOperands->Source->getReg();
320145449b1SDimitry Andric     Register AvailDef = CopyOperands->Destination->getReg();
321145449b1SDimitry Andric     if (!TRI.isSubRegisterEq(AvailDef, Reg))
322d8e91e46SDimitry Andric       return nullptr;
323d8e91e46SDimitry Andric 
324d8e91e46SDimitry Andric     // Check that the available copy isn't clobbered by any regmasks between
325d8e91e46SDimitry Andric     // itself and the destination.
326d8e91e46SDimitry Andric     for (const MachineInstr &MI :
327d8e91e46SDimitry Andric          make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
328d8e91e46SDimitry Andric       for (const MachineOperand &MO : MI.operands())
329d8e91e46SDimitry Andric         if (MO.isRegMask())
330d8e91e46SDimitry Andric           if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
331d8e91e46SDimitry Andric             return nullptr;
332d8e91e46SDimitry Andric 
333d8e91e46SDimitry Andric     return AvailCopy;
334d8e91e46SDimitry Andric   }
335d8e91e46SDimitry Andric 
3367fa27ce4SDimitry Andric   // Find last COPY that defines Reg before Current MachineInstr.
findLastSeenDefInCopy(const MachineInstr & Current,MCRegister Reg,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)3377fa27ce4SDimitry Andric   MachineInstr *findLastSeenDefInCopy(const MachineInstr &Current,
3387fa27ce4SDimitry Andric                                       MCRegister Reg,
3397fa27ce4SDimitry Andric                                       const TargetRegisterInfo &TRI,
3407fa27ce4SDimitry Andric                                       const TargetInstrInfo &TII,
3417fa27ce4SDimitry Andric                                       bool UseCopyInstr) {
3427fa27ce4SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
3437fa27ce4SDimitry Andric     auto CI = Copies.find(RU);
3447fa27ce4SDimitry Andric     if (CI == Copies.end() || !CI->second.Avail)
3457fa27ce4SDimitry Andric       return nullptr;
3467fa27ce4SDimitry Andric 
3477fa27ce4SDimitry Andric     MachineInstr *DefCopy = CI->second.MI;
3487fa27ce4SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
3497fa27ce4SDimitry Andric         isCopyInstr(*DefCopy, TII, UseCopyInstr);
3507fa27ce4SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
3517fa27ce4SDimitry Andric     if (!TRI.isSubRegisterEq(Def, Reg))
3527fa27ce4SDimitry Andric       return nullptr;
3537fa27ce4SDimitry Andric 
3547fa27ce4SDimitry Andric     for (const MachineInstr &MI :
3557fa27ce4SDimitry Andric          make_range(static_cast<const MachineInstr *>(DefCopy)->getIterator(),
3567fa27ce4SDimitry Andric                     Current.getIterator()))
3577fa27ce4SDimitry Andric       for (const MachineOperand &MO : MI.operands())
3587fa27ce4SDimitry Andric         if (MO.isRegMask())
3597fa27ce4SDimitry Andric           if (MO.clobbersPhysReg(Def)) {
3607fa27ce4SDimitry Andric             LLVM_DEBUG(dbgs() << "MCP: Removed tracking of "
3617fa27ce4SDimitry Andric                               << printReg(Def, &TRI) << "\n");
3627fa27ce4SDimitry Andric             return nullptr;
3637fa27ce4SDimitry Andric           }
3647fa27ce4SDimitry Andric 
3657fa27ce4SDimitry Andric     return DefCopy;
3667fa27ce4SDimitry Andric   }
3677fa27ce4SDimitry Andric 
3687fa27ce4SDimitry Andric   // Find last COPY that uses Reg.
findLastSeenUseInCopy(MCRegister Reg,const TargetRegisterInfo & TRI)3697fa27ce4SDimitry Andric   MachineInstr *findLastSeenUseInCopy(MCRegister Reg,
3707fa27ce4SDimitry Andric                                       const TargetRegisterInfo &TRI) {
3717fa27ce4SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
3727fa27ce4SDimitry Andric     auto CI = Copies.find(RU);
3737fa27ce4SDimitry Andric     if (CI == Copies.end())
3747fa27ce4SDimitry Andric       return nullptr;
3757fa27ce4SDimitry Andric     return CI->second.LastSeenUseInCopy;
3767fa27ce4SDimitry Andric   }
3777fa27ce4SDimitry Andric 
clear()378d8e91e46SDimitry Andric   void clear() {
379d8e91e46SDimitry Andric     Copies.clear();
380d8e91e46SDimitry Andric   }
381d8e91e46SDimitry Andric };
38201095a5dSDimitry Andric 
38363faed5bSDimitry Andric class MachineCopyPropagation : public MachineFunctionPass {
3847fa27ce4SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
3857fa27ce4SDimitry Andric   const TargetInstrInfo *TII = nullptr;
3867fa27ce4SDimitry Andric   const MachineRegisterInfo *MRI = nullptr;
38763faed5bSDimitry Andric 
388145449b1SDimitry Andric   // Return true if this is a copy instruction and false otherwise.
389145449b1SDimitry Andric   bool UseCopyInstr;
390145449b1SDimitry Andric 
39163faed5bSDimitry Andric public:
39263faed5bSDimitry Andric   static char ID; // Pass identification, replacement for typeid
393044eb2f6SDimitry Andric 
MachineCopyPropagation(bool CopyInstr=false)394145449b1SDimitry Andric   MachineCopyPropagation(bool CopyInstr = false)
395145449b1SDimitry Andric       : MachineFunctionPass(ID), UseCopyInstr(CopyInstr || MCPUseCopyInstr) {
39663faed5bSDimitry Andric     initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
39763faed5bSDimitry Andric   }
39863faed5bSDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const39901095a5dSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
40001095a5dSDimitry Andric     AU.setPreservesCFG();
40101095a5dSDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
40201095a5dSDimitry Andric   }
40301095a5dSDimitry Andric 
4045ca98fd9SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
40563faed5bSDimitry Andric 
getRequiredProperties() const40601095a5dSDimitry Andric   MachineFunctionProperties getRequiredProperties() const override {
40701095a5dSDimitry Andric     return MachineFunctionProperties().set(
408b915e9e0SDimitry Andric         MachineFunctionProperties::Property::NoVRegs);
40901095a5dSDimitry Andric   }
41063faed5bSDimitry Andric 
41101095a5dSDimitry Andric private:
4121d5ae102SDimitry Andric   typedef enum { DebugUse = false, RegularUse = true } DebugType;
4131d5ae102SDimitry Andric 
414b60736ecSDimitry Andric   void ReadRegister(MCRegister Reg, MachineInstr &Reader, DebugType DT);
415ac9a064cSDimitry Andric   void readSuccessorLiveIns(const MachineBasicBlock &MBB);
416706b4fc4SDimitry Andric   void ForwardCopyPropagateBlock(MachineBasicBlock &MBB);
417706b4fc4SDimitry Andric   void BackwardCopyPropagateBlock(MachineBasicBlock &MBB);
4187fa27ce4SDimitry Andric   void EliminateSpillageCopies(MachineBasicBlock &MBB);
419b60736ecSDimitry Andric   bool eraseIfRedundant(MachineInstr &Copy, MCRegister Src, MCRegister Def);
420eb11fae6SDimitry Andric   void forwardUses(MachineInstr &MI);
421706b4fc4SDimitry Andric   void propagateDefs(MachineInstr &MI);
422eb11fae6SDimitry Andric   bool isForwardableRegClassCopy(const MachineInstr &Copy,
423eb11fae6SDimitry Andric                                  const MachineInstr &UseI, unsigned UseIdx);
424706b4fc4SDimitry Andric   bool isBackwardPropagatableRegClassCopy(const MachineInstr &Copy,
425706b4fc4SDimitry Andric                                           const MachineInstr &UseI,
426706b4fc4SDimitry Andric                                           unsigned UseIdx);
427eb11fae6SDimitry Andric   bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
428b60736ecSDimitry Andric   bool hasOverlappingMultipleDef(const MachineInstr &MI,
429b60736ecSDimitry Andric                                  const MachineOperand &MODef, Register Def);
43001095a5dSDimitry Andric 
43101095a5dSDimitry Andric   /// Candidates for deletion.
43201095a5dSDimitry Andric   SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
433044eb2f6SDimitry Andric 
4341d5ae102SDimitry Andric   /// Multimap tracking debug users in current BB
435344a3780SDimitry Andric   DenseMap<MachineInstr *, SmallSet<MachineInstr *, 2>> CopyDbgUsers;
4361d5ae102SDimitry Andric 
437d8e91e46SDimitry Andric   CopyTracker Tracker;
438044eb2f6SDimitry Andric 
4397fa27ce4SDimitry Andric   bool Changed = false;
44063faed5bSDimitry Andric };
441044eb2f6SDimitry Andric 
442044eb2f6SDimitry Andric } // end anonymous namespace
443044eb2f6SDimitry Andric 
44463faed5bSDimitry Andric char MachineCopyPropagation::ID = 0;
445044eb2f6SDimitry Andric 
44663faed5bSDimitry Andric char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
44763faed5bSDimitry Andric 
448ab44ce3dSDimitry Andric INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
44963faed5bSDimitry Andric                 "Machine Copy Propagation Pass", false, false)
45063faed5bSDimitry Andric 
ReadRegister(MCRegister Reg,MachineInstr & Reader,DebugType DT)451b60736ecSDimitry Andric void MachineCopyPropagation::ReadRegister(MCRegister Reg, MachineInstr &Reader,
4521d5ae102SDimitry Andric                                           DebugType DT) {
4533897d3b8SDimitry Andric   // If 'Reg' is defined by a copy, the copy is no longer a candidate
4541d5ae102SDimitry Andric   // for elimination. If a copy is "read" by a debug user, record the user
4551d5ae102SDimitry Andric   // for propagation.
4567fa27ce4SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(Reg)) {
4577fa27ce4SDimitry Andric     if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI)) {
4581d5ae102SDimitry Andric       if (DT == RegularUse) {
459d8e91e46SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
460d8e91e46SDimitry Andric         MaybeDeadCopies.remove(Copy);
4611d5ae102SDimitry Andric       } else {
462344a3780SDimitry Andric         CopyDbgUsers[Copy].insert(&Reader);
4631d5ae102SDimitry Andric       }
4643897d3b8SDimitry Andric     }
4653897d3b8SDimitry Andric   }
4663897d3b8SDimitry Andric }
4673897d3b8SDimitry Andric 
readSuccessorLiveIns(const MachineBasicBlock & MBB)468ac9a064cSDimitry Andric void MachineCopyPropagation::readSuccessorLiveIns(
469ac9a064cSDimitry Andric     const MachineBasicBlock &MBB) {
470ac9a064cSDimitry Andric   if (MaybeDeadCopies.empty())
471ac9a064cSDimitry Andric     return;
472ac9a064cSDimitry Andric 
473ac9a064cSDimitry Andric   // If a copy result is livein to a successor, it is not dead.
474ac9a064cSDimitry Andric   for (const MachineBasicBlock *Succ : MBB.successors()) {
475ac9a064cSDimitry Andric     for (const auto &LI : Succ->liveins()) {
476ac9a064cSDimitry Andric       for (MCRegUnit Unit : TRI->regunits(LI.PhysReg)) {
477ac9a064cSDimitry Andric         if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI))
478ac9a064cSDimitry Andric           MaybeDeadCopies.remove(Copy);
479ac9a064cSDimitry Andric       }
480ac9a064cSDimitry Andric     }
481ac9a064cSDimitry Andric   }
482ac9a064cSDimitry Andric }
483ac9a064cSDimitry Andric 
48401095a5dSDimitry Andric /// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
48501095a5dSDimitry Andric /// This fact may have been obscured by sub register usage or may not be true at
48601095a5dSDimitry Andric /// all even though Src and Def are subregisters of the registers used in
48701095a5dSDimitry Andric /// PreviousCopy. e.g.
48801095a5dSDimitry Andric /// isNopCopy("ecx = COPY eax", AX, CX) == true
48901095a5dSDimitry Andric /// isNopCopy("ecx = COPY eax", AH, CL) == false
isNopCopy(const MachineInstr & PreviousCopy,MCRegister Src,MCRegister Def,const TargetRegisterInfo * TRI,const TargetInstrInfo * TII,bool UseCopyInstr)490b60736ecSDimitry Andric static bool isNopCopy(const MachineInstr &PreviousCopy, MCRegister Src,
491145449b1SDimitry Andric                       MCRegister Def, const TargetRegisterInfo *TRI,
492145449b1SDimitry Andric                       const TargetInstrInfo *TII, bool UseCopyInstr) {
493145449b1SDimitry Andric 
494e3b55780SDimitry Andric   std::optional<DestSourcePair> CopyOperands =
495145449b1SDimitry Andric       isCopyInstr(PreviousCopy, *TII, UseCopyInstr);
496145449b1SDimitry Andric   MCRegister PreviousSrc = CopyOperands->Source->getReg().asMCReg();
497145449b1SDimitry Andric   MCRegister PreviousDef = CopyOperands->Destination->getReg().asMCReg();
498b60736ecSDimitry Andric   if (Src == PreviousSrc && Def == PreviousDef)
49901095a5dSDimitry Andric     return true;
50001095a5dSDimitry Andric   if (!TRI->isSubRegister(PreviousSrc, Src))
50101095a5dSDimitry Andric     return false;
50201095a5dSDimitry Andric   unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
50301095a5dSDimitry Andric   return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
50401095a5dSDimitry Andric }
50501095a5dSDimitry Andric 
50601095a5dSDimitry Andric /// Remove instruction \p Copy if there exists a previous copy that copies the
50701095a5dSDimitry Andric /// register \p Src to the register \p Def; This may happen indirectly by
50801095a5dSDimitry Andric /// copying the super registers.
eraseIfRedundant(MachineInstr & Copy,MCRegister Src,MCRegister Def)509b60736ecSDimitry Andric bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy,
510b60736ecSDimitry Andric                                               MCRegister Src, MCRegister Def) {
51101095a5dSDimitry Andric   // Avoid eliminating a copy from/to a reserved registers as we cannot predict
51201095a5dSDimitry Andric   // the value (Example: The sparc zero register is writable but stays zero).
51301095a5dSDimitry Andric   if (MRI->isReserved(Src) || MRI->isReserved(Def))
51401095a5dSDimitry Andric     return false;
51501095a5dSDimitry Andric 
51601095a5dSDimitry Andric   // Search for an existing copy.
517145449b1SDimitry Andric   MachineInstr *PrevCopy =
518145449b1SDimitry Andric       Tracker.findAvailCopy(Copy, Def, *TRI, *TII, UseCopyInstr);
519d8e91e46SDimitry Andric   if (!PrevCopy)
52001095a5dSDimitry Andric     return false;
52101095a5dSDimitry Andric 
522145449b1SDimitry Andric   auto PrevCopyOperands = isCopyInstr(*PrevCopy, *TII, UseCopyInstr);
52301095a5dSDimitry Andric   // Check that the existing copy uses the correct sub registers.
524145449b1SDimitry Andric   if (PrevCopyOperands->Destination->isDead())
525044eb2f6SDimitry Andric     return false;
526145449b1SDimitry Andric   if (!isNopCopy(*PrevCopy, Src, Def, TRI, TII, UseCopyInstr))
52701095a5dSDimitry Andric     return false;
52801095a5dSDimitry Andric 
529eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
53001095a5dSDimitry Andric 
53101095a5dSDimitry Andric   // Copy was redundantly redefining either Src or Def. Remove earlier kill
53201095a5dSDimitry Andric   // flags between Copy and PrevCopy because the value will be reused now.
533e3b55780SDimitry Andric   std::optional<DestSourcePair> CopyOperands =
534e3b55780SDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
535145449b1SDimitry Andric   assert(CopyOperands);
536145449b1SDimitry Andric 
537145449b1SDimitry Andric   Register CopyDef = CopyOperands->Destination->getReg();
53801095a5dSDimitry Andric   assert(CopyDef == Src || CopyDef == Def);
53901095a5dSDimitry Andric   for (MachineInstr &MI :
540d8e91e46SDimitry Andric        make_range(PrevCopy->getIterator(), Copy.getIterator()))
54101095a5dSDimitry Andric     MI.clearRegisterKills(CopyDef, TRI);
54201095a5dSDimitry Andric 
5437fa27ce4SDimitry Andric   // Clear undef flag from remaining copy if needed.
5447fa27ce4SDimitry Andric   if (!CopyOperands->Source->isUndef()) {
5457fa27ce4SDimitry Andric     PrevCopy->getOperand(PrevCopyOperands->Source->getOperandNo())
5467fa27ce4SDimitry Andric         .setIsUndef(false);
5477fa27ce4SDimitry Andric   }
5487fa27ce4SDimitry Andric 
54901095a5dSDimitry Andric   Copy.eraseFromParent();
55001095a5dSDimitry Andric   Changed = true;
55101095a5dSDimitry Andric   ++NumDeletes;
55263faed5bSDimitry Andric   return true;
55363faed5bSDimitry Andric }
55463faed5bSDimitry Andric 
isBackwardPropagatableRegClassCopy(const MachineInstr & Copy,const MachineInstr & UseI,unsigned UseIdx)555706b4fc4SDimitry Andric bool MachineCopyPropagation::isBackwardPropagatableRegClassCopy(
556706b4fc4SDimitry Andric     const MachineInstr &Copy, const MachineInstr &UseI, unsigned UseIdx) {
557e3b55780SDimitry Andric   std::optional<DestSourcePair> CopyOperands =
558e3b55780SDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
559145449b1SDimitry Andric   Register Def = CopyOperands->Destination->getReg();
560706b4fc4SDimitry Andric 
561706b4fc4SDimitry Andric   if (const TargetRegisterClass *URC =
562706b4fc4SDimitry Andric           UseI.getRegClassConstraint(UseIdx, TII, TRI))
563706b4fc4SDimitry Andric     return URC->contains(Def);
564706b4fc4SDimitry Andric 
565706b4fc4SDimitry Andric   // We don't process further if UseI is a COPY, since forward copy propagation
566706b4fc4SDimitry Andric   // should handle that.
567706b4fc4SDimitry Andric   return false;
568706b4fc4SDimitry Andric }
569706b4fc4SDimitry Andric 
570eb11fae6SDimitry Andric /// Decide whether we should forward the source of \param Copy to its use in
571eb11fae6SDimitry Andric /// \param UseI based on the physical register class constraints of the opcode
572eb11fae6SDimitry Andric /// and avoiding introducing more cross-class COPYs.
isForwardableRegClassCopy(const MachineInstr & Copy,const MachineInstr & UseI,unsigned UseIdx)573eb11fae6SDimitry Andric bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
574eb11fae6SDimitry Andric                                                        const MachineInstr &UseI,
575eb11fae6SDimitry Andric                                                        unsigned UseIdx) {
576e3b55780SDimitry Andric   std::optional<DestSourcePair> CopyOperands =
577e3b55780SDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
578145449b1SDimitry Andric   Register CopySrcReg = CopyOperands->Source->getReg();
579eb11fae6SDimitry Andric 
580eb11fae6SDimitry Andric   // If the new register meets the opcode register constraints, then allow
581eb11fae6SDimitry Andric   // forwarding.
582eb11fae6SDimitry Andric   if (const TargetRegisterClass *URC =
583eb11fae6SDimitry Andric           UseI.getRegClassConstraint(UseIdx, TII, TRI))
584eb11fae6SDimitry Andric     return URC->contains(CopySrcReg);
585eb11fae6SDimitry Andric 
586145449b1SDimitry Andric   auto UseICopyOperands = isCopyInstr(UseI, *TII, UseCopyInstr);
587145449b1SDimitry Andric   if (!UseICopyOperands)
588eb11fae6SDimitry Andric     return false;
589eb11fae6SDimitry Andric 
590eb11fae6SDimitry Andric   /// COPYs don't have register class constraints, so if the user instruction
591eb11fae6SDimitry Andric   /// is a COPY, we just try to avoid introducing additional cross-class
592eb11fae6SDimitry Andric   /// COPYs.  For example:
593eb11fae6SDimitry Andric   ///
594eb11fae6SDimitry Andric   ///   RegClassA = COPY RegClassB  // Copy parameter
595eb11fae6SDimitry Andric   ///   ...
596eb11fae6SDimitry Andric   ///   RegClassB = COPY RegClassA  // UseI parameter
597eb11fae6SDimitry Andric   ///
598eb11fae6SDimitry Andric   /// which after forwarding becomes
599eb11fae6SDimitry Andric   ///
600eb11fae6SDimitry Andric   ///   RegClassA = COPY RegClassB
601eb11fae6SDimitry Andric   ///   ...
602eb11fae6SDimitry Andric   ///   RegClassB = COPY RegClassB
603eb11fae6SDimitry Andric   ///
604eb11fae6SDimitry Andric   /// so we have reduced the number of cross-class COPYs and potentially
605eb11fae6SDimitry Andric   /// introduced a nop COPY that can be removed.
606eb11fae6SDimitry Andric 
607145449b1SDimitry Andric   // Allow forwarding if src and dst belong to any common class, so long as they
608145449b1SDimitry Andric   // don't belong to any (possibly smaller) common class that requires copies to
609145449b1SDimitry Andric   // go via a different class.
610145449b1SDimitry Andric   Register UseDstReg = UseICopyOperands->Destination->getReg();
611145449b1SDimitry Andric   bool Found = false;
612145449b1SDimitry Andric   bool IsCrossClass = false;
613145449b1SDimitry Andric   for (const TargetRegisterClass *RC : TRI->regclasses()) {
614145449b1SDimitry Andric     if (RC->contains(CopySrcReg) && RC->contains(UseDstReg)) {
615145449b1SDimitry Andric       Found = true;
616145449b1SDimitry Andric       if (TRI->getCrossCopyRegClass(RC) != RC) {
617145449b1SDimitry Andric         IsCrossClass = true;
618145449b1SDimitry Andric         break;
619145449b1SDimitry Andric       }
620145449b1SDimitry Andric     }
621145449b1SDimitry Andric   }
622145449b1SDimitry Andric   if (!Found)
623145449b1SDimitry Andric     return false;
624145449b1SDimitry Andric   if (!IsCrossClass)
625145449b1SDimitry Andric     return true;
626145449b1SDimitry Andric   // The forwarded copy would be cross-class. Only do this if the original copy
627145449b1SDimitry Andric   // was also cross-class.
628145449b1SDimitry Andric   Register CopyDstReg = CopyOperands->Destination->getReg();
629145449b1SDimitry Andric   for (const TargetRegisterClass *RC : TRI->regclasses()) {
630145449b1SDimitry Andric     if (RC->contains(CopySrcReg) && RC->contains(CopyDstReg) &&
631145449b1SDimitry Andric         TRI->getCrossCopyRegClass(RC) != RC)
632145449b1SDimitry Andric       return true;
633145449b1SDimitry Andric   }
634eb11fae6SDimitry Andric   return false;
635eb11fae6SDimitry Andric }
636eb11fae6SDimitry Andric 
637eb11fae6SDimitry Andric /// Check that \p MI does not have implicit uses that overlap with it's \p Use
638eb11fae6SDimitry Andric /// operand (the register being replaced), since these can sometimes be
639eb11fae6SDimitry Andric /// implicitly tied to other operands.  For example, on AMDGPU:
640eb11fae6SDimitry Andric ///
641eb11fae6SDimitry Andric /// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
642eb11fae6SDimitry Andric ///
643eb11fae6SDimitry Andric /// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
644eb11fae6SDimitry Andric /// way of knowing we need to update the latter when updating the former.
hasImplicitOverlap(const MachineInstr & MI,const MachineOperand & Use)645eb11fae6SDimitry Andric bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
646eb11fae6SDimitry Andric                                                 const MachineOperand &Use) {
647eb11fae6SDimitry Andric   for (const MachineOperand &MIUse : MI.uses())
648eb11fae6SDimitry Andric     if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
649eb11fae6SDimitry Andric         MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
650eb11fae6SDimitry Andric       return true;
651eb11fae6SDimitry Andric 
652eb11fae6SDimitry Andric   return false;
653eb11fae6SDimitry Andric }
654eb11fae6SDimitry Andric 
655b60736ecSDimitry Andric /// For an MI that has multiple definitions, check whether \p MI has
656b60736ecSDimitry Andric /// a definition that overlaps with another of its definitions.
657b60736ecSDimitry Andric /// For example, on ARM: umull   r9, r9, lr, r0
658b60736ecSDimitry Andric /// The umull instruction is unpredictable unless RdHi and RdLo are different.
hasOverlappingMultipleDef(const MachineInstr & MI,const MachineOperand & MODef,Register Def)659b60736ecSDimitry Andric bool MachineCopyPropagation::hasOverlappingMultipleDef(
660b60736ecSDimitry Andric     const MachineInstr &MI, const MachineOperand &MODef, Register Def) {
661ac9a064cSDimitry Andric   for (const MachineOperand &MIDef : MI.all_defs()) {
662b60736ecSDimitry Andric     if ((&MIDef != &MODef) && MIDef.isReg() &&
663b60736ecSDimitry Andric         TRI->regsOverlap(Def, MIDef.getReg()))
664b60736ecSDimitry Andric       return true;
665b60736ecSDimitry Andric   }
666b60736ecSDimitry Andric 
667b60736ecSDimitry Andric   return false;
668b60736ecSDimitry Andric }
669b60736ecSDimitry Andric 
670eb11fae6SDimitry Andric /// Look for available copies whose destination register is used by \p MI and
671eb11fae6SDimitry Andric /// replace the use in \p MI with the copy's source register.
forwardUses(MachineInstr & MI)672eb11fae6SDimitry Andric void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
673d8e91e46SDimitry Andric   if (!Tracker.hasAnyCopies())
674eb11fae6SDimitry Andric     return;
675eb11fae6SDimitry Andric 
676eb11fae6SDimitry Andric   // Look for non-tied explicit vreg uses that have an active COPY
677eb11fae6SDimitry Andric   // instruction that defines the physical register allocated to them.
678eb11fae6SDimitry Andric   // Replace the vreg with the source of the active COPY.
679eb11fae6SDimitry Andric   for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
680eb11fae6SDimitry Andric        ++OpIdx) {
681eb11fae6SDimitry Andric     MachineOperand &MOUse = MI.getOperand(OpIdx);
682eb11fae6SDimitry Andric     // Don't forward into undef use operands since doing so can cause problems
683eb11fae6SDimitry Andric     // with the machine verifier, since it doesn't treat undef reads as reads,
684eb11fae6SDimitry Andric     // so we can end up with a live range that ends on an undef read, leading to
685eb11fae6SDimitry Andric     // an error that the live range doesn't end on a read of the live range
686eb11fae6SDimitry Andric     // register.
687eb11fae6SDimitry Andric     if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
688eb11fae6SDimitry Andric         MOUse.isImplicit())
689eb11fae6SDimitry Andric       continue;
690eb11fae6SDimitry Andric 
691eb11fae6SDimitry Andric     if (!MOUse.getReg())
692eb11fae6SDimitry Andric       continue;
693eb11fae6SDimitry Andric 
694eb11fae6SDimitry Andric     // Check that the register is marked 'renamable' so we know it is safe to
695eb11fae6SDimitry Andric     // rename it without violating any constraints that aren't expressed in the
696eb11fae6SDimitry Andric     // IR (e.g. ABI or opcode requirements).
697eb11fae6SDimitry Andric     if (!MOUse.isRenamable())
698eb11fae6SDimitry Andric       continue;
699eb11fae6SDimitry Andric 
700145449b1SDimitry Andric     MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg().asMCReg(),
701145449b1SDimitry Andric                                                *TRI, *TII, UseCopyInstr);
702d8e91e46SDimitry Andric     if (!Copy)
703eb11fae6SDimitry Andric       continue;
704eb11fae6SDimitry Andric 
705e3b55780SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
706145449b1SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
707145449b1SDimitry Andric     Register CopyDstReg = CopyOperands->Destination->getReg();
708145449b1SDimitry Andric     const MachineOperand &CopySrc = *CopyOperands->Source;
7091d5ae102SDimitry Andric     Register CopySrcReg = CopySrc.getReg();
710eb11fae6SDimitry Andric 
7117fa27ce4SDimitry Andric     Register ForwardedReg = CopySrcReg;
7127fa27ce4SDimitry Andric     // MI might use a sub-register of the Copy destination, in which case the
7137fa27ce4SDimitry Andric     // forwarded register is the matching sub-register of the Copy source.
714eb11fae6SDimitry Andric     if (MOUse.getReg() != CopyDstReg) {
7157fa27ce4SDimitry Andric       unsigned SubRegIdx = TRI->getSubRegIndex(CopyDstReg, MOUse.getReg());
7167fa27ce4SDimitry Andric       assert(SubRegIdx &&
7177fa27ce4SDimitry Andric              "MI source is not a sub-register of Copy destination");
7187fa27ce4SDimitry Andric       ForwardedReg = TRI->getSubReg(CopySrcReg, SubRegIdx);
7197fa27ce4SDimitry Andric       if (!ForwardedReg) {
7207fa27ce4SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy source does not have sub-register "
7217fa27ce4SDimitry Andric                           << TRI->getSubRegIndexName(SubRegIdx) << '\n');
722eb11fae6SDimitry Andric         continue;
723eb11fae6SDimitry Andric       }
7247fa27ce4SDimitry Andric     }
725eb11fae6SDimitry Andric 
726eb11fae6SDimitry Andric     // Don't forward COPYs of reserved regs unless they are constant.
727eb11fae6SDimitry Andric     if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
728eb11fae6SDimitry Andric       continue;
729eb11fae6SDimitry Andric 
730d8e91e46SDimitry Andric     if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
731eb11fae6SDimitry Andric       continue;
732eb11fae6SDimitry Andric 
733eb11fae6SDimitry Andric     if (hasImplicitOverlap(MI, MOUse))
734eb11fae6SDimitry Andric       continue;
735eb11fae6SDimitry Andric 
736706b4fc4SDimitry Andric     // Check that the instruction is not a copy that partially overwrites the
737706b4fc4SDimitry Andric     // original copy source that we are about to use. The tracker mechanism
738706b4fc4SDimitry Andric     // cannot cope with that.
739145449b1SDimitry Andric     if (isCopyInstr(MI, *TII, UseCopyInstr) &&
740145449b1SDimitry Andric         MI.modifiesRegister(CopySrcReg, TRI) &&
741ac9a064cSDimitry Andric         !MI.definesRegister(CopySrcReg, /*TRI=*/nullptr)) {
742706b4fc4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Copy source overlap with dest in " << MI);
743706b4fc4SDimitry Andric       continue;
744706b4fc4SDimitry Andric     }
745706b4fc4SDimitry Andric 
746eb11fae6SDimitry Andric     if (!DebugCounter::shouldExecute(FwdCounter)) {
747eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n  "
748eb11fae6SDimitry Andric                         << MI);
749eb11fae6SDimitry Andric       continue;
750eb11fae6SDimitry Andric     }
751eb11fae6SDimitry Andric 
752eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
7537fa27ce4SDimitry Andric                       << "\n     with " << printReg(ForwardedReg, TRI)
754d8e91e46SDimitry Andric                       << "\n     in " << MI << "     from " << *Copy);
755eb11fae6SDimitry Andric 
7567fa27ce4SDimitry Andric     MOUse.setReg(ForwardedReg);
7577fa27ce4SDimitry Andric 
758eb11fae6SDimitry Andric     if (!CopySrc.isRenamable())
759eb11fae6SDimitry Andric       MOUse.setIsRenamable(false);
760c0981da4SDimitry Andric     MOUse.setIsUndef(CopySrc.isUndef());
761eb11fae6SDimitry Andric 
762eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
763eb11fae6SDimitry Andric 
764eb11fae6SDimitry Andric     // Clear kill markers that may have been invalidated.
765eb11fae6SDimitry Andric     for (MachineInstr &KMI :
766d8e91e46SDimitry Andric          make_range(Copy->getIterator(), std::next(MI.getIterator())))
767eb11fae6SDimitry Andric       KMI.clearRegisterKills(CopySrcReg, TRI);
768eb11fae6SDimitry Andric 
769eb11fae6SDimitry Andric     ++NumCopyForwards;
770eb11fae6SDimitry Andric     Changed = true;
771eb11fae6SDimitry Andric   }
772eb11fae6SDimitry Andric }
773eb11fae6SDimitry Andric 
ForwardCopyPropagateBlock(MachineBasicBlock & MBB)774706b4fc4SDimitry Andric void MachineCopyPropagation::ForwardCopyPropagateBlock(MachineBasicBlock &MBB) {
775706b4fc4SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: ForwardCopyPropagateBlock " << MBB.getName()
776706b4fc4SDimitry Andric                     << "\n");
7775ca98fd9SDimitry Andric 
778c0981da4SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
779eb11fae6SDimitry Andric     // Analyze copies (which don't overlap themselves).
780e3b55780SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
781e3b55780SDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
782145449b1SDimitry Andric     if (CopyOperands) {
783145449b1SDimitry Andric 
784145449b1SDimitry Andric       Register RegSrc = CopyOperands->Source->getReg();
785145449b1SDimitry Andric       Register RegDef = CopyOperands->Destination->getReg();
786145449b1SDimitry Andric 
787145449b1SDimitry Andric       if (!TRI->regsOverlap(RegDef, RegSrc)) {
788145449b1SDimitry Andric         assert(RegDef.isPhysical() && RegSrc.isPhysical() &&
78901095a5dSDimitry Andric               "MachineCopyPropagation should be run after register allocation!");
79063faed5bSDimitry Andric 
791145449b1SDimitry Andric         MCRegister Def = RegDef.asMCReg();
792145449b1SDimitry Andric         MCRegister Src = RegSrc.asMCReg();
793b60736ecSDimitry Andric 
79463faed5bSDimitry Andric         // The two copies cancel out and the source of the first copy
79563faed5bSDimitry Andric         // hasn't been overridden, eliminate the second one. e.g.
796044eb2f6SDimitry Andric         //  %ecx = COPY %eax
797044eb2f6SDimitry Andric         //  ... nothing clobbered eax.
798044eb2f6SDimitry Andric         //  %eax = COPY %ecx
79963faed5bSDimitry Andric         // =>
800044eb2f6SDimitry Andric         //  %ecx = COPY %eax
80163faed5bSDimitry Andric         //
80201095a5dSDimitry Andric         // or
80301095a5dSDimitry Andric         //
804044eb2f6SDimitry Andric         //  %ecx = COPY %eax
805044eb2f6SDimitry Andric         //  ... nothing clobbered eax.
806044eb2f6SDimitry Andric         //  %ecx = COPY %eax
80701095a5dSDimitry Andric         // =>
808044eb2f6SDimitry Andric         //  %ecx = COPY %eax
809c0981da4SDimitry Andric         if (eraseIfRedundant(MI, Def, Src) || eraseIfRedundant(MI, Src, Def))
81063faed5bSDimitry Andric           continue;
81163faed5bSDimitry Andric 
812c0981da4SDimitry Andric         forwardUses(MI);
813eb11fae6SDimitry Andric 
814eb11fae6SDimitry Andric         // Src may have been changed by forwardUses()
815145449b1SDimitry Andric         CopyOperands = isCopyInstr(MI, *TII, UseCopyInstr);
816145449b1SDimitry Andric         Src = CopyOperands->Source->getReg().asMCReg();
817eb11fae6SDimitry Andric 
81801095a5dSDimitry Andric         // If Src is defined by a previous copy, the previous copy cannot be
81901095a5dSDimitry Andric         // eliminated.
820c0981da4SDimitry Andric         ReadRegister(Src, MI, RegularUse);
821c0981da4SDimitry Andric         for (const MachineOperand &MO : MI.implicit_operands()) {
8223897d3b8SDimitry Andric           if (!MO.isReg() || !MO.readsReg())
8233897d3b8SDimitry Andric             continue;
824b60736ecSDimitry Andric           MCRegister Reg = MO.getReg().asMCReg();
8253897d3b8SDimitry Andric           if (!Reg)
8263897d3b8SDimitry Andric             continue;
827c0981da4SDimitry Andric           ReadRegister(Reg, MI, RegularUse);
8285ca98fd9SDimitry Andric         }
8295ca98fd9SDimitry Andric 
830c0981da4SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI.dump());
83163faed5bSDimitry Andric 
83263faed5bSDimitry Andric         // Copy is now a candidate for deletion.
83301095a5dSDimitry Andric         if (!MRI->isReserved(Def))
834c0981da4SDimitry Andric           MaybeDeadCopies.insert(&MI);
83563faed5bSDimitry Andric 
83601095a5dSDimitry Andric         // If 'Def' is previously source of another copy, then this earlier copy's
83763faed5bSDimitry Andric         // source is no longer available. e.g.
838044eb2f6SDimitry Andric         // %xmm9 = copy %xmm2
83963faed5bSDimitry Andric         // ...
840044eb2f6SDimitry Andric         // %xmm2 = copy %xmm0
84163faed5bSDimitry Andric         // ...
842044eb2f6SDimitry Andric         // %xmm2 = copy %xmm9
843145449b1SDimitry Andric         Tracker.clobberRegister(Def, *TRI, *TII, UseCopyInstr);
844c0981da4SDimitry Andric         for (const MachineOperand &MO : MI.implicit_operands()) {
8453897d3b8SDimitry Andric           if (!MO.isReg() || !MO.isDef())
8463897d3b8SDimitry Andric             continue;
847b60736ecSDimitry Andric           MCRegister Reg = MO.getReg().asMCReg();
8483897d3b8SDimitry Andric           if (!Reg)
8493897d3b8SDimitry Andric             continue;
850145449b1SDimitry Andric           Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
8513897d3b8SDimitry Andric         }
85263faed5bSDimitry Andric 
853145449b1SDimitry Andric         Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
85463faed5bSDimitry Andric 
85563faed5bSDimitry Andric         continue;
85663faed5bSDimitry Andric       }
857145449b1SDimitry Andric     }
85863faed5bSDimitry Andric 
859eb11fae6SDimitry Andric     // Clobber any earlyclobber regs first.
860c0981da4SDimitry Andric     for (const MachineOperand &MO : MI.operands())
861eb11fae6SDimitry Andric       if (MO.isReg() && MO.isEarlyClobber()) {
862b60736ecSDimitry Andric         MCRegister Reg = MO.getReg().asMCReg();
863eb11fae6SDimitry Andric         // If we have a tied earlyclobber, that means it is also read by this
864eb11fae6SDimitry Andric         // instruction, so we need to make sure we don't remove it as dead
865eb11fae6SDimitry Andric         // later.
866eb11fae6SDimitry Andric         if (MO.isTied())
867c0981da4SDimitry Andric           ReadRegister(Reg, MI, RegularUse);
868145449b1SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
869eb11fae6SDimitry Andric       }
870eb11fae6SDimitry Andric 
871c0981da4SDimitry Andric     forwardUses(MI);
872eb11fae6SDimitry Andric 
87363faed5bSDimitry Andric     // Not a copy.
8744df029ccSDimitry Andric     SmallVector<Register, 4> Defs;
87501095a5dSDimitry Andric     const MachineOperand *RegMask = nullptr;
876c0981da4SDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
87763faed5bSDimitry Andric       if (MO.isRegMask())
87801095a5dSDimitry Andric         RegMask = &MO;
87963faed5bSDimitry Andric       if (!MO.isReg())
88063faed5bSDimitry Andric         continue;
8811d5ae102SDimitry Andric       Register Reg = MO.getReg();
88263faed5bSDimitry Andric       if (!Reg)
88363faed5bSDimitry Andric         continue;
88463faed5bSDimitry Andric 
885b60736ecSDimitry Andric       assert(!Reg.isVirtual() &&
88601095a5dSDimitry Andric              "MachineCopyPropagation should be run after register allocation!");
88763faed5bSDimitry Andric 
888eb11fae6SDimitry Andric       if (MO.isDef() && !MO.isEarlyClobber()) {
889b60736ecSDimitry Andric         Defs.push_back(Reg.asMCReg());
89071d5a254SDimitry Andric         continue;
8911d5ae102SDimitry Andric       } else if (MO.readsReg())
892c0981da4SDimitry Andric         ReadRegister(Reg.asMCReg(), MI, MO.isDebug() ? DebugUse : RegularUse);
89363faed5bSDimitry Andric     }
89463faed5bSDimitry Andric 
89563faed5bSDimitry Andric     // The instruction has a register mask operand which means that it clobbers
89601095a5dSDimitry Andric     // a large set of registers.  Treat clobbered registers the same way as
89701095a5dSDimitry Andric     // defined registers.
89801095a5dSDimitry Andric     if (RegMask) {
89963faed5bSDimitry Andric       // Erase any MaybeDeadCopies whose destination register is clobbered.
90001095a5dSDimitry Andric       for (SmallSetVector<MachineInstr *, 8>::iterator DI =
90101095a5dSDimitry Andric                MaybeDeadCopies.begin();
90201095a5dSDimitry Andric            DI != MaybeDeadCopies.end();) {
90301095a5dSDimitry Andric         MachineInstr *MaybeDead = *DI;
904e3b55780SDimitry Andric         std::optional<DestSourcePair> CopyOperands =
905145449b1SDimitry Andric             isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
906145449b1SDimitry Andric         MCRegister Reg = CopyOperands->Destination->getReg().asMCReg();
90701095a5dSDimitry Andric         assert(!MRI->isReserved(Reg));
90801095a5dSDimitry Andric 
90901095a5dSDimitry Andric         if (!RegMask->clobbersPhysReg(Reg)) {
91001095a5dSDimitry Andric           ++DI;
91163faed5bSDimitry Andric           continue;
91201095a5dSDimitry Andric         }
91301095a5dSDimitry Andric 
914eb11fae6SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
91501095a5dSDimitry Andric                    MaybeDead->dump());
91601095a5dSDimitry Andric 
917d8e91e46SDimitry Andric         // Make sure we invalidate any entries in the copy maps before erasing
918d8e91e46SDimitry Andric         // the instruction.
919145449b1SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
920d8e91e46SDimitry Andric 
92101095a5dSDimitry Andric         // erase() will return the next valid iterator pointing to the next
92201095a5dSDimitry Andric         // element after the erased one.
92301095a5dSDimitry Andric         DI = MaybeDeadCopies.erase(DI);
92401095a5dSDimitry Andric         MaybeDead->eraseFromParent();
92563faed5bSDimitry Andric         Changed = true;
92663faed5bSDimitry Andric         ++NumDeletes;
92763faed5bSDimitry Andric       }
92863faed5bSDimitry Andric     }
92963faed5bSDimitry Andric 
93001095a5dSDimitry Andric     // Any previous copy definition or reading the Defs is no longer available.
931b60736ecSDimitry Andric     for (MCRegister Reg : Defs)
932145449b1SDimitry Andric       Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
93363faed5bSDimitry Andric   }
93463faed5bSDimitry Andric 
935ac9a064cSDimitry Andric   bool TracksLiveness = MRI->tracksLiveness();
936ac9a064cSDimitry Andric 
937ac9a064cSDimitry Andric   // If liveness is tracked, we can use the live-in lists to know which
938ac9a064cSDimitry Andric   // copies aren't dead.
939ac9a064cSDimitry Andric   if (TracksLiveness)
940ac9a064cSDimitry Andric     readSuccessorLiveIns(MBB);
941ac9a064cSDimitry Andric 
942ac9a064cSDimitry Andric   // If MBB doesn't have succesor, delete copies whose defs are not used.
943ac9a064cSDimitry Andric   // If MBB does have successors, we can only delete copies if we are able to
944ac9a064cSDimitry Andric   // use liveness information from successors to confirm they are really dead.
945ac9a064cSDimitry Andric   if (MBB.succ_empty() || TracksLiveness) {
94601095a5dSDimitry Andric     for (MachineInstr *MaybeDead : MaybeDeadCopies) {
947eb11fae6SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
948eb11fae6SDimitry Andric                  MaybeDead->dump());
949145449b1SDimitry Andric 
950e3b55780SDimitry Andric       std::optional<DestSourcePair> CopyOperands =
951145449b1SDimitry Andric           isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
952145449b1SDimitry Andric       assert(CopyOperands);
953145449b1SDimitry Andric 
954145449b1SDimitry Andric       Register SrcReg = CopyOperands->Source->getReg();
955145449b1SDimitry Andric       Register DestReg = CopyOperands->Destination->getReg();
956145449b1SDimitry Andric       assert(!MRI->isReserved(DestReg));
957d8e91e46SDimitry Andric 
9581d5ae102SDimitry Andric       // Update matching debug values, if any.
959344a3780SDimitry Andric       SmallVector<MachineInstr *> MaybeDeadDbgUsers(
960344a3780SDimitry Andric           CopyDbgUsers[MaybeDead].begin(), CopyDbgUsers[MaybeDead].end());
961344a3780SDimitry Andric       MRI->updateDbgUsersToReg(DestReg.asMCReg(), SrcReg.asMCReg(),
962344a3780SDimitry Andric                                MaybeDeadDbgUsers);
963d8e91e46SDimitry Andric 
96401095a5dSDimitry Andric       MaybeDead->eraseFromParent();
96563faed5bSDimitry Andric       Changed = true;
96663faed5bSDimitry Andric       ++NumDeletes;
96763faed5bSDimitry Andric     }
96863faed5bSDimitry Andric   }
96963faed5bSDimitry Andric 
97001095a5dSDimitry Andric   MaybeDeadCopies.clear();
9711d5ae102SDimitry Andric   CopyDbgUsers.clear();
972d8e91e46SDimitry Andric   Tracker.clear();
97363faed5bSDimitry Andric }
97463faed5bSDimitry Andric 
isBackwardPropagatableCopy(const DestSourcePair & CopyOperands,const MachineRegisterInfo & MRI)9757fa27ce4SDimitry Andric static bool isBackwardPropagatableCopy(const DestSourcePair &CopyOperands,
976ac9a064cSDimitry Andric                                        const MachineRegisterInfo &MRI) {
9777fa27ce4SDimitry Andric   Register Def = CopyOperands.Destination->getReg();
9787fa27ce4SDimitry Andric   Register Src = CopyOperands.Source->getReg();
979706b4fc4SDimitry Andric 
980706b4fc4SDimitry Andric   if (!Def || !Src)
981706b4fc4SDimitry Andric     return false;
982706b4fc4SDimitry Andric 
983706b4fc4SDimitry Andric   if (MRI.isReserved(Def) || MRI.isReserved(Src))
984706b4fc4SDimitry Andric     return false;
985706b4fc4SDimitry Andric 
9867fa27ce4SDimitry Andric   return CopyOperands.Source->isRenamable() && CopyOperands.Source->isKill();
987706b4fc4SDimitry Andric }
988706b4fc4SDimitry Andric 
propagateDefs(MachineInstr & MI)989706b4fc4SDimitry Andric void MachineCopyPropagation::propagateDefs(MachineInstr &MI) {
990706b4fc4SDimitry Andric   if (!Tracker.hasAnyCopies())
991706b4fc4SDimitry Andric     return;
992706b4fc4SDimitry Andric 
993706b4fc4SDimitry Andric   for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx != OpEnd;
994706b4fc4SDimitry Andric        ++OpIdx) {
995706b4fc4SDimitry Andric     MachineOperand &MODef = MI.getOperand(OpIdx);
996706b4fc4SDimitry Andric 
997706b4fc4SDimitry Andric     if (!MODef.isReg() || MODef.isUse())
998706b4fc4SDimitry Andric       continue;
999706b4fc4SDimitry Andric 
1000706b4fc4SDimitry Andric     // Ignore non-trivial cases.
1001706b4fc4SDimitry Andric     if (MODef.isTied() || MODef.isUndef() || MODef.isImplicit())
1002706b4fc4SDimitry Andric       continue;
1003706b4fc4SDimitry Andric 
1004706b4fc4SDimitry Andric     if (!MODef.getReg())
1005706b4fc4SDimitry Andric       continue;
1006706b4fc4SDimitry Andric 
1007706b4fc4SDimitry Andric     // We only handle if the register comes from a vreg.
1008706b4fc4SDimitry Andric     if (!MODef.isRenamable())
1009706b4fc4SDimitry Andric       continue;
1010706b4fc4SDimitry Andric 
1011145449b1SDimitry Andric     MachineInstr *Copy = Tracker.findAvailBackwardCopy(
1012145449b1SDimitry Andric         MI, MODef.getReg().asMCReg(), *TRI, *TII, UseCopyInstr);
1013706b4fc4SDimitry Andric     if (!Copy)
1014706b4fc4SDimitry Andric       continue;
1015706b4fc4SDimitry Andric 
1016e3b55780SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
1017145449b1SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
1018145449b1SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
1019145449b1SDimitry Andric     Register Src = CopyOperands->Source->getReg();
1020706b4fc4SDimitry Andric 
1021706b4fc4SDimitry Andric     if (MODef.getReg() != Src)
1022706b4fc4SDimitry Andric       continue;
1023706b4fc4SDimitry Andric 
1024706b4fc4SDimitry Andric     if (!isBackwardPropagatableRegClassCopy(*Copy, MI, OpIdx))
1025706b4fc4SDimitry Andric       continue;
1026706b4fc4SDimitry Andric 
1027706b4fc4SDimitry Andric     if (hasImplicitOverlap(MI, MODef))
1028706b4fc4SDimitry Andric       continue;
1029706b4fc4SDimitry Andric 
1030b60736ecSDimitry Andric     if (hasOverlappingMultipleDef(MI, MODef, Def))
1031b60736ecSDimitry Andric       continue;
1032b60736ecSDimitry Andric 
1033706b4fc4SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MODef.getReg(), TRI)
1034706b4fc4SDimitry Andric                       << "\n     with " << printReg(Def, TRI) << "\n     in "
1035706b4fc4SDimitry Andric                       << MI << "     from " << *Copy);
1036706b4fc4SDimitry Andric 
1037706b4fc4SDimitry Andric     MODef.setReg(Def);
1038145449b1SDimitry Andric     MODef.setIsRenamable(CopyOperands->Destination->isRenamable());
1039706b4fc4SDimitry Andric 
1040706b4fc4SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
1041706b4fc4SDimitry Andric     MaybeDeadCopies.insert(Copy);
1042706b4fc4SDimitry Andric     Changed = true;
1043706b4fc4SDimitry Andric     ++NumCopyBackwardPropagated;
1044706b4fc4SDimitry Andric   }
1045706b4fc4SDimitry Andric }
1046706b4fc4SDimitry Andric 
BackwardCopyPropagateBlock(MachineBasicBlock & MBB)1047706b4fc4SDimitry Andric void MachineCopyPropagation::BackwardCopyPropagateBlock(
1048706b4fc4SDimitry Andric     MachineBasicBlock &MBB) {
1049706b4fc4SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: BackwardCopyPropagateBlock " << MBB.getName()
1050706b4fc4SDimitry Andric                     << "\n");
1051706b4fc4SDimitry Andric 
105277fc4c14SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(MBB))) {
1053706b4fc4SDimitry Andric     // Ignore non-trivial COPYs.
1054e3b55780SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
1055e3b55780SDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
1056145449b1SDimitry Andric     if (CopyOperands && MI.getNumOperands() == 2) {
1057145449b1SDimitry Andric       Register DefReg = CopyOperands->Destination->getReg();
1058145449b1SDimitry Andric       Register SrcReg = CopyOperands->Source->getReg();
1059706b4fc4SDimitry Andric 
1060145449b1SDimitry Andric       if (!TRI->regsOverlap(DefReg, SrcReg)) {
1061706b4fc4SDimitry Andric         // Unlike forward cp, we don't invoke propagateDefs here,
1062706b4fc4SDimitry Andric         // just let forward cp do COPY-to-COPY propagation.
1063ac9a064cSDimitry Andric         if (isBackwardPropagatableCopy(*CopyOperands, *MRI)) {
10647fa27ce4SDimitry Andric           Tracker.invalidateRegister(SrcReg.asMCReg(), *TRI, *TII,
10657fa27ce4SDimitry Andric                                      UseCopyInstr);
10667fa27ce4SDimitry Andric           Tracker.invalidateRegister(DefReg.asMCReg(), *TRI, *TII,
10677fa27ce4SDimitry Andric                                      UseCopyInstr);
1068145449b1SDimitry Andric           Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1069706b4fc4SDimitry Andric           continue;
1070706b4fc4SDimitry Andric         }
1071706b4fc4SDimitry Andric       }
1072145449b1SDimitry Andric     }
1073706b4fc4SDimitry Andric 
1074706b4fc4SDimitry Andric     // Invalidate any earlyclobber regs first.
107577fc4c14SDimitry Andric     for (const MachineOperand &MO : MI.operands())
1076706b4fc4SDimitry Andric       if (MO.isReg() && MO.isEarlyClobber()) {
1077b60736ecSDimitry Andric         MCRegister Reg = MO.getReg().asMCReg();
1078706b4fc4SDimitry Andric         if (!Reg)
1079706b4fc4SDimitry Andric           continue;
1080145449b1SDimitry Andric         Tracker.invalidateRegister(Reg, *TRI, *TII, UseCopyInstr);
1081706b4fc4SDimitry Andric       }
1082706b4fc4SDimitry Andric 
108377fc4c14SDimitry Andric     propagateDefs(MI);
108477fc4c14SDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
1085706b4fc4SDimitry Andric       if (!MO.isReg())
1086706b4fc4SDimitry Andric         continue;
1087706b4fc4SDimitry Andric 
1088706b4fc4SDimitry Andric       if (!MO.getReg())
1089706b4fc4SDimitry Andric         continue;
1090706b4fc4SDimitry Andric 
1091706b4fc4SDimitry Andric       if (MO.isDef())
1092145449b1SDimitry Andric         Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
1093145449b1SDimitry Andric                                    UseCopyInstr);
1094706b4fc4SDimitry Andric 
1095344a3780SDimitry Andric       if (MO.readsReg()) {
1096344a3780SDimitry Andric         if (MO.isDebug()) {
1097344a3780SDimitry Andric           //  Check if the register in the debug instruction is utilized
1098344a3780SDimitry Andric           // in a copy instruction, so we can update the debug info if the
1099344a3780SDimitry Andric           // register is changed.
11007fa27ce4SDimitry Andric           for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
11017fa27ce4SDimitry Andric             if (auto *Copy = Tracker.findCopyDefViaUnit(Unit, *TRI)) {
110277fc4c14SDimitry Andric               CopyDbgUsers[Copy].insert(&MI);
1103344a3780SDimitry Andric             }
1104344a3780SDimitry Andric           }
1105344a3780SDimitry Andric         } else {
1106145449b1SDimitry Andric           Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
1107145449b1SDimitry Andric                                      UseCopyInstr);
1108706b4fc4SDimitry Andric         }
1109706b4fc4SDimitry Andric       }
1110344a3780SDimitry Andric     }
1111344a3780SDimitry Andric   }
1112706b4fc4SDimitry Andric 
1113706b4fc4SDimitry Andric   for (auto *Copy : MaybeDeadCopies) {
1114e3b55780SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
1115145449b1SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
1116145449b1SDimitry Andric     Register Src = CopyOperands->Source->getReg();
1117145449b1SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
1118344a3780SDimitry Andric     SmallVector<MachineInstr *> MaybeDeadDbgUsers(CopyDbgUsers[Copy].begin(),
1119344a3780SDimitry Andric                                                   CopyDbgUsers[Copy].end());
1120344a3780SDimitry Andric 
1121344a3780SDimitry Andric     MRI->updateDbgUsersToReg(Src.asMCReg(), Def.asMCReg(), MaybeDeadDbgUsers);
1122706b4fc4SDimitry Andric     Copy->eraseFromParent();
1123706b4fc4SDimitry Andric     ++NumDeletes;
1124706b4fc4SDimitry Andric   }
1125706b4fc4SDimitry Andric 
1126706b4fc4SDimitry Andric   MaybeDeadCopies.clear();
1127706b4fc4SDimitry Andric   CopyDbgUsers.clear();
1128706b4fc4SDimitry Andric   Tracker.clear();
1129706b4fc4SDimitry Andric }
1130706b4fc4SDimitry Andric 
printSpillReloadChain(DenseMap<MachineInstr *,SmallVector<MachineInstr * >> & SpillChain,DenseMap<MachineInstr *,SmallVector<MachineInstr * >> & ReloadChain,MachineInstr * Leader)11317fa27ce4SDimitry Andric static void LLVM_ATTRIBUTE_UNUSED printSpillReloadChain(
11327fa27ce4SDimitry Andric     DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &SpillChain,
11337fa27ce4SDimitry Andric     DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &ReloadChain,
11347fa27ce4SDimitry Andric     MachineInstr *Leader) {
11357fa27ce4SDimitry Andric   auto &SC = SpillChain[Leader];
11367fa27ce4SDimitry Andric   auto &RC = ReloadChain[Leader];
11377fa27ce4SDimitry Andric   for (auto I = SC.rbegin(), E = SC.rend(); I != E; ++I)
11387fa27ce4SDimitry Andric     (*I)->dump();
11397fa27ce4SDimitry Andric   for (MachineInstr *MI : RC)
11407fa27ce4SDimitry Andric     MI->dump();
11417fa27ce4SDimitry Andric }
11427fa27ce4SDimitry Andric 
11437fa27ce4SDimitry Andric // Remove spill-reload like copy chains. For example
11447fa27ce4SDimitry Andric // r0 = COPY r1
11457fa27ce4SDimitry Andric // r1 = COPY r2
11467fa27ce4SDimitry Andric // r2 = COPY r3
11477fa27ce4SDimitry Andric // r3 = COPY r4
11487fa27ce4SDimitry Andric // <def-use r4>
11497fa27ce4SDimitry Andric // r4 = COPY r3
11507fa27ce4SDimitry Andric // r3 = COPY r2
11517fa27ce4SDimitry Andric // r2 = COPY r1
11527fa27ce4SDimitry Andric // r1 = COPY r0
11537fa27ce4SDimitry Andric // will be folded into
11547fa27ce4SDimitry Andric // r0 = COPY r1
11557fa27ce4SDimitry Andric // r1 = COPY r4
11567fa27ce4SDimitry Andric // <def-use r4>
11577fa27ce4SDimitry Andric // r4 = COPY r1
11587fa27ce4SDimitry Andric // r1 = COPY r0
11597fa27ce4SDimitry Andric // TODO: Currently we don't track usage of r0 outside the chain, so we
11607fa27ce4SDimitry Andric // conservatively keep its value as it was before the rewrite.
11617fa27ce4SDimitry Andric //
11627fa27ce4SDimitry Andric // The algorithm is trying to keep
11637fa27ce4SDimitry Andric // property#1: No Def of spill COPY in the chain is used or defined until the
11647fa27ce4SDimitry Andric // paired reload COPY in the chain uses the Def.
11657fa27ce4SDimitry Andric //
11667fa27ce4SDimitry Andric // property#2: NO Source of COPY in the chain is used or defined until the next
11677fa27ce4SDimitry Andric // COPY in the chain defines the Source, except the innermost spill-reload
11687fa27ce4SDimitry Andric // pair.
11697fa27ce4SDimitry Andric //
11707fa27ce4SDimitry Andric // The algorithm is conducted by checking every COPY inside the MBB, assuming
11717fa27ce4SDimitry Andric // the COPY is a reload COPY, then try to find paired spill COPY by searching
11727fa27ce4SDimitry Andric // the COPY defines the Src of the reload COPY backward. If such pair is found,
11737fa27ce4SDimitry Andric // it either belongs to an existing chain or a new chain depends on
11747fa27ce4SDimitry Andric // last available COPY uses the Def of the reload COPY.
11757fa27ce4SDimitry Andric // Implementation notes, we use CopyTracker::findLastDefCopy(Reg, ...) to find
11767fa27ce4SDimitry Andric // out last COPY that defines Reg; we use CopyTracker::findLastUseCopy(Reg, ...)
11777fa27ce4SDimitry Andric // to find out last COPY that uses Reg. When we are encountered with a Non-COPY
11787fa27ce4SDimitry Andric // instruction, we check registers in the operands of this instruction. If this
11797fa27ce4SDimitry Andric // Reg is defined by a COPY, we untrack this Reg via
11807fa27ce4SDimitry Andric // CopyTracker::clobberRegister(Reg, ...).
EliminateSpillageCopies(MachineBasicBlock & MBB)11817fa27ce4SDimitry Andric void MachineCopyPropagation::EliminateSpillageCopies(MachineBasicBlock &MBB) {
11827fa27ce4SDimitry Andric   // ChainLeader maps MI inside a spill-reload chain to its innermost reload COPY.
11837fa27ce4SDimitry Andric   // Thus we can track if a MI belongs to an existing spill-reload chain.
11847fa27ce4SDimitry Andric   DenseMap<MachineInstr *, MachineInstr *> ChainLeader;
11857fa27ce4SDimitry Andric   // SpillChain maps innermost reload COPY of a spill-reload chain to a sequence
11867fa27ce4SDimitry Andric   // of COPYs that forms spills of a spill-reload chain.
11877fa27ce4SDimitry Andric   // ReloadChain maps innermost reload COPY of a spill-reload chain to a
11887fa27ce4SDimitry Andric   // sequence of COPYs that forms reloads of a spill-reload chain.
11897fa27ce4SDimitry Andric   DenseMap<MachineInstr *, SmallVector<MachineInstr *>> SpillChain, ReloadChain;
11907fa27ce4SDimitry Andric   // If a COPY's Source has use or def until next COPY defines the Source,
11917fa27ce4SDimitry Andric   // we put the COPY in this set to keep property#2.
11927fa27ce4SDimitry Andric   DenseSet<const MachineInstr *> CopySourceInvalid;
11937fa27ce4SDimitry Andric 
11947fa27ce4SDimitry Andric   auto TryFoldSpillageCopies =
11957fa27ce4SDimitry Andric       [&, this](const SmallVectorImpl<MachineInstr *> &SC,
11967fa27ce4SDimitry Andric                 const SmallVectorImpl<MachineInstr *> &RC) {
11977fa27ce4SDimitry Andric         assert(SC.size() == RC.size() && "Spill-reload should be paired");
11987fa27ce4SDimitry Andric 
11997fa27ce4SDimitry Andric         // We need at least 3 pairs of copies for the transformation to apply,
12007fa27ce4SDimitry Andric         // because the first outermost pair cannot be removed since we don't
12017fa27ce4SDimitry Andric         // recolor outside of the chain and that we need at least one temporary
12027fa27ce4SDimitry Andric         // spill slot to shorten the chain. If we only have a chain of two
12037fa27ce4SDimitry Andric         // pairs, we already have the shortest sequence this code can handle:
12047fa27ce4SDimitry Andric         // the outermost pair for the temporary spill slot, and the pair that
12057fa27ce4SDimitry Andric         // use that temporary spill slot for the other end of the chain.
12067fa27ce4SDimitry Andric         // TODO: We might be able to simplify to one spill-reload pair if collecting
12077fa27ce4SDimitry Andric         // more infomation about the outermost COPY.
12087fa27ce4SDimitry Andric         if (SC.size() <= 2)
12097fa27ce4SDimitry Andric           return;
12107fa27ce4SDimitry Andric 
12117fa27ce4SDimitry Andric         // If violate property#2, we don't fold the chain.
1212b1c73532SDimitry Andric         for (const MachineInstr *Spill : drop_begin(SC))
12137fa27ce4SDimitry Andric           if (CopySourceInvalid.count(Spill))
12147fa27ce4SDimitry Andric             return;
12157fa27ce4SDimitry Andric 
1216b1c73532SDimitry Andric         for (const MachineInstr *Reload : drop_end(RC))
12177fa27ce4SDimitry Andric           if (CopySourceInvalid.count(Reload))
12187fa27ce4SDimitry Andric             return;
12197fa27ce4SDimitry Andric 
12207fa27ce4SDimitry Andric         auto CheckCopyConstraint = [this](Register Def, Register Src) {
12217fa27ce4SDimitry Andric           for (const TargetRegisterClass *RC : TRI->regclasses()) {
12227fa27ce4SDimitry Andric             if (RC->contains(Def) && RC->contains(Src))
12237fa27ce4SDimitry Andric               return true;
12247fa27ce4SDimitry Andric           }
12257fa27ce4SDimitry Andric           return false;
12267fa27ce4SDimitry Andric         };
12277fa27ce4SDimitry Andric 
12287fa27ce4SDimitry Andric         auto UpdateReg = [](MachineInstr *MI, const MachineOperand *Old,
12297fa27ce4SDimitry Andric                             const MachineOperand *New) {
12307fa27ce4SDimitry Andric           for (MachineOperand &MO : MI->operands()) {
12317fa27ce4SDimitry Andric             if (&MO == Old)
12327fa27ce4SDimitry Andric               MO.setReg(New->getReg());
12337fa27ce4SDimitry Andric           }
12347fa27ce4SDimitry Andric         };
12357fa27ce4SDimitry Andric 
12367fa27ce4SDimitry Andric         std::optional<DestSourcePair> InnerMostSpillCopy =
12377fa27ce4SDimitry Andric             isCopyInstr(*SC[0], *TII, UseCopyInstr);
12387fa27ce4SDimitry Andric         std::optional<DestSourcePair> OuterMostSpillCopy =
12397fa27ce4SDimitry Andric             isCopyInstr(*SC.back(), *TII, UseCopyInstr);
12407fa27ce4SDimitry Andric         std::optional<DestSourcePair> InnerMostReloadCopy =
12417fa27ce4SDimitry Andric             isCopyInstr(*RC[0], *TII, UseCopyInstr);
12427fa27ce4SDimitry Andric         std::optional<DestSourcePair> OuterMostReloadCopy =
12437fa27ce4SDimitry Andric             isCopyInstr(*RC.back(), *TII, UseCopyInstr);
12447fa27ce4SDimitry Andric         if (!CheckCopyConstraint(OuterMostSpillCopy->Source->getReg(),
12457fa27ce4SDimitry Andric                                  InnerMostSpillCopy->Source->getReg()) ||
12467fa27ce4SDimitry Andric             !CheckCopyConstraint(InnerMostReloadCopy->Destination->getReg(),
12477fa27ce4SDimitry Andric                                  OuterMostReloadCopy->Destination->getReg()))
12487fa27ce4SDimitry Andric           return;
12497fa27ce4SDimitry Andric 
12507fa27ce4SDimitry Andric         SpillageChainsLength += SC.size() + RC.size();
12517fa27ce4SDimitry Andric         NumSpillageChains += 1;
12527fa27ce4SDimitry Andric         UpdateReg(SC[0], InnerMostSpillCopy->Destination,
12537fa27ce4SDimitry Andric                   OuterMostSpillCopy->Source);
12547fa27ce4SDimitry Andric         UpdateReg(RC[0], InnerMostReloadCopy->Source,
12557fa27ce4SDimitry Andric                   OuterMostReloadCopy->Destination);
12567fa27ce4SDimitry Andric 
12577fa27ce4SDimitry Andric         for (size_t I = 1; I < SC.size() - 1; ++I) {
12587fa27ce4SDimitry Andric           SC[I]->eraseFromParent();
12597fa27ce4SDimitry Andric           RC[I]->eraseFromParent();
12607fa27ce4SDimitry Andric           NumDeletes += 2;
12617fa27ce4SDimitry Andric         }
12627fa27ce4SDimitry Andric       };
12637fa27ce4SDimitry Andric 
12647fa27ce4SDimitry Andric   auto IsFoldableCopy = [this](const MachineInstr &MaybeCopy) {
12657fa27ce4SDimitry Andric     if (MaybeCopy.getNumImplicitOperands() > 0)
12667fa27ce4SDimitry Andric       return false;
12677fa27ce4SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
12687fa27ce4SDimitry Andric         isCopyInstr(MaybeCopy, *TII, UseCopyInstr);
12697fa27ce4SDimitry Andric     if (!CopyOperands)
12707fa27ce4SDimitry Andric       return false;
12717fa27ce4SDimitry Andric     Register Src = CopyOperands->Source->getReg();
12727fa27ce4SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
12737fa27ce4SDimitry Andric     return Src && Def && !TRI->regsOverlap(Src, Def) &&
12747fa27ce4SDimitry Andric            CopyOperands->Source->isRenamable() &&
12757fa27ce4SDimitry Andric            CopyOperands->Destination->isRenamable();
12767fa27ce4SDimitry Andric   };
12777fa27ce4SDimitry Andric 
12787fa27ce4SDimitry Andric   auto IsSpillReloadPair = [&, this](const MachineInstr &Spill,
12797fa27ce4SDimitry Andric                                      const MachineInstr &Reload) {
12807fa27ce4SDimitry Andric     if (!IsFoldableCopy(Spill) || !IsFoldableCopy(Reload))
12817fa27ce4SDimitry Andric       return false;
12827fa27ce4SDimitry Andric     std::optional<DestSourcePair> SpillCopy =
12837fa27ce4SDimitry Andric         isCopyInstr(Spill, *TII, UseCopyInstr);
12847fa27ce4SDimitry Andric     std::optional<DestSourcePair> ReloadCopy =
12857fa27ce4SDimitry Andric         isCopyInstr(Reload, *TII, UseCopyInstr);
12867fa27ce4SDimitry Andric     if (!SpillCopy || !ReloadCopy)
12877fa27ce4SDimitry Andric       return false;
12887fa27ce4SDimitry Andric     return SpillCopy->Source->getReg() == ReloadCopy->Destination->getReg() &&
12897fa27ce4SDimitry Andric            SpillCopy->Destination->getReg() == ReloadCopy->Source->getReg();
12907fa27ce4SDimitry Andric   };
12917fa27ce4SDimitry Andric 
12927fa27ce4SDimitry Andric   auto IsChainedCopy = [&, this](const MachineInstr &Prev,
12937fa27ce4SDimitry Andric                                  const MachineInstr &Current) {
12947fa27ce4SDimitry Andric     if (!IsFoldableCopy(Prev) || !IsFoldableCopy(Current))
12957fa27ce4SDimitry Andric       return false;
12967fa27ce4SDimitry Andric     std::optional<DestSourcePair> PrevCopy =
12977fa27ce4SDimitry Andric         isCopyInstr(Prev, *TII, UseCopyInstr);
12987fa27ce4SDimitry Andric     std::optional<DestSourcePair> CurrentCopy =
12997fa27ce4SDimitry Andric         isCopyInstr(Current, *TII, UseCopyInstr);
13007fa27ce4SDimitry Andric     if (!PrevCopy || !CurrentCopy)
13017fa27ce4SDimitry Andric       return false;
13027fa27ce4SDimitry Andric     return PrevCopy->Source->getReg() == CurrentCopy->Destination->getReg();
13037fa27ce4SDimitry Andric   };
13047fa27ce4SDimitry Andric 
13057fa27ce4SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
13067fa27ce4SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
13077fa27ce4SDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
13087fa27ce4SDimitry Andric 
13097fa27ce4SDimitry Andric     // Update track information via non-copy instruction.
13107fa27ce4SDimitry Andric     SmallSet<Register, 8> RegsToClobber;
13117fa27ce4SDimitry Andric     if (!CopyOperands) {
13127fa27ce4SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
13137fa27ce4SDimitry Andric         if (!MO.isReg())
13147fa27ce4SDimitry Andric           continue;
13157fa27ce4SDimitry Andric         Register Reg = MO.getReg();
13167fa27ce4SDimitry Andric         if (!Reg)
13177fa27ce4SDimitry Andric           continue;
13187fa27ce4SDimitry Andric         MachineInstr *LastUseCopy =
13197fa27ce4SDimitry Andric             Tracker.findLastSeenUseInCopy(Reg.asMCReg(), *TRI);
13207fa27ce4SDimitry Andric         if (LastUseCopy) {
13217fa27ce4SDimitry Andric           LLVM_DEBUG(dbgs() << "MCP: Copy source of\n");
13227fa27ce4SDimitry Andric           LLVM_DEBUG(LastUseCopy->dump());
13237fa27ce4SDimitry Andric           LLVM_DEBUG(dbgs() << "might be invalidated by\n");
13247fa27ce4SDimitry Andric           LLVM_DEBUG(MI.dump());
13257fa27ce4SDimitry Andric           CopySourceInvalid.insert(LastUseCopy);
13267fa27ce4SDimitry Andric         }
13277fa27ce4SDimitry Andric         // Must be noted Tracker.clobberRegister(Reg, ...) removes tracking of
13287fa27ce4SDimitry Andric         // Reg, i.e, COPY that defines Reg is removed from the mapping as well
13297fa27ce4SDimitry Andric         // as marking COPYs that uses Reg unavailable.
13307fa27ce4SDimitry Andric         // We don't invoke CopyTracker::clobberRegister(Reg, ...) if Reg is not
13317fa27ce4SDimitry Andric         // defined by a previous COPY, since we don't want to make COPYs uses
13327fa27ce4SDimitry Andric         // Reg unavailable.
13337fa27ce4SDimitry Andric         if (Tracker.findLastSeenDefInCopy(MI, Reg.asMCReg(), *TRI, *TII,
13347fa27ce4SDimitry Andric                                     UseCopyInstr))
13357fa27ce4SDimitry Andric           // Thus we can keep the property#1.
13367fa27ce4SDimitry Andric           RegsToClobber.insert(Reg);
13377fa27ce4SDimitry Andric       }
13387fa27ce4SDimitry Andric       for (Register Reg : RegsToClobber) {
13397fa27ce4SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
13407fa27ce4SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Reg, TRI)
13417fa27ce4SDimitry Andric                           << "\n");
13427fa27ce4SDimitry Andric       }
13437fa27ce4SDimitry Andric       continue;
13447fa27ce4SDimitry Andric     }
13457fa27ce4SDimitry Andric 
13467fa27ce4SDimitry Andric     Register Src = CopyOperands->Source->getReg();
13477fa27ce4SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
13487fa27ce4SDimitry Andric     // Check if we can find a pair spill-reload copy.
13497fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Searching paired spill for reload: ");
13507fa27ce4SDimitry Andric     LLVM_DEBUG(MI.dump());
13517fa27ce4SDimitry Andric     MachineInstr *MaybeSpill =
13527fa27ce4SDimitry Andric         Tracker.findLastSeenDefInCopy(MI, Src.asMCReg(), *TRI, *TII, UseCopyInstr);
13537fa27ce4SDimitry Andric     bool MaybeSpillIsChained = ChainLeader.count(MaybeSpill);
13547fa27ce4SDimitry Andric     if (!MaybeSpillIsChained && MaybeSpill &&
13557fa27ce4SDimitry Andric         IsSpillReloadPair(*MaybeSpill, MI)) {
13567fa27ce4SDimitry Andric       // Check if we already have an existing chain. Now we have a
13577fa27ce4SDimitry Andric       // spill-reload pair.
13587fa27ce4SDimitry Andric       // L2: r2 = COPY r3
13597fa27ce4SDimitry Andric       // L5: r3 = COPY r2
13607fa27ce4SDimitry Andric       // Looking for a valid COPY before L5 which uses r3.
13617fa27ce4SDimitry Andric       // This can be serverial cases.
13627fa27ce4SDimitry Andric       // Case #1:
13637fa27ce4SDimitry Andric       // No COPY is found, which can be r3 is def-use between (L2, L5), we
13647fa27ce4SDimitry Andric       // create a new chain for L2 and L5.
13657fa27ce4SDimitry Andric       // Case #2:
13667fa27ce4SDimitry Andric       // L2: r2 = COPY r3
13677fa27ce4SDimitry Andric       // L5: r3 = COPY r2
13687fa27ce4SDimitry Andric       // Such COPY is found and is L2, we create a new chain for L2 and L5.
13697fa27ce4SDimitry Andric       // Case #3:
13707fa27ce4SDimitry Andric       // L2: r2 = COPY r3
13717fa27ce4SDimitry Andric       // L3: r1 = COPY r3
13727fa27ce4SDimitry Andric       // L5: r3 = COPY r2
13737fa27ce4SDimitry Andric       // we create a new chain for L2 and L5.
13747fa27ce4SDimitry Andric       // Case #4:
13757fa27ce4SDimitry Andric       // L2: r2 = COPY r3
13767fa27ce4SDimitry Andric       // L3: r1 = COPY r3
13777fa27ce4SDimitry Andric       // L4: r3 = COPY r1
13787fa27ce4SDimitry Andric       // L5: r3 = COPY r2
13797fa27ce4SDimitry Andric       // Such COPY won't be found since L4 defines r3. we create a new chain
13807fa27ce4SDimitry Andric       // for L2 and L5.
13817fa27ce4SDimitry Andric       // Case #5:
13827fa27ce4SDimitry Andric       // L2: r2 = COPY r3
13837fa27ce4SDimitry Andric       // L3: r3 = COPY r1
13847fa27ce4SDimitry Andric       // L4: r1 = COPY r3
13857fa27ce4SDimitry Andric       // L5: r3 = COPY r2
13867fa27ce4SDimitry Andric       // COPY is found and is L4 which belongs to an existing chain, we add
13877fa27ce4SDimitry Andric       // L2 and L5 to this chain.
13887fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Found spill: ");
13897fa27ce4SDimitry Andric       LLVM_DEBUG(MaybeSpill->dump());
13907fa27ce4SDimitry Andric       MachineInstr *MaybePrevReload =
13917fa27ce4SDimitry Andric           Tracker.findLastSeenUseInCopy(Def.asMCReg(), *TRI);
13927fa27ce4SDimitry Andric       auto Leader = ChainLeader.find(MaybePrevReload);
13937fa27ce4SDimitry Andric       MachineInstr *L = nullptr;
13947fa27ce4SDimitry Andric       if (Leader == ChainLeader.end() ||
13957fa27ce4SDimitry Andric           (MaybePrevReload && !IsChainedCopy(*MaybePrevReload, MI))) {
13967fa27ce4SDimitry Andric         L = &MI;
13977fa27ce4SDimitry Andric         assert(!SpillChain.count(L) &&
13987fa27ce4SDimitry Andric                "SpillChain should not have contained newly found chain");
13997fa27ce4SDimitry Andric       } else {
14007fa27ce4SDimitry Andric         assert(MaybePrevReload &&
14017fa27ce4SDimitry Andric                "Found a valid leader through nullptr should not happend");
14027fa27ce4SDimitry Andric         L = Leader->second;
14037fa27ce4SDimitry Andric         assert(SpillChain[L].size() > 0 &&
14047fa27ce4SDimitry Andric                "Existing chain's length should be larger than zero");
14057fa27ce4SDimitry Andric       }
14067fa27ce4SDimitry Andric       assert(!ChainLeader.count(&MI) && !ChainLeader.count(MaybeSpill) &&
14077fa27ce4SDimitry Andric              "Newly found paired spill-reload should not belong to any chain "
14087fa27ce4SDimitry Andric              "at this point");
14097fa27ce4SDimitry Andric       ChainLeader.insert({MaybeSpill, L});
14107fa27ce4SDimitry Andric       ChainLeader.insert({&MI, L});
14117fa27ce4SDimitry Andric       SpillChain[L].push_back(MaybeSpill);
14127fa27ce4SDimitry Andric       ReloadChain[L].push_back(&MI);
14137fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Chain " << L << " now is:\n");
14147fa27ce4SDimitry Andric       LLVM_DEBUG(printSpillReloadChain(SpillChain, ReloadChain, L));
14157fa27ce4SDimitry Andric     } else if (MaybeSpill && !MaybeSpillIsChained) {
14167fa27ce4SDimitry Andric       // MaybeSpill is unable to pair with MI. That's to say adding MI makes
14177fa27ce4SDimitry Andric       // the chain invalid.
14187fa27ce4SDimitry Andric       // The COPY defines Src is no longer considered as a candidate of a
14197fa27ce4SDimitry Andric       // valid chain. Since we expect the Def of a spill copy isn't used by
14207fa27ce4SDimitry Andric       // any COPY instruction until a reload copy. For example:
14217fa27ce4SDimitry Andric       // L1: r1 = COPY r2
14227fa27ce4SDimitry Andric       // L2: r3 = COPY r1
14237fa27ce4SDimitry Andric       // If we later have
14247fa27ce4SDimitry Andric       // L1: r1 = COPY r2
14257fa27ce4SDimitry Andric       // L2: r3 = COPY r1
14267fa27ce4SDimitry Andric       // L3: r2 = COPY r1
14277fa27ce4SDimitry Andric       // L1 and L3 can't be a valid spill-reload pair.
14287fa27ce4SDimitry Andric       // Thus we keep the property#1.
14297fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Not paired spill-reload:\n");
14307fa27ce4SDimitry Andric       LLVM_DEBUG(MaybeSpill->dump());
14317fa27ce4SDimitry Andric       LLVM_DEBUG(MI.dump());
14327fa27ce4SDimitry Andric       Tracker.clobberRegister(Src.asMCReg(), *TRI, *TII, UseCopyInstr);
14337fa27ce4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Src, TRI)
14347fa27ce4SDimitry Andric                         << "\n");
14357fa27ce4SDimitry Andric     }
14367fa27ce4SDimitry Andric     Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
14377fa27ce4SDimitry Andric   }
14387fa27ce4SDimitry Andric 
14397fa27ce4SDimitry Andric   for (auto I = SpillChain.begin(), E = SpillChain.end(); I != E; ++I) {
14407fa27ce4SDimitry Andric     auto &SC = I->second;
14417fa27ce4SDimitry Andric     assert(ReloadChain.count(I->first) &&
14427fa27ce4SDimitry Andric            "Reload chain of the same leader should exist");
14437fa27ce4SDimitry Andric     auto &RC = ReloadChain[I->first];
14447fa27ce4SDimitry Andric     TryFoldSpillageCopies(SC, RC);
14457fa27ce4SDimitry Andric   }
14467fa27ce4SDimitry Andric 
14477fa27ce4SDimitry Andric   MaybeDeadCopies.clear();
14487fa27ce4SDimitry Andric   CopyDbgUsers.clear();
14497fa27ce4SDimitry Andric   Tracker.clear();
14507fa27ce4SDimitry Andric }
14517fa27ce4SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)145263faed5bSDimitry Andric bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
1453044eb2f6SDimitry Andric   if (skipFunction(MF.getFunction()))
14545ca98fd9SDimitry Andric     return false;
14555ca98fd9SDimitry Andric 
14567fa27ce4SDimitry Andric   bool isSpillageCopyElimEnabled = false;
14577fa27ce4SDimitry Andric   switch (EnableSpillageCopyElimination) {
14587fa27ce4SDimitry Andric   case cl::BOU_UNSET:
14597fa27ce4SDimitry Andric     isSpillageCopyElimEnabled =
14607fa27ce4SDimitry Andric         MF.getSubtarget().enableSpillageCopyElimination();
14617fa27ce4SDimitry Andric     break;
14627fa27ce4SDimitry Andric   case cl::BOU_TRUE:
14637fa27ce4SDimitry Andric     isSpillageCopyElimEnabled = true;
14647fa27ce4SDimitry Andric     break;
14657fa27ce4SDimitry Andric   case cl::BOU_FALSE:
14667fa27ce4SDimitry Andric     isSpillageCopyElimEnabled = false;
14677fa27ce4SDimitry Andric     break;
14687fa27ce4SDimitry Andric   }
14697fa27ce4SDimitry Andric 
147001095a5dSDimitry Andric   Changed = false;
147163faed5bSDimitry Andric 
147267c32a98SDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
147367c32a98SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
1474522600a2SDimitry Andric   MRI = &MF.getRegInfo();
147563faed5bSDimitry Andric 
1476706b4fc4SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
14777fa27ce4SDimitry Andric     if (isSpillageCopyElimEnabled)
14787fa27ce4SDimitry Andric       EliminateSpillageCopies(MBB);
1479706b4fc4SDimitry Andric     BackwardCopyPropagateBlock(MBB);
1480706b4fc4SDimitry Andric     ForwardCopyPropagateBlock(MBB);
1481706b4fc4SDimitry Andric   }
148263faed5bSDimitry Andric 
148363faed5bSDimitry Andric   return Changed;
148463faed5bSDimitry Andric }
1485145449b1SDimitry Andric 
1486145449b1SDimitry Andric MachineFunctionPass *
createMachineCopyPropagationPass(bool UseCopyInstr=false)1487145449b1SDimitry Andric llvm::createMachineCopyPropagationPass(bool UseCopyInstr = false) {
1488145449b1SDimitry Andric   return new MachineCopyPropagation(UseCopyInstr);
1489145449b1SDimitry Andric }
1490