Don't hoist or sink instructions with physreg uses if the physreg is
[oota-llvm.git] / lib / CodeGen / MachineSink.cpp
1 //===-- MachineSink.cpp - Sinking for machine instructions ----------------===//
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 moves instructions into successor blocks, when possible, so that
11 // they aren't executed on paths where their results aren't needed.
12 //
13 // This pass is not intended to be a replacement or a complete alternative
14 // for an LLVM-IR-level sinking pass. It is only designed to sink simple
15 // constructs that are not exposed before lowering and instruction selection.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "machine-sink"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm;
31
32 STATISTIC(NumSunk, "Number of machine instructions sunk");
33
34 namespace {
35   class VISIBILITY_HIDDEN MachineSinking : public MachineFunctionPass {
36     const TargetMachine   *TM;
37     const TargetInstrInfo *TII;
38     const TargetRegisterInfo *TRI;
39     MachineFunction       *CurMF; // Current MachineFunction
40     MachineRegisterInfo  *RegInfo; // Machine register information
41     MachineDominatorTree *DT;   // Machine dominator tree
42     BitVector AllocatableSet;   // Which physregs are allocatable?
43
44   public:
45     static char ID; // Pass identification
46     MachineSinking() : 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       AU.addRequired<MachineDominatorTree>();
54       AU.addPreserved<MachineDominatorTree>();
55     }
56   private:
57     bool ProcessBlock(MachineBasicBlock &MBB);
58     bool SinkInstruction(MachineInstr *MI, bool &SawStore);
59     bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
60   };
61 } // end anonymous namespace
62   
63 char MachineSinking::ID = 0;
64 static RegisterPass<MachineSinking>
65 X("machine-sink", "Machine code sinking");
66
67 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
68
69 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
70 /// occur in blocks dominated by the specified block.
71 bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg, 
72                                              MachineBasicBlock *MBB) const {
73   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
74          "Only makes sense for vregs");
75   for (MachineRegisterInfo::use_iterator I = RegInfo->use_begin(Reg),
76        E = RegInfo->use_end(); I != E; ++I) {
77     // Determine the block of the use.
78     MachineInstr *UseInst = &*I;
79     MachineBasicBlock *UseBlock = UseInst->getParent();
80     if (UseInst->getOpcode() == TargetInstrInfo::PHI) {
81       // PHI nodes use the operand in the predecessor block, not the block with
82       // the PHI.
83       UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
84     }
85     // Check that it dominates.
86     if (!DT->dominates(MBB, UseBlock))
87       return false;
88   }
89   return true;
90 }
91
92
93
94 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
95   DEBUG(errs() << "******** Machine Sinking ********\n");
96   
97   CurMF = &MF;
98   TM = &CurMF->getTarget();
99   TII = TM->getInstrInfo();
100   TRI = TM->getRegisterInfo();
101   RegInfo = &CurMF->getRegInfo();
102   DT = &getAnalysis<MachineDominatorTree>();
103   AllocatableSet = TRI->getAllocatableSet(*CurMF);
104
105   bool EverMadeChange = false;
106   
107   while (1) {
108     bool MadeChange = false;
109
110     // Process all basic blocks.
111     for (MachineFunction::iterator I = CurMF->begin(), E = CurMF->end(); 
112          I != E; ++I)
113       MadeChange |= ProcessBlock(*I);
114     
115     // If this iteration over the code changed anything, keep iterating.
116     if (!MadeChange) break;
117     EverMadeChange = true;
118   } 
119   return EverMadeChange;
120 }
121
122 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
123   // Can't sink anything out of a block that has less than two successors.
124   if (MBB.succ_size() <= 1 || MBB.empty()) return false;
125
126   bool MadeChange = false;
127
128   // Walk the basic block bottom-up.  Remember if we saw a store.
129   MachineBasicBlock::iterator I = MBB.end();
130   --I;
131   bool ProcessedBegin, SawStore = false;
132   do {
133     MachineInstr *MI = I;  // The instruction to sink.
134     
135     // Predecrement I (if it's not begin) so that it isn't invalidated by
136     // sinking.
137     ProcessedBegin = I == MBB.begin();
138     if (!ProcessedBegin)
139       --I;
140     
141     if (SinkInstruction(MI, SawStore))
142       ++NumSunk, MadeChange = true;
143     
144     // If we just processed the first instruction in the block, we're done.
145   } while (!ProcessedBegin);
146   
147   return MadeChange;
148 }
149
150 /// SinkInstruction - Determine whether it is safe to sink the specified machine
151 /// instruction out of its current block into a successor.
152 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
153   // Check if it's safe to move the instruction.
154   if (!MI->isSafeToMove(TII, SawStore))
155     return false;
156   
157   // FIXME: This should include support for sinking instructions within the
158   // block they are currently in to shorten the live ranges.  We often get
159   // instructions sunk into the top of a large block, but it would be better to
160   // also sink them down before their first use in the block.  This xform has to
161   // be careful not to *increase* register pressure though, e.g. sinking
162   // "x = y + z" down if it kills y and z would increase the live ranges of y
163   // and z and only shrink the live range of x.
164   
165   // Loop over all the operands of the specified instruction.  If there is
166   // anything we can't handle, bail out.
167   MachineBasicBlock *ParentBlock = MI->getParent();
168   
169   // SuccToSinkTo - This is the successor to sink this instruction to, once we
170   // decide.
171   MachineBasicBlock *SuccToSinkTo = 0;
172   
173   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
174     const MachineOperand &MO = MI->getOperand(i);
175     if (!MO.isReg()) continue;  // Ignore non-register operands.
176     
177     unsigned Reg = MO.getReg();
178     if (Reg == 0) continue;
179     
180     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
181       // If this is a physical register use, we can't move it.  If it is a def,
182       // we can move it, but only if the def is dead.
183       if (MO.isUse()) {
184         // If the physreg has no defs anywhere, it's just an ambient register
185         // and we can freely move its uses. Alternatively, if it's allocatable,
186         // it could get allocated to something with a def during allocation.
187         if (!RegInfo->def_empty(Reg))
188           return false;
189         if (AllocatableSet.test(Reg))
190           return false;
191         // Check for a def among the register's aliases too.
192         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
193           unsigned AliasReg = *Alias;
194           if (!RegInfo->def_empty(AliasReg))
195             return false;
196           if (AllocatableSet.test(AliasReg))
197             return false;
198         }
199       } else if (!MO.isDead()) {
200         // A def that isn't dead. We can't move it.
201         return false;
202       }
203     } else {
204       // Virtual register uses are always safe to sink.
205       if (MO.isUse()) continue;
206
207       // If it's not safe to move defs of the register class, then abort.
208       if (!TII->isSafeToMoveRegClassDefs(RegInfo->getRegClass(Reg)))
209         return false;
210       
211       // FIXME: This picks a successor to sink into based on having one
212       // successor that dominates all the uses.  However, there are cases where
213       // sinking can happen but where the sink point isn't a successor.  For
214       // example:
215       //   x = computation
216       //   if () {} else {}
217       //   use x
218       // the instruction could be sunk over the whole diamond for the 
219       // if/then/else (or loop, etc), allowing it to be sunk into other blocks
220       // after that.
221       
222       // Virtual register defs can only be sunk if all their uses are in blocks
223       // dominated by one of the successors.
224       if (SuccToSinkTo) {
225         // If a previous operand picked a block to sink to, then this operand
226         // must be sinkable to the same block.
227         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo)) 
228           return false;
229         continue;
230       }
231       
232       // Otherwise, we should look at all the successors and decide which one
233       // we should sink to.
234       for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
235            E = ParentBlock->succ_end(); SI != E; ++SI) {
236         if (AllUsesDominatedByBlock(Reg, *SI)) {
237           SuccToSinkTo = *SI;
238           break;
239         }
240       }
241       
242       // If we couldn't find a block to sink to, ignore this instruction.
243       if (SuccToSinkTo == 0)
244         return false;
245     }
246   }
247   
248   // If there are no outputs, it must have side-effects.
249   if (SuccToSinkTo == 0)
250     return false;
251
252   // It's not safe to sink instructions to EH landing pad. Control flow into
253   // landing pad is implicitly defined.
254   if (SuccToSinkTo->isLandingPad())
255     return false;
256   
257   // If is not possible to sink an instruction into its own block.  This can
258   // happen with loops.
259   if (MI->getParent() == SuccToSinkTo)
260     return false;
261   
262   DEBUG(errs() << "Sink instr " << *MI);
263   DEBUG(errs() << "to block " << *SuccToSinkTo);
264   
265   // If the block has multiple predecessors, this would introduce computation on
266   // a path that it doesn't already exist.  We could split the critical edge,
267   // but for now we just punt.
268   // FIXME: Split critical edges if not backedges.
269   if (SuccToSinkTo->pred_size() > 1) {
270     DEBUG(errs() << " *** PUNTING: Critical edge found\n");
271     return false;
272   }
273   
274   // Determine where to insert into.  Skip phi nodes.
275   MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
276   while (InsertPos != SuccToSinkTo->end() && 
277          InsertPos->getOpcode() == TargetInstrInfo::PHI)
278     ++InsertPos;
279   
280   // Move the instruction.
281   SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
282                        ++MachineBasicBlock::iterator(MI));
283   return true;
284 }