Revert r106066, "Create a more targeted fix for not sinking instructions into a range...
[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/CodeGen/MachineLoopInfo.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Target/TargetRegisterInfo.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33
34 STATISTIC(NumSunk, "Number of machine instructions sunk");
35
36 namespace {
37   class MachineSinking : public MachineFunctionPass {
38     const TargetInstrInfo *TII;
39     const TargetRegisterInfo *TRI;
40     MachineRegisterInfo  *RegInfo; // Machine register information
41     MachineDominatorTree *DT;   // Machine dominator tree
42     MachineLoopInfo *LI;
43     AliasAnalysis *AA;
44     BitVector AllocatableSet;   // Which physregs are allocatable?
45
46   public:
47     static char ID; // Pass identification
48     MachineSinking() : MachineFunctionPass(&ID) {}
49
50     virtual bool runOnMachineFunction(MachineFunction &MF);
51
52     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53       AU.setPreservesCFG();
54       MachineFunctionPass::getAnalysisUsage(AU);
55       AU.addRequired<AliasAnalysis>();
56       AU.addRequired<MachineDominatorTree>();
57       AU.addRequired<MachineLoopInfo>();
58       AU.addPreserved<MachineDominatorTree>();
59       AU.addPreserved<MachineLoopInfo>();
60     }
61   private:
62     bool ProcessBlock(MachineBasicBlock &MBB);
63     bool SinkInstruction(MachineInstr *MI, bool &SawStore);
64     bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB) const;
65     bool LiveOutOfBasicBlock(const MachineInstr *MI, unsigned Reg) const;
66   };
67 } // end anonymous namespace
68
69 char MachineSinking::ID = 0;
70 static RegisterPass<MachineSinking>
71 X("machine-sink", "Machine code sinking");
72
73 FunctionPass *llvm::createMachineSinkingPass() { return new MachineSinking(); }
74
75 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
76 /// occur in blocks dominated by the specified block.
77 bool MachineSinking::AllUsesDominatedByBlock(unsigned Reg,
78                                              MachineBasicBlock *MBB) const {
79   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
80          "Only makes sense for vregs");
81   // Ignoring debug uses is necessary so debug info doesn't affect the code.
82   // This may leave a referencing dbg_value in the original block, before
83   // the definition of the vreg.  Dwarf generator handles this although the
84   // user might not get the right info at runtime.
85   for (MachineRegisterInfo::use_nodbg_iterator
86          I = RegInfo->use_nodbg_begin(Reg), E = RegInfo->use_nodbg_end();
87        I != E; ++I) {
88     // Determine the block of the use.
89     MachineInstr *UseInst = &*I;
90     MachineBasicBlock *UseBlock = UseInst->getParent();
91
92     if (UseInst->isPHI()) {
93       // PHI nodes use the operand in the predecessor block, not the block with
94       // the PHI.
95       UseBlock = UseInst->getOperand(I.getOperandNo()+1).getMBB();
96     }
97
98     // Check that it dominates.
99     if (!DT->dominates(MBB, UseBlock))
100       return false;
101   }
102
103   return true;
104 }
105
106 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) {
107   DEBUG(dbgs() << "******** Machine Sinking ********\n");
108
109   const TargetMachine &TM = MF.getTarget();
110   TII = TM.getInstrInfo();
111   TRI = TM.getRegisterInfo();
112   RegInfo = &MF.getRegInfo();
113   DT = &getAnalysis<MachineDominatorTree>();
114   LI = &getAnalysis<MachineLoopInfo>();
115   AA = &getAnalysis<AliasAnalysis>();
116   AllocatableSet = TRI->getAllocatableSet(MF);
117
118   bool EverMadeChange = false;
119
120   while (1) {
121     bool MadeChange = false;
122
123     // Process all basic blocks.
124     for (MachineFunction::iterator I = MF.begin(), E = MF.end();
125          I != E; ++I)
126       MadeChange |= ProcessBlock(*I);
127
128     // If this iteration over the code changed anything, keep iterating.
129     if (!MadeChange) break;
130     EverMadeChange = true;
131   }
132   return EverMadeChange;
133 }
134
135 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) {
136   // Can't sink anything out of a block that has less than two successors.
137   if (MBB.succ_size() <= 1 || MBB.empty()) return false;
138
139   // Don't bother sinking code out of unreachable blocks. In addition to being
140   // unprofitable, it can also lead to infinite looping, because in an
141   // unreachable loop there may be nowhere to stop.
142   if (!DT->isReachableFromEntry(&MBB)) return false;
143
144   bool MadeChange = false;
145
146   // Walk the basic block bottom-up.  Remember if we saw a store.
147   MachineBasicBlock::iterator I = MBB.end();
148   --I;
149   bool ProcessedBegin, SawStore = false;
150   do {
151     MachineInstr *MI = I;  // The instruction to sink.
152
153     // Predecrement I (if it's not begin) so that it isn't invalidated by
154     // sinking.
155     ProcessedBegin = I == MBB.begin();
156     if (!ProcessedBegin)
157       --I;
158
159     if (MI->isDebugValue())
160       continue;
161
162     if (SinkInstruction(MI, SawStore))
163       ++NumSunk, MadeChange = true;
164
165     // If we just processed the first instruction in the block, we're done.
166   } while (!ProcessedBegin);
167
168   return MadeChange;
169 }
170
171 /// LiveOutOfBasicBlock - Determine if the physical register, defined and dead
172 /// in MI, is live on exit from the basic block.
173 bool MachineSinking::LiveOutOfBasicBlock(const MachineInstr *MI,
174                                          unsigned Reg) const {
175   assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
176          "Only want to determine if a physical register is live out of a BB!");
177
178   const MachineBasicBlock *MBB = MI->getParent();
179   SmallSet<unsigned, 8> KilledRegs;
180   MachineBasicBlock::const_iterator I = MBB->end();
181   MachineBasicBlock::const_iterator E = MBB->begin();
182   assert(I != E && "How can there be an empty block at this point?!");
183
184   // Loop through the instructions bottom-up. If we see a kill of the preg
185   // first, then it's not live out of the BB. If we see a use or def first, then
186   // we assume that it is live out of the BB.
187   do {
188     const MachineInstr &CurMI = *--I;
189
190     for (unsigned i = 0, e = CurMI.getNumOperands(); i != e; ++i) {
191       const MachineOperand &MO = CurMI.getOperand(i);
192       if (!MO.isReg()) continue;  // Ignore non-register operands.
193
194       unsigned MOReg = MO.getReg();
195       if (MOReg == 0) continue;
196
197       if (MOReg == Reg) {
198         if (MO.isKill())
199           return false;
200         if (MO.isUse() || MO.isDef())
201           return true;
202       }
203     }
204   } while (I != E);
205
206   return false;
207 }
208
209 /// SinkInstruction - Determine whether it is safe to sink the specified machine
210 /// instruction out of its current block into a successor.
211 bool MachineSinking::SinkInstruction(MachineInstr *MI, bool &SawStore) {
212   // Check if it's safe to move the instruction.
213   if (!MI->isSafeToMove(TII, AA, SawStore))
214     return false;
215
216   // FIXME: This should include support for sinking instructions within the
217   // block they are currently in to shorten the live ranges.  We often get
218   // instructions sunk into the top of a large block, but it would be better to
219   // also sink them down before their first use in the block.  This xform has to
220   // be careful not to *increase* register pressure though, e.g. sinking
221   // "x = y + z" down if it kills y and z would increase the live ranges of y
222   // and z and only shrink the live range of x.
223
224   // Loop over all the operands of the specified instruction.  If there is
225   // anything we can't handle, bail out.
226   MachineBasicBlock *ParentBlock = MI->getParent();
227
228   // SuccToSinkTo - This is the successor to sink this instruction to, once we
229   // decide.
230   MachineBasicBlock *SuccToSinkTo = 0;
231   SmallVector<unsigned, 4> PhysRegs;
232
233   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
234     const MachineOperand &MO = MI->getOperand(i);
235     if (!MO.isReg()) continue;  // Ignore non-register operands.
236
237     unsigned Reg = MO.getReg();
238     if (Reg == 0) continue;
239
240     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
241       if (MO.isUse()) {
242         // If the physreg has no defs anywhere, it's just an ambient register
243         // and we can freely move its uses. Alternatively, if it's allocatable,
244         // it could get allocated to something with a def during allocation.
245         if (!RegInfo->def_empty(Reg))
246           return false;
247
248         if (AllocatableSet.test(Reg))
249           return false;
250
251         // Check for a def among the register's aliases too.
252         for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
253           unsigned AliasReg = *Alias;
254           if (!RegInfo->def_empty(AliasReg))
255             return false;
256
257           if (AllocatableSet.test(AliasReg))
258             return false;
259         }
260       } else {
261         if (!MO.isDead())
262           // A def that isn't dead. We can't move it.
263           return false;
264         else
265           PhysRegs.push_back(Reg);
266       }
267     } else {
268       // Virtual register uses are always safe to sink.
269       if (MO.isUse()) continue;
270
271       // If it's not safe to move defs of the register class, then abort.
272       if (!TII->isSafeToMoveRegClassDefs(RegInfo->getRegClass(Reg)))
273         return false;
274
275       // FIXME: This picks a successor to sink into based on having one
276       // successor that dominates all the uses.  However, there are cases where
277       // sinking can happen but where the sink point isn't a successor.  For
278       // example:
279       //
280       //   x = computation
281       //   if () {} else {}
282       //   use x
283       //
284       // the instruction could be sunk over the whole diamond for the
285       // if/then/else (or loop, etc), allowing it to be sunk into other blocks
286       // after that.
287
288       // Virtual register defs can only be sunk if all their uses are in blocks
289       // dominated by one of the successors.
290       if (SuccToSinkTo) {
291         // If a previous operand picked a block to sink to, then this operand
292         // must be sinkable to the same block.
293         if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo))
294           return false;
295
296         continue;
297       }
298
299       // Otherwise, we should look at all the successors and decide which one
300       // we should sink to.
301       for (MachineBasicBlock::succ_iterator SI = ParentBlock->succ_begin(),
302            E = ParentBlock->succ_end(); SI != E; ++SI) {
303         if (AllUsesDominatedByBlock(Reg, *SI)) {
304           SuccToSinkTo = *SI;
305           break;
306         }
307       }
308
309       // If we couldn't find a block to sink to, ignore this instruction.
310       if (SuccToSinkTo == 0)
311         return false;
312     }
313   }
314
315   // If there are no outputs, it must have side-effects.
316   if (SuccToSinkTo == 0)
317     return false;
318
319   // It's not safe to sink instructions to EH landing pad. Control flow into
320   // landing pad is implicitly defined.
321   if (SuccToSinkTo->isLandingPad())
322     return false;
323
324   // It is not possible to sink an instruction into its own block.  This can
325   // happen with loops.
326   if (MI->getParent() == SuccToSinkTo)
327     return false;
328
329   // If the instruction to move defines a dead physical register which is live
330   // when leaving the basic block, don't move it because it could turn into a
331   // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
332   for (SmallVectorImpl<unsigned>::const_iterator
333          I = PhysRegs.begin(), E = PhysRegs.end(); I != E; ++I)
334     if (LiveOutOfBasicBlock(MI, *I))
335       return false;
336
337   DEBUG(dbgs() << "Sink instr " << *MI << "\tinto block " << *SuccToSinkTo);
338
339   // If the block has multiple predecessors, this would introduce computation on
340   // a path that it doesn't already exist.  We could split the critical edge,
341   // but for now we just punt.
342   // FIXME: Split critical edges if not backedges.
343   if (SuccToSinkTo->pred_size() > 1) {
344     // We cannot sink a load across a critical edge - there may be stores in
345     // other code paths.
346     bool store = true;
347     if (!MI->isSafeToMove(TII, AA, store)) {
348       DEBUG(dbgs() << " *** PUNTING: Wont sink load along critical edge.\n");
349       return false;
350     }
351
352     // We don't want to sink across a critical edge if we don't dominate the
353     // successor. We could be introducing calculations to new code paths.
354     if (!DT->dominates(ParentBlock, SuccToSinkTo)) {
355       DEBUG(dbgs() << " *** PUNTING: Critical edge found\n");
356       return false;
357     }
358
359     // Don't sink instructions into a loop.
360     if (LI->isLoopHeader(SuccToSinkTo)) {
361       DEBUG(dbgs() << " *** PUNTING: Loop header found\n");
362       return false;
363     }
364
365     // Otherwise we are OK with sinking along a critical edge.
366     DEBUG(dbgs() << "Sinking along critical edge.\n");
367   }
368
369   // Determine where to insert into. Skip phi nodes.
370   MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin();
371   while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI())
372     ++InsertPos;
373
374   // Move the instruction.
375   SuccToSinkTo->splice(InsertPos, ParentBlock, MI,
376                        ++MachineBasicBlock::iterator(MI));
377
378   // Conservatively, clear any kill flags, since it's possible that they are no
379   // longer correct.
380   MI->clearKillInfo();
381
382   return true;
383 }