1 //===-- X86PeepholeOpt.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 "llvm/Target/TargetInstrInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/STLExtras.h"
26 Statistic<> NumPHOpts("x86-peephole",
27 "Number of peephole optimization performed");
28 Statistic<> NumPHMoves("x86-peephole", "Number of peephole moves folded");
29 struct PH : public MachineFunctionPass {
30 virtual bool runOnMachineFunction(MachineFunction &MF);
32 bool PeepholeOptimize(MachineBasicBlock &MBB,
33 MachineBasicBlock::iterator &I);
35 virtual const char *getPassName() const { return "X86 Peephole Optimizer"; }
39 FunctionPass *llvm::createX86PeepholeOptimizerPass() { return new PH(); }
41 bool PH::runOnMachineFunction(MachineFunction &MF) {
44 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI != E; ++BI)
45 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); )
46 if (PeepholeOptimize(*BI, I)) {
56 bool PH::PeepholeOptimize(MachineBasicBlock &MBB,
57 MachineBasicBlock::iterator &I) {
58 assert(I != MBB.end());
59 MachineBasicBlock::iterator NextI = next(I);
62 MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
64 switch (MI->getOpcode()) {
67 case X86::MOV32rr: // Destroy X = X copies...
68 if (MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) {
74 // A large number of X86 instructions have forms which take an 8-bit
75 // immediate despite the fact that the operands are 16 or 32 bits. Because
76 // this can save three bytes of code size (and icache space), we want to
77 // shrink them if possible.
78 case X86::IMUL16rri: case X86::IMUL32rri:
79 assert(MI->getNumOperands() == 3 && "These should all have 3 operands!");
80 if (MI->getOperand(2).isImmediate()) {
81 int Val = MI->getOperand(2).getImmedValue();
82 // If the value is the same when signed extended from 8 bits...
83 if (Val == (signed int)(signed char)Val) {
85 switch (MI->getOpcode()) {
86 default: assert(0 && "Unknown opcode value!");
87 case X86::IMUL16rri: Opcode = X86::IMUL16rri8; break;
88 case X86::IMUL32rri: Opcode = X86::IMUL32rri8; break;
90 unsigned R0 = MI->getOperand(0).getReg();
91 unsigned R1 = MI->getOperand(1).getReg();
92 I = MBB.insert(MBB.erase(I),
93 BuildMI(Opcode, 2, R0).addReg(R1).addZImm((char)Val));
100 case X86::IMUL16rmi: case X86::IMUL32rmi:
101 assert(MI->getNumOperands() == 6 && "These should all have 6 operands!");
102 if (MI->getOperand(5).isImmediate()) {
103 int Val = MI->getOperand(5).getImmedValue();
104 // If the value is the same when signed extended from 8 bits...
105 if (Val == (signed int)(signed char)Val) {
107 switch (MI->getOpcode()) {
108 default: assert(0 && "Unknown opcode value!");
109 case X86::IMUL16rmi: Opcode = X86::IMUL16rmi8; break;
110 case X86::IMUL32rmi: Opcode = X86::IMUL32rmi8; break;
112 unsigned R0 = MI->getOperand(0).getReg();
113 unsigned R1 = MI->getOperand(1).getReg();
114 unsigned Scale = MI->getOperand(2).getImmedValue();
115 unsigned R2 = MI->getOperand(3).getReg();
116 unsigned Offset = MI->getOperand(4).getImmedValue();
117 I = MBB.insert(MBB.erase(I),
118 BuildMI(Opcode, 5, R0).addReg(R1).addZImm(Scale).
119 addReg(R2).addSImm(Offset).addZImm((char)Val));
126 case X86::ADD16ri: case X86::ADD32ri: case X86::ADC32ri:
127 case X86::SUB16ri: case X86::SUB32ri: case X86::SBB32ri:
128 case X86::AND16ri: case X86::AND32ri:
129 case X86::OR16ri: case X86::OR32ri:
130 case X86::XOR16ri: case X86::XOR32ri:
131 assert(MI->getNumOperands() == 2 && "These should all have 2 operands!");
132 if (MI->getOperand(1).isImmediate()) {
133 int Val = MI->getOperand(1).getImmedValue();
134 // If the value is the same when signed extended from 8 bits...
135 if (Val == (signed int)(signed char)Val) {
137 switch (MI->getOpcode()) {
138 default: assert(0 && "Unknown opcode value!");
139 case X86::ADD16ri: Opcode = X86::ADD16ri8; break;
140 case X86::ADD32ri: Opcode = X86::ADD32ri8; break;
141 case X86::ADC32ri: Opcode = X86::ADC32ri8; break;
142 case X86::SUB16ri: Opcode = X86::SUB16ri8; break;
143 case X86::SUB32ri: Opcode = X86::SUB32ri8; break;
144 case X86::SBB32ri: Opcode = X86::SBB32ri8; break;
145 case X86::AND16ri: Opcode = X86::AND16ri8; break;
146 case X86::AND32ri: Opcode = X86::AND32ri8; break;
147 case X86::OR16ri: Opcode = X86::OR16ri8; break;
148 case X86::OR32ri: Opcode = X86::OR32ri8; break;
149 case X86::XOR16ri: Opcode = X86::XOR16ri8; break;
150 case X86::XOR32ri: Opcode = X86::XOR32ri8; break;
152 unsigned R0 = MI->getOperand(0).getReg();
153 I = MBB.insert(MBB.erase(I),
154 BuildMI(Opcode, 1, R0, MachineOperand::UseAndDef)
155 .addZImm((char)Val));
161 case X86::ADD16mi: case X86::ADD32mi: case X86::ADC32mi:
162 case X86::SUB16mi: case X86::SUB32mi: case X86::SBB32mi:
163 case X86::AND16mi: case X86::AND32mi:
164 case X86::OR16mi: case X86::OR32mi:
165 case X86::XOR16mi: case X86::XOR32mi:
166 assert(MI->getNumOperands() == 5 && "These should all have 5 operands!");
167 if (MI->getOperand(4).isImmediate()) {
168 int Val = MI->getOperand(4).getImmedValue();
169 // If the value is the same when signed extended from 8 bits...
170 if (Val == (signed int)(signed char)Val) {
172 switch (MI->getOpcode()) {
173 default: assert(0 && "Unknown opcode value!");
174 case X86::ADD16mi: Opcode = X86::ADD16mi8; break;
175 case X86::ADD32mi: Opcode = X86::ADD32mi8; break;
176 case X86::ADC32mi: Opcode = X86::ADC32mi8; break;
177 case X86::SUB16mi: Opcode = X86::SUB16mi8; break;
178 case X86::SUB32mi: Opcode = X86::SUB32mi8; break;
179 case X86::SBB32mi: Opcode = X86::SBB32mi8; break;
180 case X86::AND16mi: Opcode = X86::AND16mi8; break;
181 case X86::AND32mi: Opcode = X86::AND32mi8; break;
182 case X86::OR16mi: Opcode = X86::OR16mi8; break;
183 case X86::OR32mi: Opcode = X86::OR32mi8; break;
184 case X86::XOR16mi: Opcode = X86::XOR16mi8; break;
185 case X86::XOR32mi: Opcode = X86::XOR32mi8; break;
187 unsigned R0 = MI->getOperand(0).getReg();
188 unsigned Scale = MI->getOperand(1).getImmedValue();
189 unsigned R1 = MI->getOperand(2).getReg();
190 unsigned Offset = MI->getOperand(3).getImmedValue();
191 I = MBB.insert(MBB.erase(I),
192 BuildMI(Opcode, 5).addReg(R0).addZImm(Scale).
193 addReg(R1).addSImm(Offset).addZImm((char)Val));
200 case X86::MOV32ri: Size++;
201 case X86::MOV16ri: Size++;
203 // FIXME: We can only do this transformation if we know that flags are not
204 // used here, because XOR clobbers the flags!
205 if (MI->getOperand(1).isImmediate()) { // avoid mov EAX, <value>
206 int Val = MI->getOperand(1).getImmedValue();
207 if (Val == 0) { // mov EAX, 0 -> xor EAX, EAX
208 static const unsigned Opcode[] ={X86::XOR8rr,X86::XOR16rr,X86::XOR32rr};
209 unsigned Reg = MI->getOperand(0).getReg();
210 I = MBB.insert(MBB.erase(I),
211 BuildMI(Opcode[Size], 2, Reg).addReg(Reg).addReg(Reg));
213 } else if (Val == -1) { // mov EAX, -1 -> or EAX, -1
214 // TODO: 'or Reg, -1' has a smaller encoding than 'mov Reg, -1'
219 case X86::BSWAP32r: // Change bswap EAX, bswap EAX into nothing
220 if (Next->getOpcode() == X86::BSWAP32r &&
221 MI->getOperand(0).getReg() == Next->getOperand(0).getReg()) {
222 I = MBB.erase(MBB.erase(I));
232 class UseDefChains : public MachineFunctionPass {
233 std::vector<MachineInstr*> DefiningInst;
235 // getDefinition - Return the machine instruction that defines the specified
236 // SSA virtual register.
237 MachineInstr *getDefinition(unsigned Reg) {
238 assert(MRegisterInfo::isVirtualRegister(Reg) &&
239 "use-def chains only exist for SSA registers!");
240 assert(Reg - MRegisterInfo::FirstVirtualRegister < DefiningInst.size() &&
241 "Unknown register number!");
242 assert(DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] &&
243 "Unknown register number!");
244 return DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister];
247 // setDefinition - Update the use-def chains to indicate that MI defines
249 void setDefinition(unsigned Reg, MachineInstr *MI) {
250 if (Reg-MRegisterInfo::FirstVirtualRegister >= DefiningInst.size())
251 DefiningInst.resize(Reg-MRegisterInfo::FirstVirtualRegister+1);
252 DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = MI;
255 // removeDefinition - Update the use-def chains to forget about Reg
257 void removeDefinition(unsigned Reg) {
258 assert(getDefinition(Reg)); // Check validity
259 DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = 0;
262 virtual bool runOnMachineFunction(MachineFunction &MF) {
263 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI!=E; ++BI)
264 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); ++I) {
265 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
266 MachineOperand &MO = I->getOperand(i);
267 if (MO.isRegister() && MO.isDef() && !MO.isUse() &&
268 MRegisterInfo::isVirtualRegister(MO.getReg()))
269 setDefinition(MO.getReg(), I);
275 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
276 AU.setPreservesAll();
277 MachineFunctionPass::getAnalysisUsage(AU);
280 virtual void releaseMemory() {
281 std::vector<MachineInstr*>().swap(DefiningInst);
285 RegisterAnalysis<UseDefChains> X("use-def-chains",
286 "use-def chain construction for machine code");
291 Statistic<> NumSSAPHOpts("x86-ssa-peephole",
292 "Number of SSA peephole optimization performed");
294 /// SSAPH - This pass is an X86-specific, SSA-based, peephole optimizer. This
295 /// pass is really a bad idea: a better instruction selector should completely
296 /// supersume it. However, that will take some time to develop, and the
297 /// simple things this can do are important now.
298 class SSAPH : public MachineFunctionPass {
301 virtual bool runOnMachineFunction(MachineFunction &MF);
303 bool PeepholeOptimize(MachineBasicBlock &MBB,
304 MachineBasicBlock::iterator &I);
306 virtual const char *getPassName() const {
307 return "X86 SSA-based Peephole Optimizer";
310 /// Propagate - Set MI[DestOpNo] = Src[SrcOpNo], optionally change the
311 /// opcode of the instruction, then return true.
312 bool Propagate(MachineInstr *MI, unsigned DestOpNo,
313 MachineInstr *Src, unsigned SrcOpNo, unsigned NewOpcode = 0){
314 MI->getOperand(DestOpNo) = Src->getOperand(SrcOpNo);
315 if (NewOpcode) MI->setOpcode(NewOpcode);
319 /// OptimizeAddress - If we can fold the addressing arithmetic for this
320 /// memory instruction into the instruction itself, do so and return true.
321 bool OptimizeAddress(MachineInstr *MI, unsigned OpNo);
323 /// getDefininingInst - If the specified operand is a read of an SSA
324 /// register, return the machine instruction defining it, otherwise, return
326 MachineInstr *getDefiningInst(MachineOperand &MO) {
327 if (MO.isDef() || !MO.isRegister() ||
328 !MRegisterInfo::isVirtualRegister(MO.getReg())) return 0;
329 return UDC->getDefinition(MO.getReg());
332 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
333 AU.addRequired<UseDefChains>();
334 AU.addPreserved<UseDefChains>();
335 MachineFunctionPass::getAnalysisUsage(AU);
340 FunctionPass *llvm::createX86SSAPeepholeOptimizerPass() { return new SSAPH(); }
342 bool SSAPH::runOnMachineFunction(MachineFunction &MF) {
343 bool Changed = false;
346 UDC = &getAnalysis<UseDefChains>();
349 LocalChanged = false;
351 for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI != E; ++BI)
352 for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); )
353 if (PeepholeOptimize(*BI, I)) {
358 Changed |= LocalChanged;
359 } while (LocalChanged);
364 static bool isValidScaleAmount(unsigned Scale) {
365 return Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8;
368 /// OptimizeAddress - If we can fold the addressing arithmetic for this
369 /// memory instruction into the instruction itself, do so and return true.
370 bool SSAPH::OptimizeAddress(MachineInstr *MI, unsigned OpNo) {
371 MachineOperand &BaseRegOp = MI->getOperand(OpNo+0);
372 MachineOperand &ScaleOp = MI->getOperand(OpNo+1);
373 MachineOperand &IndexRegOp = MI->getOperand(OpNo+2);
374 MachineOperand &DisplacementOp = MI->getOperand(OpNo+3);
376 unsigned BaseReg = BaseRegOp.hasAllocatedReg() ? BaseRegOp.getReg() : 0;
377 unsigned Scale = ScaleOp.getImmedValue();
378 unsigned IndexReg = IndexRegOp.hasAllocatedReg() ? IndexRegOp.getReg() : 0;
380 bool Changed = false;
382 // If the base register is unset, and the index register is set with a scale
383 // of 1, move it to be the base register.
384 if (BaseRegOp.hasAllocatedReg() && BaseReg == 0 &&
385 Scale == 1 && IndexReg != 0) {
386 BaseRegOp.setReg(IndexReg);
387 IndexRegOp.setReg(0);
391 // Attempt to fold instructions used by the base register into the instruction
392 if (MachineInstr *DefInst = getDefiningInst(BaseRegOp)) {
393 switch (DefInst->getOpcode()) {
395 // If there is no displacement set for this instruction set one now.
396 // FIXME: If we can fold two immediates together, we should do so!
397 if (DisplacementOp.isImmediate() && !DisplacementOp.getImmedValue()) {
398 if (DefInst->getOperand(1).isImmediate()) {
400 return Propagate(MI, OpNo+3, DefInst, 1);
406 // If the source is a register-register add, and we do not yet have an
407 // index register, fold the add into the memory address.
409 BaseRegOp = DefInst->getOperand(1);
410 IndexRegOp = DefInst->getOperand(2);
411 ScaleOp.setImmedValue(1);
417 // If this shift could be folded into the index portion of the address if
418 // it were the index register, move it to the index register operand now,
419 // so it will be folded in below.
420 if ((Scale == 1 || (IndexReg == 0 && IndexRegOp.hasAllocatedReg())) &&
421 DefInst->getOperand(2).getImmedValue() < 4) {
422 std::swap(BaseRegOp, IndexRegOp);
423 ScaleOp.setImmedValue(1); Scale = 1;
424 std::swap(IndexReg, BaseReg);
431 // Attempt to fold instructions used by the index into the instruction
432 if (MachineInstr *DefInst = getDefiningInst(IndexRegOp)) {
433 switch (DefInst->getOpcode()) {
435 // Figure out what the resulting scale would be if we folded this shift.
436 unsigned ResScale = Scale * (1 << DefInst->getOperand(2).getImmedValue());
437 if (isValidScaleAmount(ResScale)) {
438 IndexRegOp = DefInst->getOperand(1);
439 ScaleOp.setImmedValue(ResScale);
450 bool SSAPH::PeepholeOptimize(MachineBasicBlock &MBB,
451 MachineBasicBlock::iterator &I) {
452 MachineBasicBlock::iterator NextI = next(I);
454 MachineInstr *MI = I;
455 MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
457 bool Changed = false;
459 const TargetInstrInfo &TII = *MBB.getParent()->getTarget().getInstrInfo();
461 // Scan the operands of this instruction. If any operands are
462 // register-register copies, replace the operand with the source.
463 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
464 // Is this an SSA register use?
465 if (MachineInstr *DefInst = getDefiningInst(MI->getOperand(i))) {
466 // If the operand is a vreg-vreg copy, it is always safe to replace the
467 // source value with the input operand.
468 unsigned Source, Dest;
469 if (TII.isMoveInstr(*DefInst, Source, Dest)) {
470 // Don't propagate physical registers into any instructions.
471 if (DefInst->getOperand(1).isRegister() &&
472 MRegisterInfo::isVirtualRegister(Source)) {
473 MI->getOperand(i).setReg(Source);
481 // Perform instruction specific optimizations.
482 switch (MI->getOpcode()) {
484 // Register to memory stores. Format: <base,scale,indexreg,immdisp>, srcreg
485 case X86::MOV32mr: case X86::MOV16mr: case X86::MOV8mr:
486 case X86::MOV32mi: case X86::MOV16mi: case X86::MOV8mi:
487 // Check to see if we can fold the source instruction into this one...
488 if (MachineInstr *SrcInst = getDefiningInst(MI->getOperand(4))) {
489 switch (SrcInst->getOpcode()) {
490 // Fold the immediate value into the store, if possible.
491 case X86::MOV8ri: return Propagate(MI, 4, SrcInst, 1, X86::MOV8mi);
492 case X86::MOV16ri: return Propagate(MI, 4, SrcInst, 1, X86::MOV16mi);
493 case X86::MOV32ri: return Propagate(MI, 4, SrcInst, 1, X86::MOV32mi);
498 // If we can optimize the addressing expression, do so now.
499 if (OptimizeAddress(MI, 0))
506 // If we can optimize the addressing expression, do so now.
507 if (OptimizeAddress(MI, 1))