xref: /llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp (revision 05da2fe52162c80dfa18aedf70cf73cb11201811)
1 //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is an extremely simple MachineInstr-level copy propagation pass.
10 //
11 // This pass forwards the source of COPYs to the users of their destinations
12 // when doing so is legal.  For example:
13 //
14 //   %reg1 = COPY %reg0
15 //   ...
16 //   ... = OP %reg1
17 //
18 // If
19 //   - %reg0 has not been clobbered by the time of the use of %reg1
20 //   - the register class constraints are satisfied
21 //   - the COPY def is the only value that reaches OP
22 // then this pass replaces the above with:
23 //
24 //   %reg1 = COPY %reg0
25 //   ...
26 //   ... = OP %reg0
27 //
28 // This pass also removes some redundant COPYs.  For example:
29 //
30 //    %R1 = COPY %R0
31 //    ... // No clobber of %R1
32 //    %R0 = COPY %R1 <<< Removed
33 //
34 // or
35 //
36 //    %R1 = COPY %R0
37 //    ... // No clobber of %R0
38 //    %R1 = COPY %R0 <<< Removed
39 //
40 //===----------------------------------------------------------------------===//
41 
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/SetVector.h"
45 #include "llvm/ADT/SmallVector.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/ADT/iterator_range.h"
48 #include "llvm/CodeGen/MachineBasicBlock.h"
49 #include "llvm/CodeGen/MachineFunction.h"
50 #include "llvm/CodeGen/MachineFunctionPass.h"
51 #include "llvm/CodeGen/MachineInstr.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/TargetInstrInfo.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/InitializePasses.h"
58 #include "llvm/MC/MCRegisterInfo.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/DebugCounter.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include <cassert>
64 #include <iterator>
65 
66 using namespace llvm;
67 
68 #define DEBUG_TYPE "machine-cp"
69 
70 STATISTIC(NumDeletes, "Number of dead copies deleted");
71 STATISTIC(NumCopyForwards, "Number of copy uses forwarded");
72 DEBUG_COUNTER(FwdCounter, "machine-cp-fwd",
73               "Controls which register COPYs are forwarded");
74 
75 namespace {
76 
77 class CopyTracker {
78   struct CopyInfo {
79     MachineInstr *MI;
80     SmallVector<unsigned, 4> DefRegs;
81     bool Avail;
82   };
83 
84   DenseMap<unsigned, CopyInfo> Copies;
85 
86 public:
87   /// Mark all of the given registers and their subregisters as unavailable for
88   /// copying.
89   void markRegsUnavailable(ArrayRef<unsigned> Regs,
90                            const TargetRegisterInfo &TRI) {
91     for (unsigned Reg : Regs) {
92       // Source of copy is no longer available for propagation.
93       for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
94         auto CI = Copies.find(*RUI);
95         if (CI != Copies.end())
96           CI->second.Avail = false;
97       }
98     }
99   }
100 
101   /// Clobber a single register, removing it from the tracker's copy maps.
102   void clobberRegister(unsigned Reg, const TargetRegisterInfo &TRI) {
103     for (MCRegUnitIterator RUI(Reg, &TRI); RUI.isValid(); ++RUI) {
104       auto I = Copies.find(*RUI);
105       if (I != Copies.end()) {
106         // When we clobber the source of a copy, we need to clobber everything
107         // it defined.
108         markRegsUnavailable(I->second.DefRegs, TRI);
109         // When we clobber the destination of a copy, we need to clobber the
110         // whole register it defined.
111         if (MachineInstr *MI = I->second.MI)
112           markRegsUnavailable({MI->getOperand(0).getReg()}, TRI);
113         // Now we can erase the copy.
114         Copies.erase(I);
115       }
116     }
117   }
118 
119   /// Add this copy's registers into the tracker's copy maps.
120   void trackCopy(MachineInstr *MI, const TargetRegisterInfo &TRI) {
121     assert(MI->isCopy() && "Tracking non-copy?");
122 
123     Register Def = MI->getOperand(0).getReg();
124     Register Src = MI->getOperand(1).getReg();
125 
126     // Remember Def is defined by the copy.
127     for (MCRegUnitIterator RUI(Def, &TRI); RUI.isValid(); ++RUI)
128       Copies[*RUI] = {MI, {}, true};
129 
130     // Remember source that's copied to Def. Once it's clobbered, then
131     // it's no longer available for copy propagation.
132     for (MCRegUnitIterator RUI(Src, &TRI); RUI.isValid(); ++RUI) {
133       auto I = Copies.insert({*RUI, {nullptr, {}, false}});
134       auto &Copy = I.first->second;
135       if (!is_contained(Copy.DefRegs, Def))
136         Copy.DefRegs.push_back(Def);
137     }
138   }
139 
140   bool hasAnyCopies() {
141     return !Copies.empty();
142   }
143 
144   MachineInstr *findCopyForUnit(unsigned RegUnit, const TargetRegisterInfo &TRI,
145                          bool MustBeAvailable = false) {
146     auto CI = Copies.find(RegUnit);
147     if (CI == Copies.end())
148       return nullptr;
149     if (MustBeAvailable && !CI->second.Avail)
150       return nullptr;
151     return CI->second.MI;
152   }
153 
154   MachineInstr *findAvailCopy(MachineInstr &DestCopy, unsigned Reg,
155                               const TargetRegisterInfo &TRI) {
156     // We check the first RegUnit here, since we'll only be interested in the
157     // copy if it copies the entire register anyway.
158     MCRegUnitIterator RUI(Reg, &TRI);
159     MachineInstr *AvailCopy =
160         findCopyForUnit(*RUI, TRI, /*MustBeAvailable=*/true);
161     if (!AvailCopy ||
162         !TRI.isSubRegisterEq(AvailCopy->getOperand(0).getReg(), Reg))
163       return nullptr;
164 
165     // Check that the available copy isn't clobbered by any regmasks between
166     // itself and the destination.
167     Register AvailSrc = AvailCopy->getOperand(1).getReg();
168     Register AvailDef = AvailCopy->getOperand(0).getReg();
169     for (const MachineInstr &MI :
170          make_range(AvailCopy->getIterator(), DestCopy.getIterator()))
171       for (const MachineOperand &MO : MI.operands())
172         if (MO.isRegMask())
173           if (MO.clobbersPhysReg(AvailSrc) || MO.clobbersPhysReg(AvailDef))
174             return nullptr;
175 
176     return AvailCopy;
177   }
178 
179   void clear() {
180     Copies.clear();
181   }
182 };
183 
184 class MachineCopyPropagation : public MachineFunctionPass {
185   const TargetRegisterInfo *TRI;
186   const TargetInstrInfo *TII;
187   const MachineRegisterInfo *MRI;
188 
189 public:
190   static char ID; // Pass identification, replacement for typeid
191 
192   MachineCopyPropagation() : MachineFunctionPass(ID) {
193     initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
194   }
195 
196   void getAnalysisUsage(AnalysisUsage &AU) const override {
197     AU.setPreservesCFG();
198     MachineFunctionPass::getAnalysisUsage(AU);
199   }
200 
201   bool runOnMachineFunction(MachineFunction &MF) override;
202 
203   MachineFunctionProperties getRequiredProperties() const override {
204     return MachineFunctionProperties().set(
205         MachineFunctionProperties::Property::NoVRegs);
206   }
207 
208 private:
209   typedef enum { DebugUse = false, RegularUse = true } DebugType;
210 
211   void ClobberRegister(unsigned Reg);
212   void ReadRegister(unsigned Reg, MachineInstr &Reader,
213                     DebugType DT);
214   void CopyPropagateBlock(MachineBasicBlock &MBB);
215   bool eraseIfRedundant(MachineInstr &Copy, unsigned Src, unsigned Def);
216   void forwardUses(MachineInstr &MI);
217   bool isForwardableRegClassCopy(const MachineInstr &Copy,
218                                  const MachineInstr &UseI, unsigned UseIdx);
219   bool hasImplicitOverlap(const MachineInstr &MI, const MachineOperand &Use);
220 
221   /// Candidates for deletion.
222   SmallSetVector<MachineInstr *, 8> MaybeDeadCopies;
223 
224   /// Multimap tracking debug users in current BB
225   DenseMap<MachineInstr*, SmallVector<MachineInstr*, 2>> CopyDbgUsers;
226 
227   CopyTracker Tracker;
228 
229   bool Changed;
230 };
231 
232 } // end anonymous namespace
233 
234 char MachineCopyPropagation::ID = 0;
235 
236 char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
237 
238 INITIALIZE_PASS(MachineCopyPropagation, DEBUG_TYPE,
239                 "Machine Copy Propagation Pass", false, false)
240 
241 void MachineCopyPropagation::ReadRegister(unsigned Reg, MachineInstr &Reader,
242                                           DebugType DT) {
243   // If 'Reg' is defined by a copy, the copy is no longer a candidate
244   // for elimination. If a copy is "read" by a debug user, record the user
245   // for propagation.
246   for (MCRegUnitIterator RUI(Reg, TRI); RUI.isValid(); ++RUI) {
247     if (MachineInstr *Copy = Tracker.findCopyForUnit(*RUI, *TRI)) {
248       if (DT == RegularUse) {
249         LLVM_DEBUG(dbgs() << "MCP: Copy is used - not dead: "; Copy->dump());
250         MaybeDeadCopies.remove(Copy);
251       } else {
252         CopyDbgUsers[Copy].push_back(&Reader);
253       }
254     }
255   }
256 }
257 
258 /// Return true if \p PreviousCopy did copy register \p Src to register \p Def.
259 /// This fact may have been obscured by sub register usage or may not be true at
260 /// all even though Src and Def are subregisters of the registers used in
261 /// PreviousCopy. e.g.
262 /// isNopCopy("ecx = COPY eax", AX, CX) == true
263 /// isNopCopy("ecx = COPY eax", AH, CL) == false
264 static bool isNopCopy(const MachineInstr &PreviousCopy, unsigned Src,
265                       unsigned Def, const TargetRegisterInfo *TRI) {
266   Register PreviousSrc = PreviousCopy.getOperand(1).getReg();
267   Register PreviousDef = PreviousCopy.getOperand(0).getReg();
268   if (Src == PreviousSrc) {
269     assert(Def == PreviousDef);
270     return true;
271   }
272   if (!TRI->isSubRegister(PreviousSrc, Src))
273     return false;
274   unsigned SubIdx = TRI->getSubRegIndex(PreviousSrc, Src);
275   return SubIdx == TRI->getSubRegIndex(PreviousDef, Def);
276 }
277 
278 /// Remove instruction \p Copy if there exists a previous copy that copies the
279 /// register \p Src to the register \p Def; This may happen indirectly by
280 /// copying the super registers.
281 bool MachineCopyPropagation::eraseIfRedundant(MachineInstr &Copy, unsigned Src,
282                                               unsigned Def) {
283   // Avoid eliminating a copy from/to a reserved registers as we cannot predict
284   // the value (Example: The sparc zero register is writable but stays zero).
285   if (MRI->isReserved(Src) || MRI->isReserved(Def))
286     return false;
287 
288   // Search for an existing copy.
289   MachineInstr *PrevCopy = Tracker.findAvailCopy(Copy, Def, *TRI);
290   if (!PrevCopy)
291     return false;
292 
293   // Check that the existing copy uses the correct sub registers.
294   if (PrevCopy->getOperand(0).isDead())
295     return false;
296   if (!isNopCopy(*PrevCopy, Src, Def, TRI))
297     return false;
298 
299   LLVM_DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; Copy.dump());
300 
301   // Copy was redundantly redefining either Src or Def. Remove earlier kill
302   // flags between Copy and PrevCopy because the value will be reused now.
303   assert(Copy.isCopy());
304   Register CopyDef = Copy.getOperand(0).getReg();
305   assert(CopyDef == Src || CopyDef == Def);
306   for (MachineInstr &MI :
307        make_range(PrevCopy->getIterator(), Copy.getIterator()))
308     MI.clearRegisterKills(CopyDef, TRI);
309 
310   Copy.eraseFromParent();
311   Changed = true;
312   ++NumDeletes;
313   return true;
314 }
315 
316 /// Decide whether we should forward the source of \param Copy to its use in
317 /// \param UseI based on the physical register class constraints of the opcode
318 /// and avoiding introducing more cross-class COPYs.
319 bool MachineCopyPropagation::isForwardableRegClassCopy(const MachineInstr &Copy,
320                                                        const MachineInstr &UseI,
321                                                        unsigned UseIdx) {
322 
323   Register CopySrcReg = Copy.getOperand(1).getReg();
324 
325   // If the new register meets the opcode register constraints, then allow
326   // forwarding.
327   if (const TargetRegisterClass *URC =
328           UseI.getRegClassConstraint(UseIdx, TII, TRI))
329     return URC->contains(CopySrcReg);
330 
331   if (!UseI.isCopy())
332     return false;
333 
334   /// COPYs don't have register class constraints, so if the user instruction
335   /// is a COPY, we just try to avoid introducing additional cross-class
336   /// COPYs.  For example:
337   ///
338   ///   RegClassA = COPY RegClassB  // Copy parameter
339   ///   ...
340   ///   RegClassB = COPY RegClassA  // UseI parameter
341   ///
342   /// which after forwarding becomes
343   ///
344   ///   RegClassA = COPY RegClassB
345   ///   ...
346   ///   RegClassB = COPY RegClassB
347   ///
348   /// so we have reduced the number of cross-class COPYs and potentially
349   /// introduced a nop COPY that can be removed.
350   const TargetRegisterClass *UseDstRC =
351       TRI->getMinimalPhysRegClass(UseI.getOperand(0).getReg());
352 
353   const TargetRegisterClass *SuperRC = UseDstRC;
354   for (TargetRegisterClass::sc_iterator SuperRCI = UseDstRC->getSuperClasses();
355        SuperRC; SuperRC = *SuperRCI++)
356     if (SuperRC->contains(CopySrcReg))
357       return true;
358 
359   return false;
360 }
361 
362 /// Check that \p MI does not have implicit uses that overlap with it's \p Use
363 /// operand (the register being replaced), since these can sometimes be
364 /// implicitly tied to other operands.  For example, on AMDGPU:
365 ///
366 /// V_MOVRELS_B32_e32 %VGPR2, %M0<imp-use>, %EXEC<imp-use>, %VGPR2_VGPR3_VGPR4_VGPR5<imp-use>
367 ///
368 /// the %VGPR2 is implicitly tied to the larger reg operand, but we have no
369 /// way of knowing we need to update the latter when updating the former.
370 bool MachineCopyPropagation::hasImplicitOverlap(const MachineInstr &MI,
371                                                 const MachineOperand &Use) {
372   for (const MachineOperand &MIUse : MI.uses())
373     if (&MIUse != &Use && MIUse.isReg() && MIUse.isImplicit() &&
374         MIUse.isUse() && TRI->regsOverlap(Use.getReg(), MIUse.getReg()))
375       return true;
376 
377   return false;
378 }
379 
380 /// Look for available copies whose destination register is used by \p MI and
381 /// replace the use in \p MI with the copy's source register.
382 void MachineCopyPropagation::forwardUses(MachineInstr &MI) {
383   if (!Tracker.hasAnyCopies())
384     return;
385 
386   // Look for non-tied explicit vreg uses that have an active COPY
387   // instruction that defines the physical register allocated to them.
388   // Replace the vreg with the source of the active COPY.
389   for (unsigned OpIdx = 0, OpEnd = MI.getNumOperands(); OpIdx < OpEnd;
390        ++OpIdx) {
391     MachineOperand &MOUse = MI.getOperand(OpIdx);
392     // Don't forward into undef use operands since doing so can cause problems
393     // with the machine verifier, since it doesn't treat undef reads as reads,
394     // so we can end up with a live range that ends on an undef read, leading to
395     // an error that the live range doesn't end on a read of the live range
396     // register.
397     if (!MOUse.isReg() || MOUse.isTied() || MOUse.isUndef() || MOUse.isDef() ||
398         MOUse.isImplicit())
399       continue;
400 
401     if (!MOUse.getReg())
402       continue;
403 
404     // Check that the register is marked 'renamable' so we know it is safe to
405     // rename it without violating any constraints that aren't expressed in the
406     // IR (e.g. ABI or opcode requirements).
407     if (!MOUse.isRenamable())
408       continue;
409 
410     MachineInstr *Copy = Tracker.findAvailCopy(MI, MOUse.getReg(), *TRI);
411     if (!Copy)
412       continue;
413 
414     Register CopyDstReg = Copy->getOperand(0).getReg();
415     const MachineOperand &CopySrc = Copy->getOperand(1);
416     Register CopySrcReg = CopySrc.getReg();
417 
418     // FIXME: Don't handle partial uses of wider COPYs yet.
419     if (MOUse.getReg() != CopyDstReg) {
420       LLVM_DEBUG(
421           dbgs() << "MCP: FIXME! Not forwarding COPY to sub-register use:\n  "
422                  << MI);
423       continue;
424     }
425 
426     // Don't forward COPYs of reserved regs unless they are constant.
427     if (MRI->isReserved(CopySrcReg) && !MRI->isConstantPhysReg(CopySrcReg))
428       continue;
429 
430     if (!isForwardableRegClassCopy(*Copy, MI, OpIdx))
431       continue;
432 
433     if (hasImplicitOverlap(MI, MOUse))
434       continue;
435 
436     // Check that the instruction is not a copy that partially overwrites the
437     // original copy source that we are about to use. The tracker mechanism
438     // cannot cope with that.
439     if (MI.isCopy() && MI.modifiesRegister(CopySrcReg, TRI) &&
440         !MI.definesRegister(CopySrcReg)) {
441       LLVM_DEBUG(dbgs() << "MCP: Copy source overlap with dest in " << MI);
442       continue;
443     }
444 
445     if (!DebugCounter::shouldExecute(FwdCounter)) {
446       LLVM_DEBUG(dbgs() << "MCP: Skipping forwarding due to debug counter:\n  "
447                         << MI);
448       continue;
449     }
450 
451     LLVM_DEBUG(dbgs() << "MCP: Replacing " << printReg(MOUse.getReg(), TRI)
452                       << "\n     with " << printReg(CopySrcReg, TRI)
453                       << "\n     in " << MI << "     from " << *Copy);
454 
455     MOUse.setReg(CopySrcReg);
456     if (!CopySrc.isRenamable())
457       MOUse.setIsRenamable(false);
458 
459     LLVM_DEBUG(dbgs() << "MCP: After replacement: " << MI << "\n");
460 
461     // Clear kill markers that may have been invalidated.
462     for (MachineInstr &KMI :
463          make_range(Copy->getIterator(), std::next(MI.getIterator())))
464       KMI.clearRegisterKills(CopySrcReg, TRI);
465 
466     ++NumCopyForwards;
467     Changed = true;
468   }
469 }
470 
471 void MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
472   LLVM_DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
473 
474   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
475     MachineInstr *MI = &*I;
476     ++I;
477 
478     // Analyze copies (which don't overlap themselves).
479     if (MI->isCopy() && !TRI->regsOverlap(MI->getOperand(0).getReg(),
480                                           MI->getOperand(1).getReg())) {
481       Register Def = MI->getOperand(0).getReg();
482       Register Src = MI->getOperand(1).getReg();
483 
484       assert(!Register::isVirtualRegister(Def) &&
485              !Register::isVirtualRegister(Src) &&
486              "MachineCopyPropagation should be run after register allocation!");
487 
488       // The two copies cancel out and the source of the first copy
489       // hasn't been overridden, eliminate the second one. e.g.
490       //  %ecx = COPY %eax
491       //  ... nothing clobbered eax.
492       //  %eax = COPY %ecx
493       // =>
494       //  %ecx = COPY %eax
495       //
496       // or
497       //
498       //  %ecx = COPY %eax
499       //  ... nothing clobbered eax.
500       //  %ecx = COPY %eax
501       // =>
502       //  %ecx = COPY %eax
503       if (eraseIfRedundant(*MI, Def, Src) || eraseIfRedundant(*MI, Src, Def))
504         continue;
505 
506       forwardUses(*MI);
507 
508       // Src may have been changed by forwardUses()
509       Src = MI->getOperand(1).getReg();
510 
511       // If Src is defined by a previous copy, the previous copy cannot be
512       // eliminated.
513       ReadRegister(Src, *MI, RegularUse);
514       for (const MachineOperand &MO : MI->implicit_operands()) {
515         if (!MO.isReg() || !MO.readsReg())
516           continue;
517         Register Reg = MO.getReg();
518         if (!Reg)
519           continue;
520         ReadRegister(Reg, *MI, RegularUse);
521       }
522 
523       LLVM_DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
524 
525       // Copy is now a candidate for deletion.
526       if (!MRI->isReserved(Def))
527         MaybeDeadCopies.insert(MI);
528 
529       // If 'Def' is previously source of another copy, then this earlier copy's
530       // source is no longer available. e.g.
531       // %xmm9 = copy %xmm2
532       // ...
533       // %xmm2 = copy %xmm0
534       // ...
535       // %xmm2 = copy %xmm9
536       Tracker.clobberRegister(Def, *TRI);
537       for (const MachineOperand &MO : MI->implicit_operands()) {
538         if (!MO.isReg() || !MO.isDef())
539           continue;
540         Register Reg = MO.getReg();
541         if (!Reg)
542           continue;
543         Tracker.clobberRegister(Reg, *TRI);
544       }
545 
546       Tracker.trackCopy(MI, *TRI);
547 
548       continue;
549     }
550 
551     // Clobber any earlyclobber regs first.
552     for (const MachineOperand &MO : MI->operands())
553       if (MO.isReg() && MO.isEarlyClobber()) {
554         Register Reg = MO.getReg();
555         // If we have a tied earlyclobber, that means it is also read by this
556         // instruction, so we need to make sure we don't remove it as dead
557         // later.
558         if (MO.isTied())
559           ReadRegister(Reg, *MI, RegularUse);
560         Tracker.clobberRegister(Reg, *TRI);
561       }
562 
563     forwardUses(*MI);
564 
565     // Not a copy.
566     SmallVector<unsigned, 2> Defs;
567     const MachineOperand *RegMask = nullptr;
568     for (const MachineOperand &MO : MI->operands()) {
569       if (MO.isRegMask())
570         RegMask = &MO;
571       if (!MO.isReg())
572         continue;
573       Register Reg = MO.getReg();
574       if (!Reg)
575         continue;
576 
577       assert(!Register::isVirtualRegister(Reg) &&
578              "MachineCopyPropagation should be run after register allocation!");
579 
580       if (MO.isDef() && !MO.isEarlyClobber()) {
581         Defs.push_back(Reg);
582         continue;
583       } else if (MO.readsReg())
584         ReadRegister(Reg, *MI, MO.isDebug() ? DebugUse : RegularUse);
585     }
586 
587     // The instruction has a register mask operand which means that it clobbers
588     // a large set of registers.  Treat clobbered registers the same way as
589     // defined registers.
590     if (RegMask) {
591       // Erase any MaybeDeadCopies whose destination register is clobbered.
592       for (SmallSetVector<MachineInstr *, 8>::iterator DI =
593                MaybeDeadCopies.begin();
594            DI != MaybeDeadCopies.end();) {
595         MachineInstr *MaybeDead = *DI;
596         Register Reg = MaybeDead->getOperand(0).getReg();
597         assert(!MRI->isReserved(Reg));
598 
599         if (!RegMask->clobbersPhysReg(Reg)) {
600           ++DI;
601           continue;
602         }
603 
604         LLVM_DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
605                    MaybeDead->dump());
606 
607         // Make sure we invalidate any entries in the copy maps before erasing
608         // the instruction.
609         Tracker.clobberRegister(Reg, *TRI);
610 
611         // erase() will return the next valid iterator pointing to the next
612         // element after the erased one.
613         DI = MaybeDeadCopies.erase(DI);
614         MaybeDead->eraseFromParent();
615         Changed = true;
616         ++NumDeletes;
617       }
618     }
619 
620     // Any previous copy definition or reading the Defs is no longer available.
621     for (unsigned Reg : Defs)
622       Tracker.clobberRegister(Reg, *TRI);
623   }
624 
625   // If MBB doesn't have successors, delete the copies whose defs are not used.
626   // If MBB does have successors, then conservative assume the defs are live-out
627   // since we don't want to trust live-in lists.
628   if (MBB.succ_empty()) {
629     for (MachineInstr *MaybeDead : MaybeDeadCopies) {
630       LLVM_DEBUG(dbgs() << "MCP: Removing copy due to no live-out succ: ";
631                  MaybeDead->dump());
632       assert(!MRI->isReserved(MaybeDead->getOperand(0).getReg()));
633 
634       // Update matching debug values, if any.
635       assert(MaybeDead->isCopy());
636       unsigned SrcReg = MaybeDead->getOperand(1).getReg();
637       MRI->updateDbgUsersToReg(SrcReg, CopyDbgUsers[MaybeDead]);
638 
639       MaybeDead->eraseFromParent();
640       Changed = true;
641       ++NumDeletes;
642     }
643   }
644 
645   MaybeDeadCopies.clear();
646   CopyDbgUsers.clear();
647   Tracker.clear();
648 }
649 
650 bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
651   if (skipFunction(MF.getFunction()))
652     return false;
653 
654   Changed = false;
655 
656   TRI = MF.getSubtarget().getRegisterInfo();
657   TII = MF.getSubtarget().getInstrInfo();
658   MRI = &MF.getRegInfo();
659 
660   for (MachineBasicBlock &MBB : MF)
661     CopyPropagateBlock(MBB);
662 
663   return Changed;
664 }
665