Add an LLVM IR version of code sinking. This uses the same simple algorithm
[oota-llvm.git] / lib / Transforms / Scalar / Sink.cpp
1 //===-- Sink.cpp - Code Sinking -------------------------------------------===//
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 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "sink"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Analysis/Dominators.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Support/CFG.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 using namespace llvm;
27
28 STATISTIC(NumSunk, "Number of instructions sunk");
29
30 namespace {
31   class Sinking : public FunctionPass {
32     DominatorTree *DT;
33     LoopInfo *LI;
34     AliasAnalysis *AA;
35
36   public:
37     static char ID; // Pass identification
38     Sinking() : FunctionPass(&ID) {}
39     
40     virtual bool runOnFunction(Function &F);
41     
42     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
43       AU.setPreservesCFG();
44       FunctionPass::getAnalysisUsage(AU);
45       AU.addRequired<AliasAnalysis>();
46       AU.addRequired<DominatorTree>();
47       AU.addRequired<LoopInfo>();
48       AU.addPreserved<DominatorTree>();
49       AU.addPreserved<LoopInfo>();
50     }
51   private:
52     bool ProcessBlock(BasicBlock &BB);
53     bool SinkInstruction(Instruction *I, SmallPtrSet<Instruction *, 8> &Stores);
54     bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
55   };
56 } // end anonymous namespace
57   
58 char Sinking::ID = 0;
59 static RegisterPass<Sinking>
60 X("sink", "Code sinking");
61
62 FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
63
64 /// AllUsesDominatedByBlock - Return true if all uses of the specified value
65 /// occur in blocks dominated by the specified block.
66 bool Sinking::AllUsesDominatedByBlock(Instruction *Inst, 
67                                       BasicBlock *BB) const {
68   // Ignoring debug uses is necessary so debug info doesn't affect the code.
69   // This may leave a referencing dbg_value in the original block, before
70   // the definition of the vreg.  Dwarf generator handles this although the
71   // user might not get the right info at runtime.
72   for (Value::use_iterator I = Inst->use_begin(),
73        E = Inst->use_end(); I != E; ++I) {
74     // Determine the block of the use.
75     Instruction *UseInst = cast<Instruction>(*I);
76     BasicBlock *UseBlock = UseInst->getParent();
77     if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
78       // PHI nodes use the operand in the predecessor block, not the block with
79       // the PHI.
80       unsigned Num = PHINode::getIncomingValueNumForOperand(I.getOperandNo());
81       UseBlock = PN->getIncomingBlock(Num);
82     }
83     // Check that it dominates.
84     if (!DT->dominates(BB, UseBlock))
85       return false;
86   }
87   return true;
88 }
89
90 bool Sinking::runOnFunction(Function &F) {
91   DT = &getAnalysis<DominatorTree>();
92   LI = &getAnalysis<LoopInfo>();
93   AA = &getAnalysis<AliasAnalysis>();
94
95   bool EverMadeChange = false;
96   
97   while (1) {
98     bool MadeChange = false;
99
100     // Process all basic blocks.
101     for (Function::iterator I = F.begin(), E = F.end(); 
102          I != E; ++I)
103       MadeChange |= ProcessBlock(*I);
104     
105     // If this iteration over the code changed anything, keep iterating.
106     if (!MadeChange) break;
107     EverMadeChange = true;
108   } 
109   return EverMadeChange;
110 }
111
112 bool Sinking::ProcessBlock(BasicBlock &BB) {
113   // Can't sink anything out of a block that has less than two successors.
114   if (BB.getTerminator()->getNumSuccessors() <= 1 || BB.empty()) return false;
115
116   // Don't bother sinking code out of unreachable blocks. In addition to being
117   // unprofitable, it can also lead to infinite looping, because in an unreachable
118   // loop there may be nowhere to stop.
119   if (!DT->isReachableFromEntry(&BB)) return false;
120
121   bool MadeChange = false;
122
123   // Walk the basic block bottom-up.  Remember if we saw a store.
124   BasicBlock::iterator I = BB.end();
125   --I;
126   bool ProcessedBegin = false;
127   SmallPtrSet<Instruction *, 8> Stores;
128   do {
129     Instruction *Inst = I;  // The instruction to sink.
130     
131     // Predecrement I (if it's not begin) so that it isn't invalidated by
132     // sinking.
133     ProcessedBegin = I == BB.begin();
134     if (!ProcessedBegin)
135       --I;
136
137     if (isa<DbgInfoIntrinsic>(Inst))
138       continue;
139
140     if (SinkInstruction(Inst, Stores))
141       ++NumSunk, MadeChange = true;
142     
143     // If we just processed the first instruction in the block, we're done.
144   } while (!ProcessedBegin);
145   
146   return MadeChange;
147 }
148
149 static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
150                          SmallPtrSet<Instruction *, 8> &Stores) {
151   if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
152     if (L->isVolatile()) return false;
153
154     Value *Ptr = L->getPointerOperand();
155     unsigned Size = AA->getTypeStoreSize(L->getType());
156     for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
157          E = Stores.end(); I != E; ++I)
158       if (AA->getModRefInfo(*I, Ptr, Size) & AliasAnalysis::Mod)
159         return false;
160   }
161
162   if (Inst->mayWriteToMemory()) {
163     Stores.insert(Inst);
164     return false;
165   }
166
167   return Inst->isSafeToSpeculativelyExecute();
168 }
169
170 /// SinkInstruction - Determine whether it is safe to sink the specified machine
171 /// instruction out of its current block into a successor.
172 bool Sinking::SinkInstruction(Instruction *Inst,
173                               SmallPtrSet<Instruction *, 8> &Stores) {
174   // Check if it's safe to move the instruction.
175   if (!isSafeToMove(Inst, AA, Stores))
176     return false;
177   
178   // FIXME: This should include support for sinking instructions within the
179   // block they are currently in to shorten the live ranges.  We often get
180   // instructions sunk into the top of a large block, but it would be better to
181   // also sink them down before their first use in the block.  This xform has to
182   // be careful not to *increase* register pressure though, e.g. sinking
183   // "x = y + z" down if it kills y and z would increase the live ranges of y
184   // and z and only shrink the live range of x.
185   
186   // Loop over all the operands of the specified instruction.  If there is
187   // anything we can't handle, bail out.
188   BasicBlock *ParentBlock = Inst->getParent();
189   
190   // SuccToSinkTo - This is the successor to sink this instruction to, once we
191   // decide.
192   BasicBlock *SuccToSinkTo = 0;
193   
194   // FIXME: This picks a successor to sink into based on having one
195   // successor that dominates all the uses.  However, there are cases where
196   // sinking can happen but where the sink point isn't a successor.  For
197   // example:
198   //   x = computation
199   //   if () {} else {}
200   //   use x
201   // the instruction could be sunk over the whole diamond for the 
202   // if/then/else (or loop, etc), allowing it to be sunk into other blocks
203   // after that.
204   
205   // Instructions can only be sunk if all their uses are in blocks
206   // dominated by one of the successors.
207   // Look at all the successors and decide which one
208   // we should sink to.
209   for (succ_iterator SI = succ_begin(ParentBlock),
210        E = succ_end(ParentBlock); SI != E; ++SI) {
211     if (AllUsesDominatedByBlock(Inst, *SI)) {
212       SuccToSinkTo = *SI;
213       break;
214     }
215   }
216       
217   // If we couldn't find a block to sink to, ignore this instruction.
218   if (SuccToSinkTo == 0)
219     return false;
220   
221   // It is not possible to sink an instruction into its own block.  This can
222   // happen with loops.
223   if (Inst->getParent() == SuccToSinkTo)
224     return false;
225   
226   DEBUG(dbgs() << "Sink instr " << *Inst);
227   DEBUG(dbgs() << "to block ";
228         WriteAsOperand(dbgs(), SuccToSinkTo, false));
229   
230   // If the block has multiple predecessors, this would introduce computation on
231   // a path that it doesn't already exist.  We could split the critical edge,
232   // but for now we just punt.
233   // FIXME: Split critical edges if not backedges.
234   if (SuccToSinkTo->getUniquePredecessor() != ParentBlock) {
235     // We cannot sink a load across a critical edge - there may be stores in
236     // other code paths.
237     if (!Inst->isSafeToSpeculativelyExecute()) {
238       DEBUG(dbgs() << " *** PUNTING: Wont sink load along critical edge.\n");
239       return false;
240     }
241
242     // We don't want to sink across a critical edge if we don't dominate the
243     // successor. We could be introducing calculations to new code paths.
244     if (!DT->dominates(ParentBlock, SuccToSinkTo)) {
245       DEBUG(dbgs() << " *** PUNTING: Critical edge found\n");
246       return false;
247     }
248
249     // Don't sink instructions into a loop.
250     if (LI->isLoopHeader(SuccToSinkTo)) {
251       DEBUG(dbgs() << " *** PUNTING: Loop header found\n");
252       return false;
253     }
254
255     // Otherwise we are OK with sinking along a critical edge.
256     DEBUG(dbgs() << "Sinking along critical edge.\n");
257   }
258   
259   // Determine where to insert into.  Skip phi nodes.
260   BasicBlock::iterator InsertPos = SuccToSinkTo->begin();
261   while (InsertPos != SuccToSinkTo->end() && isa<PHINode>(InsertPos))
262     ++InsertPos;
263   
264   // Move the instruction.
265   Inst->moveBefore(InsertPos);
266   return true;
267 }