blob: cde9c178ad8c4bb84e73ba93bbad578c614fc631 [file] [log] [blame]
Dan Gohman28a193e2010-05-07 15:40:13 +00001//===-- 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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman28a193e2010-05-07 15:40:13 +000019#include "llvm/Analysis/Dominators.h"
20#include "llvm/Analysis/LoopInfo.h"
Dan Gohmanf0426602011-12-14 23:49:11 +000021#include "llvm/Analysis/ValueTracking.h"
Dan Gohman28a193e2010-05-07 15:40:13 +000022#include "llvm/Assembly/Writer.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000023#include "llvm/IntrinsicInst.h"
Dan Gohman28a193e2010-05-07 15:40:13 +000024#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");
Duncan Sands53b41772012-05-31 08:09:49 +000030STATISTIC(NumSinkIter, "Number of sinking iterations");
Dan Gohman28a193e2010-05-07 15:40:13 +000031
32namespace {
33 class Sinking : public FunctionPass {
34 DominatorTree *DT;
35 LoopInfo *LI;
36 AliasAnalysis *AA;
37
38 public:
39 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +000040 Sinking() : FunctionPass(ID) {
41 initializeSinkingPass(*PassRegistry::getPassRegistry());
42 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000043
Dan Gohman28a193e2010-05-07 15:40:13 +000044 virtual bool runOnFunction(Function &F);
Nadav Rotema94d6e82012-07-24 10:51:42 +000045
Dan Gohman28a193e2010-05-07 15:40:13 +000046 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;
Duncan Sands53b41772012-05-31 08:09:49 +000059 bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
Dan Gohman28a193e2010-05-07 15:40:13 +000060 };
61} // end anonymous namespace
Nadav Rotema94d6e82012-07-24 10:51:42 +000062
Dan Gohman28a193e2010-05-07 15:40:13 +000063char Sinking::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000064INITIALIZE_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)
Dan Gohman28a193e2010-05-07 15:40:13 +000069
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.
Nadav Rotema94d6e82012-07-24 10:51:42 +000074bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
Dan Gohman28a193e2010-05-07 15:40:13 +000075 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
Duncan Sands53b41772012-05-31 08:09:49 +0000103 bool MadeChange, EverMadeChange = false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000104
Duncan Sands53b41772012-05-31 08:09:49 +0000105 do {
106 MadeChange = false;
107 DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
Dan Gohman28a193e2010-05-07 15:40:13 +0000108 // Process all basic blocks.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000109 for (Function::iterator I = F.begin(), E = F.end();
Dan Gohman28a193e2010-05-07 15:40:13 +0000110 I != E; ++I)
111 MadeChange |= ProcessBlock(*I);
Duncan Sands53b41772012-05-31 08:09:49 +0000112 EverMadeChange |= MadeChange;
113 NumSinkIter++;
114 } while (MadeChange);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000115
Dan Gohman28a193e2010-05-07 15:40:13 +0000116 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
Nadav Rotema94d6e82012-07-24 10:51:42 +0000124 // unprofitable, it can also lead to infinite looping, because in an
125 // unreachable loop there may be nowhere to stop.
Dan Gohman28a193e2010-05-07 15:40:13 +0000126 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.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000137
Dan Gohman28a193e2010-05-07 15:40:13 +0000138 // 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;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000149
Dan Gohman28a193e2010-05-07 15:40:13 +0000150 // If we just processed the first instruction in the block, we're done.
151 } while (!ProcessedBegin);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000152
Dan Gohman28a193e2010-05-07 15:40:13 +0000153 return MadeChange;
154}
155
156static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
157 SmallPtrSet<Instruction *, 8> &Stores) {
Dan Gohman28a193e2010-05-07 15:40:13 +0000158
Eli Friedman86b5db82011-09-01 21:21:24 +0000159 if (Inst->mayWriteToMemory()) {
160 Stores.insert(Inst);
161 return false;
162 }
163
164 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
Dan Gohman6d8eb152010-11-11 21:50:19 +0000165 AliasAnalysis::Location Loc = AA->getLocation(L);
Dan Gohman28a193e2010-05-07 15:40:13 +0000166 for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
167 E = Stores.end(); I != E; ++I)
Dan Gohman5aae3dc2010-11-11 16:21:47 +0000168 if (AA->getModRefInfo(*I, Loc) & AliasAnalysis::Mod)
Dan Gohman28a193e2010-05-07 15:40:13 +0000169 return false;
170 }
171
Dan Gohman2c71f182010-11-11 16:20:28 +0000172 if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
173 return false;
174
175 return true;
Dan Gohman28a193e2010-05-07 15:40:13 +0000176}
177
Duncan Sands53b41772012-05-31 08:09:49 +0000178/// IsAcceptableTarget - Return true if it is possible to sink the instruction
179/// in the specified basic block.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000180bool Sinking::IsAcceptableTarget(Instruction *Inst,
181 BasicBlock *SuccToSinkTo) const {
Duncan Sands53b41772012-05-31 08:09:49 +0000182 assert(Inst && "Instruction to be sunk is null");
183 assert(SuccToSinkTo && "Candidate sink target is null");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000184
Duncan Sands53b41772012-05-31 08:09:49 +0000185 // 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;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000189
190 // If the block has multiple predecessors, this would introduce computation
Duncan Sands53b41772012-05-31 08:09:49 +0000191 // 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;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000199
Duncan Sands53b41772012-05-31 08:09:49 +0000200 // 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;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000204
Duncan Sands53b41772012-05-31 08:09:49 +0000205 // Don't sink instructions into a loop.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000206 Loop *succ = LI->getLoopFor(SuccToSinkTo);
207 Loop *cur = LI->getLoopFor(Inst->getParent());
Duncan Sands53b41772012-05-31 08:09:49 +0000208 if (succ != 0 && succ != cur)
209 return false;
210 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000211
Duncan Sands53b41772012-05-31 08:09:49 +0000212 // Finally, check that all the uses of the instruction are actually
213 // dominated by the candidate
214 return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
215}
216
Dan Gohman28a193e2010-05-07 15:40:13 +0000217/// 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;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000224
Dan Gohman28a193e2010-05-07 15:40:13 +0000225 // 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.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000232
Dan Gohman28a193e2010-05-07 15:40:13 +0000233 // SuccToSinkTo - This is the successor to sink this instruction to, once we
234 // decide.
235 BasicBlock *SuccToSinkTo = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000236
Dan Gohman28a193e2010-05-07 15:40:13 +0000237 // Instructions can only be sunk if all their uses are in blocks
238 // dominated by one of the successors.
Duncan Sands53b41772012-05-31 08:09:49 +0000239 // Look at all the postdominators and see if we can sink it in one.
240 DomTreeNode *DTN = DT->getNode(Inst->getParent());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000241 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
Duncan Sands53b41772012-05-31 08:09:49 +0000242 I != E && SuccToSinkTo == 0; ++I) {
243 BasicBlock *Candidate = (*I)->getBlock();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000244 if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
Duncan Sands53b41772012-05-31 08:09:49 +0000245 IsAcceptableTarget(Inst, Candidate))
246 SuccToSinkTo = Candidate;
247 }
248
Nadav Rotema94d6e82012-07-24 10:51:42 +0000249 // If no suitable postdominator was found, look at all the successors and
Duncan Sands53b41772012-05-31 08:09:49 +0000250 // decide which one we should sink to, if any.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000251 for (succ_iterator I = succ_begin(Inst->getParent()),
Duncan Sands53b41772012-05-31 08:09:49 +0000252 E = succ_end(Inst->getParent()); I != E && SuccToSinkTo == 0; ++I) {
253 if (IsAcceptableTarget(Inst, *I))
254 SuccToSinkTo = *I;
Dan Gohman28a193e2010-05-07 15:40:13 +0000255 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000256
Dan Gohman28a193e2010-05-07 15:40:13 +0000257 // If we couldn't find a block to sink to, ignore this instruction.
258 if (SuccToSinkTo == 0)
259 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000260
Duncan Sands53b41772012-05-31 08:09:49 +0000261 DEBUG(dbgs() << "Sink" << *Inst << " (";
Nadav Rotema94d6e82012-07-24 10:51:42 +0000262 WriteAsOperand(dbgs(), Inst->getParent(), false);
Duncan Sands53b41772012-05-31 08:09:49 +0000263 dbgs() << " -> ";
Nadav Rotema94d6e82012-07-24 10:51:42 +0000264 WriteAsOperand(dbgs(), SuccToSinkTo, false);
Duncan Sands53b41772012-05-31 08:09:49 +0000265 dbgs() << ")\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000266
Dan Gohman28a193e2010-05-07 15:40:13 +0000267 // Move the instruction.
Duncan Sands53b41772012-05-31 08:09:49 +0000268 Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
Dan Gohman28a193e2010-05-07 15:40:13 +0000269 return true;
270}