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");
83fe013be4SDimitry Andric STATISTIC(SpillageChainsLength, "Length of spillage chains");
84fe013be4SDimitry 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);
90fe013be4SDimitry Andric static cl::opt<cl::boolOrDefault>
91fe013be4SDimitry Andric     EnableSpillageCopyElimination("enable-spill-copy-elim", cl::Hidden);
9281ad6265SDimitry Andric 
930b57cec5SDimitry Andric namespace {
940b57cec5SDimitry Andric 
isCopyInstr(const MachineInstr & MI,const TargetInstrInfo & TII,bool UseCopyInstr)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 {
110fe013be4SDimitry 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.
markRegsUnavailable(ArrayRef<MCRegister> Regs,const TargetRegisterInfo & TRI)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.
124fe013be4SDimitry Andric       for (MCRegUnit Unit : TRI.regunits(Reg)) {
125fe013be4SDimitry 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.
invalidateRegister(MCRegister Reg,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)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
137c9157d92SDimitry Andric     // and invalidate all of them. Similarly, we must invalidate all of the
138c9157d92SDimitry Andric     // the subregisters used in the source of the COPY.
139c9157d92SDimitry Andric     SmallSet<MCRegUnit, 8> RegUnitsToInvalidate;
140c9157d92SDimitry 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 
145c9157d92SDimitry Andric       auto Dest = TRI.regunits(CopyOperands->Destination->getReg().asMCReg());
146c9157d92SDimitry Andric       auto Src = TRI.regunits(CopyOperands->Source->getReg().asMCReg());
147c9157d92SDimitry Andric       RegUnitsToInvalidate.insert(Dest.begin(), Dest.end());
148c9157d92SDimitry Andric       RegUnitsToInvalidate.insert(Src.begin(), Src.end());
149c9157d92SDimitry Andric     };
150c9157d92SDimitry Andric 
151c9157d92SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Reg)) {
152c9157d92SDimitry Andric       auto I = Copies.find(Unit);
153c9157d92SDimitry Andric       if (I != Copies.end()) {
154c9157d92SDimitry Andric         if (MachineInstr *MI = I->second.MI)
155c9157d92SDimitry Andric           InvalidateCopy(MI);
156c9157d92SDimitry Andric         if (MachineInstr *MI = I->second.LastSeenUseInCopy)
157c9157d92SDimitry Andric           InvalidateCopy(MI);
158480093f4SDimitry Andric       }
159480093f4SDimitry Andric     }
160c9157d92SDimitry Andric     for (MCRegUnit Unit : RegUnitsToInvalidate)
161fe013be4SDimitry Andric       Copies.erase(Unit);
162480093f4SDimitry Andric   }
163480093f4SDimitry Andric 
1640b57cec5SDimitry Andric   /// Clobber a single register, removing it from the tracker's copy maps.
clobberRegister(MCRegister Reg,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)16581ad6265SDimitry Andric   void clobberRegister(MCRegister Reg, const TargetRegisterInfo &TRI,
16681ad6265SDimitry Andric                        const TargetInstrInfo &TII, bool UseCopyInstr) {
167fe013be4SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Reg)) {
168fe013be4SDimitry 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);
178de8261c4SDimitry Andric 
179de8261c4SDimitry Andric           MCRegister Def = CopyOperands->Destination->getReg().asMCReg();
180de8261c4SDimitry Andric           MCRegister Src = CopyOperands->Source->getReg().asMCReg();
181de8261c4SDimitry Andric 
182de8261c4SDimitry Andric           markRegsUnavailable(Def, TRI);
183de8261c4SDimitry Andric 
184de8261c4SDimitry Andric           // Since we clobber the destination of a copy, the semantic of Src's
185de8261c4SDimitry Andric           // "DefRegs" to contain Def is no longer effectual. We will also need
186de8261c4SDimitry Andric           // to remove the record from the copy maps that indicates Src defined
187de8261c4SDimitry Andric           // Def. Failing to do so might cause the target to miss some
188de8261c4SDimitry Andric           // opportunities to further eliminate redundant copy instructions.
189de8261c4SDimitry Andric           // Consider the following sequence during the
190de8261c4SDimitry Andric           // ForwardCopyPropagateBlock procedure:
191de8261c4SDimitry Andric           // L1: r0 = COPY r9     <- TrackMI
192de8261c4SDimitry Andric           // L2: r0 = COPY r8     <- TrackMI (Remove r9 defined r0 from tracker)
193de8261c4SDimitry Andric           // L3: use r0           <- Remove L2 from MaybeDeadCopies
194de8261c4SDimitry Andric           // L4: early-clobber r9 <- Clobber r9 (L2 is still valid in tracker)
195de8261c4SDimitry Andric           // L5: r0 = COPY r8     <- Remove NopCopy
196de8261c4SDimitry Andric           for (MCRegUnit SrcUnit : TRI.regunits(Src)) {
197de8261c4SDimitry Andric             auto SrcCopy = Copies.find(SrcUnit);
198de8261c4SDimitry Andric             if (SrcCopy != Copies.end() && SrcCopy->second.LastSeenUseInCopy) {
199de8261c4SDimitry Andric               // If SrcCopy defines multiple values, we only need
200de8261c4SDimitry Andric               // to erase the record for Def in DefRegs.
201de8261c4SDimitry Andric               for (auto itr = SrcCopy->second.DefRegs.begin();
202de8261c4SDimitry Andric                    itr != SrcCopy->second.DefRegs.end(); itr++) {
203de8261c4SDimitry Andric                 if (*itr == Def) {
204de8261c4SDimitry Andric                   SrcCopy->second.DefRegs.erase(itr);
205de8261c4SDimitry Andric                   // If DefReg becomes empty after removal, we can remove the
206de8261c4SDimitry Andric                   // SrcCopy from the tracker's copy maps. We only remove those
207de8261c4SDimitry Andric                   // entries solely record the Def is defined by Src. If an
208de8261c4SDimitry Andric                   // entry also contains the definition record of other Def'
209de8261c4SDimitry Andric                   // registers, it cannot be cleared.
210de8261c4SDimitry Andric                   if (SrcCopy->second.DefRegs.empty() && !SrcCopy->second.MI) {
211de8261c4SDimitry Andric                     Copies.erase(SrcCopy);
212de8261c4SDimitry Andric                   }
213de8261c4SDimitry Andric                   break;
214de8261c4SDimitry Andric                 }
215de8261c4SDimitry Andric               }
216de8261c4SDimitry Andric             }
217de8261c4SDimitry 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.
trackCopy(MachineInstr * MI,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)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.
236fe013be4SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Def))
237fe013be4SDimitry 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.
241fe013be4SDimitry Andric     for (MCRegUnit Unit : TRI.regunits(Src)) {
242fe013be4SDimitry 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);
246fe013be4SDimitry Andric       Copy.LastSeenUseInCopy = MI;
2470b57cec5SDimitry Andric     }
2480b57cec5SDimitry Andric   }
2490b57cec5SDimitry Andric 
hasAnyCopies()2500b57cec5SDimitry Andric   bool hasAnyCopies() {
2510b57cec5SDimitry Andric     return !Copies.empty();
2520b57cec5SDimitry Andric   }
2530b57cec5SDimitry Andric 
findCopyForUnit(MCRegister RegUnit,const TargetRegisterInfo & TRI,bool MustBeAvailable=false)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 
findCopyDefViaUnit(MCRegister RegUnit,const TargetRegisterInfo & TRI)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;
272fe013be4SDimitry Andric     MCRegUnit RU = *TRI.regunits(CI->second.DefRegs[0]).begin();
273fe013be4SDimitry Andric     return findCopyForUnit(RU, TRI, true);
274480093f4SDimitry Andric   }
275480093f4SDimitry Andric 
findAvailBackwardCopy(MachineInstr & I,MCRegister Reg,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)276e8d8bef9SDimitry Andric   MachineInstr *findAvailBackwardCopy(MachineInstr &I, MCRegister Reg,
27781ad6265SDimitry Andric                                       const TargetRegisterInfo &TRI,
27881ad6265SDimitry Andric                                       const TargetInstrInfo &TII,
27981ad6265SDimitry Andric                                       bool UseCopyInstr) {
280fe013be4SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
281fe013be4SDimitry 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 
findAvailCopy(MachineInstr & DestCopy,MCRegister Reg,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)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.
309fe013be4SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
3100b57cec5SDimitry Andric     MachineInstr *AvailCopy =
311fe013be4SDimitry 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 
335fe013be4SDimitry Andric   // Find last COPY that defines Reg before Current MachineInstr.
findLastSeenDefInCopy(const MachineInstr & Current,MCRegister Reg,const TargetRegisterInfo & TRI,const TargetInstrInfo & TII,bool UseCopyInstr)336fe013be4SDimitry Andric   MachineInstr *findLastSeenDefInCopy(const MachineInstr &Current,
337fe013be4SDimitry Andric                                       MCRegister Reg,
338fe013be4SDimitry Andric                                       const TargetRegisterInfo &TRI,
339fe013be4SDimitry Andric                                       const TargetInstrInfo &TII,
340fe013be4SDimitry Andric                                       bool UseCopyInstr) {
341fe013be4SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
342fe013be4SDimitry Andric     auto CI = Copies.find(RU);
343fe013be4SDimitry Andric     if (CI == Copies.end() || !CI->second.Avail)
344fe013be4SDimitry Andric       return nullptr;
345fe013be4SDimitry Andric 
346fe013be4SDimitry Andric     MachineInstr *DefCopy = CI->second.MI;
347fe013be4SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
348fe013be4SDimitry Andric         isCopyInstr(*DefCopy, TII, UseCopyInstr);
349fe013be4SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
350fe013be4SDimitry Andric     if (!TRI.isSubRegisterEq(Def, Reg))
351fe013be4SDimitry Andric       return nullptr;
352fe013be4SDimitry Andric 
353fe013be4SDimitry Andric     for (const MachineInstr &MI :
354fe013be4SDimitry Andric          make_range(static_cast<const MachineInstr *>(DefCopy)->getIterator(),
355fe013be4SDimitry Andric                     Current.getIterator()))
356fe013be4SDimitry Andric       for (const MachineOperand &MO : MI.operands())
357fe013be4SDimitry Andric         if (MO.isRegMask())
358fe013be4SDimitry Andric           if (MO.clobbersPhysReg(Def)) {
359fe013be4SDimitry Andric             LLVM_DEBUG(dbgs() << "MCP: Removed tracking of "
360fe013be4SDimitry Andric                               << printReg(Def, &TRI) << "\n");
361fe013be4SDimitry Andric             return nullptr;
362fe013be4SDimitry Andric           }
363fe013be4SDimitry Andric 
364fe013be4SDimitry Andric     return DefCopy;
365fe013be4SDimitry Andric   }
366fe013be4SDimitry Andric 
367fe013be4SDimitry Andric   // Find last COPY that uses Reg.
findLastSeenUseInCopy(MCRegister Reg,const TargetRegisterInfo & TRI)368fe013be4SDimitry Andric   MachineInstr *findLastSeenUseInCopy(MCRegister Reg,
369fe013be4SDimitry Andric                                       const TargetRegisterInfo &TRI) {
370fe013be4SDimitry Andric     MCRegUnit RU = *TRI.regunits(Reg).begin();
371fe013be4SDimitry Andric     auto CI = Copies.find(RU);
372fe013be4SDimitry Andric     if (CI == Copies.end())
373fe013be4SDimitry Andric       return nullptr;
374fe013be4SDimitry Andric     return CI->second.LastSeenUseInCopy;
375fe013be4SDimitry Andric   }
376fe013be4SDimitry Andric 
clear()3770b57cec5SDimitry Andric   void clear() {
3780b57cec5SDimitry Andric     Copies.clear();
3790b57cec5SDimitry Andric   }
3800b57cec5SDimitry Andric };
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric class MachineCopyPropagation : public MachineFunctionPass {
383fe013be4SDimitry Andric   const TargetRegisterInfo *TRI = nullptr;
384fe013be4SDimitry Andric   const TargetInstrInfo *TII = nullptr;
385fe013be4SDimitry 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 
MachineCopyPropagation(bool CopyInstr=false)39381ad6265SDimitry Andric   MachineCopyPropagation(bool CopyInstr = false)
39481ad6265SDimitry Andric       : MachineFunctionPass(ID), UseCopyInstr(CopyInstr || MCPUseCopyInstr) {
3950b57cec5SDimitry Andric     initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
3960b57cec5SDimitry Andric   }
3970b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const3980b57cec5SDimitry 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 
getRequiredProperties() const4050b57cec5SDimitry 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);
416fe013be4SDimitry 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 
437fe013be4SDimitry 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 
ReadRegister(MCRegister Reg,MachineInstr & Reader,DebugType DT)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.
454fe013be4SDimitry Andric   for (MCRegUnit Unit : TRI->regunits(Reg)) {
455fe013be4SDimitry 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
isNopCopy(const MachineInstr & PreviousCopy,MCRegister Src,MCRegister Def,const TargetRegisterInfo * TRI,const TargetInstrInfo * TII,bool UseCopyInstr)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.
eraseIfRedundant(MachineInstr & Copy,MCRegister Src,MCRegister Def)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 
525fe013be4SDimitry Andric   // Clear undef flag from remaining copy if needed.
526fe013be4SDimitry Andric   if (!CopyOperands->Source->isUndef()) {
527fe013be4SDimitry Andric     PrevCopy->getOperand(PrevCopyOperands->Source->getOperandNo())
528fe013be4SDimitry Andric         .setIsUndef(false);
529fe013be4SDimitry Andric   }
530fe013be4SDimitry Andric 
5310b57cec5SDimitry Andric   Copy.eraseFromParent();
5320b57cec5SDimitry Andric   Changed = true;
5330b57cec5SDimitry Andric   ++NumDeletes;
5340b57cec5SDimitry Andric   return true;
5350b57cec5SDimitry Andric }
5360b57cec5SDimitry Andric 
isBackwardPropagatableRegClassCopy(const MachineInstr & Copy,const MachineInstr & UseI,unsigned UseIdx)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.
isForwardableRegClassCopy(const MachineInstr & Copy,const MachineInstr & UseI,unsigned UseIdx)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.
hasImplicitOverlap(const MachineInstr & MI,const MachineOperand & Use)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.
hasOverlappingMultipleDef(const MachineInstr & MI,const MachineOperand & MODef,Register Def)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.
forwardUses(MachineInstr & MI)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 
693fe013be4SDimitry Andric     Register ForwardedReg = CopySrcReg;
694fe013be4SDimitry Andric     // MI might use a sub-register of the Copy destination, in which case the
695fe013be4SDimitry Andric     // forwarded register is the matching sub-register of the Copy source.
6960b57cec5SDimitry Andric     if (MOUse.getReg() != CopyDstReg) {
697fe013be4SDimitry Andric       unsigned SubRegIdx = TRI->getSubRegIndex(CopyDstReg, MOUse.getReg());
698fe013be4SDimitry Andric       assert(SubRegIdx &&
699fe013be4SDimitry Andric              "MI source is not a sub-register of Copy destination");
700fe013be4SDimitry Andric       ForwardedReg = TRI->getSubReg(CopySrcReg, SubRegIdx);
701fe013be4SDimitry Andric       if (!ForwardedReg) {
702fe013be4SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Copy source does not have sub-register "
703fe013be4SDimitry Andric                           << TRI->getSubRegIndexName(SubRegIdx) << '\n');
7040b57cec5SDimitry Andric         continue;
7050b57cec5SDimitry Andric       }
706fe013be4SDimitry 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)
735fe013be4SDimitry Andric                       << "\n     with " << printReg(ForwardedReg, TRI)
7360b57cec5SDimitry Andric                       << "\n     in " << MI << "     from " << *Copy);
7370b57cec5SDimitry Andric 
738fe013be4SDimitry Andric     MOUse.setReg(ForwardedReg);
739fe013be4SDimitry 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 
ForwardCopyPropagateBlock(MachineBasicBlock & MBB)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.
856*a58f00eaSDimitry Andric     SmallVector<Register, 4> 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 
isBackwardPropagatableCopy(const DestSourcePair & CopyOperands,const MachineRegisterInfo & MRI,const TargetInstrInfo & TII)950fe013be4SDimitry Andric static bool isBackwardPropagatableCopy(const DestSourcePair &CopyOperands,
95181ad6265SDimitry Andric                                        const MachineRegisterInfo &MRI,
952fe013be4SDimitry Andric                                        const TargetInstrInfo &TII) {
953fe013be4SDimitry Andric   Register Def = CopyOperands.Destination->getReg();
954fe013be4SDimitry 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 
962fe013be4SDimitry Andric   return CopyOperands.Source->isRenamable() && CopyOperands.Source->isKill();
963480093f4SDimitry Andric }
964480093f4SDimitry Andric 
propagateDefs(MachineInstr & MI)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 
BackwardCopyPropagateBlock(MachineBasicBlock & MBB)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.
1039fe013be4SDimitry Andric         if (isBackwardPropagatableCopy(*CopyOperands, *MRI, *TII)) {
1040fe013be4SDimitry Andric           Tracker.invalidateRegister(SrcReg.asMCReg(), *TRI, *TII,
1041fe013be4SDimitry Andric                                      UseCopyInstr);
1042fe013be4SDimitry Andric           Tracker.invalidateRegister(DefReg.asMCReg(), *TRI, *TII,
1043fe013be4SDimitry 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.
1076fe013be4SDimitry Andric           for (MCRegUnit Unit : TRI->regunits(MO.getReg().asMCReg())) {
1077fe013be4SDimitry 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 
printSpillReloadChain(DenseMap<MachineInstr *,SmallVector<MachineInstr * >> & SpillChain,DenseMap<MachineInstr *,SmallVector<MachineInstr * >> & ReloadChain,MachineInstr * Leader)1107fe013be4SDimitry Andric static void LLVM_ATTRIBUTE_UNUSED printSpillReloadChain(
1108fe013be4SDimitry Andric     DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &SpillChain,
1109fe013be4SDimitry Andric     DenseMap<MachineInstr *, SmallVector<MachineInstr *>> &ReloadChain,
1110fe013be4SDimitry Andric     MachineInstr *Leader) {
1111fe013be4SDimitry Andric   auto &SC = SpillChain[Leader];
1112fe013be4SDimitry Andric   auto &RC = ReloadChain[Leader];
1113fe013be4SDimitry Andric   for (auto I = SC.rbegin(), E = SC.rend(); I != E; ++I)
1114fe013be4SDimitry Andric     (*I)->dump();
1115fe013be4SDimitry Andric   for (MachineInstr *MI : RC)
1116fe013be4SDimitry Andric     MI->dump();
1117fe013be4SDimitry Andric }
1118fe013be4SDimitry Andric 
1119fe013be4SDimitry Andric // Remove spill-reload like copy chains. For example
1120fe013be4SDimitry Andric // r0 = COPY r1
1121fe013be4SDimitry Andric // r1 = COPY r2
1122fe013be4SDimitry Andric // r2 = COPY r3
1123fe013be4SDimitry Andric // r3 = COPY r4
1124fe013be4SDimitry Andric // <def-use r4>
1125fe013be4SDimitry Andric // r4 = COPY r3
1126fe013be4SDimitry Andric // r3 = COPY r2
1127fe013be4SDimitry Andric // r2 = COPY r1
1128fe013be4SDimitry Andric // r1 = COPY r0
1129fe013be4SDimitry Andric // will be folded into
1130fe013be4SDimitry Andric // r0 = COPY r1
1131fe013be4SDimitry Andric // r1 = COPY r4
1132fe013be4SDimitry Andric // <def-use r4>
1133fe013be4SDimitry Andric // r4 = COPY r1
1134fe013be4SDimitry Andric // r1 = COPY r0
1135fe013be4SDimitry Andric // TODO: Currently we don't track usage of r0 outside the chain, so we
1136fe013be4SDimitry Andric // conservatively keep its value as it was before the rewrite.
1137fe013be4SDimitry Andric //
1138fe013be4SDimitry Andric // The algorithm is trying to keep
1139fe013be4SDimitry Andric // property#1: No Def of spill COPY in the chain is used or defined until the
1140fe013be4SDimitry Andric // paired reload COPY in the chain uses the Def.
1141fe013be4SDimitry Andric //
1142fe013be4SDimitry Andric // property#2: NO Source of COPY in the chain is used or defined until the next
1143fe013be4SDimitry Andric // COPY in the chain defines the Source, except the innermost spill-reload
1144fe013be4SDimitry Andric // pair.
1145fe013be4SDimitry Andric //
1146fe013be4SDimitry Andric // The algorithm is conducted by checking every COPY inside the MBB, assuming
1147fe013be4SDimitry Andric // the COPY is a reload COPY, then try to find paired spill COPY by searching
1148fe013be4SDimitry Andric // the COPY defines the Src of the reload COPY backward. If such pair is found,
1149fe013be4SDimitry Andric // it either belongs to an existing chain or a new chain depends on
1150fe013be4SDimitry Andric // last available COPY uses the Def of the reload COPY.
1151fe013be4SDimitry Andric // Implementation notes, we use CopyTracker::findLastDefCopy(Reg, ...) to find
1152fe013be4SDimitry Andric // out last COPY that defines Reg; we use CopyTracker::findLastUseCopy(Reg, ...)
1153fe013be4SDimitry Andric // to find out last COPY that uses Reg. When we are encountered with a Non-COPY
1154fe013be4SDimitry Andric // instruction, we check registers in the operands of this instruction. If this
1155fe013be4SDimitry Andric // Reg is defined by a COPY, we untrack this Reg via
1156fe013be4SDimitry Andric // CopyTracker::clobberRegister(Reg, ...).
EliminateSpillageCopies(MachineBasicBlock & MBB)1157fe013be4SDimitry Andric void MachineCopyPropagation::EliminateSpillageCopies(MachineBasicBlock &MBB) {
1158fe013be4SDimitry Andric   // ChainLeader maps MI inside a spill-reload chain to its innermost reload COPY.
1159fe013be4SDimitry Andric   // Thus we can track if a MI belongs to an existing spill-reload chain.
1160fe013be4SDimitry Andric   DenseMap<MachineInstr *, MachineInstr *> ChainLeader;
1161fe013be4SDimitry Andric   // SpillChain maps innermost reload COPY of a spill-reload chain to a sequence
1162fe013be4SDimitry Andric   // of COPYs that forms spills of a spill-reload chain.
1163fe013be4SDimitry Andric   // ReloadChain maps innermost reload COPY of a spill-reload chain to a
1164fe013be4SDimitry Andric   // sequence of COPYs that forms reloads of a spill-reload chain.
1165fe013be4SDimitry Andric   DenseMap<MachineInstr *, SmallVector<MachineInstr *>> SpillChain, ReloadChain;
1166fe013be4SDimitry Andric   // If a COPY's Source has use or def until next COPY defines the Source,
1167fe013be4SDimitry Andric   // we put the COPY in this set to keep property#2.
1168fe013be4SDimitry Andric   DenseSet<const MachineInstr *> CopySourceInvalid;
1169fe013be4SDimitry Andric 
1170fe013be4SDimitry Andric   auto TryFoldSpillageCopies =
1171fe013be4SDimitry Andric       [&, this](const SmallVectorImpl<MachineInstr *> &SC,
1172fe013be4SDimitry Andric                 const SmallVectorImpl<MachineInstr *> &RC) {
1173fe013be4SDimitry Andric         assert(SC.size() == RC.size() && "Spill-reload should be paired");
1174fe013be4SDimitry Andric 
1175fe013be4SDimitry Andric         // We need at least 3 pairs of copies for the transformation to apply,
1176fe013be4SDimitry Andric         // because the first outermost pair cannot be removed since we don't
1177fe013be4SDimitry Andric         // recolor outside of the chain and that we need at least one temporary
1178fe013be4SDimitry Andric         // spill slot to shorten the chain. If we only have a chain of two
1179fe013be4SDimitry Andric         // pairs, we already have the shortest sequence this code can handle:
1180fe013be4SDimitry Andric         // the outermost pair for the temporary spill slot, and the pair that
1181fe013be4SDimitry Andric         // use that temporary spill slot for the other end of the chain.
1182fe013be4SDimitry Andric         // TODO: We might be able to simplify to one spill-reload pair if collecting
1183fe013be4SDimitry Andric         // more infomation about the outermost COPY.
1184fe013be4SDimitry Andric         if (SC.size() <= 2)
1185fe013be4SDimitry Andric           return;
1186fe013be4SDimitry Andric 
1187fe013be4SDimitry Andric         // If violate property#2, we don't fold the chain.
1188c9157d92SDimitry Andric         for (const MachineInstr *Spill : drop_begin(SC))
1189fe013be4SDimitry Andric           if (CopySourceInvalid.count(Spill))
1190fe013be4SDimitry Andric             return;
1191fe013be4SDimitry Andric 
1192c9157d92SDimitry Andric         for (const MachineInstr *Reload : drop_end(RC))
1193fe013be4SDimitry Andric           if (CopySourceInvalid.count(Reload))
1194fe013be4SDimitry Andric             return;
1195fe013be4SDimitry Andric 
1196fe013be4SDimitry Andric         auto CheckCopyConstraint = [this](Register Def, Register Src) {
1197fe013be4SDimitry Andric           for (const TargetRegisterClass *RC : TRI->regclasses()) {
1198fe013be4SDimitry Andric             if (RC->contains(Def) && RC->contains(Src))
1199fe013be4SDimitry Andric               return true;
1200fe013be4SDimitry Andric           }
1201fe013be4SDimitry Andric           return false;
1202fe013be4SDimitry Andric         };
1203fe013be4SDimitry Andric 
1204fe013be4SDimitry Andric         auto UpdateReg = [](MachineInstr *MI, const MachineOperand *Old,
1205fe013be4SDimitry Andric                             const MachineOperand *New) {
1206fe013be4SDimitry Andric           for (MachineOperand &MO : MI->operands()) {
1207fe013be4SDimitry Andric             if (&MO == Old)
1208fe013be4SDimitry Andric               MO.setReg(New->getReg());
1209fe013be4SDimitry Andric           }
1210fe013be4SDimitry Andric         };
1211fe013be4SDimitry Andric 
1212fe013be4SDimitry Andric         std::optional<DestSourcePair> InnerMostSpillCopy =
1213fe013be4SDimitry Andric             isCopyInstr(*SC[0], *TII, UseCopyInstr);
1214fe013be4SDimitry Andric         std::optional<DestSourcePair> OuterMostSpillCopy =
1215fe013be4SDimitry Andric             isCopyInstr(*SC.back(), *TII, UseCopyInstr);
1216fe013be4SDimitry Andric         std::optional<DestSourcePair> InnerMostReloadCopy =
1217fe013be4SDimitry Andric             isCopyInstr(*RC[0], *TII, UseCopyInstr);
1218fe013be4SDimitry Andric         std::optional<DestSourcePair> OuterMostReloadCopy =
1219fe013be4SDimitry Andric             isCopyInstr(*RC.back(), *TII, UseCopyInstr);
1220fe013be4SDimitry Andric         if (!CheckCopyConstraint(OuterMostSpillCopy->Source->getReg(),
1221fe013be4SDimitry Andric                                  InnerMostSpillCopy->Source->getReg()) ||
1222fe013be4SDimitry Andric             !CheckCopyConstraint(InnerMostReloadCopy->Destination->getReg(),
1223fe013be4SDimitry Andric                                  OuterMostReloadCopy->Destination->getReg()))
1224fe013be4SDimitry Andric           return;
1225fe013be4SDimitry Andric 
1226fe013be4SDimitry Andric         SpillageChainsLength += SC.size() + RC.size();
1227fe013be4SDimitry Andric         NumSpillageChains += 1;
1228fe013be4SDimitry Andric         UpdateReg(SC[0], InnerMostSpillCopy->Destination,
1229fe013be4SDimitry Andric                   OuterMostSpillCopy->Source);
1230fe013be4SDimitry Andric         UpdateReg(RC[0], InnerMostReloadCopy->Source,
1231fe013be4SDimitry Andric                   OuterMostReloadCopy->Destination);
1232fe013be4SDimitry Andric 
1233fe013be4SDimitry Andric         for (size_t I = 1; I < SC.size() - 1; ++I) {
1234fe013be4SDimitry Andric           SC[I]->eraseFromParent();
1235fe013be4SDimitry Andric           RC[I]->eraseFromParent();
1236fe013be4SDimitry Andric           NumDeletes += 2;
1237fe013be4SDimitry Andric         }
1238fe013be4SDimitry Andric       };
1239fe013be4SDimitry Andric 
1240fe013be4SDimitry Andric   auto IsFoldableCopy = [this](const MachineInstr &MaybeCopy) {
1241fe013be4SDimitry Andric     if (MaybeCopy.getNumImplicitOperands() > 0)
1242fe013be4SDimitry Andric       return false;
1243fe013be4SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
1244fe013be4SDimitry Andric         isCopyInstr(MaybeCopy, *TII, UseCopyInstr);
1245fe013be4SDimitry Andric     if (!CopyOperands)
1246fe013be4SDimitry Andric       return false;
1247fe013be4SDimitry Andric     Register Src = CopyOperands->Source->getReg();
1248fe013be4SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
1249fe013be4SDimitry Andric     return Src && Def && !TRI->regsOverlap(Src, Def) &&
1250fe013be4SDimitry Andric            CopyOperands->Source->isRenamable() &&
1251fe013be4SDimitry Andric            CopyOperands->Destination->isRenamable();
1252fe013be4SDimitry Andric   };
1253fe013be4SDimitry Andric 
1254fe013be4SDimitry Andric   auto IsSpillReloadPair = [&, this](const MachineInstr &Spill,
1255fe013be4SDimitry Andric                                      const MachineInstr &Reload) {
1256fe013be4SDimitry Andric     if (!IsFoldableCopy(Spill) || !IsFoldableCopy(Reload))
1257fe013be4SDimitry Andric       return false;
1258fe013be4SDimitry Andric     std::optional<DestSourcePair> SpillCopy =
1259fe013be4SDimitry Andric         isCopyInstr(Spill, *TII, UseCopyInstr);
1260fe013be4SDimitry Andric     std::optional<DestSourcePair> ReloadCopy =
1261fe013be4SDimitry Andric         isCopyInstr(Reload, *TII, UseCopyInstr);
1262fe013be4SDimitry Andric     if (!SpillCopy || !ReloadCopy)
1263fe013be4SDimitry Andric       return false;
1264fe013be4SDimitry Andric     return SpillCopy->Source->getReg() == ReloadCopy->Destination->getReg() &&
1265fe013be4SDimitry Andric            SpillCopy->Destination->getReg() == ReloadCopy->Source->getReg();
1266fe013be4SDimitry Andric   };
1267fe013be4SDimitry Andric 
1268fe013be4SDimitry Andric   auto IsChainedCopy = [&, this](const MachineInstr &Prev,
1269fe013be4SDimitry Andric                                  const MachineInstr &Current) {
1270fe013be4SDimitry Andric     if (!IsFoldableCopy(Prev) || !IsFoldableCopy(Current))
1271fe013be4SDimitry Andric       return false;
1272fe013be4SDimitry Andric     std::optional<DestSourcePair> PrevCopy =
1273fe013be4SDimitry Andric         isCopyInstr(Prev, *TII, UseCopyInstr);
1274fe013be4SDimitry Andric     std::optional<DestSourcePair> CurrentCopy =
1275fe013be4SDimitry Andric         isCopyInstr(Current, *TII, UseCopyInstr);
1276fe013be4SDimitry Andric     if (!PrevCopy || !CurrentCopy)
1277fe013be4SDimitry Andric       return false;
1278fe013be4SDimitry Andric     return PrevCopy->Source->getReg() == CurrentCopy->Destination->getReg();
1279fe013be4SDimitry Andric   };
1280fe013be4SDimitry Andric 
1281fe013be4SDimitry Andric   for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
1282fe013be4SDimitry Andric     std::optional<DestSourcePair> CopyOperands =
1283fe013be4SDimitry Andric         isCopyInstr(MI, *TII, UseCopyInstr);
1284fe013be4SDimitry Andric 
1285fe013be4SDimitry Andric     // Update track information via non-copy instruction.
1286fe013be4SDimitry Andric     SmallSet<Register, 8> RegsToClobber;
1287fe013be4SDimitry Andric     if (!CopyOperands) {
1288fe013be4SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
1289fe013be4SDimitry Andric         if (!MO.isReg())
1290fe013be4SDimitry Andric           continue;
1291fe013be4SDimitry Andric         Register Reg = MO.getReg();
1292fe013be4SDimitry Andric         if (!Reg)
1293fe013be4SDimitry Andric           continue;
1294fe013be4SDimitry Andric         MachineInstr *LastUseCopy =
1295fe013be4SDimitry Andric             Tracker.findLastSeenUseInCopy(Reg.asMCReg(), *TRI);
1296fe013be4SDimitry Andric         if (LastUseCopy) {
1297fe013be4SDimitry Andric           LLVM_DEBUG(dbgs() << "MCP: Copy source of\n");
1298fe013be4SDimitry Andric           LLVM_DEBUG(LastUseCopy->dump());
1299fe013be4SDimitry Andric           LLVM_DEBUG(dbgs() << "might be invalidated by\n");
1300fe013be4SDimitry Andric           LLVM_DEBUG(MI.dump());
1301fe013be4SDimitry Andric           CopySourceInvalid.insert(LastUseCopy);
1302fe013be4SDimitry Andric         }
1303fe013be4SDimitry Andric         // Must be noted Tracker.clobberRegister(Reg, ...) removes tracking of
1304fe013be4SDimitry Andric         // Reg, i.e, COPY that defines Reg is removed from the mapping as well
1305fe013be4SDimitry Andric         // as marking COPYs that uses Reg unavailable.
1306fe013be4SDimitry Andric         // We don't invoke CopyTracker::clobberRegister(Reg, ...) if Reg is not
1307fe013be4SDimitry Andric         // defined by a previous COPY, since we don't want to make COPYs uses
1308fe013be4SDimitry Andric         // Reg unavailable.
1309fe013be4SDimitry Andric         if (Tracker.findLastSeenDefInCopy(MI, Reg.asMCReg(), *TRI, *TII,
1310fe013be4SDimitry Andric                                     UseCopyInstr))
1311fe013be4SDimitry Andric           // Thus we can keep the property#1.
1312fe013be4SDimitry Andric           RegsToClobber.insert(Reg);
1313fe013be4SDimitry Andric       }
1314fe013be4SDimitry Andric       for (Register Reg : RegsToClobber) {
1315fe013be4SDimitry Andric         Tracker.clobberRegister(Reg, *TRI, *TII, UseCopyInstr);
1316fe013be4SDimitry Andric         LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Reg, TRI)
1317fe013be4SDimitry Andric                           << "\n");
1318fe013be4SDimitry Andric       }
1319fe013be4SDimitry Andric       continue;
1320fe013be4SDimitry Andric     }
1321fe013be4SDimitry Andric 
1322fe013be4SDimitry Andric     Register Src = CopyOperands->Source->getReg();
1323fe013be4SDimitry Andric     Register Def = CopyOperands->Destination->getReg();
1324fe013be4SDimitry Andric     // Check if we can find a pair spill-reload copy.
1325fe013be4SDimitry Andric     LLVM_DEBUG(dbgs() << "MCP: Searching paired spill for reload: ");
1326fe013be4SDimitry Andric     LLVM_DEBUG(MI.dump());
1327fe013be4SDimitry Andric     MachineInstr *MaybeSpill =
1328fe013be4SDimitry Andric         Tracker.findLastSeenDefInCopy(MI, Src.asMCReg(), *TRI, *TII, UseCopyInstr);
1329fe013be4SDimitry Andric     bool MaybeSpillIsChained = ChainLeader.count(MaybeSpill);
1330fe013be4SDimitry Andric     if (!MaybeSpillIsChained && MaybeSpill &&
1331fe013be4SDimitry Andric         IsSpillReloadPair(*MaybeSpill, MI)) {
1332fe013be4SDimitry Andric       // Check if we already have an existing chain. Now we have a
1333fe013be4SDimitry Andric       // spill-reload pair.
1334fe013be4SDimitry Andric       // L2: r2 = COPY r3
1335fe013be4SDimitry Andric       // L5: r3 = COPY r2
1336fe013be4SDimitry Andric       // Looking for a valid COPY before L5 which uses r3.
1337fe013be4SDimitry Andric       // This can be serverial cases.
1338fe013be4SDimitry Andric       // Case #1:
1339fe013be4SDimitry Andric       // No COPY is found, which can be r3 is def-use between (L2, L5), we
1340fe013be4SDimitry Andric       // create a new chain for L2 and L5.
1341fe013be4SDimitry Andric       // Case #2:
1342fe013be4SDimitry Andric       // L2: r2 = COPY r3
1343fe013be4SDimitry Andric       // L5: r3 = COPY r2
1344fe013be4SDimitry Andric       // Such COPY is found and is L2, we create a new chain for L2 and L5.
1345fe013be4SDimitry Andric       // Case #3:
1346fe013be4SDimitry Andric       // L2: r2 = COPY r3
1347fe013be4SDimitry Andric       // L3: r1 = COPY r3
1348fe013be4SDimitry Andric       // L5: r3 = COPY r2
1349fe013be4SDimitry Andric       // we create a new chain for L2 and L5.
1350fe013be4SDimitry Andric       // Case #4:
1351fe013be4SDimitry Andric       // L2: r2 = COPY r3
1352fe013be4SDimitry Andric       // L3: r1 = COPY r3
1353fe013be4SDimitry Andric       // L4: r3 = COPY r1
1354fe013be4SDimitry Andric       // L5: r3 = COPY r2
1355fe013be4SDimitry Andric       // Such COPY won't be found since L4 defines r3. we create a new chain
1356fe013be4SDimitry Andric       // for L2 and L5.
1357fe013be4SDimitry Andric       // Case #5:
1358fe013be4SDimitry Andric       // L2: r2 = COPY r3
1359fe013be4SDimitry Andric       // L3: r3 = COPY r1
1360fe013be4SDimitry Andric       // L4: r1 = COPY r3
1361fe013be4SDimitry Andric       // L5: r3 = COPY r2
1362fe013be4SDimitry Andric       // COPY is found and is L4 which belongs to an existing chain, we add
1363fe013be4SDimitry Andric       // L2 and L5 to this chain.
1364fe013be4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Found spill: ");
1365fe013be4SDimitry Andric       LLVM_DEBUG(MaybeSpill->dump());
1366fe013be4SDimitry Andric       MachineInstr *MaybePrevReload =
1367fe013be4SDimitry Andric           Tracker.findLastSeenUseInCopy(Def.asMCReg(), *TRI);
1368fe013be4SDimitry Andric       auto Leader = ChainLeader.find(MaybePrevReload);
1369fe013be4SDimitry Andric       MachineInstr *L = nullptr;
1370fe013be4SDimitry Andric       if (Leader == ChainLeader.end() ||
1371fe013be4SDimitry Andric           (MaybePrevReload && !IsChainedCopy(*MaybePrevReload, MI))) {
1372fe013be4SDimitry Andric         L = &MI;
1373fe013be4SDimitry Andric         assert(!SpillChain.count(L) &&
1374fe013be4SDimitry Andric                "SpillChain should not have contained newly found chain");
1375fe013be4SDimitry Andric       } else {
1376fe013be4SDimitry Andric         assert(MaybePrevReload &&
1377fe013be4SDimitry Andric                "Found a valid leader through nullptr should not happend");
1378fe013be4SDimitry Andric         L = Leader->second;
1379fe013be4SDimitry Andric         assert(SpillChain[L].size() > 0 &&
1380fe013be4SDimitry Andric                "Existing chain's length should be larger than zero");
1381fe013be4SDimitry Andric       }
1382fe013be4SDimitry Andric       assert(!ChainLeader.count(&MI) && !ChainLeader.count(MaybeSpill) &&
1383fe013be4SDimitry Andric              "Newly found paired spill-reload should not belong to any chain "
1384fe013be4SDimitry Andric              "at this point");
1385fe013be4SDimitry Andric       ChainLeader.insert({MaybeSpill, L});
1386fe013be4SDimitry Andric       ChainLeader.insert({&MI, L});
1387fe013be4SDimitry Andric       SpillChain[L].push_back(MaybeSpill);
1388fe013be4SDimitry Andric       ReloadChain[L].push_back(&MI);
1389fe013be4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Chain " << L << " now is:\n");
1390fe013be4SDimitry Andric       LLVM_DEBUG(printSpillReloadChain(SpillChain, ReloadChain, L));
1391fe013be4SDimitry Andric     } else if (MaybeSpill && !MaybeSpillIsChained) {
1392fe013be4SDimitry Andric       // MaybeSpill is unable to pair with MI. That's to say adding MI makes
1393fe013be4SDimitry Andric       // the chain invalid.
1394fe013be4SDimitry Andric       // The COPY defines Src is no longer considered as a candidate of a
1395fe013be4SDimitry Andric       // valid chain. Since we expect the Def of a spill copy isn't used by
1396fe013be4SDimitry Andric       // any COPY instruction until a reload copy. For example:
1397fe013be4SDimitry Andric       // L1: r1 = COPY r2
1398fe013be4SDimitry Andric       // L2: r3 = COPY r1
1399fe013be4SDimitry Andric       // If we later have
1400fe013be4SDimitry Andric       // L1: r1 = COPY r2
1401fe013be4SDimitry Andric       // L2: r3 = COPY r1
1402fe013be4SDimitry Andric       // L3: r2 = COPY r1
1403fe013be4SDimitry Andric       // L1 and L3 can't be a valid spill-reload pair.
1404fe013be4SDimitry Andric       // Thus we keep the property#1.
1405fe013be4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Not paired spill-reload:\n");
1406fe013be4SDimitry Andric       LLVM_DEBUG(MaybeSpill->dump());
1407fe013be4SDimitry Andric       LLVM_DEBUG(MI.dump());
1408fe013be4SDimitry Andric       Tracker.clobberRegister(Src.asMCReg(), *TRI, *TII, UseCopyInstr);
1409fe013be4SDimitry Andric       LLVM_DEBUG(dbgs() << "MCP: Removed tracking of " << printReg(Src, TRI)
1410fe013be4SDimitry Andric                         << "\n");
1411fe013be4SDimitry Andric     }
1412fe013be4SDimitry Andric     Tracker.trackCopy(&MI, *TRI, *TII, UseCopyInstr);
1413fe013be4SDimitry Andric   }
1414fe013be4SDimitry Andric 
1415fe013be4SDimitry Andric   for (auto I = SpillChain.begin(), E = SpillChain.end(); I != E; ++I) {
1416fe013be4SDimitry Andric     auto &SC = I->second;
1417fe013be4SDimitry Andric     assert(ReloadChain.count(I->first) &&
1418fe013be4SDimitry Andric            "Reload chain of the same leader should exist");
1419fe013be4SDimitry Andric     auto &RC = ReloadChain[I->first];
1420fe013be4SDimitry Andric     TryFoldSpillageCopies(SC, RC);
1421fe013be4SDimitry Andric   }
1422fe013be4SDimitry Andric 
1423fe013be4SDimitry Andric   MaybeDeadCopies.clear();
1424fe013be4SDimitry Andric   CopyDbgUsers.clear();
1425fe013be4SDimitry Andric   Tracker.clear();
1426fe013be4SDimitry Andric }
1427fe013be4SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)14280b57cec5SDimitry Andric bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
14290b57cec5SDimitry Andric   if (skipFunction(MF.getFunction()))
14300b57cec5SDimitry Andric     return false;
14310b57cec5SDimitry Andric 
1432fe013be4SDimitry Andric   bool isSpillageCopyElimEnabled = false;
1433fe013be4SDimitry Andric   switch (EnableSpillageCopyElimination) {
1434fe013be4SDimitry Andric   case cl::BOU_UNSET:
1435fe013be4SDimitry Andric     isSpillageCopyElimEnabled =
1436fe013be4SDimitry Andric         MF.getSubtarget().enableSpillageCopyElimination();
1437fe013be4SDimitry Andric     break;
1438fe013be4SDimitry Andric   case cl::BOU_TRUE:
1439fe013be4SDimitry Andric     isSpillageCopyElimEnabled = true;
1440fe013be4SDimitry Andric     break;
1441fe013be4SDimitry Andric   case cl::BOU_FALSE:
1442fe013be4SDimitry Andric     isSpillageCopyElimEnabled = false;
1443fe013be4SDimitry Andric     break;
1444fe013be4SDimitry Andric   }
1445fe013be4SDimitry 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) {
1453fe013be4SDimitry Andric     if (isSpillageCopyElimEnabled)
1454fe013be4SDimitry 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 *
createMachineCopyPropagationPass(bool UseCopyInstr=false)146381ad6265SDimitry Andric llvm::createMachineCopyPropagationPass(bool UseCopyInstr = false) {
146481ad6265SDimitry Andric   return new MachineCopyPropagation(UseCopyInstr);
146581ad6265SDimitry Andric }
1466