xref: /llvm-project/llvm/lib/CodeGen/MachineCopyPropagation.cpp (revision 57b5f11aa706a182a85c6d7a89e762aa63661c18)
1 //===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is an extremely simple MachineInstr-level copy propagation pass.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/Passes.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "codegen-cp"
31 
32 STATISTIC(NumDeletes, "Number of dead copies deleted");
33 
34 namespace {
35   class MachineCopyPropagation : public MachineFunctionPass {
36     const TargetRegisterInfo *TRI;
37     const TargetInstrInfo *TII;
38     MachineRegisterInfo *MRI;
39 
40   public:
41     static char ID; // Pass identification, replacement for typeid
42     MachineCopyPropagation() : MachineFunctionPass(ID) {
43      initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
44     }
45 
46     bool runOnMachineFunction(MachineFunction &MF) override;
47 
48   private:
49     typedef SmallVector<unsigned, 4> DestList;
50     typedef DenseMap<unsigned, DestList> SourceMap;
51 
52     void SourceNoLongerAvailable(unsigned Reg,
53                                  SourceMap &SrcMap,
54                                  DenseMap<unsigned, MachineInstr*> &AvailCopyMap);
55     bool CopyPropagateBlock(MachineBasicBlock &MBB);
56   };
57 }
58 char MachineCopyPropagation::ID = 0;
59 char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
60 
61 INITIALIZE_PASS(MachineCopyPropagation, "machine-cp",
62                 "Machine Copy Propagation Pass", false, false)
63 
64 void
65 MachineCopyPropagation::SourceNoLongerAvailable(unsigned Reg,
66                               SourceMap &SrcMap,
67                               DenseMap<unsigned, MachineInstr*> &AvailCopyMap) {
68   for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
69     SourceMap::iterator SI = SrcMap.find(*AI);
70     if (SI != SrcMap.end()) {
71       const DestList& Defs = SI->second;
72       for (DestList::const_iterator I = Defs.begin(), E = Defs.end();
73            I != E; ++I) {
74         unsigned MappedDef = *I;
75         // Source of copy is no longer available for propagation.
76         AvailCopyMap.erase(MappedDef);
77         for (MCSubRegIterator SR(MappedDef, TRI); SR.isValid(); ++SR)
78           AvailCopyMap.erase(*SR);
79       }
80     }
81   }
82 }
83 
84 static bool NoInterveningSideEffect(const MachineInstr *CopyMI,
85                                     const MachineInstr *MI) {
86   const MachineBasicBlock *MBB = CopyMI->getParent();
87   if (MI->getParent() != MBB)
88     return false;
89   MachineBasicBlock::const_iterator I = CopyMI;
90   MachineBasicBlock::const_iterator E = MBB->end();
91   MachineBasicBlock::const_iterator E2 = MI;
92 
93   ++I;
94   while (I != E && I != E2) {
95     if (I->hasUnmodeledSideEffects() || I->isCall() ||
96         I->isTerminator())
97       return false;
98     ++I;
99   }
100   return true;
101 }
102 
103 /// isNopCopy - Return true if the specified copy is really a nop. That is
104 /// if the source of the copy is the same of the definition of the copy that
105 /// supplied the source. If the source of the copy is a sub-register than it
106 /// must check the sub-indices match. e.g.
107 /// ecx = mov eax
108 /// al  = mov cl
109 /// But not
110 /// ecx = mov eax
111 /// al  = mov ch
112 static bool isNopCopy(MachineInstr *CopyMI, unsigned Def, unsigned Src,
113                       const TargetRegisterInfo *TRI) {
114   unsigned SrcSrc = CopyMI->getOperand(1).getReg();
115   if (Def == SrcSrc)
116     return true;
117   if (TRI->isSubRegister(SrcSrc, Def)) {
118     unsigned SrcDef = CopyMI->getOperand(0).getReg();
119     unsigned SubIdx = TRI->getSubRegIndex(SrcSrc, Def);
120     if (!SubIdx)
121       return false;
122     return SubIdx == TRI->getSubRegIndex(SrcDef, Src);
123   }
124 
125   return false;
126 }
127 
128 bool MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
129   SmallSetVector<MachineInstr*, 8> MaybeDeadCopies;  // Candidates for deletion
130   DenseMap<unsigned, MachineInstr*> AvailCopyMap;    // Def -> available copies map
131   DenseMap<unsigned, MachineInstr*> CopyMap;         // Def -> copies map
132   SourceMap SrcMap; // Src -> Def map
133 
134   DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
135 
136   bool Changed = false;
137   for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
138     MachineInstr *MI = &*I;
139     ++I;
140 
141     if (MI->isCopy()) {
142       unsigned Def = MI->getOperand(0).getReg();
143       unsigned Src = MI->getOperand(1).getReg();
144 
145       assert(!TargetRegisterInfo::isVirtualRegister(Def) &&
146              !TargetRegisterInfo::isVirtualRegister(Src) &&
147              "MachineCopyPropagation should be run after register allocation!");
148 
149       DenseMap<unsigned, MachineInstr*>::iterator CI = AvailCopyMap.find(Src);
150       if (CI != AvailCopyMap.end()) {
151         MachineInstr *CopyMI = CI->second;
152         if (!MRI->isReserved(Def) &&
153             (!MRI->isReserved(Src) || NoInterveningSideEffect(CopyMI, MI)) &&
154             isNopCopy(CopyMI, Def, Src, TRI)) {
155           // The two copies cancel out and the source of the first copy
156           // hasn't been overridden, eliminate the second one. e.g.
157           //  %ECX<def> = COPY %EAX<kill>
158           //  ... nothing clobbered EAX.
159           //  %EAX<def> = COPY %ECX
160           // =>
161           //  %ECX<def> = COPY %EAX
162           //
163           // Also avoid eliminating a copy from reserved registers unless the
164           // definition is proven not clobbered. e.g.
165           // %RSP<def> = COPY %RAX
166           // CALL
167           // %RAX<def> = COPY %RSP
168 
169           DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; MI->dump());
170 
171           // Clear any kills of Def between CopyMI and MI. This extends the
172           // live range.
173           for (MachineBasicBlock::iterator I = CopyMI, E = MI; I != E; ++I)
174             I->clearRegisterKills(Def, TRI);
175 
176           MI->eraseFromParent();
177           Changed = true;
178           ++NumDeletes;
179           continue;
180         }
181       }
182 
183       // If Src is defined by a previous copy, the previous copy cannot be
184       // eliminated.
185       for (MCRegAliasIterator AI(Src, TRI, true); AI.isValid(); ++AI) {
186         CI = CopyMap.find(*AI);
187         if (CI != CopyMap.end()) {
188           DEBUG(dbgs() << "MCP: Copy is no longer dead: "; CI->second->dump());
189           MaybeDeadCopies.remove(CI->second);
190         }
191       }
192 
193       DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
194 
195       // Copy is now a candidate for deletion.
196       MaybeDeadCopies.insert(MI);
197 
198       // If 'Def' is previously source of another copy, then this earlier copy's
199       // source is no longer available. e.g.
200       // %xmm9<def> = copy %xmm2
201       // ...
202       // %xmm2<def> = copy %xmm0
203       // ...
204       // %xmm2<def> = copy %xmm9
205       SourceNoLongerAvailable(Def, SrcMap, AvailCopyMap);
206 
207       // Remember Def is defined by the copy.
208       // ... Make sure to clear the def maps of aliases first.
209       for (MCRegAliasIterator AI(Def, TRI, false); AI.isValid(); ++AI) {
210         CopyMap.erase(*AI);
211         AvailCopyMap.erase(*AI);
212       }
213       for (MCSubRegIterator SR(Def, TRI, /*IncludeSelf=*/true); SR.isValid();
214            ++SR) {
215         CopyMap[*SR] = MI;
216         AvailCopyMap[*SR] = MI;
217       }
218 
219       // Remember source that's copied to Def. Once it's clobbered, then
220       // it's no longer available for copy propagation.
221       if (std::find(SrcMap[Src].begin(), SrcMap[Src].end(), Def) ==
222           SrcMap[Src].end()) {
223         SrcMap[Src].push_back(Def);
224       }
225 
226       continue;
227     }
228 
229     // Not a copy.
230     SmallVector<unsigned, 2> Defs;
231     int RegMaskOpNum = -1;
232     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
233       MachineOperand &MO = MI->getOperand(i);
234       if (MO.isRegMask())
235         RegMaskOpNum = i;
236       if (!MO.isReg())
237         continue;
238       unsigned Reg = MO.getReg();
239       if (!Reg)
240         continue;
241 
242       assert(!TargetRegisterInfo::isVirtualRegister(Reg) &&
243              "MachineCopyPropagation should be run after register allocation!");
244 
245       if (MO.isDef()) {
246         Defs.push_back(Reg);
247         continue;
248       }
249 
250       // If 'Reg' is defined by a copy, the copy is no longer a candidate
251       // for elimination.
252       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
253         DenseMap<unsigned, MachineInstr*>::iterator CI = CopyMap.find(*AI);
254         if (CI != CopyMap.end()) {
255           DEBUG(dbgs() << "MCP: Copy is used - not dead: "; CI->second->dump());
256           MaybeDeadCopies.remove(CI->second);
257         }
258       }
259       // Treat undef use like defs for copy propagation but not for
260       // dead copy. We would need to do a liveness check to be sure the copy
261       // is dead for undef uses.
262       // The backends are allowed to do whatever they want with undef value
263       // and we cannot be sure this register will not be rewritten to break
264       // some false dependencies for the hardware for instance.
265       if (MO.isUndef())
266         Defs.push_back(Reg);
267     }
268 
269     // The instruction has a register mask operand which means that it clobbers
270     // a large set of registers.  It is possible to use the register mask to
271     // prune the available copies, but treat it like a basic block boundary for
272     // now.
273     if (RegMaskOpNum >= 0) {
274       // Erase any MaybeDeadCopies whose destination register is clobbered.
275       const MachineOperand &MaskMO = MI->getOperand(RegMaskOpNum);
276       for (SmallSetVector<MachineInstr*, 8>::iterator
277            DI = MaybeDeadCopies.begin(), DE = MaybeDeadCopies.end();
278            DI != DE; ++DI) {
279         unsigned Reg = (*DI)->getOperand(0).getReg();
280         if (MRI->isReserved(Reg) || !MaskMO.clobbersPhysReg(Reg))
281           continue;
282         DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
283               (*DI)->dump());
284         (*DI)->eraseFromParent();
285         Changed = true;
286         ++NumDeletes;
287       }
288 
289       // Clear all data structures as if we were beginning a new basic block.
290       MaybeDeadCopies.clear();
291       AvailCopyMap.clear();
292       CopyMap.clear();
293       SrcMap.clear();
294       continue;
295     }
296 
297     for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
298       unsigned Reg = Defs[i];
299 
300       // No longer defined by a copy.
301       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
302         CopyMap.erase(*AI);
303         AvailCopyMap.erase(*AI);
304       }
305 
306       // If 'Reg' is previously source of a copy, it is no longer available for
307       // copy propagation.
308       SourceNoLongerAvailable(Reg, SrcMap, AvailCopyMap);
309     }
310   }
311 
312   // If MBB doesn't have successors, delete the copies whose defs are not used.
313   // If MBB does have successors, then conservative assume the defs are live-out
314   // since we don't want to trust live-in lists.
315   if (MBB.succ_empty()) {
316     for (SmallSetVector<MachineInstr*, 8>::iterator
317            DI = MaybeDeadCopies.begin(), DE = MaybeDeadCopies.end();
318          DI != DE; ++DI) {
319       if (!MRI->isReserved((*DI)->getOperand(0).getReg())) {
320         (*DI)->eraseFromParent();
321         Changed = true;
322         ++NumDeletes;
323       }
324     }
325   }
326 
327   return Changed;
328 }
329 
330 bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
331   if (skipOptnoneFunction(*MF.getFunction()))
332     return false;
333 
334   bool Changed = false;
335 
336   TRI = MF.getSubtarget().getRegisterInfo();
337   TII = MF.getSubtarget().getInstrInfo();
338   MRI = &MF.getRegInfo();
339 
340   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
341     Changed |= CopyPropagateBlock(*I);
342 
343   return Changed;
344 }
345