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/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"
28 STATISTIC(NumSunk, "Number of instructions sunk");
29 STATISTIC(NumSinkIter, "Number of sinking iterations");
32 class Sinking : public FunctionPass {
38 static char ID; // Pass identification
39 Sinking() : FunctionPass(ID) {
40 initializeSinkingPass(*PassRegistry::getPassRegistry());
43 virtual bool runOnFunction(Function &F);
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 FunctionPass::getAnalysisUsage(AU);
48 AU.addRequired<AliasAnalysis>();
49 AU.addRequired<DominatorTreeWrapperPass>();
50 AU.addRequired<LoopInfo>();
51 AU.addPreserved<DominatorTreeWrapperPass>();
52 AU.addPreserved<LoopInfo>();
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;
60 } // end anonymous namespace
63 INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
64 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
65 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
66 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
67 INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
69 FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
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
87 unsigned Num = PHINode::getIncomingValueNumForOperand(I.getOperandNo());
88 UseBlock = PN->getIncomingBlock(Num);
90 // Check that it dominates.
91 if (!DT->dominates(BB, UseBlock))
97 bool Sinking::runOnFunction(Function &F) {
98 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
99 LI = &getAnalysis<LoopInfo>();
100 AA = &getAnalysis<AliasAnalysis>();
102 bool MadeChange, EverMadeChange = false;
106 DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
107 // Process all basic blocks.
108 for (Function::iterator I = F.begin(), E = F.end();
110 MadeChange |= ProcessBlock(*I);
111 EverMadeChange |= MadeChange;
113 } while (MadeChange);
115 return EverMadeChange;
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;
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;
127 bool MadeChange = false;
129 // Walk the basic block bottom-up. Remember if we saw a store.
130 BasicBlock::iterator I = BB.end();
132 bool ProcessedBegin = false;
133 SmallPtrSet<Instruction *, 8> Stores;
135 Instruction *Inst = I; // The instruction to sink.
137 // Predecrement I (if it's not begin) so that it isn't invalidated by
139 ProcessedBegin = I == BB.begin();
143 if (isa<DbgInfoIntrinsic>(Inst))
146 if (SinkInstruction(Inst, Stores))
147 ++NumSunk, MadeChange = true;
149 // If we just processed the first instruction in the block, we're done.
150 } while (!ProcessedBegin);
155 static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
156 SmallPtrSet<Instruction *, 8> &Stores) {
158 if (Inst->mayWriteToMemory()) {
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)
171 if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
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");
184 // It is not possible to sink an instruction into its own block. This can
185 // happen with loops.
186 if (Inst->getParent() == SuccToSinkTo)
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
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
196 if (!isSafeToSpeculativelyExecute(Inst))
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))
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)
211 // Finally, check that all the uses of the instruction are actually
212 // dominated by the candidate
213 return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
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))
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.
232 // SuccToSinkTo - This is the successor to sink this instruction to, once we
234 BasicBlock *SuccToSinkTo = 0;
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;
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))
256 // If we couldn't find a block to sink to, ignore this instruction.
257 if (SuccToSinkTo == 0)
260 DEBUG(dbgs() << "Sink" << *Inst << " (";
261 Inst->getParent()->printAsOperand(dbgs(), false);
263 SuccToSinkTo->printAsOperand(dbgs(), false);
266 // Move the instruction.
267 Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());