Make Sink tbaa-aware.
[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/LLVMContext.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Assembly/Writer.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
29 STATISTIC(NumSunk, "Number of instructions sunk");
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   };
59 } // end anonymous namespace
60   
61 char Sinking::ID = 0;
62 INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
63 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
64 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
65 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
66 INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
67
68 FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
69
70 /// AllUsesDominatedByBlock - Return true if all uses of the specified value
71 /// occur in blocks dominated by the specified block.
72 bool Sinking::AllUsesDominatedByBlock(Instruction *Inst, 
73                                       BasicBlock *BB) const {
74   // Ignoring debug uses is necessary so debug info doesn't affect the code.
75   // This may leave a referencing dbg_value in the original block, before
76   // the definition of the vreg.  Dwarf generator handles this although the
77   // user might not get the right info at runtime.
78   for (Value::use_iterator I = Inst->use_begin(),
79        E = Inst->use_end(); I != E; ++I) {
80     // Determine the block of the use.
81     Instruction *UseInst = cast<Instruction>(*I);
82     BasicBlock *UseBlock = UseInst->getParent();
83     if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
84       // PHI nodes use the operand in the predecessor block, not the block with
85       // the PHI.
86       unsigned Num = PHINode::getIncomingValueNumForOperand(I.getOperandNo());
87       UseBlock = PN->getIncomingBlock(Num);
88     }
89     // Check that it dominates.
90     if (!DT->dominates(BB, UseBlock))
91       return false;
92   }
93   return true;
94 }
95
96 bool Sinking::runOnFunction(Function &F) {
97   DT = &getAnalysis<DominatorTree>();
98   LI = &getAnalysis<LoopInfo>();
99   AA = &getAnalysis<AliasAnalysis>();
100
101   bool EverMadeChange = false;
102   
103   while (1) {
104     bool MadeChange = false;
105
106     // Process all basic blocks.
107     for (Function::iterator I = F.begin(), E = F.end(); 
108          I != E; ++I)
109       MadeChange |= ProcessBlock(*I);
110     
111     // If this iteration over the code changed anything, keep iterating.
112     if (!MadeChange) break;
113     EverMadeChange = true;
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 unreachable
124   // 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   if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
158     if (L->isVolatile()) return false;
159
160     Value *Ptr = L->getPointerOperand();
161     uint64_t Size = AA->getTypeStoreSize(L->getType());
162     const MDNode *TBAAInfo = L->getMetadata(LLVMContext::MD_tbaa);
163     AliasAnalysis::Location Loc(Ptr, Size, TBAAInfo);
164     for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
165          E = Stores.end(); I != E; ++I)
166       if (AA->getModRefInfo(*I, Loc) & AliasAnalysis::Mod)
167         return false;
168   }
169
170   if (Inst->mayWriteToMemory()) {
171     Stores.insert(Inst);
172     return false;
173   }
174
175   if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
176     return false;
177
178   return true;
179 }
180
181 /// SinkInstruction - Determine whether it is safe to sink the specified machine
182 /// instruction out of its current block into a successor.
183 bool Sinking::SinkInstruction(Instruction *Inst,
184                               SmallPtrSet<Instruction *, 8> &Stores) {
185   // Check if it's safe to move the instruction.
186   if (!isSafeToMove(Inst, AA, Stores))
187     return false;
188   
189   // FIXME: This should include support for sinking instructions within the
190   // block they are currently in to shorten the live ranges.  We often get
191   // instructions sunk into the top of a large block, but it would be better to
192   // also sink them down before their first use in the block.  This xform has to
193   // be careful not to *increase* register pressure though, e.g. sinking
194   // "x = y + z" down if it kills y and z would increase the live ranges of y
195   // and z and only shrink the live range of x.
196   
197   // Loop over all the operands of the specified instruction.  If there is
198   // anything we can't handle, bail out.
199   BasicBlock *ParentBlock = Inst->getParent();
200   
201   // SuccToSinkTo - This is the successor to sink this instruction to, once we
202   // decide.
203   BasicBlock *SuccToSinkTo = 0;
204   
205   // FIXME: This picks a successor to sink into based on having one
206   // successor that dominates all the uses.  However, there are cases where
207   // sinking can happen but where the sink point isn't a successor.  For
208   // example:
209   //   x = computation
210   //   if () {} else {}
211   //   use x
212   // the instruction could be sunk over the whole diamond for the 
213   // if/then/else (or loop, etc), allowing it to be sunk into other blocks
214   // after that.
215   
216   // Instructions can only be sunk if all their uses are in blocks
217   // dominated by one of the successors.
218   // Look at all the successors and decide which one
219   // we should sink to.
220   for (succ_iterator SI = succ_begin(ParentBlock),
221        E = succ_end(ParentBlock); SI != E; ++SI) {
222     if (AllUsesDominatedByBlock(Inst, *SI)) {
223       SuccToSinkTo = *SI;
224       break;
225     }
226   }
227       
228   // If we couldn't find a block to sink to, ignore this instruction.
229   if (SuccToSinkTo == 0)
230     return false;
231   
232   // It is not possible to sink an instruction into its own block.  This can
233   // happen with loops.
234   if (Inst->getParent() == SuccToSinkTo)
235     return false;
236   
237   DEBUG(dbgs() << "Sink instr " << *Inst);
238   DEBUG(dbgs() << "to block ";
239         WriteAsOperand(dbgs(), SuccToSinkTo, false));
240   
241   // If the block has multiple predecessors, this would introduce computation on
242   // a path that it doesn't already exist.  We could split the critical edge,
243   // but for now we just punt.
244   // FIXME: Split critical edges if not backedges.
245   if (SuccToSinkTo->getUniquePredecessor() != ParentBlock) {
246     // We cannot sink a load across a critical edge - there may be stores in
247     // other code paths.
248     if (!Inst->isSafeToSpeculativelyExecute()) {
249       DEBUG(dbgs() << " *** PUNTING: Wont sink load along critical edge.\n");
250       return false;
251     }
252
253     // We don't want to sink across a critical edge if we don't dominate the
254     // successor. We could be introducing calculations to new code paths.
255     if (!DT->dominates(ParentBlock, SuccToSinkTo)) {
256       DEBUG(dbgs() << " *** PUNTING: Critical edge found\n");
257       return false;
258     }
259
260     // Don't sink instructions into a loop.
261     if (LI->isLoopHeader(SuccToSinkTo)) {
262       DEBUG(dbgs() << " *** PUNTING: Loop header found\n");
263       return false;
264     }
265
266     // Otherwise we are OK with sinking along a critical edge.
267     DEBUG(dbgs() << "Sinking along critical edge.\n");
268   }
269   
270   // Determine where to insert into.  Skip phi nodes.
271   BasicBlock::iterator InsertPos = SuccToSinkTo->begin();
272   while (InsertPos != SuccToSinkTo->end() && isa<PHINode>(InsertPos))
273     ++InsertPos;
274   
275   // Move the instruction.
276   Inst->moveBefore(InsertPos);
277   return true;
278 }