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