blob: b24569233820ce14ad4dc850f11e6de327d3b81e [file] [log] [blame]
Bill Wendling6cdb1ab2010-08-09 23:59:04 +00001//===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
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// Perform peephole optimizations on the machine code:
11//
12// - Optimize Extensions
13//
14// Optimization of sign / zero extension instructions. It may be extended to
15// handle other instructions with similar properties.
16//
17// On some targets, some instructions, e.g. X86 sign / zero extension, may
18// leave the source value in the lower part of the result. This optimization
19// will replace some uses of the pre-extension value with uses of the
20// sub-register of the results.
21//
22// - Optimize Comparisons
23//
24// Optimization of comparison instructions. For instance, in this code:
25//
26// sub r1, 1
27// cmp r1, 0
28// bz L1
29//
30// If the "sub" instruction all ready sets (or could be modified to set) the
31// same flag that the "cmp" instruction sets and that "bz" uses, then we can
32// eliminate the "cmp" instruction.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "peephole-opt"
37#include "llvm/CodeGen/Passes.h"
38#include "llvm/CodeGen/MachineDominators.h"
39#include "llvm/CodeGen/MachineInstrBuilder.h"
40#include "llvm/CodeGen/MachineRegisterInfo.h"
41#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetRegisterInfo.h"
43#include "llvm/Support/CommandLine.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/Statistic.h"
46using namespace llvm;
47
48// Optimize Extensions
49static cl::opt<bool>
50Aggressive("aggressive-ext-opt", cl::Hidden,
51 cl::desc("Aggressive extension optimization"));
52
Bill Wendling69c5eb52010-08-27 20:39:09 +000053STATISTIC(NumReuse, "Number of extension results reused");
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000054STATISTIC(NumEliminated, "Number of compares eliminated");
55
56namespace {
57 class PeepholeOptimizer : public MachineFunctionPass {
58 const TargetMachine *TM;
59 const TargetInstrInfo *TII;
60 MachineRegisterInfo *MRI;
61 MachineDominatorTree *DT; // Machine dominator tree
62
63 public:
64 static char ID; // Pass identification
65 PeepholeOptimizer() : MachineFunctionPass(ID) {}
66
67 virtual bool runOnMachineFunction(MachineFunction &MF);
68
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.setPreservesCFG();
71 MachineFunctionPass::getAnalysisUsage(AU);
72 if (Aggressive) {
73 AU.addRequired<MachineDominatorTree>();
74 AU.addPreserved<MachineDominatorTree>();
75 }
76 }
77
78 private:
Bill Wendling220e2402010-09-10 21:55:43 +000079 bool OptimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB,
80 MachineBasicBlock::iterator &MII);
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000081 bool OptimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
82 SmallPtrSet<MachineInstr*, 8> &LocalMIs);
83 };
84}
85
86char PeepholeOptimizer::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000087INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
88 "Peephole Optimizations", false, false)
89INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
90INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
Owen Andersonce665bd2010-10-07 22:25:06 +000091 "Peephole Optimizations", false, false)
Bill Wendling6cdb1ab2010-08-09 23:59:04 +000092
93FunctionPass *llvm::createPeepholeOptimizerPass() {
94 return new PeepholeOptimizer();
95}
96
97/// OptimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
98/// a single register and writes a single register and it does not modify the
99/// source, and if the source value is preserved as a sub-register of the
100/// result, then replace all reachable uses of the source with the subreg of the
101/// result.
102///
103/// Do not generate an EXTRACT that is used only in a debug use, as this changes
104/// the code. Since this code does not currently share EXTRACTs, just ignore all
105/// debug uses.
106bool PeepholeOptimizer::
107OptimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
108 SmallPtrSet<MachineInstr*, 8> &LocalMIs) {
109 LocalMIs.insert(MI);
110
111 unsigned SrcReg, DstReg, SubIdx;
112 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
113 return false;
114
115 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
116 TargetRegisterInfo::isPhysicalRegister(SrcReg))
117 return false;
118
119 MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(SrcReg);
120 if (++UI == MRI->use_nodbg_end())
121 // No other uses.
122 return false;
123
124 // The source has other uses. See if we can replace the other uses with use of
125 // the result of the extension.
126 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
127 UI = MRI->use_nodbg_begin(DstReg);
128 for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
129 UI != UE; ++UI)
130 ReachedBBs.insert(UI->getParent());
131
132 // Uses that are in the same BB of uses of the result of the instruction.
133 SmallVector<MachineOperand*, 8> Uses;
134
135 // Uses that the result of the instruction can reach.
136 SmallVector<MachineOperand*, 8> ExtendedUses;
137
138 bool ExtendLife = true;
139 UI = MRI->use_nodbg_begin(SrcReg);
140 for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
141 UI != UE; ++UI) {
142 MachineOperand &UseMO = UI.getOperand();
143 MachineInstr *UseMI = &*UI;
144 if (UseMI == MI)
145 continue;
146
147 if (UseMI->isPHI()) {
148 ExtendLife = false;
149 continue;
150 }
151
152 // It's an error to translate this:
153 //
154 // %reg1025 = <sext> %reg1024
155 // ...
156 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
157 //
158 // into this:
159 //
160 // %reg1025 = <sext> %reg1024
161 // ...
162 // %reg1027 = COPY %reg1025:4
163 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
164 //
165 // The problem here is that SUBREG_TO_REG is there to assert that an
166 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
167 // the COPY here, it will give us the value after the <sext>, not the
168 // original value of %reg1024 before <sext>.
169 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
170 continue;
171
172 MachineBasicBlock *UseMBB = UseMI->getParent();
173 if (UseMBB == MBB) {
174 // Local uses that come after the extension.
175 if (!LocalMIs.count(UseMI))
176 Uses.push_back(&UseMO);
177 } else if (ReachedBBs.count(UseMBB)) {
178 // Non-local uses where the result of the extension is used. Always
179 // replace these unless it's a PHI.
180 Uses.push_back(&UseMO);
181 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
182 // We may want to extend the live range of the extension result in order
183 // to replace these uses.
184 ExtendedUses.push_back(&UseMO);
185 } else {
186 // Both will be live out of the def MBB anyway. Don't extend live range of
187 // the extension result.
188 ExtendLife = false;
189 break;
190 }
191 }
192
193 if (ExtendLife && !ExtendedUses.empty())
194 // Extend the liveness of the extension result.
195 std::copy(ExtendedUses.begin(), ExtendedUses.end(),
196 std::back_inserter(Uses));
197
198 // Now replace all uses.
199 bool Changed = false;
200 if (!Uses.empty()) {
201 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
202
203 // Look for PHI uses of the extended result, we don't want to extend the
204 // liveness of a PHI input. It breaks all kinds of assumptions down
205 // stream. A PHI use is expected to be the kill of its source values.
206 UI = MRI->use_nodbg_begin(DstReg);
207 for (MachineRegisterInfo::use_nodbg_iterator
208 UE = MRI->use_nodbg_end(); UI != UE; ++UI)
209 if (UI->isPHI())
210 PHIBBs.insert(UI->getParent());
211
212 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
213 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
214 MachineOperand *UseMO = Uses[i];
215 MachineInstr *UseMI = UseMO->getParent();
216 MachineBasicBlock *UseMBB = UseMI->getParent();
217 if (PHIBBs.count(UseMBB))
218 continue;
219
220 unsigned NewVR = MRI->createVirtualRegister(RC);
221 BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
222 TII->get(TargetOpcode::COPY), NewVR)
223 .addReg(DstReg, 0, SubIdx);
224
225 UseMO->setReg(NewVR);
226 ++NumReuse;
227 Changed = true;
228 }
229 }
230
231 return Changed;
232}
233
234/// OptimizeCmpInstr - If the instruction is a compare and the previous
235/// instruction it's comparing against all ready sets (or could be modified to
236/// set) the same flag as the compare, then we can remove the comparison and use
237/// the flag from the previous instruction.
238bool PeepholeOptimizer::OptimizeCmpInstr(MachineInstr *MI,
Bill Wendling220e2402010-09-10 21:55:43 +0000239 MachineBasicBlock *MBB,
240 MachineBasicBlock::iterator &NextIter){
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000241 // If this instruction is a comparison against zero and isn't comparing a
242 // physical register, we can try to optimize it.
243 unsigned SrcReg;
Gabor Greif04ac81d2010-09-21 12:01:15 +0000244 int CmpMask, CmpValue;
245 if (!TII->AnalyzeCompare(MI, SrcReg, CmpMask, CmpValue) ||
Bill Wendling92ad57f2010-09-10 23:34:19 +0000246 TargetRegisterInfo::isPhysicalRegister(SrcReg))
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000247 return false;
248
Bill Wendlinga6556862010-09-11 00:13:50 +0000249 // Attempt to optimize the comparison instruction.
Gabor Greif04ac81d2010-09-21 12:01:15 +0000250 if (TII->OptimizeCompareInstr(MI, SrcReg, CmpMask, CmpValue, NextIter)) {
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000251 ++NumEliminated;
252 return true;
253 }
254
255 return false;
256}
257
258bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
259 TM = &MF.getTarget();
260 TII = TM->getInstrInfo();
261 MRI = &MF.getRegInfo();
262 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0;
263
264 bool Changed = false;
265
266 SmallPtrSet<MachineInstr*, 8> LocalMIs;
267 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
268 MachineBasicBlock *MBB = &*I;
269 LocalMIs.clear();
270
271 for (MachineBasicBlock::iterator
Bill Wendling220e2402010-09-10 21:55:43 +0000272 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000273 MachineInstr *MI = &*MII;
274
Gabor Greif4f7d1072010-09-14 20:46:08 +0000275 if (MI->getDesc().isCompare() &&
276 !MI->getDesc().hasUnmodeledSideEffects()) {
Bill Wendling220e2402010-09-10 21:55:43 +0000277 if (OptimizeCmpInstr(MI, MBB, MII))
278 Changed = true;
279 else
280 ++MII;
Bill Wendling6cdb1ab2010-08-09 23:59:04 +0000281 } else {
282 Changed |= OptimizeExtInstr(MI, MBB, LocalMIs);
283 ++MII;
284 }
285 }
286 }
287
288 return Changed;
289}