LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Sink.cpp
Go to the documentation of this file.
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"
20 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Assembly/Writer.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Support/Debug.h"
27 using namespace llvm;
28 
29 STATISTIC(NumSunk, "Number of instructions sunk");
30 STATISTIC(NumSinkIter, "Number of sinking iterations");
31 
32 namespace {
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) {
42  }
43 
44  virtual bool runOnFunction(Function &F);
45 
46  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47  AU.setPreservesCFG();
51  AU.addRequired<LoopInfo>();
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 
63 char Sinking::ID = 0;
64 INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
68 INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
69 
70 FunctionPass *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.
74 bool 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 
98 bool 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 
119 bool 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;
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 
156 static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
158 
159  if (Inst->mayWriteToMemory()) {
160  Stores.insert(Inst);
161  return false;
162  }
163 
164  if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
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.
180 bool 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.
219 bool Sinking::SinkInstruction(Instruction *Inst,
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 }
use_iterator use_end()
Definition: Value.h:152
AnalysisUsage & addPreserved()
BasicBlock * getUniquePredecessor()
Return this block if it has a unique predecessor block. Otherwise return a null pointer.
Definition: BasicBlock.cpp:196
static PassRegistry * getPassRegistry()
ModRefResult getModRefInfo(const Instruction *I, const Location &Loc)
iterator end()
Definition: Function.h:397
virtual void getAnalysisUsage(AnalysisUsage &) const
Definition: Pass.cpp:75
bool insert(PtrType Ptr)
Definition: SmallPtrSet.h:253
machine Machine code sinking
F(f)
LoopInfoBase< BlockT, LoopT > * LI
Definition: LoopInfoImpl.h:411
iterator begin()
Definition: BasicBlock.h:193
void WriteAsOperand(raw_ostream &, const Value *, bool PrintTy=true, const Module *Context=0)
Definition: AsmWriter.cpp:1179
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:167
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:172
FunctionPass * createSinkingPass()
Definition: Sink.cpp:70
ID
LLVM Calling Convention Representation.
Definition: CallingConv.h:26
#define false
Definition: ConvertUTF.c:64
Interval::succ_iterator succ_begin(Interval *I)
Definition: Interval.h:107
bool empty() const
Definition: BasicBlock.h:204
iterator begin()
Definition: Function.h:395
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:110
unsigned getNumSuccessors() const
Definition: InstrTypes.h:59
LLVM Basic Block Representation.
Definition: BasicBlock.h:72
Location - A description of a memory location.
#define INITIALIZE_AG_DEPENDENCY(depName)
Definition: PassSupport.h:169
STATISTIC(NumSunk,"Number of instructions sunk")
static unsigned getIncomingValueNumForOperand(unsigned i)
bool mayWriteToMemory() const
bool isSafeToSpeculativelyExecute(const Value *V, const DataLayout *TD=0)
SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
Definition: SmallPtrSet.h:174
iterator end()
Definition: BasicBlock.h:195
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:164
void setPreservesCFG()
Definition: Pass.cpp:249
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
Definition: Debug.cpp:101
void initializeSinkingPass(PassRegistry &)
static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA, SmallPtrSet< Instruction *, 8 > &Stores)
Definition: Sink.cpp:156
Location getLocation(const LoadInst *LI)
use_iterator use_begin()
Definition: Value.h:150
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
iterator end() const
Definition: SmallPtrSet.h:279
machine sink
std::vector< DomTreeNodeBase< NodeT > * >::iterator iterator
Definition: Dominators.h:73
iterator begin() const
Definition: SmallPtrSet.h:276
void moveBefore(Instruction *MovePos)
Definition: Instruction.cpp:91
#define DEBUG(X)
Definition: Debug.h:97
const BasicBlock * getParent() const
Definition: Instruction.h:52