blob: 41073749abc716643cbe750169a297995cc1c023 [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/LoopInfo.h"
Dan Gohmanf0426602011-12-14 23:49:11 +000020#include "llvm/Analysis/ValueTracking.h"
Stephen Hines36b56882014-04-23 16:57:46 -070021#include "llvm/IR/CFG.h"
22#include "llvm/IR/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000023#include "llvm/IR/IntrinsicInst.h"
Dan Gohman28a193e2010-05-07 15:40:13 +000024#include "llvm/Support/Debug.h"
25#include "llvm/Support/raw_ostream.h"
26using namespace llvm;
27
28STATISTIC(NumSunk, "Number of instructions sunk");
Duncan Sands53b41772012-05-31 08:09:49 +000029STATISTIC(NumSinkIter, "Number of sinking iterations");
Dan Gohman28a193e2010-05-07 15:40:13 +000030
31namespace {
32 class Sinking : public FunctionPass {
33 DominatorTree *DT;
34 LoopInfo *LI;
35 AliasAnalysis *AA;
36
37 public:
38 static char ID; // Pass identification
Owen Anderson081c34b2010-10-19 17:21:58 +000039 Sinking() : FunctionPass(ID) {
40 initializeSinkingPass(*PassRegistry::getPassRegistry());
41 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000042
Stephen Hines36b56882014-04-23 16:57:46 -070043 bool runOnFunction(Function &F) override;
Nadav Rotema94d6e82012-07-24 10:51:42 +000044
Stephen Hines36b56882014-04-23 16:57:46 -070045 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman28a193e2010-05-07 15:40:13 +000046 AU.setPreservesCFG();
47 FunctionPass::getAnalysisUsage(AU);
48 AU.addRequired<AliasAnalysis>();
Stephen Hines36b56882014-04-23 16:57:46 -070049 AU.addRequired<DominatorTreeWrapperPass>();
Dan Gohman28a193e2010-05-07 15:40:13 +000050 AU.addRequired<LoopInfo>();
Stephen Hines36b56882014-04-23 16:57:46 -070051 AU.addPreserved<DominatorTreeWrapperPass>();
Dan Gohman28a193e2010-05-07 15:40:13 +000052 AU.addPreserved<LoopInfo>();
53 }
54 private:
55 bool ProcessBlock(BasicBlock &BB);
56 bool SinkInstruction(Instruction *I, SmallPtrSet<Instruction *, 8> &Stores);
57 bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
Duncan Sands53b41772012-05-31 08:09:49 +000058 bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
Dan Gohman28a193e2010-05-07 15:40:13 +000059 };
60} // end anonymous namespace
Nadav Rotema94d6e82012-07-24 10:51:42 +000061
Dan Gohman28a193e2010-05-07 15:40:13 +000062char Sinking::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000063INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
64INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Stephen Hines36b56882014-04-23 16:57:46 -070065INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson2ab36d32010-10-12 19:48:12 +000066INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
67INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
Dan Gohman28a193e2010-05-07 15:40:13 +000068
69FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
70
71/// AllUsesDominatedByBlock - Return true if all uses of the specified value
72/// occur in blocks dominated by the specified block.
Nadav Rotema94d6e82012-07-24 10:51:42 +000073bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
Dan Gohman28a193e2010-05-07 15:40:13 +000074 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.
Stephen Hines36b56882014-04-23 16:57:46 -070079 for (Use &U : Inst->uses()) {
Dan Gohman28a193e2010-05-07 15:40:13 +000080 // Determine the block of the use.
Stephen Hines36b56882014-04-23 16:57:46 -070081 Instruction *UseInst = cast<Instruction>(U.getUser());
Dan Gohman28a193e2010-05-07 15:40:13 +000082 BasicBlock *UseBlock = UseInst->getParent();
83 if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
84 // PHI nodes use the operand in the predecessor block, not the block with
85 // the PHI.
Stephen Hines36b56882014-04-23 16:57:46 -070086 unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
Dan Gohman28a193e2010-05-07 15:40:13 +000087 UseBlock = PN->getIncomingBlock(Num);
88 }
89 // Check that it dominates.
90 if (!DT->dominates(BB, UseBlock))
91 return false;
92 }
93 return true;
94}
95
96bool Sinking::runOnFunction(Function &F) {
Stephen Hines36b56882014-04-23 16:57:46 -070097 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Dan Gohman28a193e2010-05-07 15:40:13 +000098 LI = &getAnalysis<LoopInfo>();
99 AA = &getAnalysis<AliasAnalysis>();
100
Duncan Sands53b41772012-05-31 08:09:49 +0000101 bool MadeChange, EverMadeChange = false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000102
Duncan Sands53b41772012-05-31 08:09:49 +0000103 do {
104 MadeChange = false;
105 DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
Dan Gohman28a193e2010-05-07 15:40:13 +0000106 // Process all basic blocks.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000107 for (Function::iterator I = F.begin(), E = F.end();
Dan Gohman28a193e2010-05-07 15:40:13 +0000108 I != E; ++I)
109 MadeChange |= ProcessBlock(*I);
Duncan Sands53b41772012-05-31 08:09:49 +0000110 EverMadeChange |= MadeChange;
111 NumSinkIter++;
112 } while (MadeChange);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000113
Dan Gohman28a193e2010-05-07 15:40:13 +0000114 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
Nadav Rotema94d6e82012-07-24 10:51:42 +0000122 // unprofitable, it can also lead to infinite looping, because in an
123 // unreachable loop there may be nowhere to stop.
Dan Gohman28a193e2010-05-07 15:40:13 +0000124 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.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000135
Dan Gohman28a193e2010-05-07 15:40:13 +0000136 // 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;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000147
Dan Gohman28a193e2010-05-07 15:40:13 +0000148 // If we just processed the first instruction in the block, we're done.
149 } while (!ProcessedBegin);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000150
Dan Gohman28a193e2010-05-07 15:40:13 +0000151 return MadeChange;
152}
153
154static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
155 SmallPtrSet<Instruction *, 8> &Stores) {
Dan Gohman28a193e2010-05-07 15:40:13 +0000156
Eli Friedman86b5db82011-09-01 21:21:24 +0000157 if (Inst->mayWriteToMemory()) {
158 Stores.insert(Inst);
159 return false;
160 }
161
162 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
Dan Gohman6d8eb152010-11-11 21:50:19 +0000163 AliasAnalysis::Location Loc = AA->getLocation(L);
Dan Gohman28a193e2010-05-07 15:40:13 +0000164 for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
165 E = Stores.end(); I != E; ++I)
Dan Gohman5aae3dc2010-11-11 16:21:47 +0000166 if (AA->getModRefInfo(*I, Loc) & AliasAnalysis::Mod)
Dan Gohman28a193e2010-05-07 15:40:13 +0000167 return false;
168 }
169
Dan Gohman2c71f182010-11-11 16:20:28 +0000170 if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
171 return false;
172
173 return true;
Dan Gohman28a193e2010-05-07 15:40:13 +0000174}
175
Duncan Sands53b41772012-05-31 08:09:49 +0000176/// IsAcceptableTarget - Return true if it is possible to sink the instruction
177/// in the specified basic block.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000178bool Sinking::IsAcceptableTarget(Instruction *Inst,
179 BasicBlock *SuccToSinkTo) const {
Duncan Sands53b41772012-05-31 08:09:49 +0000180 assert(Inst && "Instruction to be sunk is null");
181 assert(SuccToSinkTo && "Candidate sink target is null");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000182
Duncan Sands53b41772012-05-31 08:09:49 +0000183 // It is not possible to sink an instruction into its own block. This can
184 // happen with loops.
185 if (Inst->getParent() == SuccToSinkTo)
186 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000187
188 // If the block has multiple predecessors, this would introduce computation
Duncan Sands53b41772012-05-31 08:09:49 +0000189 // on different code paths. We could split the critical edge, but for now we
190 // just punt.
191 // FIXME: Split critical edges if not backedges.
192 if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
193 // We cannot sink a load across a critical edge - there may be stores in
194 // other code paths.
195 if (!isSafeToSpeculativelyExecute(Inst))
196 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000197
Duncan Sands53b41772012-05-31 08:09:49 +0000198 // We don't want to sink across a critical edge if we don't dominate the
199 // successor. We could be introducing calculations to new code paths.
200 if (!DT->dominates(Inst->getParent(), SuccToSinkTo))
201 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000202
Duncan Sands53b41772012-05-31 08:09:49 +0000203 // Don't sink instructions into a loop.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000204 Loop *succ = LI->getLoopFor(SuccToSinkTo);
205 Loop *cur = LI->getLoopFor(Inst->getParent());
Duncan Sands53b41772012-05-31 08:09:49 +0000206 if (succ != 0 && succ != cur)
207 return false;
208 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000209
Duncan Sands53b41772012-05-31 08:09:49 +0000210 // Finally, check that all the uses of the instruction are actually
211 // dominated by the candidate
212 return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
213}
214
Dan Gohman28a193e2010-05-07 15:40:13 +0000215/// SinkInstruction - Determine whether it is safe to sink the specified machine
216/// instruction out of its current block into a successor.
217bool Sinking::SinkInstruction(Instruction *Inst,
218 SmallPtrSet<Instruction *, 8> &Stores) {
Stephen Hines36b56882014-04-23 16:57:46 -0700219
220 // Don't sink static alloca instructions. CodeGen assumes allocas outside the
221 // entry block are dynamically sized stack objects.
222 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
223 if (AI->isStaticAlloca())
224 return false;
225
Dan Gohman28a193e2010-05-07 15:40:13 +0000226 // Check if it's safe to move the instruction.
227 if (!isSafeToMove(Inst, AA, Stores))
228 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000229
Dan Gohman28a193e2010-05-07 15:40:13 +0000230 // FIXME: This should include support for sinking instructions within the
231 // block they are currently in to shorten the live ranges. We often get
232 // instructions sunk into the top of a large block, but it would be better to
233 // also sink them down before their first use in the block. This xform has to
234 // be careful not to *increase* register pressure though, e.g. sinking
235 // "x = y + z" down if it kills y and z would increase the live ranges of y
236 // and z and only shrink the live range of x.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000237
Dan Gohman28a193e2010-05-07 15:40:13 +0000238 // SuccToSinkTo - This is the successor to sink this instruction to, once we
239 // decide.
240 BasicBlock *SuccToSinkTo = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000241
Dan Gohman28a193e2010-05-07 15:40:13 +0000242 // Instructions can only be sunk if all their uses are in blocks
243 // dominated by one of the successors.
Duncan Sands53b41772012-05-31 08:09:49 +0000244 // Look at all the postdominators and see if we can sink it in one.
245 DomTreeNode *DTN = DT->getNode(Inst->getParent());
Nadav Rotema94d6e82012-07-24 10:51:42 +0000246 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
Duncan Sands53b41772012-05-31 08:09:49 +0000247 I != E && SuccToSinkTo == 0; ++I) {
248 BasicBlock *Candidate = (*I)->getBlock();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000249 if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
Duncan Sands53b41772012-05-31 08:09:49 +0000250 IsAcceptableTarget(Inst, Candidate))
251 SuccToSinkTo = Candidate;
252 }
253
Nadav Rotema94d6e82012-07-24 10:51:42 +0000254 // If no suitable postdominator was found, look at all the successors and
Duncan Sands53b41772012-05-31 08:09:49 +0000255 // decide which one we should sink to, if any.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000256 for (succ_iterator I = succ_begin(Inst->getParent()),
Duncan Sands53b41772012-05-31 08:09:49 +0000257 E = succ_end(Inst->getParent()); I != E && SuccToSinkTo == 0; ++I) {
258 if (IsAcceptableTarget(Inst, *I))
259 SuccToSinkTo = *I;
Dan Gohman28a193e2010-05-07 15:40:13 +0000260 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000261
Dan Gohman28a193e2010-05-07 15:40:13 +0000262 // If we couldn't find a block to sink to, ignore this instruction.
263 if (SuccToSinkTo == 0)
264 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000265
Duncan Sands53b41772012-05-31 08:09:49 +0000266 DEBUG(dbgs() << "Sink" << *Inst << " (";
Stephen Hines36b56882014-04-23 16:57:46 -0700267 Inst->getParent()->printAsOperand(dbgs(), false);
Duncan Sands53b41772012-05-31 08:09:49 +0000268 dbgs() << " -> ";
Stephen Hines36b56882014-04-23 16:57:46 -0700269 SuccToSinkTo->printAsOperand(dbgs(), false);
Duncan Sands53b41772012-05-31 08:09:49 +0000270 dbgs() << ")\n");
Nadav Rotema94d6e82012-07-24 10:51:42 +0000271
Dan Gohman28a193e2010-05-07 15:40:13 +0000272 // Move the instruction.
Duncan Sands53b41772012-05-31 08:09:49 +0000273 Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
Dan Gohman28a193e2010-05-07 15:40:13 +0000274 return true;
275}