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