1 //===-- Sink.cpp - Code Sinking -------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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"
28 STATISTIC(NumSunk, "Number of instructions sunk");
31 class Sinking : public FunctionPass {
37 static char ID; // Pass identification
38 Sinking() : FunctionPass(ID) {}
40 virtual bool runOnFunction(Function &F);
42 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
44 FunctionPass::getAnalysisUsage(AU);
45 AU.addRequired<AliasAnalysis>();
46 AU.addRequired<DominatorTree>();
47 AU.addRequired<LoopInfo>();
48 AU.addPreserved<DominatorTree>();
49 AU.addPreserved<LoopInfo>();
52 bool ProcessBlock(BasicBlock &BB);
53 bool SinkInstruction(Instruction *I, SmallPtrSet<Instruction *, 8> &Stores);
54 bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
56 } // end anonymous namespace
59 INITIALIZE_PASS(Sinking, "sink", "Code sinking", false, false)
61 FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
63 /// AllUsesDominatedByBlock - Return true if all uses of the specified value
64 /// occur in blocks dominated by the specified block.
65 bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
66 BasicBlock *BB) const {
67 // Ignoring debug uses is necessary so debug info doesn't affect the code.
68 // This may leave a referencing dbg_value in the original block, before
69 // the definition of the vreg. Dwarf generator handles this although the
70 // user might not get the right info at runtime.
71 for (Value::use_iterator I = Inst->use_begin(),
72 E = Inst->use_end(); I != E; ++I) {
73 // Determine the block of the use.
74 Instruction *UseInst = cast<Instruction>(*I);
75 BasicBlock *UseBlock = UseInst->getParent();
76 if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
77 // PHI nodes use the operand in the predecessor block, not the block with
79 unsigned Num = PHINode::getIncomingValueNumForOperand(I.getOperandNo());
80 UseBlock = PN->getIncomingBlock(Num);
82 // Check that it dominates.
83 if (!DT->dominates(BB, UseBlock))
89 bool Sinking::runOnFunction(Function &F) {
90 DT = &getAnalysis<DominatorTree>();
91 LI = &getAnalysis<LoopInfo>();
92 AA = &getAnalysis<AliasAnalysis>();
94 bool EverMadeChange = false;
97 bool MadeChange = false;
99 // Process all basic blocks.
100 for (Function::iterator I = F.begin(), E = F.end();
102 MadeChange |= ProcessBlock(*I);
104 // If this iteration over the code changed anything, keep iterating.
105 if (!MadeChange) break;
106 EverMadeChange = true;
108 return EverMadeChange;
111 bool Sinking::ProcessBlock(BasicBlock &BB) {
112 // Can't sink anything out of a block that has less than two successors.
113 if (BB.getTerminator()->getNumSuccessors() <= 1 || BB.empty()) return false;
115 // Don't bother sinking code out of unreachable blocks. In addition to being
116 // unprofitable, it can also lead to infinite looping, because in an unreachable
117 // loop there may be nowhere to stop.
118 if (!DT->isReachableFromEntry(&BB)) return false;
120 bool MadeChange = false;
122 // Walk the basic block bottom-up. Remember if we saw a store.
123 BasicBlock::iterator I = BB.end();
125 bool ProcessedBegin = false;
126 SmallPtrSet<Instruction *, 8> Stores;
128 Instruction *Inst = I; // The instruction to sink.
130 // Predecrement I (if it's not begin) so that it isn't invalidated by
132 ProcessedBegin = I == BB.begin();
136 if (isa<DbgInfoIntrinsic>(Inst))
139 if (SinkInstruction(Inst, Stores))
140 ++NumSunk, MadeChange = true;
142 // If we just processed the first instruction in the block, we're done.
143 } while (!ProcessedBegin);
148 static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
149 SmallPtrSet<Instruction *, 8> &Stores) {
150 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
151 if (L->isVolatile()) return false;
153 Value *Ptr = L->getPointerOperand();
154 unsigned Size = AA->getTypeStoreSize(L->getType());
155 for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
156 E = Stores.end(); I != E; ++I)
157 if (AA->getModRefInfo(*I, Ptr, Size) & AliasAnalysis::Mod)
161 if (Inst->mayWriteToMemory()) {
166 return Inst->isSafeToSpeculativelyExecute();
169 /// SinkInstruction - Determine whether it is safe to sink the specified machine
170 /// instruction out of its current block into a successor.
171 bool Sinking::SinkInstruction(Instruction *Inst,
172 SmallPtrSet<Instruction *, 8> &Stores) {
173 // Check if it's safe to move the instruction.
174 if (!isSafeToMove(Inst, AA, Stores))
177 // FIXME: This should include support for sinking instructions within the
178 // block they are currently in to shorten the live ranges. We often get
179 // instructions sunk into the top of a large block, but it would be better to
180 // also sink them down before their first use in the block. This xform has to
181 // be careful not to *increase* register pressure though, e.g. sinking
182 // "x = y + z" down if it kills y and z would increase the live ranges of y
183 // and z and only shrink the live range of x.
185 // Loop over all the operands of the specified instruction. If there is
186 // anything we can't handle, bail out.
187 BasicBlock *ParentBlock = Inst->getParent();
189 // SuccToSinkTo - This is the successor to sink this instruction to, once we
191 BasicBlock *SuccToSinkTo = 0;
193 // FIXME: This picks a successor to sink into based on having one
194 // successor that dominates all the uses. However, there are cases where
195 // sinking can happen but where the sink point isn't a successor. For
200 // the instruction could be sunk over the whole diamond for the
201 // if/then/else (or loop, etc), allowing it to be sunk into other blocks
204 // Instructions can only be sunk if all their uses are in blocks
205 // dominated by one of the successors.
206 // Look at all the successors and decide which one
207 // we should sink to.
208 for (succ_iterator SI = succ_begin(ParentBlock),
209 E = succ_end(ParentBlock); SI != E; ++SI) {
210 if (AllUsesDominatedByBlock(Inst, *SI)) {
216 // If we couldn't find a block to sink to, ignore this instruction.
217 if (SuccToSinkTo == 0)
220 // It is not possible to sink an instruction into its own block. This can
221 // happen with loops.
222 if (Inst->getParent() == SuccToSinkTo)
225 DEBUG(dbgs() << "Sink instr " << *Inst);
226 DEBUG(dbgs() << "to block ";
227 WriteAsOperand(dbgs(), SuccToSinkTo, false));
229 // If the block has multiple predecessors, this would introduce computation on
230 // a path that it doesn't already exist. We could split the critical edge,
231 // but for now we just punt.
232 // FIXME: Split critical edges if not backedges.
233 if (SuccToSinkTo->getUniquePredecessor() != ParentBlock) {
234 // We cannot sink a load across a critical edge - there may be stores in
236 if (!Inst->isSafeToSpeculativelyExecute()) {
237 DEBUG(dbgs() << " *** PUNTING: Wont sink load along critical edge.\n");
241 // We don't want to sink across a critical edge if we don't dominate the
242 // successor. We could be introducing calculations to new code paths.
243 if (!DT->dominates(ParentBlock, SuccToSinkTo)) {
244 DEBUG(dbgs() << " *** PUNTING: Critical edge found\n");
248 // Don't sink instructions into a loop.
249 if (LI->isLoopHeader(SuccToSinkTo)) {
250 DEBUG(dbgs() << " *** PUNTING: Loop header found\n");
254 // Otherwise we are OK with sinking along a critical edge.
255 DEBUG(dbgs() << "Sinking along critical edge.\n");
258 // Determine where to insert into. Skip phi nodes.
259 BasicBlock::iterator InsertPos = SuccToSinkTo->begin();
260 while (InsertPos != SuccToSinkTo->end() && isa<PHINode>(InsertPos))
263 // Move the instruction.
264 Inst->moveBefore(InsertPos);