Be a bit more efficient when processing the active and inactive
[oota-llvm.git] / lib / Target / X86 / X86PeepholeOpt.cpp
1 //===-- X86PeepholeOpt.cpp - X86 Peephole Optimizer -----------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a peephole optimizer for the X86.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "X86.h"
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 "Support/Statistic.h"
21 #include "Support/STLExtras.h"
22
23 using namespace llvm;
24
25 namespace {
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);
31
32     bool PeepholeOptimize(MachineBasicBlock &MBB,
33                           MachineBasicBlock::iterator &I);
34
35     virtual const char *getPassName() const { return "X86 Peephole Optimizer"; }
36   };
37 }
38
39 FunctionPass *llvm::createX86PeepholeOptimizerPass() { return new PH(); }
40
41 bool PH::runOnMachineFunction(MachineFunction &MF) {
42   bool Changed = false;
43
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)) {
47         Changed = true;
48         ++NumPHOpts;
49       } else
50         ++I;
51
52   return Changed;
53 }
54
55
56 bool PH::PeepholeOptimize(MachineBasicBlock &MBB,
57                           MachineBasicBlock::iterator &I) {
58   assert(I != MBB.end());
59   MachineBasicBlock::iterator NextI = next(I);
60
61   MachineInstr *MI = I;
62   MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
63   unsigned Size = 0;
64   switch (MI->getOpcode()) {
65   case X86::MOV8rr:
66   case X86::MOV16rr:
67   case X86::MOV32rr:   // Destroy X = X copies...
68     if (MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) {
69       I = MBB.erase(I);
70       return true;
71     }
72     return false;
73
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) {
84         unsigned Opcode;
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;
89         }
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));
94         return true;
95       }
96     }
97     return false;
98
99 #if 0
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) {
106         unsigned Opcode;
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;
111         }
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));
120         return true;
121       }
122     }
123     return false;
124 #endif
125
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) {
136         unsigned Opcode;
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;
151         }
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));
156         return true;
157       }
158     }
159     return false;
160
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) {
171         unsigned Opcode;
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;
186         }
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));
194         return true;
195       }
196     }
197     return false;
198
199 #if 0
200   case X86::MOV32ri: Size++;
201   case X86::MOV16ri: Size++;
202   case X86::MOV8ri:
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));
212         return true;
213       } else if (Val == -1) {                     // mov EAX, -1 -> or EAX, -1
214         // TODO: 'or Reg, -1' has a smaller encoding than 'mov Reg, -1'
215       }
216     }
217     return false;
218 #endif
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));
223       return true;
224     }
225     return false;
226   default:
227     return false;
228   }
229 }
230
231 namespace {
232   class UseDefChains : public MachineFunctionPass {
233     std::vector<MachineInstr*> DefiningInst;
234   public:
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];
245     }
246
247     // setDefinition - Update the use-def chains to indicate that MI defines
248     // register Reg.
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;
253     }
254
255     // removeDefinition - Update the use-def chains to forget about Reg
256     // entirely.
257     void removeDefinition(unsigned Reg) {
258       assert(getDefinition(Reg));      // Check validity
259       DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = 0;
260     }
261
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);
270           }
271         }
272       return false;
273     }
274
275     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
276       AU.setPreservesAll();
277       MachineFunctionPass::getAnalysisUsage(AU);
278     }
279
280     virtual void releaseMemory() {
281       std::vector<MachineInstr*>().swap(DefiningInst);
282     }
283   };
284
285   RegisterAnalysis<UseDefChains> X("use-def-chains",
286                                 "use-def chain construction for machine code");
287 }
288
289
290 namespace {
291   Statistic<> NumSSAPHOpts("x86-ssa-peephole",
292                            "Number of SSA peephole optimization performed");
293
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 {
299     UseDefChains *UDC;
300   public:
301     virtual bool runOnMachineFunction(MachineFunction &MF);
302
303     bool PeepholeOptimize(MachineBasicBlock &MBB,
304                           MachineBasicBlock::iterator &I);
305
306     virtual const char *getPassName() const {
307       return "X86 SSA-based Peephole Optimizer";
308     }
309
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);
316       return true;
317     }
318
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);
322
323     /// getDefininingInst - If the specified operand is a read of an SSA
324     /// register, return the machine instruction defining it, otherwise, return
325     /// null.
326     MachineInstr *getDefiningInst(MachineOperand &MO) {
327       if (MO.isDef() || !MO.isRegister() ||
328           !MRegisterInfo::isVirtualRegister(MO.getReg())) return 0;
329       return UDC->getDefinition(MO.getReg());
330     }
331
332     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
333       AU.addRequired<UseDefChains>();
334       AU.addPreserved<UseDefChains>();
335       MachineFunctionPass::getAnalysisUsage(AU);
336     }
337   };
338 }
339
340 FunctionPass *llvm::createX86SSAPeepholeOptimizerPass() { return new SSAPH(); }
341
342 bool SSAPH::runOnMachineFunction(MachineFunction &MF) {
343   bool Changed = false;
344   bool LocalChanged;
345
346   UDC = &getAnalysis<UseDefChains>();
347
348   do {
349     LocalChanged = false;
350
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)) {
354           LocalChanged = true;
355           ++NumSSAPHOpts;
356         } else
357           ++I;
358     Changed |= LocalChanged;
359   } while (LocalChanged);
360
361   return Changed;
362 }
363
364 static bool isValidScaleAmount(unsigned Scale) {
365   return Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8;
366 }
367
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);
375
376   unsigned BaseReg  = BaseRegOp.hasAllocatedReg() ? BaseRegOp.getReg() : 0;
377   unsigned Scale    = ScaleOp.getImmedValue();
378   unsigned IndexReg = IndexRegOp.hasAllocatedReg() ? IndexRegOp.getReg() : 0;
379
380   bool Changed = false;
381
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);
388     return true;
389   }
390
391   // Attempt to fold instructions used by the base register into the instruction
392   if (MachineInstr *DefInst = getDefiningInst(BaseRegOp)) {
393     switch (DefInst->getOpcode()) {
394     case X86::MOV32ri:
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()) {
399           BaseRegOp.setReg(0);
400           return Propagate(MI, OpNo+3, DefInst, 1);
401         }
402       }
403       break;
404
405     case X86::ADD32rr:
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.
408       if (IndexReg == 0) {
409         BaseRegOp = DefInst->getOperand(1);
410         IndexRegOp = DefInst->getOperand(2);
411         ScaleOp.setImmedValue(1);
412         return true;
413       }
414       break;
415
416     case X86::SHL32ri:
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);
425         Changed = true;
426         break;
427       }
428     }
429   }
430
431   // Attempt to fold instructions used by the index into the instruction
432   if (MachineInstr *DefInst = getDefiningInst(IndexRegOp)) {
433     switch (DefInst->getOpcode()) {
434     case X86::SHL32ri: {
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);
440         return true;
441       }
442       break;
443     }
444     }
445   }
446
447   return Changed;
448 }
449
450 bool SSAPH::PeepholeOptimize(MachineBasicBlock &MBB,
451                              MachineBasicBlock::iterator &I) {
452     MachineBasicBlock::iterator NextI = next(I);
453
454   MachineInstr *MI = I;
455   MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
456
457   bool Changed = false;
458
459   const TargetInstrInfo &TII = *MBB.getParent()->getTarget().getInstrInfo();
460
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);
474           Changed = true;
475           ++NumPHMoves;
476         }
477       }
478     }
479   
480   
481   // Perform instruction specific optimizations.
482   switch (MI->getOpcode()) {
483
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);
494       default: break;
495       }
496     }
497
498     // If we can optimize the addressing expression, do so now.
499     if (OptimizeAddress(MI, 0))
500       return true;
501     break;
502
503   case X86::MOV32rm:
504   case X86::MOV16rm:
505   case X86::MOV8rm:
506     // If we can optimize the addressing expression, do so now.
507     if (OptimizeAddress(MI, 1))
508       return true;
509     break;
510
511   default: break;
512   }
513
514   return Changed;
515 }