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