xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp (revision 647cbc5de815c5651677bf8582797f716ec7b48d)
10b57cec5SDimitry Andric //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This is an extremely simple MachineInstr-level copy propagation pass.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric // This pass forwards the source of COPYs to the users of their destinations
120b57cec5SDimitry Andric // when doing so is legal.  For example:
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric //   %reg1 = COPY %reg0
150b57cec5SDimitry Andric //   ...
160b57cec5SDimitry Andric //   ... = OP %reg1
170b57cec5SDimitry Andric //
180b57cec5SDimitry Andric // If
190b57cec5SDimitry Andric //   - %reg0 has not been clobbered by the time of the use of %reg1
200b57cec5SDimitry Andric //   - the register class constraints are satisfied
210b57cec5SDimitry Andric //   - the COPY def is the only value that reaches OP
220b57cec5SDimitry Andric // then this pass replaces the above with:
230b57cec5SDimitry Andric //
240b57cec5SDimitry Andric //   %reg1 = COPY %reg0
250b57cec5SDimitry Andric //   ...
260b57cec5SDimitry Andric //   ... = OP %reg0
270b57cec5SDimitry Andric //
280b57cec5SDimitry Andric // This pass also removes some redundant COPYs.  For example:
290b57cec5SDimitry Andric //
300b57cec5SDimitry Andric //    %R1 = COPY %R0
310b57cec5SDimitry Andric //    ... // No clobber of %R1
320b57cec5SDimitry Andric //    %R0 = COPY %R1 <<< Removed
330b57cec5SDimitry Andric //
340b57cec5SDimitry Andric // or
350b57cec5SDimitry Andric //
360b57cec5SDimitry Andric //    %R1 = COPY %R0
370b57cec5SDimitry Andric //    ... // No clobber of %R0
380b57cec5SDimitry Andric //    %R1 = COPY %R0 <<< Removed
390b57cec5SDimitry Andric //
40480093f4SDimitry Andric // or
41480093f4SDimitry Andric //
42480093f4SDimitry Andric //    $R0 = OP ...
43480093f4SDimitry Andric //    ... // No read/clobber of $R0 and $R1
44480093f4SDimitry Andric //    $R1 = COPY $R0 // $R0 is killed
45480093f4SDimitry Andric // Replace $R0 with $R1 and remove the COPY
46480093f4SDimitry Andric //    $R1 = OP ...
47480093f4SDimitry Andric //    ...
48480093f4SDimitry Andric //
490b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
520b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
530b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
545ffd83dbSDimitry Andric #include "llvm/ADT/SmallSet.h"
550b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
560b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
570b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
580b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
590b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
600b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
610b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
620b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
630b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
640b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
650b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
660b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
67480093f4SDimitry Andric #include "llvm/InitializePasses.h"
680b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
690b57cec5SDimitry Andric #include "llvm/Pass.h"
700b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
710b57cec5SDimitry Andric #include "llvm/Support/DebugCounter.h"
720b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
730b57cec5SDimitry Andric #include <cassert>
740b57cec5SDimitry Andric #include <iterator>
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric using namespace llvm;
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric #define DEBUG_TYPE "machine-cp"
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric STATISTIC(NumDeletes, "Number of dead copies deleted");
810b57cec5SDimitry Andric STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
82480093f4SDimitry Andric STATISTIC(NumCopyBackwardPropagated, "Number of copy defs backward propagated");
8306c3fb27SDimitry Andric STATISTIC(SpillageChainsLength, "Length of spillage chains");
8406c3fb27SDimitry Andric STATISTIC(NumSpillageChains, "Number of spillage chains");
850b57cec5SDimitry Andric DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
860b57cec5SDimitry Andric               "Controls which register COPYs are forwarded");
870b57cec5SDimitry Andric 
8881ad6265SDimitry Andric static cl::opt<bool> MCPUseCopyInstr("mcp-use-is-copy-instr", cl::init(false),
8981ad6265SDimitry Andric                                      cl::Hidden);
9006c3fb27SDimitry Andric static cl::opt<cl::boolOrDefault>
9106c3fb27SDimitry Andric     EnableSpillageCopyElimination("enable-spill-copy-elim", cl::Hidden);
9281ad6265SDimitry Andric 
930b57cec5SDimitry Andric namespace {
940b57cec5SDimitry Andric 
95bdd1243dSDimitry Andric static std::optional<DestSourcePair> isCopyInstr(const MachineInstr &MI,
9681ad6265SDimitry Andric                                                  const TargetInstrInfo &TII,
9781ad6265SDimitry Andric                                                  bool UseCopyInstr) {
9881ad6265SDimitry Andric   if (UseCopyInstr)
9981ad6265SDimitry Andric     return TII.isCopyInstr(MI);
10081ad6265SDimitry Andric 
10181ad6265SDimitry Andric   if (MI.isCopy())
102bdd1243dSDimitry Andric     return std::optional<DestSourcePair>(
10381ad6265SDimitry Andric         DestSourcePair{MI.getOperand(0), MI.getOperand(1)});
10481ad6265SDimitry Andric 
105bdd1243dSDimitry Andric   return std::nullopt;
10681ad6265SDimitry Andric }
10781ad6265SDimitry Andric 
1080b57cec5SDimitry Andric class CopyTracker {
1090b57cec5SDimitry Andric   struct CopyInfo {
11006c3fb27SDimitry Andric     MachineInstr *MI, *LastSeenUseInCopy;
111e8d8bef9SDimitry Andric     SmallVector<MCRegister, 4> DefRegs;
1120b57cec5SDimitry Andric     bool Avail;
1130b57cec5SDimitry Andric   };
1140b57cec5SDimitry Andric 
115e8d8bef9SDimitry Andric   DenseMap<MCRegister, CopyInfo> Copies;
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric public:
1180b57cec5SDimitry Andric   /// Mark all of the given registers and their subregisters as unavailable for
1190b57cec5SDimitry Andric   /// copying.
120e8d8bef9SDimitry Andric   void markRegsUnavailable(ArrayRef<MCRegister> Regs,
1210b57cec5SDimitry Andric                            const TargetRegisterInfo &TRI) {
122e8d8bef9SDimitry Andric     for (MCRegister Reg : Regs) {
1230b57cec5SDimitry Andric       // Source of copy is no longer available for propagation.
12406c3fb27SDimitry Andric       for (MCRegUnit Unit : TRI.regunits(Reg)) {
12506c3fb27SDimitry Andric         auto CI = Copies.find(Unit);
1260b57cec5SDimitry Andric         if (CI != Copies.end())
1270b57cec5SDimitry Andric           CI->second.Avail = false;
1280b57cec5SDimitry Andric       }
1290b57cec5SDimitry Andric     }
1300b57cec5SDimitry Andric   }
1310b57cec5SDimitry Andric 
132480093f4SDimitry Andric   /// Remove register from copy maps.
13381ad6265SDimitry Andric   void invalidateRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
13481ad6265SDimitry Andric                           const TargetInstrInfo &TII, bool UseCopyInstr) {
135480093f4SDimitry Andric     // Since Reg might be a subreg of some registers, only invalidate Reg is not
136480093f4SDimitry Andric     // enough. We have to find the COPY defines Reg or registers defined by Reg
1375f757f3fSDimitry Andric     // and invalidate all of them. Similarly, we must invalidate all of the
1385f757f3fSDimitry Andric     // the subregisters used in the source of the COPY.
1395f757f3fSDimitry Andric     SmallSet<MCRegUnit, 8> RegUnitsToInvalidate;
1405f757f3fSDimitry Andric     auto InvalidateCopy = [&](MachineInstr *MI) {
141bdd1243dSDimitry Andric       std::optional<DestSourcePair> CopyOperands =
14281ad6265SDimitry Andric           isCopyInstr(*MI, TII, UseCopyInstr);
14381ad6265SDimitry Andric       assert(CopyOperands && "Expect copy");
14481ad6265SDimitry Andric 
1455f757f3fSDimitry Andric       auto Dest = TRI.regunits(CopyOperands->Destination->getReg().asMCReg());
1465f757f3fSDimitry Andric       auto Src = TRI.regunits(CopyOperands->Source->getReg().asMCReg());
1475f757f3fSDimitry Andric       RegUnitsToInvalidate.insert(Dest.begin(), Dest.end());
1485f757f3fSDimitry Andric       RegUnitsToInvalidate.insert(Src.begin(), Src.end());
1495f757f3fSDimitry Andric     };
1505f757f3fSDimitry Andric 
1515f757f3fSDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Reg)) {
1525f757f3fSDimitry Andric       auto I = Copies.find(Unit);
1535f757f3fSDimitry Andric       if (I != Copies.end()) {
1545f757f3fSDimitry Andric         if (MachineInstr *MI = I->second.MI)
1555f757f3fSDimitry Andric           InvalidateCopy(MI);
1565f757f3fSDimitry Andric         if (MachineInstr *MI = I->second.LastSeenUseInCopy)
1575f757f3fSDimitry Andric           InvalidateCopy(MI);
158480093f4SDimitry Andric       }
159480093f4SDimitry Andric     }
1605f757f3fSDimitry Andric     for (MCRegUnit Unit : RegUnitsToInvalidate)
16106c3fb27SDimitry Andric       Copies.erase(Unit);
162480093f4SDimitry Andric   }
163480093f4SDimitry Andric 
1640b57cec5SDimitry Andric   /// Clobber a single register, removing it from the tracker's copy maps.
16581ad6265SDimitry Andric   void clobberRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
16681ad6265SDimitry Andric                        const TargetInstrInfo &TII, bool UseCopyInstr) {
16706c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Reg)) {
16806c3fb27SDimitry Andric       auto I = Copies.find(Unit);
1690b57cec5SDimitry Andric       if (I != Copies.end()) {
1700b57cec5SDimitry Andric         // When we clobber the source of a copy, we need to clobber everything
1710b57cec5SDimitry Andric         // it defined.
1720b57cec5SDimitry Andric         markRegsUnavailable(I->second.DefRegs, TRI);
1730b57cec5SDimitry Andric         // When we clobber the destination of a copy, we need to clobber the
1740b57cec5SDimitry Andric         // whole register it defined.
17581ad6265SDimitry Andric         if (MachineInstr *MI = I->second.MI) {
176bdd1243dSDimitry Andric           std::optional<DestSourcePair> CopyOperands =
17781ad6265SDimitry Andric               isCopyInstr(*MI, TII, UseCopyInstr);
178*647cbc5dSDimitry Andric 
179*647cbc5dSDimitry Andric           MCRegister Def = CopyOperands->Destination->getReg().asMCReg();
180*647cbc5dSDimitry Andric           MCRegister Src = CopyOperands->Source->getReg().asMCReg();
181*647cbc5dSDimitry Andric 
182*647cbc5dSDimitry Andric           markRegsUnavailable(Def, TRI);
183*647cbc5dSDimitry Andric 
184*647cbc5dSDimitry Andric           // Since we clobber the destination of a copy, the semantic of Src's
185*647cbc5dSDimitry Andric           // "DefRegs" to contain Def is no longer effectual. We will also need
186*647cbc5dSDimitry Andric           // to remove the record from the copy maps that indicates Src defined
187*647cbc5dSDimitry Andric           // Def. Failing to do so might cause the target to miss some
188*647cbc5dSDimitry Andric           // opportunities to further eliminate redundant copy instructions.
189*647cbc5dSDimitry Andric           // Consider the following sequence during the
190*647cbc5dSDimitry Andric           // ForwardCopyPropagateBlock procedure:
191*647cbc5dSDimitry Andric           // L1: r0 = COPY r9     <- TrackMI
192*647cbc5dSDimitry Andric           // L2: r0 = COPY r8     <- TrackMI (Remove r9 defined r0 from tracker)
193*647cbc5dSDimitry Andric           // L3: use r0           <- Remove L2 from MaybeDeadCopies
194*647cbc5dSDimitry Andric           // L4: early-clobber r9 <- Clobber r9 (L2 is still valid in tracker)
195*647cbc5dSDimitry Andric           // L5: r0 = COPY r8     <- Remove NopCopy
196*647cbc5dSDimitry Andric           for (MCRegUnit SrcUnit : TRI.regunits(Src)) {
197*647cbc5dSDimitry Andric             auto SrcCopy = Copies.find(SrcUnit);
198*647cbc5dSDimitry Andric             if (SrcCopy != Copies.end() && SrcCopy->second.LastSeenUseInCopy) {
199*647cbc5dSDimitry Andric               // If SrcCopy defines multiple values, we only need
200*647cbc5dSDimitry Andric               // to erase the record for Def in DefRegs.
201*647cbc5dSDimitry Andric               for (auto itr = SrcCopy->second.DefRegs.begin();
202*647cbc5dSDimitry Andric                    itr != SrcCopy->second.DefRegs.end(); itr++) {
203*647cbc5dSDimitry Andric                 if (*itr == Def) {
204*647cbc5dSDimitry Andric                   SrcCopy->second.DefRegs.erase(itr);
205*647cbc5dSDimitry Andric                   // If DefReg becomes empty after removal, we can remove the
206*647cbc5dSDimitry Andric                   // SrcCopy from the tracker's copy maps. We only remove those
207*647cbc5dSDimitry Andric                   // entries solely record the Def is defined by Src. If an
208*647cbc5dSDimitry Andric                   // entry also contains the definition record of other Def'
209*647cbc5dSDimitry Andric                   // registers, it cannot be cleared.
210*647cbc5dSDimitry Andric                   if (SrcCopy->second.DefRegs.empty() && !SrcCopy->second.MI) {
211*647cbc5dSDimitry Andric                     Copies.erase(SrcCopy);
212*647cbc5dSDimitry Andric                   }
213*647cbc5dSDimitry Andric                   break;
214*647cbc5dSDimitry Andric                 }
215*647cbc5dSDimitry Andric               }
216*647cbc5dSDimitry Andric             }
217*647cbc5dSDimitry Andric           }
21881ad6265SDimitry Andric         }
2190b57cec5SDimitry Andric         // Now we can erase the copy.
2200b57cec5SDimitry Andric         Copies.erase(I);
2210b57cec5SDimitry Andric       }
2220b57cec5SDimitry Andric     }
2230b57cec5SDimitry Andric   }
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric   /// Add this copy's registers into the tracker's copy maps.
22681ad6265SDimitry Andric   void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI,
22781ad6265SDimitry Andric                  const TargetInstrInfo &TII, bool UseCopyInstr) {
228bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
229bdd1243dSDimitry Andric         isCopyInstr(*MI, TII, UseCopyInstr);
23081ad6265SDimitry Andric     assert(CopyOperands && "Tracking non-copy?");
2310b57cec5SDimitry Andric 
23281ad6265SDimitry Andric     MCRegister Src = CopyOperands->Source->getReg().asMCReg();
23381ad6265SDimitry Andric     MCRegister Def = CopyOperands->Destination->getReg().asMCReg();
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric     // Remember Def is defined by the copy.
23606c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Def))
23706c3fb27SDimitry Andric       Copies[Unit] = {MI, nullptr, {}, true};
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric     // Remember source that's copied to Def. Once it's clobbered, then
2400b57cec5SDimitry Andric     // it's no longer available for copy propagation.
24106c3fb27SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Src)) {
24206c3fb27SDimitry Andric       auto I = Copies.insert({Unit, {nullptr, nullptr, {}, false}});
2430b57cec5SDimitry Andric       auto &Copy = I.first->second;
2440b57cec5SDimitry Andric       if (!is_contained(Copy.DefRegs, Def))
2450b57cec5SDimitry Andric         Copy.DefRegs.push_back(Def);
24606c3fb27SDimitry Andric       Copy.LastSeenUseInCopy = MI;
2470b57cec5SDimitry Andric     }
2480b57cec5SDimitry Andric   }
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric   bool hasAnyCopies() {
2510b57cec5SDimitry Andric     return !Copies.empty();
2520b57cec5SDimitry Andric   }
2530b57cec5SDimitry Andric 
254e8d8bef9SDimitry Andric   MachineInstr *findCopyForUnit(MCRegister RegUnit,
255e8d8bef9SDimitry Andric                                 const TargetRegisterInfo &TRI,
2560b57cec5SDimitry Andric                                 bool MustBeAvailable = false) {
2570b57cec5SDimitry Andric     auto CI = Copies.find(RegUnit);
2580b57cec5SDimitry Andric     if (CI == Copies.end())
2590b57cec5SDimitry Andric       return nullptr;
2600b57cec5SDimitry Andric     if (MustBeAvailable && !CI->second.Avail)
2610b57cec5SDimitry Andric       return nullptr;
2620b57cec5SDimitry Andric     return CI->second.MI;
2630b57cec5SDimitry Andric   }
2640b57cec5SDimitry Andric 
265e8d8bef9SDimitry Andric   MachineInstr *findCopyDefViaUnit(MCRegister RegUnit,
266480093f4SDimitry Andric                                    const TargetRegisterInfo &TRI) {
267480093f4SDimitry Andric     auto CI = Copies.find(RegUnit);
268480093f4SDimitry Andric     if (CI == Copies.end())
269480093f4SDimitry Andric       return nullptr;
270480093f4SDimitry Andric     if (CI->second.DefRegs.size() != 1)
271480093f4SDimitry Andric       return nullptr;
27206c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(CI->second.DefRegs[0]).begin();
27306c3fb27SDimitry Andric     return findCopyForUnit(RU, TRI, true);
274480093f4SDimitry Andric   }
275480093f4SDimitry Andric 
276e8d8bef9SDimitry Andric   MachineInstr *findAvailBackwardCopy(MachineInstr &I, MCRegister Reg,
27781ad6265SDimitry Andric                                       const TargetRegisterInfo &TRI,
27881ad6265SDimitry Andric                                       const TargetInstrInfo &TII,
27981ad6265SDimitry Andric                                       bool UseCopyInstr) {
28006c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
28106c3fb27SDimitry Andric     MachineInstr *AvailCopy = findCopyDefViaUnit(RU, TRI);
28281ad6265SDimitry Andric 
28381ad6265SDimitry Andric     if (!AvailCopy)
284480093f4SDimitry Andric       return nullptr;
285480093f4SDimitry Andric 
286bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
28781ad6265SDimitry Andric         isCopyInstr(*AvailCopy, TII, UseCopyInstr);
28881ad6265SDimitry Andric     Register AvailSrc = CopyOperands->Source->getReg();
28981ad6265SDimitry Andric     Register AvailDef = CopyOperands->Destination->getReg();
29081ad6265SDimitry Andric     if (!TRI.isSubRegisterEq(AvailSrc, Reg))
29181ad6265SDimitry Andric       return nullptr;
29281ad6265SDimitry Andric 
293480093f4SDimitry Andric     for (const MachineInstr &MI :
294480093f4SDimitry Andric          make_range(AvailCopy->getReverseIterator(), I.getReverseIterator()))
295480093f4SDimitry Andric       for (const MachineOperand &MO : MI.operands())
296480093f4SDimitry Andric         if (MO.isRegMask())
297480093f4SDimitry Andric           // FIXME: Shall we simultaneously invalidate AvailSrc or AvailDef?
298480093f4SDimitry Andric           if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
299480093f4SDimitry Andric             return nullptr;
300480093f4SDimitry Andric 
301480093f4SDimitry Andric     return AvailCopy;
302480093f4SDimitry Andric   }
303480093f4SDimitry Andric 
304e8d8bef9SDimitry Andric   MachineInstr *findAvailCopy(MachineInstr &DestCopy, MCRegister Reg,
30581ad6265SDimitry Andric                               const TargetRegisterInfo &TRI,
30681ad6265SDimitry Andric                               const TargetInstrInfo &TII, bool UseCopyInstr) {
3070b57cec5SDimitry Andric     // We check the first RegUnit here, since we'll only be interested in the
3080b57cec5SDimitry Andric     // copy if it copies the entire register anyway.
30906c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
3100b57cec5SDimitry Andric     MachineInstr *AvailCopy =
31106c3fb27SDimitry Andric         findCopyForUnit(RU, TRI, /*MustBeAvailable=*/true);
31281ad6265SDimitry Andric 
31381ad6265SDimitry Andric     if (!AvailCopy)
31481ad6265SDimitry Andric       return nullptr;
31581ad6265SDimitry Andric 
316bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
31781ad6265SDimitry Andric         isCopyInstr(*AvailCopy, TII, UseCopyInstr);
31881ad6265SDimitry Andric     Register AvailSrc = CopyOperands->Source->getReg();
31981ad6265SDimitry Andric     Register AvailDef = CopyOperands->Destination->getReg();
32081ad6265SDimitry Andric     if (!TRI.isSubRegisterEq(AvailDef, Reg))
3210b57cec5SDimitry Andric       return nullptr;
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric     // Check that the available copy isn't clobbered by any regmasks between
3240b57cec5SDimitry Andric     // itself and the destination.
3250b57cec5SDimitry Andric     for (const MachineInstr &MI :
3260b57cec5SDimitry Andric          make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
3270b57cec5SDimitry Andric       for (const MachineOperand &MO : MI.operands())
3280b57cec5SDimitry Andric         if (MO.isRegMask())
3290b57cec5SDimitry Andric           if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
3300b57cec5SDimitry Andric             return nullptr;
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric     return AvailCopy;
3330b57cec5SDimitry Andric   }
3340b57cec5SDimitry Andric 
33506c3fb27SDimitry Andric   // Find last COPY that defines Reg before Current MachineInstr.
33606c3fb27SDimitry Andric   MachineInstr *findLastSeenDefInCopy(const MachineInstr &Current,
33706c3fb27SDimitry Andric                                       MCRegister Reg,
33806c3fb27SDimitry Andric                                       const TargetRegisterInfo &TRI,
33906c3fb27SDimitry Andric                                       const TargetInstrInfo &TII,
34006c3fb27SDimitry Andric                                       bool UseCopyInstr) {
34106c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
34206c3fb27SDimitry Andric     auto CI = Copies.find(RU);
34306c3fb27SDimitry Andric     if (CI == Copies.end() || !CI->second.Avail)
34406c3fb27SDimitry Andric       return nullptr;
34506c3fb27SDimitry Andric 
34606c3fb27SDimitry Andric     MachineInstr *DefCopy = CI->second.MI;
34706c3fb27SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
34806c3fb27SDimitry Andric         isCopyInstr(*DefCopy, TII, UseCopyInstr);
34906c3fb27SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
35006c3fb27SDimitry Andric     if (!TRI.isSubRegisterEq(Def, Reg))
35106c3fb27SDimitry Andric       return nullptr;
35206c3fb27SDimitry Andric 
35306c3fb27SDimitry Andric     for (const MachineInstr &MI :
35406c3fb27SDimitry Andric          make_range(static_cast<const MachineInstr *>(DefCopy)->getIterator(),
35506c3fb27SDimitry Andric                     Current.getIterator()))
35606c3fb27SDimitry Andric       for (const MachineOperand &MO : MI.operands())
35706c3fb27SDimitry Andric         if (MO.isRegMask())
35806c3fb27SDimitry Andric           if (MO.clobbersPhysReg(Def)) {
35906c3fb27SDimitry Andric             LLVM_DEBUG(dbgs() << "MCP: Removed tracking of "
36006c3fb27SDimitry Andric                               << printReg(Def, &TRI) << "\n");
36106c3fb27SDimitry Andric             return nullptr;
36206c3fb27SDimitry Andric           }
36306c3fb27SDimitry Andric 
36406c3fb27SDimitry Andric     return DefCopy;
36506c3fb27SDimitry Andric   }
36606c3fb27SDimitry Andric 
36706c3fb27SDimitry Andric   // Find last COPY that uses Reg.
36806c3fb27SDimitry Andric   MachineInstr *findLastSeenUseInCopy(MCRegister Reg,
36906c3fb27SDimitry Andric                                       const TargetRegisterInfo &TRI) {
37006c3fb27SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
37106c3fb27SDimitry Andric     auto CI = Copies.find(RU);
37206c3fb27SDimitry Andric     if (CI == Copies.end())
37306c3fb27SDimitry Andric       return nullptr;
37406c3fb27SDimitry Andric     return CI->second.LastSeenUseInCopy;
37506c3fb27SDimitry Andric   }
37606c3fb27SDimitry Andric 
3770b57cec5SDimitry Andric   void clear() {
3780b57cec5SDimitry Andric     Copies.clear();
3790b57cec5SDimitry Andric   }
3800b57cec5SDimitry Andric };
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric class MachineCopyPropagation : public MachineFunctionPass {
38306c3fb27SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
38406c3fb27SDimitry Andric   const TargetInstrInfo *TII = nullptr;
38506c3fb27SDimitry Andric   const MachineRegisterInfo *MRI = nullptr;
3860b57cec5SDimitry Andric 
38781ad6265SDimitry Andric   // Return true if this is a copy instruction and false otherwise.
38881ad6265SDimitry Andric   bool UseCopyInstr;
38981ad6265SDimitry Andric 
3900b57cec5SDimitry Andric public:
3910b57cec5SDimitry Andric   static char ID; // Pass identification, replacement for typeid
3920b57cec5SDimitry Andric 
39381ad6265SDimitry Andric   MachineCopyPropagation(bool CopyInstr = false)
39481ad6265SDimitry Andric       : MachineFunctionPass(ID), UseCopyInstr(CopyInstr || MCPUseCopyInstr) {
3950b57cec5SDimitry Andric     initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
3960b57cec5SDimitry Andric   }
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
3990b57cec5SDimitry Andric     AU.setPreservesCFG();
4000b57cec5SDimitry Andric     MachineFunctionPass::getAnalysisUsage(AU);
4010b57cec5SDimitry Andric   }
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric   MachineFunctionProperties getRequiredProperties() const override {
4060b57cec5SDimitry Andric     return MachineFunctionProperties().set(
4070b57cec5SDimitry Andric         MachineFunctionProperties::Property::NoVRegs);
4080b57cec5SDimitry Andric   }
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric private:
4118bcb0991SDimitry Andric   typedef enum { DebugUse = false, RegularUse = true } DebugType;
4128bcb0991SDimitry Andric 
413e8d8bef9SDimitry Andric   void ReadRegister(MCRegister Reg, MachineInstr &Reader, DebugType DT);
414480093f4SDimitry Andric   void ForwardCopyPropagateBlock(MachineBasicBlock &MBB);
415480093f4SDimitry Andric   void BackwardCopyPropagateBlock(MachineBasicBlock &MBB);
41606c3fb27SDimitry Andric   void EliminateSpillageCopies(MachineBasicBlock &MBB);
417e8d8bef9SDimitry Andric   bool eraseIfRedundant(MachineInstr &Copy, MCRegister Src, MCRegister Def);
4180b57cec5SDimitry Andric   void forwardUses(MachineInstr &MI);
419480093f4SDimitry Andric   void propagateDefs(MachineInstr &MI);
4200b57cec5SDimitry Andric   bool isForwardableRegClassCopy(const MachineInstr &Copy,
4210b57cec5SDimitry Andric                                  const MachineInstr &UseI, unsigned UseIdx);
422480093f4SDimitry Andric   bool isBackwardPropagatableRegClassCopy(const MachineInstr &Copy,
423480093f4SDimitry Andric                                           const MachineInstr &UseI,
424480093f4SDimitry Andric                                           unsigned UseIdx);
4250b57cec5SDimitry Andric   bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
426e8d8bef9SDimitry Andric   bool hasOverlappingMultipleDef(const MachineInstr &MI,
427e8d8bef9SDimitry Andric                                  const MachineOperand &MODef, Register Def);
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   /// Candidates for deletion.
4300b57cec5SDimitry Andric   SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
4310b57cec5SDimitry Andric 
4328bcb0991SDimitry Andric   /// Multimap tracking debug users in current BB
433fe6060f1SDimitry Andric   DenseMap<MachineInstr *, SmallSet<MachineInstr *, 2>> CopyDbgUsers;
4348bcb0991SDimitry Andric 
4350b57cec5SDimitry Andric   CopyTracker Tracker;
4360b57cec5SDimitry Andric 
43706c3fb27SDimitry Andric   bool Changed = false;
4380b57cec5SDimitry Andric };
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric } // end anonymous namespace
4410b57cec5SDimitry Andric 
4420b57cec5SDimitry Andric char MachineCopyPropagation::ID = 0;
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
4470b57cec5SDimitry Andric                 "Machine Copy Propagation Pass", false, false)
4480b57cec5SDimitry Andric 
449e8d8bef9SDimitry Andric void MachineCopyPropagation::ReadRegister(MCRegister Reg, MachineInstr &Reader,
4508bcb0991SDimitry Andric                                           DebugType DT) {
4510b57cec5SDimitry Andric   // If 'Reg' is defined by a copy, the copy is no longer a candidate
4528bcb0991SDimitry Andric   // for elimination. If a copy is "read" by a debug user, record the user
4538bcb0991SDimitry Andric   // for propagation.
45406c3fb27SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(Reg)) {
45506c3fb27SDimitry Andric     if (MachineInstr *Copy = Tracker.findCopyForUnit(Unit, *TRI)) {
4568bcb0991SDimitry Andric       if (DT == RegularUse) {
4570b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
4580b57cec5SDimitry Andric         MaybeDeadCopies.remove(Copy);
4598bcb0991SDimitry Andric       } else {
460fe6060f1SDimitry Andric         CopyDbgUsers[Copy].insert(&Reader);
4618bcb0991SDimitry Andric       }
4620b57cec5SDimitry Andric     }
4630b57cec5SDimitry Andric   }
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric /// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
4670b57cec5SDimitry Andric /// This fact may have been obscured by sub register usage or may not be true at
4680b57cec5SDimitry Andric /// all even though Src and Def are subregisters of the registers used in
4690b57cec5SDimitry Andric /// PreviousCopy. e.g.
4700b57cec5SDimitry Andric /// isNopCopy("ecx = COPY eax", AX, CX) == true
4710b57cec5SDimitry Andric /// isNopCopy("ecx = COPY eax", AH, CL) == false
472e8d8bef9SDimitry Andric static bool isNopCopy(const MachineInstr &PreviousCopy, MCRegister Src,
47381ad6265SDimitry Andric                       MCRegister Def, const TargetRegisterInfo *TRI,
47481ad6265SDimitry Andric                       const TargetInstrInfo *TII, bool UseCopyInstr) {
47581ad6265SDimitry Andric 
476bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
47781ad6265SDimitry Andric       isCopyInstr(PreviousCopy, *TII, UseCopyInstr);
47881ad6265SDimitry Andric   MCRegister PreviousSrc = CopyOperands->Source->getReg().asMCReg();
47981ad6265SDimitry Andric   MCRegister PreviousDef = CopyOperands->Destination->getReg().asMCReg();
48016d6b3b3SDimitry Andric   if (Src == PreviousSrc && Def == PreviousDef)
4810b57cec5SDimitry Andric     return true;
4820b57cec5SDimitry Andric   if (!TRI->isSubRegister(PreviousSrc, Src))
4830b57cec5SDimitry Andric     return false;
4840b57cec5SDimitry Andric   unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
4850b57cec5SDimitry Andric   return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric /// Remove instruction \p Copy if there exists a previous copy that copies the
4890b57cec5SDimitry Andric /// register \p Src to the register \p Def; This may happen indirectly by
4900b57cec5SDimitry Andric /// copying the super registers.
491e8d8bef9SDimitry Andric bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy,
492e8d8bef9SDimitry Andric                                               MCRegister Src, MCRegister Def) {
4930b57cec5SDimitry Andric   // Avoid eliminating a copy from/to a reserved registers as we cannot predict
4940b57cec5SDimitry Andric   // the value (Example: The sparc zero register is writable but stays zero).
4950b57cec5SDimitry Andric   if (MRI->isReserved(Src) || MRI->isReserved(Def))
4960b57cec5SDimitry Andric     return false;
4970b57cec5SDimitry Andric 
4980b57cec5SDimitry Andric   // Search for an existing copy.
49981ad6265SDimitry Andric   MachineInstr *PrevCopy =
50081ad6265SDimitry Andric       Tracker.findAvailCopy(Copy, Def, *TRI, *TII, UseCopyInstr);
5010b57cec5SDimitry Andric   if (!PrevCopy)
5020b57cec5SDimitry Andric     return false;
5030b57cec5SDimitry Andric 
50481ad6265SDimitry Andric   auto PrevCopyOperands = isCopyInstr(*PrevCopy, *TII, UseCopyInstr);
5050b57cec5SDimitry Andric   // Check that the existing copy uses the correct sub registers.
50681ad6265SDimitry Andric   if (PrevCopyOperands->Destination->isDead())
5070b57cec5SDimitry Andric     return false;
50881ad6265SDimitry Andric   if (!isNopCopy(*PrevCopy, Src, Def, TRI, TII, UseCopyInstr))
5090b57cec5SDimitry Andric     return false;
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
5120b57cec5SDimitry Andric 
5130b57cec5SDimitry Andric   // Copy was redundantly redefining either Src or Def. Remove earlier kill
5140b57cec5SDimitry Andric   // flags between Copy and PrevCopy because the value will be reused now.
515bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
516bdd1243dSDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
51781ad6265SDimitry Andric   assert(CopyOperands);
51881ad6265SDimitry Andric 
51981ad6265SDimitry Andric   Register CopyDef = CopyOperands->Destination->getReg();
5200b57cec5SDimitry Andric   assert(CopyDef == Src || CopyDef == Def);
5210b57cec5SDimitry Andric   for (MachineInstr &MI :
5220b57cec5SDimitry Andric        make_range(PrevCopy->getIterator(), Copy.getIterator()))
5230b57cec5SDimitry Andric     MI.clearRegisterKills(CopyDef, TRI);
5240b57cec5SDimitry Andric 
52506c3fb27SDimitry Andric   // Clear undef flag from remaining copy if needed.
52606c3fb27SDimitry Andric   if (!CopyOperands->Source->isUndef()) {
52706c3fb27SDimitry Andric     PrevCopy->getOperand(PrevCopyOperands->Source->getOperandNo())
52806c3fb27SDimitry Andric         .setIsUndef(false);
52906c3fb27SDimitry Andric   }
53006c3fb27SDimitry Andric 
5310b57cec5SDimitry Andric   Copy.eraseFromParent();
5320b57cec5SDimitry Andric   Changed = true;
5330b57cec5SDimitry Andric   ++NumDeletes;
5340b57cec5SDimitry Andric   return true;
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric 
537480093f4SDimitry Andric bool MachineCopyPropagation::isBackwardPropagatableRegClassCopy(
538480093f4SDimitry Andric     const MachineInstr &Copy, const MachineInstr &UseI, unsigned UseIdx) {
539bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
540bdd1243dSDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
54181ad6265SDimitry Andric   Register Def = CopyOperands->Destination->getReg();
542480093f4SDimitry Andric 
543480093f4SDimitry Andric   if (const TargetRegisterClass *URC =
544480093f4SDimitry Andric           UseI.getRegClassConstraint(UseIdx, TII, TRI))
545480093f4SDimitry Andric     return URC->contains(Def);
546480093f4SDimitry Andric 
547480093f4SDimitry Andric   // We don't process further if UseI is a COPY, since forward copy propagation
548480093f4SDimitry Andric   // should handle that.
549480093f4SDimitry Andric   return false;
550480093f4SDimitry Andric }
551480093f4SDimitry Andric 
5520b57cec5SDimitry Andric /// Decide whether we should forward the source of \param Copy to its use in
5530b57cec5SDimitry Andric /// \param UseI based on the physical register class constraints of the opcode
5540b57cec5SDimitry Andric /// and avoiding introducing more cross-class COPYs.
5550b57cec5SDimitry Andric bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
5560b57cec5SDimitry Andric                                                        const MachineInstr &UseI,
5570b57cec5SDimitry Andric                                                        unsigned UseIdx) {
558bdd1243dSDimitry Andric   std::optional<DestSourcePair> CopyOperands =
559bdd1243dSDimitry Andric       isCopyInstr(Copy, *TII, UseCopyInstr);
56081ad6265SDimitry Andric   Register CopySrcReg = CopyOperands->Source->getReg();
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   // If the new register meets the opcode register constraints, then allow
5630b57cec5SDimitry Andric   // forwarding.
5640b57cec5SDimitry Andric   if (const TargetRegisterClass *URC =
5650b57cec5SDimitry Andric           UseI.getRegClassConstraint(UseIdx, TII, TRI))
5660b57cec5SDimitry Andric     return URC->contains(CopySrcReg);
5670b57cec5SDimitry Andric 
56881ad6265SDimitry Andric   auto UseICopyOperands = isCopyInstr(UseI, *TII, UseCopyInstr);
56981ad6265SDimitry Andric   if (!UseICopyOperands)
5700b57cec5SDimitry Andric     return false;
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   /// COPYs don't have register class constraints, so if the user instruction
5730b57cec5SDimitry Andric   /// is a COPY, we just try to avoid introducing additional cross-class
5740b57cec5SDimitry Andric   /// COPYs.  For example:
5750b57cec5SDimitry Andric   ///
5760b57cec5SDimitry Andric   ///   RegClassA = COPY RegClassB  // Copy parameter
5770b57cec5SDimitry Andric   ///   ...
5780b57cec5SDimitry Andric   ///   RegClassB = COPY RegClassA  // UseI parameter
5790b57cec5SDimitry Andric   ///
5800b57cec5SDimitry Andric   /// which after forwarding becomes
5810b57cec5SDimitry Andric   ///
5820b57cec5SDimitry Andric   ///   RegClassA = COPY RegClassB
5830b57cec5SDimitry Andric   ///   ...
5840b57cec5SDimitry Andric   ///   RegClassB = COPY RegClassB
5850b57cec5SDimitry Andric   ///
5860b57cec5SDimitry Andric   /// so we have reduced the number of cross-class COPYs and potentially
5870b57cec5SDimitry Andric   /// introduced a nop COPY that can be removed.
5880b57cec5SDimitry Andric 
58981ad6265SDimitry Andric   // Allow forwarding if src and dst belong to any common class, so long as they
59081ad6265SDimitry Andric   // don't belong to any (possibly smaller) common class that requires copies to
59181ad6265SDimitry Andric   // go via a different class.
59281ad6265SDimitry Andric   Register UseDstReg = UseICopyOperands->Destination->getReg();
59381ad6265SDimitry Andric   bool Found = false;
59481ad6265SDimitry Andric   bool IsCrossClass = false;
59581ad6265SDimitry Andric   for (const TargetRegisterClass *RC : TRI->regclasses()) {
59681ad6265SDimitry Andric     if (RC->contains(CopySrcReg) && RC->contains(UseDstReg)) {
59781ad6265SDimitry Andric       Found = true;
59881ad6265SDimitry Andric       if (TRI->getCrossCopyRegClass(RC) != RC) {
59981ad6265SDimitry Andric         IsCrossClass = true;
60081ad6265SDimitry Andric         break;
60181ad6265SDimitry Andric       }
60281ad6265SDimitry Andric     }
60381ad6265SDimitry Andric   }
60481ad6265SDimitry Andric   if (!Found)
60581ad6265SDimitry Andric     return false;
60681ad6265SDimitry Andric   if (!IsCrossClass)
60781ad6265SDimitry Andric     return true;
60881ad6265SDimitry Andric   // The forwarded copy would be cross-class. Only do this if the original copy
60981ad6265SDimitry Andric   // was also cross-class.
61081ad6265SDimitry Andric   Register CopyDstReg = CopyOperands->Destination->getReg();
61181ad6265SDimitry Andric   for (const TargetRegisterClass *RC : TRI->regclasses()) {
61281ad6265SDimitry Andric     if (RC->contains(CopySrcReg) && RC->contains(CopyDstReg) &&
61381ad6265SDimitry Andric         TRI->getCrossCopyRegClass(RC) != RC)
61481ad6265SDimitry Andric       return true;
61581ad6265SDimitry Andric   }
6160b57cec5SDimitry Andric   return false;
6170b57cec5SDimitry Andric }
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric /// Check that \p MI does not have implicit uses that overlap with it's \p Use
6200b57cec5SDimitry Andric /// operand (the register being replaced), since these can sometimes be
6210b57cec5SDimitry Andric /// implicitly tied to other operands.  For example, on AMDGPU:
6220b57cec5SDimitry Andric ///
6230b57cec5SDimitry Andric /// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
6240b57cec5SDimitry Andric ///
6250b57cec5SDimitry Andric /// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
6260b57cec5SDimitry Andric /// way of knowing we need to update the latter when updating the former.
6270b57cec5SDimitry Andric bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
6280b57cec5SDimitry Andric                                                 const MachineOperand &Use) {
6290b57cec5SDimitry Andric   for (const MachineOperand &MIUse : MI.uses())
6300b57cec5SDimitry Andric     if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
6310b57cec5SDimitry Andric         MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
6320b57cec5SDimitry Andric       return true;
6330b57cec5SDimitry Andric 
6340b57cec5SDimitry Andric   return false;
6350b57cec5SDimitry Andric }
6360b57cec5SDimitry Andric 
637e8d8bef9SDimitry Andric /// For an MI that has multiple definitions, check whether \p MI has
638e8d8bef9SDimitry Andric /// a definition that overlaps with another of its definitions.
639e8d8bef9SDimitry Andric /// For example, on ARM: umull   r9, r9, lr, r0
640e8d8bef9SDimitry Andric /// The umull instruction is unpredictable unless RdHi and RdLo are different.
641e8d8bef9SDimitry Andric bool MachineCopyPropagation::hasOverlappingMultipleDef(
642e8d8bef9SDimitry Andric     const MachineInstr &MI, const MachineOperand &MODef, Register Def) {
643e8d8bef9SDimitry Andric   for (const MachineOperand &MIDef : MI.defs()) {
644e8d8bef9SDimitry Andric     if ((&MIDef != &MODef) && MIDef.isReg() &&
645e8d8bef9SDimitry Andric         TRI->regsOverlap(Def, MIDef.getReg()))
646e8d8bef9SDimitry Andric       return true;
647e8d8bef9SDimitry Andric   }
648e8d8bef9SDimitry Andric 
649e8d8bef9SDimitry Andric   return false;
650e8d8bef9SDimitry Andric }
651e8d8bef9SDimitry Andric 
6520b57cec5SDimitry Andric /// Look for available copies whose destination register is used by \p MI and
6530b57cec5SDimitry Andric /// replace the use in \p MI with the copy's source register.
6540b57cec5SDimitry Andric void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
6550b57cec5SDimitry Andric   if (!Tracker.hasAnyCopies())
6560b57cec5SDimitry Andric     return;
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   // Look for non-tied explicit vreg uses that have an active COPY
6590b57cec5SDimitry Andric   // instruction that defines the physical register allocated to them.
6600b57cec5SDimitry Andric   // Replace the vreg with the source of the active COPY.
6610b57cec5SDimitry Andric   for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
6620b57cec5SDimitry Andric        ++OpIdx) {
6630b57cec5SDimitry Andric     MachineOperand &MOUse = MI.getOperand(OpIdx);
6640b57cec5SDimitry Andric     // Don't forward into undef use operands since doing so can cause problems
6650b57cec5SDimitry Andric     // with the machine verifier, since it doesn't treat undef reads as reads,
6660b57cec5SDimitry Andric     // so we can end up with a live range that ends on an undef read, leading to
6670b57cec5SDimitry Andric     // an error that the live range doesn't end on a read of the live range
6680b57cec5SDimitry Andric     // register.
6690b57cec5SDimitry Andric     if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
6700b57cec5SDimitry Andric         MOUse.isImplicit())
6710b57cec5SDimitry Andric       continue;
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric     if (!MOUse.getReg())
6740b57cec5SDimitry Andric       continue;
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric     // Check that the register is marked 'renamable' so we know it is safe to
6770b57cec5SDimitry Andric     // rename it without violating any constraints that aren't expressed in the
6780b57cec5SDimitry Andric     // IR (e.g. ABI or opcode requirements).
6790b57cec5SDimitry Andric     if (!MOUse.isRenamable())
6800b57cec5SDimitry Andric       continue;
6810b57cec5SDimitry Andric 
68281ad6265SDimitry Andric     MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg().asMCReg(),
68381ad6265SDimitry Andric                                                *TRI, *TII, UseCopyInstr);
6840b57cec5SDimitry Andric     if (!Copy)
6850b57cec5SDimitry Andric       continue;
6860b57cec5SDimitry Andric 
687bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
68881ad6265SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
68981ad6265SDimitry Andric     Register CopyDstReg = CopyOperands->Destination->getReg();
69081ad6265SDimitry Andric     const MachineOperand &CopySrc = *CopyOperands->Source;
6918bcb0991SDimitry Andric     Register CopySrcReg = CopySrc.getReg();
6920b57cec5SDimitry Andric 
69306c3fb27SDimitry Andric     Register ForwardedReg = CopySrcReg;
69406c3fb27SDimitry Andric     // MI might use a sub-register of the Copy destination, in which case the
69506c3fb27SDimitry Andric     // forwarded register is the matching sub-register of the Copy source.
6960b57cec5SDimitry Andric     if (MOUse.getReg() != CopyDstReg) {
69706c3fb27SDimitry Andric       unsigned SubRegIdx = TRI->getSubRegIndex(CopyDstReg, MOUse.getReg());
69806c3fb27SDimitry Andric       assert(SubRegIdx &&
69906c3fb27SDimitry Andric              "MI source is not a sub-register of Copy destination");
70006c3fb27SDimitry Andric       ForwardedReg = TRI->getSubReg(CopySrcReg, SubRegIdx);
70106c3fb27SDimitry Andric       if (!ForwardedReg) {
70206c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy source does not have sub-register "
70306c3fb27SDimitry Andric                           << TRI->getSubRegIndexName(SubRegIdx) << '\n');
7040b57cec5SDimitry Andric         continue;
7050b57cec5SDimitry Andric       }
70606c3fb27SDimitry Andric     }
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric     // Don't forward COPYs of reserved regs unless they are constant.
7090b57cec5SDimitry Andric     if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
7100b57cec5SDimitry Andric       continue;
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric     if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
7130b57cec5SDimitry Andric       continue;
7140b57cec5SDimitry Andric 
7150b57cec5SDimitry Andric     if (hasImplicitOverlap(MI, MOUse))
7160b57cec5SDimitry Andric       continue;
7170b57cec5SDimitry Andric 
718480093f4SDimitry Andric     // Check that the instruction is not a copy that partially overwrites the
719480093f4SDimitry Andric     // original copy source that we are about to use. The tracker mechanism
720480093f4SDimitry Andric     // cannot cope with that.
72181ad6265SDimitry Andric     if (isCopyInstr(MI, *TII, UseCopyInstr) &&
72281ad6265SDimitry Andric         MI.modifiesRegister(CopySrcReg, TRI) &&
723480093f4SDimitry Andric         !MI.definesRegister(CopySrcReg)) {
724480093f4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Copy source overlap with dest in " << MI);
725480093f4SDimitry Andric       continue;
726480093f4SDimitry Andric     }
727480093f4SDimitry Andric 
7280b57cec5SDimitry Andric     if (!DebugCounter::shouldExecute(FwdCounter)) {
7290b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n  "
7300b57cec5SDimitry Andric                         << MI);
7310b57cec5SDimitry Andric       continue;
7320b57cec5SDimitry Andric     }
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
73506c3fb27SDimitry Andric                       << "\n     with " << printReg(ForwardedReg, TRI)
7360b57cec5SDimitry Andric                       << "\n     in " << MI << "     from " << *Copy);
7370b57cec5SDimitry Andric 
73806c3fb27SDimitry Andric     MOUse.setReg(ForwardedReg);
73906c3fb27SDimitry Andric 
7400b57cec5SDimitry Andric     if (!CopySrc.isRenamable())
7410b57cec5SDimitry Andric       MOUse.setIsRenamable(false);
742349cc55cSDimitry Andric     MOUse.setIsUndef(CopySrc.isUndef());
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric     // Clear kill markers that may have been invalidated.
7470b57cec5SDimitry Andric     for (MachineInstr &KMI :
7480b57cec5SDimitry Andric          make_range(Copy->getIterator(), std::next(MI.getIterator())))
7490b57cec5SDimitry Andric       KMI.clearRegisterKills(CopySrcReg, TRI);
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric     ++NumCopyForwards;
7520b57cec5SDimitry Andric     Changed = true;
7530b57cec5SDimitry Andric   }
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric 
756480093f4SDimitry Andric void MachineCopyPropagation::ForwardCopyPropagateBlock(MachineBasicBlock &MBB) {
757480093f4SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: ForwardCopyPropagateBlock " << MBB.getName()
758480093f4SDimitry Andric                     << "\n");
7590b57cec5SDimitry Andric 
760349cc55cSDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
7610b57cec5SDimitry Andric     // Analyze copies (which don't overlap themselves).
762bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
763bdd1243dSDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
76481ad6265SDimitry Andric     if (CopyOperands) {
76581ad6265SDimitry Andric 
76681ad6265SDimitry Andric       Register RegSrc = CopyOperands->Source->getReg();
76781ad6265SDimitry Andric       Register RegDef = CopyOperands->Destination->getReg();
76881ad6265SDimitry Andric 
76981ad6265SDimitry Andric       if (!TRI->regsOverlap(RegDef, RegSrc)) {
77081ad6265SDimitry Andric         assert(RegDef.isPhysical() && RegSrc.isPhysical() &&
7710b57cec5SDimitry Andric               "MachineCopyPropagation should be run after register allocation!");
7720b57cec5SDimitry Andric 
77381ad6265SDimitry Andric         MCRegister Def = RegDef.asMCReg();
77481ad6265SDimitry Andric         MCRegister Src = RegSrc.asMCReg();
775e8d8bef9SDimitry Andric 
7760b57cec5SDimitry Andric         // The two copies cancel out and the source of the first copy
7770b57cec5SDimitry Andric         // hasn't been overridden, eliminate the second one. e.g.
7780b57cec5SDimitry Andric         //  %ecx = COPY %eax
7790b57cec5SDimitry Andric         //  ... nothing clobbered eax.
7800b57cec5SDimitry Andric         //  %eax = COPY %ecx
7810b57cec5SDimitry Andric         // =>
7820b57cec5SDimitry Andric         //  %ecx = COPY %eax
7830b57cec5SDimitry Andric         //
7840b57cec5SDimitry Andric         // or
7850b57cec5SDimitry Andric         //
7860b57cec5SDimitry Andric         //  %ecx = COPY %eax
7870b57cec5SDimitry Andric         //  ... nothing clobbered eax.
7880b57cec5SDimitry Andric         //  %ecx = COPY %eax
7890b57cec5SDimitry Andric         // =>
7900b57cec5SDimitry Andric         //  %ecx = COPY %eax
791349cc55cSDimitry Andric         if (eraseIfRedundant(MI, Def, Src) || eraseIfRedundant(MI, Src, Def))
7920b57cec5SDimitry Andric           continue;
7930b57cec5SDimitry Andric 
794349cc55cSDimitry Andric         forwardUses(MI);
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric         // Src may have been changed by forwardUses()
79781ad6265SDimitry Andric         CopyOperands = isCopyInstr(MI, *TII, UseCopyInstr);
79881ad6265SDimitry Andric         Src = CopyOperands->Source->getReg().asMCReg();
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric         // If Src is defined by a previous copy, the previous copy cannot be
8010b57cec5SDimitry Andric         // eliminated.
802349cc55cSDimitry Andric         ReadRegister(Src, MI, RegularUse);
803349cc55cSDimitry Andric         for (const MachineOperand &MO : MI.implicit_operands()) {
8040b57cec5SDimitry Andric           if (!MO.isReg() || !MO.readsReg())
8050b57cec5SDimitry Andric             continue;
806e8d8bef9SDimitry Andric           MCRegister Reg = MO.getReg().asMCReg();
8070b57cec5SDimitry Andric           if (!Reg)
8080b57cec5SDimitry Andric             continue;
809349cc55cSDimitry Andric           ReadRegister(Reg, MI, RegularUse);
8100b57cec5SDimitry Andric         }
8110b57cec5SDimitry Andric 
812349cc55cSDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI.dump());
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric         // Copy is now a candidate for deletion.
8150b57cec5SDimitry Andric         if (!MRI->isReserved(Def))
816349cc55cSDimitry Andric           MaybeDeadCopies.insert(&MI);
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric         // If 'Def' is previously source of another copy, then this earlier copy's
8190b57cec5SDimitry Andric         // source is no longer available. e.g.
8200b57cec5SDimitry Andric         // %xmm9 = copy %xmm2
8210b57cec5SDimitry Andric         // ...
8220b57cec5SDimitry Andric         // %xmm2 = copy %xmm0
8230b57cec5SDimitry Andric         // ...
8240b57cec5SDimitry Andric         // %xmm2 = copy %xmm9
82581ad6265SDimitry Andric         Tracker.clobberRegister(Def, *TRI, *TII, UseCopyInstr);
826349cc55cSDimitry Andric         for (const MachineOperand &MO : MI.implicit_operands()) {
8270b57cec5SDimitry Andric           if (!MO.isReg() || !MO.isDef())
8280b57cec5SDimitry Andric             continue;
829e8d8bef9SDimitry Andric           MCRegister Reg = MO.getReg().asMCReg();
8300b57cec5SDimitry Andric           if (!Reg)
8310b57cec5SDimitry Andric             continue;
83281ad6265SDimitry Andric           Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
8330b57cec5SDimitry Andric         }
8340b57cec5SDimitry Andric 
83581ad6265SDimitry Andric         Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric         continue;
8380b57cec5SDimitry Andric       }
83981ad6265SDimitry Andric     }
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric     // Clobber any earlyclobber regs first.
842349cc55cSDimitry Andric     for (const MachineOperand &MO : MI.operands())
8430b57cec5SDimitry Andric       if (MO.isReg() && MO.isEarlyClobber()) {
844e8d8bef9SDimitry Andric         MCRegister Reg = MO.getReg().asMCReg();
8450b57cec5SDimitry Andric         // If we have a tied earlyclobber, that means it is also read by this
8460b57cec5SDimitry Andric         // instruction, so we need to make sure we don't remove it as dead
8470b57cec5SDimitry Andric         // later.
8480b57cec5SDimitry Andric         if (MO.isTied())
849349cc55cSDimitry Andric           ReadRegister(Reg, MI, RegularUse);
85081ad6265SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
8510b57cec5SDimitry Andric       }
8520b57cec5SDimitry Andric 
853349cc55cSDimitry Andric     forwardUses(MI);
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric     // Not a copy.
856e8d8bef9SDimitry Andric     SmallVector<Register, 2> Defs;
8570b57cec5SDimitry Andric     const MachineOperand *RegMask = nullptr;
858349cc55cSDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
8590b57cec5SDimitry Andric       if (MO.isRegMask())
8600b57cec5SDimitry Andric         RegMask = &MO;
8610b57cec5SDimitry Andric       if (!MO.isReg())
8620b57cec5SDimitry Andric         continue;
8638bcb0991SDimitry Andric       Register Reg = MO.getReg();
8640b57cec5SDimitry Andric       if (!Reg)
8650b57cec5SDimitry Andric         continue;
8660b57cec5SDimitry Andric 
867e8d8bef9SDimitry Andric       assert(!Reg.isVirtual() &&
8680b57cec5SDimitry Andric              "MachineCopyPropagation should be run after register allocation!");
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric       if (MO.isDef() && !MO.isEarlyClobber()) {
871e8d8bef9SDimitry Andric         Defs.push_back(Reg.asMCReg());
8720b57cec5SDimitry Andric         continue;
8738bcb0991SDimitry Andric       } else if (MO.readsReg())
874349cc55cSDimitry Andric         ReadRegister(Reg.asMCReg(), MI, MO.isDebug() ? DebugUse : RegularUse);
8750b57cec5SDimitry Andric     }
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric     // The instruction has a register mask operand which means that it clobbers
8780b57cec5SDimitry Andric     // a large set of registers.  Treat clobbered registers the same way as
8790b57cec5SDimitry Andric     // defined registers.
8800b57cec5SDimitry Andric     if (RegMask) {
8810b57cec5SDimitry Andric       // Erase any MaybeDeadCopies whose destination register is clobbered.
8820b57cec5SDimitry Andric       for (SmallSetVector<MachineInstr *, 8>::iterator DI =
8830b57cec5SDimitry Andric                MaybeDeadCopies.begin();
8840b57cec5SDimitry Andric            DI != MaybeDeadCopies.end();) {
8850b57cec5SDimitry Andric         MachineInstr *MaybeDead = *DI;
886bdd1243dSDimitry Andric         std::optional<DestSourcePair> CopyOperands =
88781ad6265SDimitry Andric             isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
88881ad6265SDimitry Andric         MCRegister Reg = CopyOperands->Destination->getReg().asMCReg();
8890b57cec5SDimitry Andric         assert(!MRI->isReserved(Reg));
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric         if (!RegMask->clobbersPhysReg(Reg)) {
8920b57cec5SDimitry Andric           ++DI;
8930b57cec5SDimitry Andric           continue;
8940b57cec5SDimitry Andric         }
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
8970b57cec5SDimitry Andric                    MaybeDead->dump());
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric         // Make sure we invalidate any entries in the copy maps before erasing
9000b57cec5SDimitry Andric         // the instruction.
90181ad6265SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric         // erase() will return the next valid iterator pointing to the next
9040b57cec5SDimitry Andric         // element after the erased one.
9050b57cec5SDimitry Andric         DI = MaybeDeadCopies.erase(DI);
9060b57cec5SDimitry Andric         MaybeDead->eraseFromParent();
9070b57cec5SDimitry Andric         Changed = true;
9080b57cec5SDimitry Andric         ++NumDeletes;
9090b57cec5SDimitry Andric       }
9100b57cec5SDimitry Andric     }
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric     // Any previous copy definition or reading the Defs is no longer available.
913e8d8bef9SDimitry Andric     for (MCRegister Reg : Defs)
91481ad6265SDimitry Andric       Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
9150b57cec5SDimitry Andric   }
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   // If MBB doesn't have successors, delete the copies whose defs are not used.
9180b57cec5SDimitry Andric   // If MBB does have successors, then conservative assume the defs are live-out
9190b57cec5SDimitry Andric   // since we don't want to trust live-in lists.
9200b57cec5SDimitry Andric   if (MBB.succ_empty()) {
9210b57cec5SDimitry Andric     for (MachineInstr *MaybeDead : MaybeDeadCopies) {
9220b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
9230b57cec5SDimitry Andric                  MaybeDead->dump());
92481ad6265SDimitry Andric 
925bdd1243dSDimitry Andric       std::optional<DestSourcePair> CopyOperands =
92681ad6265SDimitry Andric           isCopyInstr(*MaybeDead, *TII, UseCopyInstr);
92781ad6265SDimitry Andric       assert(CopyOperands);
92881ad6265SDimitry Andric 
92981ad6265SDimitry Andric       Register SrcReg = CopyOperands->Source->getReg();
93081ad6265SDimitry Andric       Register DestReg = CopyOperands->Destination->getReg();
93181ad6265SDimitry Andric       assert(!MRI->isReserved(DestReg));
9320b57cec5SDimitry Andric 
9338bcb0991SDimitry Andric       // Update matching debug values, if any.
934fe6060f1SDimitry Andric       SmallVector<MachineInstr *> MaybeDeadDbgUsers(
935fe6060f1SDimitry Andric           CopyDbgUsers[MaybeDead].begin(), CopyDbgUsers[MaybeDead].end());
936fe6060f1SDimitry Andric       MRI->updateDbgUsersToReg(DestReg.asMCReg(), SrcReg.asMCReg(),
937fe6060f1SDimitry Andric                                MaybeDeadDbgUsers);
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric       MaybeDead->eraseFromParent();
9400b57cec5SDimitry Andric       Changed = true;
9410b57cec5SDimitry Andric       ++NumDeletes;
9420b57cec5SDimitry Andric     }
9430b57cec5SDimitry Andric   }
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric   MaybeDeadCopies.clear();
9468bcb0991SDimitry Andric   CopyDbgUsers.clear();
9470b57cec5SDimitry Andric   Tracker.clear();
9480b57cec5SDimitry Andric }
9490b57cec5SDimitry Andric 
95006c3fb27SDimitry Andric static bool isBackwardPropagatableCopy(const DestSourcePair &CopyOperands,
95181ad6265SDimitry Andric                                        const MachineRegisterInfo &MRI,
95206c3fb27SDimitry Andric                                        const TargetInstrInfo &TII) {
95306c3fb27SDimitry Andric   Register Def = CopyOperands.Destination->getReg();
95406c3fb27SDimitry Andric   Register Src = CopyOperands.Source->getReg();
955480093f4SDimitry Andric 
956480093f4SDimitry Andric   if (!Def || !Src)
957480093f4SDimitry Andric     return false;
958480093f4SDimitry Andric 
959480093f4SDimitry Andric   if (MRI.isReserved(Def) || MRI.isReserved(Src))
960480093f4SDimitry Andric     return false;
961480093f4SDimitry Andric 
96206c3fb27SDimitry Andric   return CopyOperands.Source->isRenamable() && CopyOperands.Source->isKill();
963480093f4SDimitry Andric }
964480093f4SDimitry Andric 
965480093f4SDimitry Andric void MachineCopyPropagation::propagateDefs(MachineInstr &MI) {
966480093f4SDimitry Andric   if (!Tracker.hasAnyCopies())
967480093f4SDimitry Andric     return;
968480093f4SDimitry Andric 
969480093f4SDimitry Andric   for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx != OpEnd;
970480093f4SDimitry Andric        ++OpIdx) {
971480093f4SDimitry Andric     MachineOperand &MODef = MI.getOperand(OpIdx);
972480093f4SDimitry Andric 
973480093f4SDimitry Andric     if (!MODef.isReg() || MODef.isUse())
974480093f4SDimitry Andric       continue;
975480093f4SDimitry Andric 
976480093f4SDimitry Andric     // Ignore non-trivial cases.
977480093f4SDimitry Andric     if (MODef.isTied() || MODef.isUndef() || MODef.isImplicit())
978480093f4SDimitry Andric       continue;
979480093f4SDimitry Andric 
980480093f4SDimitry Andric     if (!MODef.getReg())
981480093f4SDimitry Andric       continue;
982480093f4SDimitry Andric 
983480093f4SDimitry Andric     // We only handle if the register comes from a vreg.
984480093f4SDimitry Andric     if (!MODef.isRenamable())
985480093f4SDimitry Andric       continue;
986480093f4SDimitry Andric 
98781ad6265SDimitry Andric     MachineInstr *Copy = Tracker.findAvailBackwardCopy(
98881ad6265SDimitry Andric         MI, MODef.getReg().asMCReg(), *TRI, *TII, UseCopyInstr);
989480093f4SDimitry Andric     if (!Copy)
990480093f4SDimitry Andric       continue;
991480093f4SDimitry Andric 
992bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
99381ad6265SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
99481ad6265SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
99581ad6265SDimitry Andric     Register Src = CopyOperands->Source->getReg();
996480093f4SDimitry Andric 
997480093f4SDimitry Andric     if (MODef.getReg() != Src)
998480093f4SDimitry Andric       continue;
999480093f4SDimitry Andric 
1000480093f4SDimitry Andric     if (!isBackwardPropagatableRegClassCopy(*Copy, MI, OpIdx))
1001480093f4SDimitry Andric       continue;
1002480093f4SDimitry Andric 
1003480093f4SDimitry Andric     if (hasImplicitOverlap(MI, MODef))
1004480093f4SDimitry Andric       continue;
1005480093f4SDimitry Andric 
1006e8d8bef9SDimitry Andric     if (hasOverlappingMultipleDef(MI, MODef, Def))
1007e8d8bef9SDimitry Andric       continue;
1008e8d8bef9SDimitry Andric 
1009480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MODef.getReg(), TRI)
1010480093f4SDimitry Andric                       << "\n     with " << printReg(Def, TRI) << "\n     in "
1011480093f4SDimitry Andric                       << MI << "     from " << *Copy);
1012480093f4SDimitry Andric 
1013480093f4SDimitry Andric     MODef.setReg(Def);
101481ad6265SDimitry Andric     MODef.setIsRenamable(CopyOperands->Destination->isRenamable());
1015480093f4SDimitry Andric 
1016480093f4SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
1017480093f4SDimitry Andric     MaybeDeadCopies.insert(Copy);
1018480093f4SDimitry Andric     Changed = true;
1019480093f4SDimitry Andric     ++NumCopyBackwardPropagated;
1020480093f4SDimitry Andric   }
1021480093f4SDimitry Andric }
1022480093f4SDimitry Andric 
1023480093f4SDimitry Andric void MachineCopyPropagation::BackwardCopyPropagateBlock(
1024480093f4SDimitry Andric     MachineBasicBlock &MBB) {
1025480093f4SDimitry Andric   LLVM_DEBUG(dbgs() << "MCP: BackwardCopyPropagateBlock " << MBB.getName()
1026480093f4SDimitry Andric                     << "\n");
1027480093f4SDimitry Andric 
10280eae32dcSDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(llvm::reverse(MBB))) {
1029480093f4SDimitry Andric     // Ignore non-trivial COPYs.
1030bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
1031bdd1243dSDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
103281ad6265SDimitry Andric     if (CopyOperands && MI.getNumOperands() == 2) {
103381ad6265SDimitry Andric       Register DefReg = CopyOperands->Destination->getReg();
103481ad6265SDimitry Andric       Register SrcReg = CopyOperands->Source->getReg();
1035480093f4SDimitry Andric 
103681ad6265SDimitry Andric       if (!TRI->regsOverlap(DefReg, SrcReg)) {
1037480093f4SDimitry Andric         // Unlike forward cp, we don't invoke propagateDefs here,
1038480093f4SDimitry Andric         // just let forward cp do COPY-to-COPY propagation.
103906c3fb27SDimitry Andric         if (isBackwardPropagatableCopy(*CopyOperands, *MRI, *TII)) {
104006c3fb27SDimitry Andric           Tracker.invalidateRegister(SrcReg.asMCReg(), *TRI, *TII,
104106c3fb27SDimitry Andric                                      UseCopyInstr);
104206c3fb27SDimitry Andric           Tracker.invalidateRegister(DefReg.asMCReg(), *TRI, *TII,
104306c3fb27SDimitry Andric                                      UseCopyInstr);
104481ad6265SDimitry Andric           Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1045480093f4SDimitry Andric           continue;
1046480093f4SDimitry Andric         }
1047480093f4SDimitry Andric       }
104881ad6265SDimitry Andric     }
1049480093f4SDimitry Andric 
1050480093f4SDimitry Andric     // Invalidate any earlyclobber regs first.
10510eae32dcSDimitry Andric     for (const MachineOperand &MO : MI.operands())
1052480093f4SDimitry Andric       if (MO.isReg() && MO.isEarlyClobber()) {
1053e8d8bef9SDimitry Andric         MCRegister Reg = MO.getReg().asMCReg();
1054480093f4SDimitry Andric         if (!Reg)
1055480093f4SDimitry Andric           continue;
105681ad6265SDimitry Andric         Tracker.invalidateRegister(Reg, *TRI, *TII, UseCopyInstr);
1057480093f4SDimitry Andric       }
1058480093f4SDimitry Andric 
10590eae32dcSDimitry Andric     propagateDefs(MI);
10600eae32dcSDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
1061480093f4SDimitry Andric       if (!MO.isReg())
1062480093f4SDimitry Andric         continue;
1063480093f4SDimitry Andric 
1064480093f4SDimitry Andric       if (!MO.getReg())
1065480093f4SDimitry Andric         continue;
1066480093f4SDimitry Andric 
1067480093f4SDimitry Andric       if (MO.isDef())
106881ad6265SDimitry Andric         Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
106981ad6265SDimitry Andric                                    UseCopyInstr);
1070480093f4SDimitry Andric 
1071fe6060f1SDimitry Andric       if (MO.readsReg()) {
1072fe6060f1SDimitry Andric         if (MO.isDebug()) {
1073fe6060f1SDimitry Andric           //  Check if the register in the debug instruction is utilized
1074fe6060f1SDimitry Andric           // in a copy instruction, so we can update the debug info if the
1075fe6060f1SDimitry Andric           // register is changed.
107606c3fb27SDimitry Andric           for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
107706c3fb27SDimitry Andric             if (auto *Copy = Tracker.findCopyDefViaUnit(Unit, *TRI)) {
10780eae32dcSDimitry Andric               CopyDbgUsers[Copy].insert(&MI);
1079fe6060f1SDimitry Andric             }
1080fe6060f1SDimitry Andric           }
1081fe6060f1SDimitry Andric         } else {
108281ad6265SDimitry Andric           Tracker.invalidateRegister(MO.getReg().asMCReg(), *TRI, *TII,
108381ad6265SDimitry Andric                                      UseCopyInstr);
1084480093f4SDimitry Andric         }
1085480093f4SDimitry Andric       }
1086fe6060f1SDimitry Andric     }
1087fe6060f1SDimitry Andric   }
1088480093f4SDimitry Andric 
1089480093f4SDimitry Andric   for (auto *Copy : MaybeDeadCopies) {
1090bdd1243dSDimitry Andric     std::optional<DestSourcePair> CopyOperands =
109181ad6265SDimitry Andric         isCopyInstr(*Copy, *TII, UseCopyInstr);
109281ad6265SDimitry Andric     Register Src = CopyOperands->Source->getReg();
109381ad6265SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
1094fe6060f1SDimitry Andric     SmallVector<MachineInstr *> MaybeDeadDbgUsers(CopyDbgUsers[Copy].begin(),
1095fe6060f1SDimitry Andric                                                   CopyDbgUsers[Copy].end());
1096fe6060f1SDimitry Andric 
1097fe6060f1SDimitry Andric     MRI->updateDbgUsersToReg(Src.asMCReg(), Def.asMCReg(), MaybeDeadDbgUsers);
1098480093f4SDimitry Andric     Copy->eraseFromParent();
1099480093f4SDimitry Andric     ++NumDeletes;
1100480093f4SDimitry Andric   }
1101480093f4SDimitry Andric 
1102480093f4SDimitry Andric   MaybeDeadCopies.clear();
1103480093f4SDimitry Andric   CopyDbgUsers.clear();
1104480093f4SDimitry Andric   Tracker.clear();
1105480093f4SDimitry Andric }
1106480093f4SDimitry Andric 
110706c3fb27SDimitry Andric static void LLVM_ATTRIBUTE_UNUSED printSpillReloadChain(
110806c3fb27SDimitry Andric     DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &SpillChain,
110906c3fb27SDimitry Andric     DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &ReloadChain,
111006c3fb27SDimitry Andric     MachineInstr *Leader) {
111106c3fb27SDimitry Andric   auto &SC = SpillChain[Leader];
111206c3fb27SDimitry Andric   auto &RC = ReloadChain[Leader];
111306c3fb27SDimitry Andric   for (auto I = SC.rbegin(), E = SC.rend(); I != E; ++I)
111406c3fb27SDimitry Andric     (*I)->dump();
111506c3fb27SDimitry Andric   for (MachineInstr *MI : RC)
111606c3fb27SDimitry Andric     MI->dump();
111706c3fb27SDimitry Andric }
111806c3fb27SDimitry Andric 
111906c3fb27SDimitry Andric // Remove spill-reload like copy chains. For example
112006c3fb27SDimitry Andric // r0 = COPY r1
112106c3fb27SDimitry Andric // r1 = COPY r2
112206c3fb27SDimitry Andric // r2 = COPY r3
112306c3fb27SDimitry Andric // r3 = COPY r4
112406c3fb27SDimitry Andric // <def-use r4>
112506c3fb27SDimitry Andric // r4 = COPY r3
112606c3fb27SDimitry Andric // r3 = COPY r2
112706c3fb27SDimitry Andric // r2 = COPY r1
112806c3fb27SDimitry Andric // r1 = COPY r0
112906c3fb27SDimitry Andric // will be folded into
113006c3fb27SDimitry Andric // r0 = COPY r1
113106c3fb27SDimitry Andric // r1 = COPY r4
113206c3fb27SDimitry Andric // <def-use r4>
113306c3fb27SDimitry Andric // r4 = COPY r1
113406c3fb27SDimitry Andric // r1 = COPY r0
113506c3fb27SDimitry Andric // TODO: Currently we don't track usage of r0 outside the chain, so we
113606c3fb27SDimitry Andric // conservatively keep its value as it was before the rewrite.
113706c3fb27SDimitry Andric //
113806c3fb27SDimitry Andric // The algorithm is trying to keep
113906c3fb27SDimitry Andric // property#1: No Def of spill COPY in the chain is used or defined until the
114006c3fb27SDimitry Andric // paired reload COPY in the chain uses the Def.
114106c3fb27SDimitry Andric //
114206c3fb27SDimitry Andric // property#2: NO Source of COPY in the chain is used or defined until the next
114306c3fb27SDimitry Andric // COPY in the chain defines the Source, except the innermost spill-reload
114406c3fb27SDimitry Andric // pair.
114506c3fb27SDimitry Andric //
114606c3fb27SDimitry Andric // The algorithm is conducted by checking every COPY inside the MBB, assuming
114706c3fb27SDimitry Andric // the COPY is a reload COPY, then try to find paired spill COPY by searching
114806c3fb27SDimitry Andric // the COPY defines the Src of the reload COPY backward. If such pair is found,
114906c3fb27SDimitry Andric // it either belongs to an existing chain or a new chain depends on
115006c3fb27SDimitry Andric // last available COPY uses the Def of the reload COPY.
115106c3fb27SDimitry Andric // Implementation notes, we use CopyTracker::findLastDefCopy(Reg, ...) to find
115206c3fb27SDimitry Andric // out last COPY that defines Reg; we use CopyTracker::findLastUseCopy(Reg, ...)
115306c3fb27SDimitry Andric // to find out last COPY that uses Reg. When we are encountered with a Non-COPY
115406c3fb27SDimitry Andric // instruction, we check registers in the operands of this instruction. If this
115506c3fb27SDimitry Andric // Reg is defined by a COPY, we untrack this Reg via
115606c3fb27SDimitry Andric // CopyTracker::clobberRegister(Reg, ...).
115706c3fb27SDimitry Andric void MachineCopyPropagation::EliminateSpillageCopies(MachineBasicBlock &MBB) {
115806c3fb27SDimitry Andric   // ChainLeader maps MI inside a spill-reload chain to its innermost reload COPY.
115906c3fb27SDimitry Andric   // Thus we can track if a MI belongs to an existing spill-reload chain.
116006c3fb27SDimitry Andric   DenseMap<MachineInstr *, MachineInstr *> ChainLeader;
116106c3fb27SDimitry Andric   // SpillChain maps innermost reload COPY of a spill-reload chain to a sequence
116206c3fb27SDimitry Andric   // of COPYs that forms spills of a spill-reload chain.
116306c3fb27SDimitry Andric   // ReloadChain maps innermost reload COPY of a spill-reload chain to a
116406c3fb27SDimitry Andric   // sequence of COPYs that forms reloads of a spill-reload chain.
116506c3fb27SDimitry Andric   DenseMap<MachineInstr *, SmallVector<MachineInstr *>> SpillChain, ReloadChain;
116606c3fb27SDimitry Andric   // If a COPY's Source has use or def until next COPY defines the Source,
116706c3fb27SDimitry Andric   // we put the COPY in this set to keep property#2.
116806c3fb27SDimitry Andric   DenseSet<const MachineInstr *> CopySourceInvalid;
116906c3fb27SDimitry Andric 
117006c3fb27SDimitry Andric   auto TryFoldSpillageCopies =
117106c3fb27SDimitry Andric       [&, this](const SmallVectorImpl<MachineInstr *> &SC,
117206c3fb27SDimitry Andric                 const SmallVectorImpl<MachineInstr *> &RC) {
117306c3fb27SDimitry Andric         assert(SC.size() == RC.size() && "Spill-reload should be paired");
117406c3fb27SDimitry Andric 
117506c3fb27SDimitry Andric         // We need at least 3 pairs of copies for the transformation to apply,
117606c3fb27SDimitry Andric         // because the first outermost pair cannot be removed since we don't
117706c3fb27SDimitry Andric         // recolor outside of the chain and that we need at least one temporary
117806c3fb27SDimitry Andric         // spill slot to shorten the chain. If we only have a chain of two
117906c3fb27SDimitry Andric         // pairs, we already have the shortest sequence this code can handle:
118006c3fb27SDimitry Andric         // the outermost pair for the temporary spill slot, and the pair that
118106c3fb27SDimitry Andric         // use that temporary spill slot for the other end of the chain.
118206c3fb27SDimitry Andric         // TODO: We might be able to simplify to one spill-reload pair if collecting
118306c3fb27SDimitry Andric         // more infomation about the outermost COPY.
118406c3fb27SDimitry Andric         if (SC.size() <= 2)
118506c3fb27SDimitry Andric           return;
118606c3fb27SDimitry Andric 
118706c3fb27SDimitry Andric         // If violate property#2, we don't fold the chain.
11885f757f3fSDimitry Andric         for (const MachineInstr *Spill : drop_begin(SC))
118906c3fb27SDimitry Andric           if (CopySourceInvalid.count(Spill))
119006c3fb27SDimitry Andric             return;
119106c3fb27SDimitry Andric 
11925f757f3fSDimitry Andric         for (const MachineInstr *Reload : drop_end(RC))
119306c3fb27SDimitry Andric           if (CopySourceInvalid.count(Reload))
119406c3fb27SDimitry Andric             return;
119506c3fb27SDimitry Andric 
119606c3fb27SDimitry Andric         auto CheckCopyConstraint = [this](Register Def, Register Src) {
119706c3fb27SDimitry Andric           for (const TargetRegisterClass *RC : TRI->regclasses()) {
119806c3fb27SDimitry Andric             if (RC->contains(Def) && RC->contains(Src))
119906c3fb27SDimitry Andric               return true;
120006c3fb27SDimitry Andric           }
120106c3fb27SDimitry Andric           return false;
120206c3fb27SDimitry Andric         };
120306c3fb27SDimitry Andric 
120406c3fb27SDimitry Andric         auto UpdateReg = [](MachineInstr *MI, const MachineOperand *Old,
120506c3fb27SDimitry Andric                             const MachineOperand *New) {
120606c3fb27SDimitry Andric           for (MachineOperand &MO : MI->operands()) {
120706c3fb27SDimitry Andric             if (&MO == Old)
120806c3fb27SDimitry Andric               MO.setReg(New->getReg());
120906c3fb27SDimitry Andric           }
121006c3fb27SDimitry Andric         };
121106c3fb27SDimitry Andric 
121206c3fb27SDimitry Andric         std::optional<DestSourcePair> InnerMostSpillCopy =
121306c3fb27SDimitry Andric             isCopyInstr(*SC[0], *TII, UseCopyInstr);
121406c3fb27SDimitry Andric         std::optional<DestSourcePair> OuterMostSpillCopy =
121506c3fb27SDimitry Andric             isCopyInstr(*SC.back(), *TII, UseCopyInstr);
121606c3fb27SDimitry Andric         std::optional<DestSourcePair> InnerMostReloadCopy =
121706c3fb27SDimitry Andric             isCopyInstr(*RC[0], *TII, UseCopyInstr);
121806c3fb27SDimitry Andric         std::optional<DestSourcePair> OuterMostReloadCopy =
121906c3fb27SDimitry Andric             isCopyInstr(*RC.back(), *TII, UseCopyInstr);
122006c3fb27SDimitry Andric         if (!CheckCopyConstraint(OuterMostSpillCopy->Source->getReg(),
122106c3fb27SDimitry Andric                                  InnerMostSpillCopy->Source->getReg()) ||
122206c3fb27SDimitry Andric             !CheckCopyConstraint(InnerMostReloadCopy->Destination->getReg(),
122306c3fb27SDimitry Andric                                  OuterMostReloadCopy->Destination->getReg()))
122406c3fb27SDimitry Andric           return;
122506c3fb27SDimitry Andric 
122606c3fb27SDimitry Andric         SpillageChainsLength += SC.size() + RC.size();
122706c3fb27SDimitry Andric         NumSpillageChains += 1;
122806c3fb27SDimitry Andric         UpdateReg(SC[0], InnerMostSpillCopy->Destination,
122906c3fb27SDimitry Andric                   OuterMostSpillCopy->Source);
123006c3fb27SDimitry Andric         UpdateReg(RC[0], InnerMostReloadCopy->Source,
123106c3fb27SDimitry Andric                   OuterMostReloadCopy->Destination);
123206c3fb27SDimitry Andric 
123306c3fb27SDimitry Andric         for (size_t I = 1; I < SC.size() - 1; ++I) {
123406c3fb27SDimitry Andric           SC[I]->eraseFromParent();
123506c3fb27SDimitry Andric           RC[I]->eraseFromParent();
123606c3fb27SDimitry Andric           NumDeletes += 2;
123706c3fb27SDimitry Andric         }
123806c3fb27SDimitry Andric       };
123906c3fb27SDimitry Andric 
124006c3fb27SDimitry Andric   auto IsFoldableCopy = [this](const MachineInstr &MaybeCopy) {
124106c3fb27SDimitry Andric     if (MaybeCopy.getNumImplicitOperands() > 0)
124206c3fb27SDimitry Andric       return false;
124306c3fb27SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
124406c3fb27SDimitry Andric         isCopyInstr(MaybeCopy, *TII, UseCopyInstr);
124506c3fb27SDimitry Andric     if (!CopyOperands)
124606c3fb27SDimitry Andric       return false;
124706c3fb27SDimitry Andric     Register Src = CopyOperands->Source->getReg();
124806c3fb27SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
124906c3fb27SDimitry Andric     return Src && Def && !TRI->regsOverlap(Src, Def) &&
125006c3fb27SDimitry Andric            CopyOperands->Source->isRenamable() &&
125106c3fb27SDimitry Andric            CopyOperands->Destination->isRenamable();
125206c3fb27SDimitry Andric   };
125306c3fb27SDimitry Andric 
125406c3fb27SDimitry Andric   auto IsSpillReloadPair = [&, this](const MachineInstr &Spill,
125506c3fb27SDimitry Andric                                      const MachineInstr &Reload) {
125606c3fb27SDimitry Andric     if (!IsFoldableCopy(Spill) || !IsFoldableCopy(Reload))
125706c3fb27SDimitry Andric       return false;
125806c3fb27SDimitry Andric     std::optional<DestSourcePair> SpillCopy =
125906c3fb27SDimitry Andric         isCopyInstr(Spill, *TII, UseCopyInstr);
126006c3fb27SDimitry Andric     std::optional<DestSourcePair> ReloadCopy =
126106c3fb27SDimitry Andric         isCopyInstr(Reload, *TII, UseCopyInstr);
126206c3fb27SDimitry Andric     if (!SpillCopy || !ReloadCopy)
126306c3fb27SDimitry Andric       return false;
126406c3fb27SDimitry Andric     return SpillCopy->Source->getReg() == ReloadCopy->Destination->getReg() &&
126506c3fb27SDimitry Andric            SpillCopy->Destination->getReg() == ReloadCopy->Source->getReg();
126606c3fb27SDimitry Andric   };
126706c3fb27SDimitry Andric 
126806c3fb27SDimitry Andric   auto IsChainedCopy = [&, this](const MachineInstr &Prev,
126906c3fb27SDimitry Andric                                  const MachineInstr &Current) {
127006c3fb27SDimitry Andric     if (!IsFoldableCopy(Prev) || !IsFoldableCopy(Current))
127106c3fb27SDimitry Andric       return false;
127206c3fb27SDimitry Andric     std::optional<DestSourcePair> PrevCopy =
127306c3fb27SDimitry Andric         isCopyInstr(Prev, *TII, UseCopyInstr);
127406c3fb27SDimitry Andric     std::optional<DestSourcePair> CurrentCopy =
127506c3fb27SDimitry Andric         isCopyInstr(Current, *TII, UseCopyInstr);
127606c3fb27SDimitry Andric     if (!PrevCopy || !CurrentCopy)
127706c3fb27SDimitry Andric       return false;
127806c3fb27SDimitry Andric     return PrevCopy->Source->getReg() == CurrentCopy->Destination->getReg();
127906c3fb27SDimitry Andric   };
128006c3fb27SDimitry Andric 
128106c3fb27SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
128206c3fb27SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
128306c3fb27SDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
128406c3fb27SDimitry Andric 
128506c3fb27SDimitry Andric     // Update track information via non-copy instruction.
128606c3fb27SDimitry Andric     SmallSet<Register, 8> RegsToClobber;
128706c3fb27SDimitry Andric     if (!CopyOperands) {
128806c3fb27SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
128906c3fb27SDimitry Andric         if (!MO.isReg())
129006c3fb27SDimitry Andric           continue;
129106c3fb27SDimitry Andric         Register Reg = MO.getReg();
129206c3fb27SDimitry Andric         if (!Reg)
129306c3fb27SDimitry Andric           continue;
129406c3fb27SDimitry Andric         MachineInstr *LastUseCopy =
129506c3fb27SDimitry Andric             Tracker.findLastSeenUseInCopy(Reg.asMCReg(), *TRI);
129606c3fb27SDimitry Andric         if (LastUseCopy) {
129706c3fb27SDimitry Andric           LLVM_DEBUG(dbgs() << "MCP: Copy source of\n");
129806c3fb27SDimitry Andric           LLVM_DEBUG(LastUseCopy->dump());
129906c3fb27SDimitry Andric           LLVM_DEBUG(dbgs() << "might be invalidated by\n");
130006c3fb27SDimitry Andric           LLVM_DEBUG(MI.dump());
130106c3fb27SDimitry Andric           CopySourceInvalid.insert(LastUseCopy);
130206c3fb27SDimitry Andric         }
130306c3fb27SDimitry Andric         // Must be noted Tracker.clobberRegister(Reg, ...) removes tracking of
130406c3fb27SDimitry Andric         // Reg, i.e, COPY that defines Reg is removed from the mapping as well
130506c3fb27SDimitry Andric         // as marking COPYs that uses Reg unavailable.
130606c3fb27SDimitry Andric         // We don't invoke CopyTracker::clobberRegister(Reg, ...) if Reg is not
130706c3fb27SDimitry Andric         // defined by a previous COPY, since we don't want to make COPYs uses
130806c3fb27SDimitry Andric         // Reg unavailable.
130906c3fb27SDimitry Andric         if (Tracker.findLastSeenDefInCopy(MI, Reg.asMCReg(), *TRI, *TII,
131006c3fb27SDimitry Andric                                     UseCopyInstr))
131106c3fb27SDimitry Andric           // Thus we can keep the property#1.
131206c3fb27SDimitry Andric           RegsToClobber.insert(Reg);
131306c3fb27SDimitry Andric       }
131406c3fb27SDimitry Andric       for (Register Reg : RegsToClobber) {
131506c3fb27SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
131606c3fb27SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Reg, TRI)
131706c3fb27SDimitry Andric                           << "\n");
131806c3fb27SDimitry Andric       }
131906c3fb27SDimitry Andric       continue;
132006c3fb27SDimitry Andric     }
132106c3fb27SDimitry Andric 
132206c3fb27SDimitry Andric     Register Src = CopyOperands->Source->getReg();
132306c3fb27SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
132406c3fb27SDimitry Andric     // Check if we can find a pair spill-reload copy.
132506c3fb27SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Searching paired spill for reload: ");
132606c3fb27SDimitry Andric     LLVM_DEBUG(MI.dump());
132706c3fb27SDimitry Andric     MachineInstr *MaybeSpill =
132806c3fb27SDimitry Andric         Tracker.findLastSeenDefInCopy(MI, Src.asMCReg(), *TRI, *TII, UseCopyInstr);
132906c3fb27SDimitry Andric     bool MaybeSpillIsChained = ChainLeader.count(MaybeSpill);
133006c3fb27SDimitry Andric     if (!MaybeSpillIsChained && MaybeSpill &&
133106c3fb27SDimitry Andric         IsSpillReloadPair(*MaybeSpill, MI)) {
133206c3fb27SDimitry Andric       // Check if we already have an existing chain. Now we have a
133306c3fb27SDimitry Andric       // spill-reload pair.
133406c3fb27SDimitry Andric       // L2: r2 = COPY r3
133506c3fb27SDimitry Andric       // L5: r3 = COPY r2
133606c3fb27SDimitry Andric       // Looking for a valid COPY before L5 which uses r3.
133706c3fb27SDimitry Andric       // This can be serverial cases.
133806c3fb27SDimitry Andric       // Case #1:
133906c3fb27SDimitry Andric       // No COPY is found, which can be r3 is def-use between (L2, L5), we
134006c3fb27SDimitry Andric       // create a new chain for L2 and L5.
134106c3fb27SDimitry Andric       // Case #2:
134206c3fb27SDimitry Andric       // L2: r2 = COPY r3
134306c3fb27SDimitry Andric       // L5: r3 = COPY r2
134406c3fb27SDimitry Andric       // Such COPY is found and is L2, we create a new chain for L2 and L5.
134506c3fb27SDimitry Andric       // Case #3:
134606c3fb27SDimitry Andric       // L2: r2 = COPY r3
134706c3fb27SDimitry Andric       // L3: r1 = COPY r3
134806c3fb27SDimitry Andric       // L5: r3 = COPY r2
134906c3fb27SDimitry Andric       // we create a new chain for L2 and L5.
135006c3fb27SDimitry Andric       // Case #4:
135106c3fb27SDimitry Andric       // L2: r2 = COPY r3
135206c3fb27SDimitry Andric       // L3: r1 = COPY r3
135306c3fb27SDimitry Andric       // L4: r3 = COPY r1
135406c3fb27SDimitry Andric       // L5: r3 = COPY r2
135506c3fb27SDimitry Andric       // Such COPY won't be found since L4 defines r3. we create a new chain
135606c3fb27SDimitry Andric       // for L2 and L5.
135706c3fb27SDimitry Andric       // Case #5:
135806c3fb27SDimitry Andric       // L2: r2 = COPY r3
135906c3fb27SDimitry Andric       // L3: r3 = COPY r1
136006c3fb27SDimitry Andric       // L4: r1 = COPY r3
136106c3fb27SDimitry Andric       // L5: r3 = COPY r2
136206c3fb27SDimitry Andric       // COPY is found and is L4 which belongs to an existing chain, we add
136306c3fb27SDimitry Andric       // L2 and L5 to this chain.
136406c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Found spill: ");
136506c3fb27SDimitry Andric       LLVM_DEBUG(MaybeSpill->dump());
136606c3fb27SDimitry Andric       MachineInstr *MaybePrevReload =
136706c3fb27SDimitry Andric           Tracker.findLastSeenUseInCopy(Def.asMCReg(), *TRI);
136806c3fb27SDimitry Andric       auto Leader = ChainLeader.find(MaybePrevReload);
136906c3fb27SDimitry Andric       MachineInstr *L = nullptr;
137006c3fb27SDimitry Andric       if (Leader == ChainLeader.end() ||
137106c3fb27SDimitry Andric           (MaybePrevReload && !IsChainedCopy(*MaybePrevReload, MI))) {
137206c3fb27SDimitry Andric         L = &MI;
137306c3fb27SDimitry Andric         assert(!SpillChain.count(L) &&
137406c3fb27SDimitry Andric                "SpillChain should not have contained newly found chain");
137506c3fb27SDimitry Andric       } else {
137606c3fb27SDimitry Andric         assert(MaybePrevReload &&
137706c3fb27SDimitry Andric                "Found a valid leader through nullptr should not happend");
137806c3fb27SDimitry Andric         L = Leader->second;
137906c3fb27SDimitry Andric         assert(SpillChain[L].size() > 0 &&
138006c3fb27SDimitry Andric                "Existing chain's length should be larger than zero");
138106c3fb27SDimitry Andric       }
138206c3fb27SDimitry Andric       assert(!ChainLeader.count(&MI) && !ChainLeader.count(MaybeSpill) &&
138306c3fb27SDimitry Andric              "Newly found paired spill-reload should not belong to any chain "
138406c3fb27SDimitry Andric              "at this point");
138506c3fb27SDimitry Andric       ChainLeader.insert({MaybeSpill, L});
138606c3fb27SDimitry Andric       ChainLeader.insert({&MI, L});
138706c3fb27SDimitry Andric       SpillChain[L].push_back(MaybeSpill);
138806c3fb27SDimitry Andric       ReloadChain[L].push_back(&MI);
138906c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Chain " << L << " now is:\n");
139006c3fb27SDimitry Andric       LLVM_DEBUG(printSpillReloadChain(SpillChain, ReloadChain, L));
139106c3fb27SDimitry Andric     } else if (MaybeSpill && !MaybeSpillIsChained) {
139206c3fb27SDimitry Andric       // MaybeSpill is unable to pair with MI. That's to say adding MI makes
139306c3fb27SDimitry Andric       // the chain invalid.
139406c3fb27SDimitry Andric       // The COPY defines Src is no longer considered as a candidate of a
139506c3fb27SDimitry Andric       // valid chain. Since we expect the Def of a spill copy isn't used by
139606c3fb27SDimitry Andric       // any COPY instruction until a reload copy. For example:
139706c3fb27SDimitry Andric       // L1: r1 = COPY r2
139806c3fb27SDimitry Andric       // L2: r3 = COPY r1
139906c3fb27SDimitry Andric       // If we later have
140006c3fb27SDimitry Andric       // L1: r1 = COPY r2
140106c3fb27SDimitry Andric       // L2: r3 = COPY r1
140206c3fb27SDimitry Andric       // L3: r2 = COPY r1
140306c3fb27SDimitry Andric       // L1 and L3 can't be a valid spill-reload pair.
140406c3fb27SDimitry Andric       // Thus we keep the property#1.
140506c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Not paired spill-reload:\n");
140606c3fb27SDimitry Andric       LLVM_DEBUG(MaybeSpill->dump());
140706c3fb27SDimitry Andric       LLVM_DEBUG(MI.dump());
140806c3fb27SDimitry Andric       Tracker.clobberRegister(Src.asMCReg(), *TRI, *TII, UseCopyInstr);
140906c3fb27SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Src, TRI)
141006c3fb27SDimitry Andric                         << "\n");
141106c3fb27SDimitry Andric     }
141206c3fb27SDimitry Andric     Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
141306c3fb27SDimitry Andric   }
141406c3fb27SDimitry Andric 
141506c3fb27SDimitry Andric   for (auto I = SpillChain.begin(), E = SpillChain.end(); I != E; ++I) {
141606c3fb27SDimitry Andric     auto &SC = I->second;
141706c3fb27SDimitry Andric     assert(ReloadChain.count(I->first) &&
141806c3fb27SDimitry Andric            "Reload chain of the same leader should exist");
141906c3fb27SDimitry Andric     auto &RC = ReloadChain[I->first];
142006c3fb27SDimitry Andric     TryFoldSpillageCopies(SC, RC);
142106c3fb27SDimitry Andric   }
142206c3fb27SDimitry Andric 
142306c3fb27SDimitry Andric   MaybeDeadCopies.clear();
142406c3fb27SDimitry Andric   CopyDbgUsers.clear();
142506c3fb27SDimitry Andric   Tracker.clear();
142606c3fb27SDimitry Andric }
142706c3fb27SDimitry Andric 
14280b57cec5SDimitry Andric bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
14290b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
14300b57cec5SDimitry Andric     return false;
14310b57cec5SDimitry Andric 
143206c3fb27SDimitry Andric   bool isSpillageCopyElimEnabled = false;
143306c3fb27SDimitry Andric   switch (EnableSpillageCopyElimination) {
143406c3fb27SDimitry Andric   case cl::BOU_UNSET:
143506c3fb27SDimitry Andric     isSpillageCopyElimEnabled =
143606c3fb27SDimitry Andric         MF.getSubtarget().enableSpillageCopyElimination();
143706c3fb27SDimitry Andric     break;
143806c3fb27SDimitry Andric   case cl::BOU_TRUE:
143906c3fb27SDimitry Andric     isSpillageCopyElimEnabled = true;
144006c3fb27SDimitry Andric     break;
144106c3fb27SDimitry Andric   case cl::BOU_FALSE:
144206c3fb27SDimitry Andric     isSpillageCopyElimEnabled = false;
144306c3fb27SDimitry Andric     break;
144406c3fb27SDimitry Andric   }
144506c3fb27SDimitry Andric 
14460b57cec5SDimitry Andric   Changed = false;
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric   TRI = MF.getSubtarget().getRegisterInfo();
14490b57cec5SDimitry Andric   TII = MF.getSubtarget().getInstrInfo();
14500b57cec5SDimitry Andric   MRI = &MF.getRegInfo();
14510b57cec5SDimitry Andric 
1452480093f4SDimitry Andric   for (MachineBasicBlock &MBB : MF) {
145306c3fb27SDimitry Andric     if (isSpillageCopyElimEnabled)
145406c3fb27SDimitry Andric       EliminateSpillageCopies(MBB);
1455480093f4SDimitry Andric     BackwardCopyPropagateBlock(MBB);
1456480093f4SDimitry Andric     ForwardCopyPropagateBlock(MBB);
1457480093f4SDimitry Andric   }
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric   return Changed;
14600b57cec5SDimitry Andric }
146181ad6265SDimitry Andric 
146281ad6265SDimitry Andric MachineFunctionPass *
146381ad6265SDimitry Andric llvm::createMachineCopyPropagationPass(bool UseCopyInstr = false) {
146481ad6265SDimitry Andric   return new MachineCopyPropagation(UseCopyInstr);
146581ad6265SDimitry Andric }
1466