move target-independent opcodes out of TargetInstrInfo
[oota-llvm.git] / lib / CodeGen / OptimizeExts.cpp
1 //===-- OptimizeExts.cpp - Optimize sign / zero extension instrs -----===//
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 // This pass performs optimization of sign / zero extension instructions. It
11 // may be extended to handle other instructions of similar property.
12 //
13 // On some targets, some instructions, e.g. X86 sign / zero extension, may
14 // leave the source value in the lower part of the result. This pass will
15 // replace (some) uses of the pre-extension value with uses of the sub-register
16 // of the results.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "ext-opt"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetRegisterInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/Statistic.h"
30 using namespace llvm;
31
32 static cl::opt<bool> Aggressive("aggressive-ext-opt", cl::Hidden,
33                                 cl::desc("Aggressive extension optimization"));
34
35 STATISTIC(NumReuse, "Number of extension results reused");
36
37 namespace {
38   class OptimizeExts : public MachineFunctionPass {
39     const TargetMachine   *TM;
40     const TargetInstrInfo *TII;
41     MachineRegisterInfo *MRI;
42     MachineDominatorTree *DT;   // Machine dominator tree
43
44   public:
45     static char ID; // Pass identification
46     OptimizeExts() : MachineFunctionPass(&ID) {}
47
48     virtual bool runOnMachineFunction(MachineFunction &MF);
49
50     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51       AU.setPreservesCFG();
52       MachineFunctionPass::getAnalysisUsage(AU);
53       if (Aggressive) {
54         AU.addRequired<MachineDominatorTree>();
55         AU.addPreserved<MachineDominatorTree>();
56       }
57     }
58
59   private:
60     bool OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,
61                        SmallPtrSet<MachineInstr*, 8> &LocalMIs);
62   };
63 }
64
65 char OptimizeExts::ID = 0;
66 static RegisterPass<OptimizeExts>
67 X("opt-exts", "Optimize sign / zero extensions");
68
69 FunctionPass *llvm::createOptimizeExtsPass() { return new OptimizeExts(); }
70
71 /// OptimizeInstr - If instruction is a copy-like instruction, i.e. it reads
72 /// a single register and writes a single register and it does not modify
73 /// the source, and if the source value is preserved as a sub-register of
74 /// the result, then replace all reachable uses of the source with the subreg
75 /// of the result.
76 bool OptimizeExts::OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,
77                                  SmallPtrSet<MachineInstr*, 8> &LocalMIs) {
78   bool Changed = false;
79   LocalMIs.insert(MI);
80
81   unsigned SrcReg, DstReg, SubIdx;
82   if (TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx)) {
83     if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
84         TargetRegisterInfo::isPhysicalRegister(SrcReg))
85       return false;
86
87     MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg);
88     if (++UI == MRI->use_end())
89       // No other uses.
90       return false;
91
92     // Ok, the source has other uses. See if we can replace the other uses
93     // with use of the result of the extension.
94     SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
95     UI = MRI->use_begin(DstReg);
96     for (MachineRegisterInfo::use_iterator UE = MRI->use_end(); UI != UE;
97          ++UI)
98       ReachedBBs.insert(UI->getParent());
99
100     bool ExtendLife = true;
101     // Uses that are in the same BB of uses of the result of the instruction.
102     SmallVector<MachineOperand*, 8> Uses;
103     // Uses that the result of the instruction can reach.
104     SmallVector<MachineOperand*, 8> ExtendedUses;
105
106     UI = MRI->use_begin(SrcReg);
107     for (MachineRegisterInfo::use_iterator UE = MRI->use_end(); UI != UE;
108          ++UI) {
109       MachineOperand &UseMO = UI.getOperand();
110       MachineInstr *UseMI = &*UI;
111       if (UseMI == MI)
112         continue;
113       if (UseMI->isPHI()) {
114         ExtendLife = false;
115         continue;
116       }
117
118       MachineBasicBlock *UseMBB = UseMI->getParent();
119       if (UseMBB == MBB) {
120         // Local uses that come after the extension.
121         if (!LocalMIs.count(UseMI))
122           Uses.push_back(&UseMO);
123       } else if (ReachedBBs.count(UseMBB))
124         // Non-local uses where the result of extension is used. Always
125         // replace these unless it's a PHI.
126         Uses.push_back(&UseMO);
127       else if (Aggressive && DT->dominates(MBB, UseMBB))
128         // We may want to extend live range of the extension result in order
129         // to replace these uses.
130         ExtendedUses.push_back(&UseMO);
131       else {
132         // Both will be live out of the def MBB anyway. Don't extend live
133         // range of the extension result.
134         ExtendLife = false;
135         break;
136       }
137     }
138
139     if (ExtendLife && !ExtendedUses.empty())
140       // Ok, we'll extend the liveness of the extension result.
141       std::copy(ExtendedUses.begin(), ExtendedUses.end(),
142                 std::back_inserter(Uses));
143
144     // Now replace all uses.
145     if (!Uses.empty()) {
146       SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
147       // Look for PHI uses of the extended result, we don't want to extend the
148       // liveness of a PHI input. It breaks all kinds of assumptions down
149       // stream. A PHI use is expected to be the kill of its source values.
150       UI = MRI->use_begin(DstReg);
151       for (MachineRegisterInfo::use_iterator UE = MRI->use_end(); UI != UE;
152            ++UI)
153         if (UI->isPHI())
154           PHIBBs.insert(UI->getParent());
155
156       const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
157       for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
158         MachineOperand *UseMO = Uses[i];
159         MachineInstr *UseMI = UseMO->getParent();
160         MachineBasicBlock *UseMBB = UseMI->getParent();
161         if (PHIBBs.count(UseMBB))
162           continue;
163         unsigned NewVR = MRI->createVirtualRegister(RC);
164         BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
165                 TII->get(TargetOpcode::EXTRACT_SUBREG), NewVR)
166           .addReg(DstReg).addImm(SubIdx);
167         UseMO->setReg(NewVR);
168         ++NumReuse;
169         Changed = true;
170       }
171     }
172   }
173
174   return Changed;
175 }
176
177 bool OptimizeExts::runOnMachineFunction(MachineFunction &MF) {
178   TM = &MF.getTarget();
179   TII = TM->getInstrInfo();
180   MRI = &MF.getRegInfo();
181   DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0;
182
183   bool Changed = false;
184
185   SmallPtrSet<MachineInstr*, 8> LocalMIs;
186   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
187     MachineBasicBlock *MBB = &*I;
188     LocalMIs.clear();
189     for (MachineBasicBlock::iterator MII = I->begin(), ME = I->end(); MII != ME;
190          ++MII) {
191       MachineInstr *MI = &*MII;
192       Changed |= OptimizeInstr(MI, MBB, LocalMIs);
193     }
194   }
195
196   return Changed;
197 }