s|llvm/Support/Visibility.h|llvm/Support/Compiler.h|
[oota-llvm.git] / lib / CodeGen / TwoAddressInstructionPass.cpp
1 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
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 implements the TwoAddress instruction pass which is used
11 // by most register allocators. Two-Address instructions are rewritten
12 // from:
13 //
14 //     A = B op C
15 //
16 // to:
17 //
18 //     A = B
19 //     A op= C
20 //
21 // Note that if a register allocator chooses to use this pass, that it
22 // has to be capable of handling the non-SSA nature of these rewritten
23 // virtual registers.
24 //
25 // It is also worth noting that the duplicate operand of the two
26 // address instruction is removed.
27 //
28 //===----------------------------------------------------------------------===//
29
30 #define DEBUG_TYPE "twoaddrinstr"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Function.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/SSARegMap.h"
37 #include "llvm/Target/MRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include <iostream>
45 using namespace llvm;
46
47 namespace {
48   static Statistic<> NumTwoAddressInstrs("twoaddressinstruction",
49                                   "Number of two-address instructions");
50   static Statistic<> NumCommuted("twoaddressinstruction",
51                           "Number of instructions commuted to coalesce");
52   static Statistic<> NumConvertedTo3Addr("twoaddressinstruction",
53                                 "Number of instructions promoted to 3-address");
54
55   struct VISIBILITY_HIDDEN TwoAddressInstructionPass
56    : public MachineFunctionPass {
57     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
58
59     /// runOnMachineFunction - pass entry point
60     bool runOnMachineFunction(MachineFunction&);
61   };
62
63   RegisterPass<TwoAddressInstructionPass>
64   X("twoaddressinstruction", "Two-Address instruction pass");
65 }
66
67 const PassInfo *llvm::TwoAddressInstructionPassID = X.getPassInfo();
68
69 void TwoAddressInstructionPass::getAnalysisUsage(AnalysisUsage &AU) const {
70   AU.addRequired<LiveVariables>();
71   AU.addPreserved<LiveVariables>();
72   AU.addPreservedID(PHIEliminationID);
73   MachineFunctionPass::getAnalysisUsage(AU);
74 }
75
76 /// runOnMachineFunction - Reduce two-address instructions to two
77 /// operands.
78 ///
79 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
80   DEBUG(std::cerr << "Machine Function\n");
81   const TargetMachine &TM = MF.getTarget();
82   const MRegisterInfo &MRI = *TM.getRegisterInfo();
83   const TargetInstrInfo &TII = *TM.getInstrInfo();
84   LiveVariables &LV = getAnalysis<LiveVariables>();
85
86   bool MadeChange = false;
87
88   DEBUG(std::cerr << "********** REWRITING TWO-ADDR INSTRS **********\n");
89   DEBUG(std::cerr << "********** Function: "
90                   << MF.getFunction()->getName() << '\n');
91
92   for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
93        mbbi != mbbe; ++mbbi) {
94     for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
95          mi != me; ++mi) {
96       unsigned opcode = mi->getOpcode();
97
98       // ignore if it is not a two-address instruction
99       if (!TII.isTwoAddrInstr(opcode))
100         continue;
101
102       ++NumTwoAddressInstrs;
103       DEBUG(std::cerr << '\t'; mi->print(std::cerr, &TM));
104       assert(mi->getOperand(1).isRegister() && mi->getOperand(1).getReg() &&
105              mi->getOperand(1).isUse() && "two address instruction invalid");
106
107       // if the two operands are the same we just remove the use
108       // and mark the def as def&use, otherwise we have to insert a copy.
109       if (mi->getOperand(0).getReg() != mi->getOperand(1).getReg()) {
110         // rewrite:
111         //     a = b op c
112         // to:
113         //     a = b
114         //     a = a op c
115         unsigned regA = mi->getOperand(0).getReg();
116         unsigned regB = mi->getOperand(1).getReg();
117
118         assert(MRegisterInfo::isVirtualRegister(regA) &&
119                MRegisterInfo::isVirtualRegister(regB) &&
120                "cannot update physical register live information");
121
122 #ifndef NDEBUG
123         // First, verify that we do not have a use of a in the instruction (a =
124         // b + a for example) because our transformation will not work. This
125         // should never occur because we are in SSA form.
126         for (unsigned i = 1; i != mi->getNumOperands(); ++i)
127           assert(!mi->getOperand(i).isRegister() ||
128                  mi->getOperand(i).getReg() != regA);
129 #endif
130
131         // If this instruction is not the killing user of B, see if we can
132         // rearrange the code to make it so.  Making it the killing user will
133         // allow us to coalesce A and B together, eliminating the copy we are
134         // about to insert.
135         if (!LV.KillsRegister(mi, regB)) {
136           const TargetInstrDescriptor &TID = TII.get(opcode);
137
138           // If this instruction is commutative, check to see if C dies.  If so,
139           // swap the B and C operands.  This makes the live ranges of A and C
140           // joinable.
141           if (TID.Flags & M_COMMUTABLE) {
142             assert(mi->getOperand(2).isRegister() &&
143                    "Not a proper commutative instruction!");
144             unsigned regC = mi->getOperand(2).getReg();
145             if (LV.KillsRegister(mi, regC)) {
146               DEBUG(std::cerr << "2addr: COMMUTING  : " << *mi);
147               MachineInstr *NewMI = TII.commuteInstruction(mi);
148               if (NewMI == 0) {
149                 DEBUG(std::cerr << "2addr: COMMUTING FAILED!\n");
150               } else {
151                 DEBUG(std::cerr << "2addr: COMMUTED TO: " << *NewMI);
152                 // If the instruction changed to commute it, update livevar.
153                 if (NewMI != mi) {
154                   LV.instructionChanged(mi, NewMI);  // Update live variables
155                   mbbi->insert(mi, NewMI);           // Insert the new inst
156                   mbbi->erase(mi);                   // Nuke the old inst.
157                   mi = NewMI;
158                 }
159
160                 ++NumCommuted;
161                 regB = regC;
162                 goto InstructionRearranged;
163               }
164             }
165           }
166           // If this instruction is potentially convertible to a true
167           // three-address instruction,
168           if (TID.Flags & M_CONVERTIBLE_TO_3_ADDR)
169             if (MachineInstr *New = TII.convertToThreeAddress(mi)) {
170               DEBUG(std::cerr << "2addr: CONVERTING 2-ADDR: " << *mi);
171               DEBUG(std::cerr << "2addr:         TO 3-ADDR: " << *New);
172               LV.instructionChanged(mi, New);  // Update live variables
173               mbbi->insert(mi, New);           // Insert the new inst
174               mbbi->erase(mi);                 // Nuke the old inst.
175               mi = New;
176               ++NumConvertedTo3Addr;
177               assert(!TII.isTwoAddrInstr(New->getOpcode()) &&
178                      "convertToThreeAddress returned a 2-addr instruction??");
179               // Done with this instruction.
180               continue;
181             }
182         }
183       InstructionRearranged:
184         const TargetRegisterClass* rc = MF.getSSARegMap()->getRegClass(regA);
185         MRI.copyRegToReg(*mbbi, mi, regA, regB, rc);
186
187         MachineBasicBlock::iterator prevMi = prior(mi);
188         DEBUG(std::cerr << "\t\tprepend:\t"; prevMi->print(std::cerr, &TM));
189
190         // Update live variables for regA
191         LiveVariables::VarInfo& varInfo = LV.getVarInfo(regA);
192         varInfo.DefInst = prevMi;
193
194         // update live variables for regB
195         if (LV.removeVirtualRegisterKilled(regB, mbbi, mi))
196           LV.addVirtualRegisterKilled(regB, prevMi);
197
198         if (LV.removeVirtualRegisterDead(regB, mbbi, mi))
199           LV.addVirtualRegisterDead(regB, prevMi);
200
201         // replace all occurences of regB with regA
202         for (unsigned i = 1, e = mi->getNumOperands(); i != e; ++i) {
203           if (mi->getOperand(i).isRegister() &&
204               mi->getOperand(i).getReg() == regB)
205             mi->getOperand(i).setReg(regA);
206         }
207       }
208
209       assert(mi->getOperand(0).isDef());
210       mi->getOperand(0).setUse();
211       mi->RemoveOperand(1);
212       MadeChange = true;
213
214       DEBUG(std::cerr << "\t\trewrite to:\t"; mi->print(std::cerr, &TM));
215     }
216   }
217
218   return MadeChange;
219 }