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