1 //===-- PeepholeOptimizer.cpp - X86 Peephole Optimizer --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a peephole optimizer for the X86.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/MachineFunctionPass.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/Target/MRegisterInfo.h"
18 #include "Support/Statistic.h"
19 #include "Support/STLExtras.h"
24 Statistic<> NumPHOpts("x86-peephole",
25 "Number of peephole optimization performed");
26 struct PH : public MachineFunctionPass {
27 virtual bool runOnMachineFunction(MachineFunction &MF);
29 bool PeepholeOptimize(MachineBasicBlock &MBB,
30 MachineBasicBlock::iterator &I);
32 virtual const char *getPassName() const { return "X86 Peephole Optimizer"; }
36 FunctionPass *llvm::createX86PeepholeOptimizerPass() { return new PH(); }
38 bool PH::runOnMachineFunction(MachineFunction &MF) {
41 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI != E; ++BI)
42 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); )
43 if (PeepholeOptimize(*BI, I)) {
53 bool PH::PeepholeOptimize(MachineBasicBlock &MBB,
54 MachineBasicBlock::iterator &I) {
55 assert(I != MBB.end());
56 MachineBasicBlock::iterator NextI = next(I);
59 MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
61 switch (MI->getOpcode()) {
64 case X86::MOVrr32: // Destroy X = X copies...
65 if (MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) {
71 // A large number of X86 instructions have forms which take an 8-bit
72 // immediate despite the fact that the operands are 16 or 32 bits. Because
73 // this can save three bytes of code size (and icache space), we want to
74 // shrink them if possible.
75 case X86::IMULrri16: case X86::IMULrri32:
76 assert(MI->getNumOperands() == 3 && "These should all have 3 operands!");
77 if (MI->getOperand(2).isImmediate()) {
78 int Val = MI->getOperand(2).getImmedValue();
79 // If the value is the same when signed extended from 8 bits...
80 if (Val == (signed int)(signed char)Val) {
82 switch (MI->getOpcode()) {
83 default: assert(0 && "Unknown opcode value!");
84 case X86::IMULrri16: Opcode = X86::IMULrri16b; break;
85 case X86::IMULrri32: Opcode = X86::IMULrri32b; break;
87 unsigned R0 = MI->getOperand(0).getReg();
88 unsigned R1 = MI->getOperand(1).getReg();
89 I = MBB.insert(MBB.erase(I),
90 BuildMI(Opcode, 2, R0).addReg(R1).addZImm((char)Val));
96 case X86::IMULrmi16: case X86::IMULrmi32:
97 assert(MI->getNumOperands() == 6 && "These should all have 6 operands!");
98 if (MI->getOperand(5).isImmediate()) {
99 int Val = MI->getOperand(5).getImmedValue();
100 // If the value is the same when signed extended from 8 bits...
101 if (Val == (signed int)(signed char)Val) {
103 switch (MI->getOpcode()) {
104 default: assert(0 && "Unknown opcode value!");
105 case X86::IMULrmi16: Opcode = X86::IMULrmi16b; break;
106 case X86::IMULrmi32: Opcode = X86::IMULrmi32b; break;
108 unsigned R0 = MI->getOperand(0).getReg();
109 unsigned R1 = MI->getOperand(1).getReg();
110 unsigned Scale = MI->getOperand(2).getImmedValue();
111 unsigned R2 = MI->getOperand(3).getReg();
112 unsigned Offset = MI->getOperand(3).getImmedValue();
113 I = MBB.insert(MBB.erase(I),
114 BuildMI(Opcode, 2, R0).addReg(R1).addZImm(Scale).
115 addReg(R2).addSImm(Offset).addZImm((char)Val));
121 case X86::ADDri16: case X86::ADDri32:
122 case X86::ADDmi16: case X86::ADDmi32:
123 case X86::SUBri16: case X86::SUBri32:
124 case X86::ANDri16: case X86::ANDri32:
125 case X86::ORri16: case X86::ORri32:
126 case X86::XORri16: case X86::XORri32:
127 assert(MI->getNumOperands() == 2 && "These should all have 2 operands!");
128 if (MI->getOperand(1).isImmediate()) {
129 int Val = MI->getOperand(1).getImmedValue();
130 // If the value is the same when signed extended from 8 bits...
131 if (Val == (signed int)(signed char)Val) {
133 switch (MI->getOpcode()) {
134 default: assert(0 && "Unknown opcode value!");
135 case X86::ADDri16: Opcode = X86::ADDri16b; break;
136 case X86::ADDri32: Opcode = X86::ADDri32b; break;
137 case X86::ADDmi16: Opcode = X86::ADDmi16b; break;
138 case X86::ADDmi32: Opcode = X86::ADDmi32b; break;
139 case X86::SUBri16: Opcode = X86::SUBri16b; break;
140 case X86::SUBri32: Opcode = X86::SUBri32b; break;
141 case X86::ANDri16: Opcode = X86::ANDri16b; break;
142 case X86::ANDri32: Opcode = X86::ANDri32b; break;
143 case X86::ORri16: Opcode = X86::ORri16b; break;
144 case X86::ORri32: Opcode = X86::ORri32b; break;
145 case X86::XORri16: Opcode = X86::XORri16b; break;
146 case X86::XORri32: Opcode = X86::XORri32b; break;
148 unsigned R0 = MI->getOperand(0).getReg();
149 I = MBB.insert(MBB.erase(I),
150 BuildMI(Opcode, 1, R0, MOTy::UseAndDef).addZImm((char)Val));
157 case X86::MOVir32: Size++;
158 case X86::MOVir16: Size++;
160 // FIXME: We can only do this transformation if we know that flags are not
161 // used here, because XOR clobbers the flags!
162 if (MI->getOperand(1).isImmediate()) { // avoid mov EAX, <value>
163 int Val = MI->getOperand(1).getImmedValue();
164 if (Val == 0) { // mov EAX, 0 -> xor EAX, EAX
165 static const unsigned Opcode[] ={X86::XORrr8,X86::XORrr16,X86::XORrr32};
166 unsigned Reg = MI->getOperand(0).getReg();
167 I = MBB.insert(MBB.erase(I),
168 BuildMI(Opcode[Size], 2, Reg).addReg(Reg).addReg(Reg));
170 } else if (Val == -1) { // mov EAX, -1 -> or EAX, -1
171 // TODO: 'or Reg, -1' has a smaller encoding than 'mov Reg, -1'
176 case X86::BSWAPr32: // Change bswap EAX, bswap EAX into nothing
177 if (Next->getOpcode() == X86::BSWAPr32 &&
178 MI->getOperand(0).getReg() == Next->getOperand(0).getReg()) {
179 I = MBB.erase(MBB.erase(I));
189 class UseDefChains : public MachineFunctionPass {
190 std::vector<MachineInstr*> DefiningInst;
192 // getDefinition - Return the machine instruction that defines the specified
193 // SSA virtual register.
194 MachineInstr *getDefinition(unsigned Reg) {
195 assert(MRegisterInfo::isVirtualRegister(Reg) &&
196 "use-def chains only exist for SSA registers!");
197 assert(Reg - MRegisterInfo::FirstVirtualRegister < DefiningInst.size() &&
198 "Unknown register number!");
199 assert(DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] &&
200 "Unknown register number!");
201 return DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister];
204 // setDefinition - Update the use-def chains to indicate that MI defines
206 void setDefinition(unsigned Reg, MachineInstr *MI) {
207 if (Reg-MRegisterInfo::FirstVirtualRegister >= DefiningInst.size())
208 DefiningInst.resize(Reg-MRegisterInfo::FirstVirtualRegister+1);
209 DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = MI;
212 // removeDefinition - Update the use-def chains to forget about Reg
214 void removeDefinition(unsigned Reg) {
215 assert(getDefinition(Reg)); // Check validity
216 DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = 0;
219 virtual bool runOnMachineFunction(MachineFunction &MF) {
220 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI!=E; ++BI)
221 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); ++I) {
222 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
223 MachineOperand &MO = I->getOperand(i);
224 if (MO.isRegister() && MO.isDef() && !MO.isUse() &&
225 MRegisterInfo::isVirtualRegister(MO.getReg()))
226 setDefinition(MO.getReg(), I);
232 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
233 AU.setPreservesAll();
234 MachineFunctionPass::getAnalysisUsage(AU);
237 virtual void releaseMemory() {
238 std::vector<MachineInstr*>().swap(DefiningInst);
242 RegisterAnalysis<UseDefChains> X("use-def-chains",
243 "use-def chain construction for machine code");
248 Statistic<> NumSSAPHOpts("x86-ssa-peephole",
249 "Number of SSA peephole optimization performed");
251 /// SSAPH - This pass is an X86-specific, SSA-based, peephole optimizer. This
252 /// pass is really a bad idea: a better instruction selector should completely
253 /// supersume it. However, that will take some time to develop, and the
254 /// simple things this can do are important now.
255 class SSAPH : public MachineFunctionPass {
258 virtual bool runOnMachineFunction(MachineFunction &MF);
260 bool PeepholeOptimize(MachineBasicBlock &MBB,
261 MachineBasicBlock::iterator &I);
263 virtual const char *getPassName() const {
264 return "X86 SSA-based Peephole Optimizer";
267 /// Propagate - Set MI[DestOpNo] = Src[SrcOpNo], optionally change the
268 /// opcode of the instruction, then return true.
269 bool Propagate(MachineInstr *MI, unsigned DestOpNo,
270 MachineInstr *Src, unsigned SrcOpNo, unsigned NewOpcode = 0){
271 MI->getOperand(DestOpNo) = Src->getOperand(SrcOpNo);
272 if (NewOpcode) MI->setOpcode(NewOpcode);
276 /// OptimizeAddress - If we can fold the addressing arithmetic for this
277 /// memory instruction into the instruction itself, do so and return true.
278 bool OptimizeAddress(MachineInstr *MI, unsigned OpNo);
280 /// getDefininingInst - If the specified operand is a read of an SSA
281 /// register, return the machine instruction defining it, otherwise, return
283 MachineInstr *getDefiningInst(MachineOperand &MO) {
284 if (MO.isDef() || !MO.isRegister() ||
285 !MRegisterInfo::isVirtualRegister(MO.getReg())) return 0;
286 return UDC->getDefinition(MO.getReg());
289 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
290 AU.addRequired<UseDefChains>();
291 AU.addPreserved<UseDefChains>();
292 MachineFunctionPass::getAnalysisUsage(AU);
297 FunctionPass *llvm::createX86SSAPeepholeOptimizerPass() { return new SSAPH(); }
299 bool SSAPH::runOnMachineFunction(MachineFunction &MF) {
300 bool Changed = false;
303 UDC = &getAnalysis<UseDefChains>();
306 LocalChanged = false;
308 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI != E; ++BI)
309 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); )
310 if (PeepholeOptimize(*BI, I)) {
315 Changed |= LocalChanged;
316 } while (LocalChanged);
321 static bool isValidScaleAmount(unsigned Scale) {
322 return Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8;
325 /// OptimizeAddress - If we can fold the addressing arithmetic for this
326 /// memory instruction into the instruction itself, do so and return true.
327 bool SSAPH::OptimizeAddress(MachineInstr *MI, unsigned OpNo) {
328 MachineOperand &BaseRegOp = MI->getOperand(OpNo+0);
329 MachineOperand &ScaleOp = MI->getOperand(OpNo+1);
330 MachineOperand &IndexRegOp = MI->getOperand(OpNo+2);
331 MachineOperand &DisplacementOp = MI->getOperand(OpNo+3);
333 unsigned BaseReg = BaseRegOp.hasAllocatedReg() ? BaseRegOp.getReg() : 0;
334 unsigned Scale = ScaleOp.getImmedValue();
335 unsigned IndexReg = IndexRegOp.hasAllocatedReg() ? IndexRegOp.getReg() : 0;
337 bool Changed = false;
339 // If the base register is unset, and the index register is set with a scale
340 // of 1, move it to be the base register.
341 if (BaseRegOp.hasAllocatedReg() && BaseReg == 0 &&
342 Scale == 1 && IndexReg != 0) {
343 BaseRegOp.setReg(IndexReg);
344 IndexRegOp.setReg(0);
348 // Attempt to fold instructions used by the base register into the instruction
349 if (MachineInstr *DefInst = getDefiningInst(BaseRegOp)) {
350 switch (DefInst->getOpcode()) {
352 // If there is no displacement set for this instruction set one now.
353 // FIXME: If we can fold two immediates together, we should do so!
354 if (DisplacementOp.isImmediate() && !DisplacementOp.getImmedValue()) {
355 if (DefInst->getOperand(1).isImmediate()) {
357 return Propagate(MI, OpNo+3, DefInst, 1);
363 // If the source is a register-register add, and we do not yet have an
364 // index register, fold the add into the memory address.
366 BaseRegOp = DefInst->getOperand(1);
367 IndexRegOp = DefInst->getOperand(2);
368 ScaleOp.setImmedValue(1);
374 // If this shift could be folded into the index portion of the address if
375 // it were the index register, move it to the index register operand now,
376 // so it will be folded in below.
377 if ((Scale == 1 || (IndexReg == 0 && IndexRegOp.hasAllocatedReg())) &&
378 DefInst->getOperand(2).getImmedValue() < 4) {
379 std::swap(BaseRegOp, IndexRegOp);
380 ScaleOp.setImmedValue(1); Scale = 1;
381 std::swap(IndexReg, BaseReg);
388 // Attempt to fold instructions used by the index into the instruction
389 if (MachineInstr *DefInst = getDefiningInst(IndexRegOp)) {
390 switch (DefInst->getOpcode()) {
392 // Figure out what the resulting scale would be if we folded this shift.
393 unsigned ResScale = Scale * (1 << DefInst->getOperand(2).getImmedValue());
394 if (isValidScaleAmount(ResScale)) {
395 IndexRegOp = DefInst->getOperand(1);
396 ScaleOp.setImmedValue(ResScale);
407 bool SSAPH::PeepholeOptimize(MachineBasicBlock &MBB,
408 MachineBasicBlock::iterator &I) {
409 MachineBasicBlock::iterator NextI = next(I);
411 MachineInstr *MI = I;
412 MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
414 bool Changed = false;
416 // Scan the operands of this instruction. If any operands are
417 // register-register copies, replace the operand with the source.
418 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
419 // Is this an SSA register use?
420 if (MachineInstr *DefInst = getDefiningInst(MI->getOperand(i)))
421 // If the operand is a vreg-vreg copy, it is always safe to replace the
422 // source value with the input operand.
423 if (DefInst->getOpcode() == X86::MOVrr8 ||
424 DefInst->getOpcode() == X86::MOVrr16 ||
425 DefInst->getOpcode() == X86::MOVrr32) {
426 // Don't propagate physical registers into PHI nodes...
427 if (MI->getOpcode() != X86::PHI ||
428 (DefInst->getOperand(1).isRegister() &&
429 MRegisterInfo::isVirtualRegister(DefInst->getOperand(1).getReg())))
430 Changed = Propagate(MI, i, DefInst, 1);
434 // Perform instruction specific optimizations.
435 switch (MI->getOpcode()) {
437 // Register to memory stores. Format: <base,scale,indexreg,immdisp>, srcreg
438 case X86::MOVrm32: case X86::MOVrm16: case X86::MOVrm8:
439 case X86::MOVim32: case X86::MOVim16: case X86::MOVim8:
440 // Check to see if we can fold the source instruction into this one...
441 if (MachineInstr *SrcInst = getDefiningInst(MI->getOperand(4))) {
442 switch (SrcInst->getOpcode()) {
443 // Fold the immediate value into the store, if possible.
444 case X86::MOVir8: return Propagate(MI, 4, SrcInst, 1, X86::MOVim8);
445 case X86::MOVir16: return Propagate(MI, 4, SrcInst, 1, X86::MOVim16);
446 case X86::MOVir32: return Propagate(MI, 4, SrcInst, 1, X86::MOVim32);
451 // If we can optimize the addressing expression, do so now.
452 if (OptimizeAddress(MI, 0))
459 // If we can optimize the addressing expression, do so now.
460 if (OptimizeAddress(MI, 1))