blob: 643a5957cf9154eb86b300028ed8b876c865dae4 [file] [log] [blame]
Dan Gohman5d5b8b12010-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 Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman5d5b8b12010-05-07 15:40:13 +000019#include "llvm/Analysis/LoopInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000020#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000021#include "llvm/IR/CFG.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/IntrinsicInst.h"
Dan Gohman5d5b8b12010-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 Sands339bb612012-05-31 08:09:49 +000029STATISTIC(NumSinkIter, "Number of sinking iterations");
Dan Gohman5d5b8b12010-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 Anderson6c18d1a2010-10-19 17:21:58 +000039 Sinking() : FunctionPass(ID) {
40 initializeSinkingPass(*PassRegistry::getPassRegistry());
41 }
Nadav Rotem465834c2012-07-24 10:51:42 +000042
Craig Topper3e4c6972014-03-05 09:10:37 +000043 bool runOnFunction(Function &F) override;
Nadav Rotem465834c2012-07-24 10:51:42 +000044
Craig Topper3e4c6972014-03-05 09:10:37 +000045 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman5d5b8b12010-05-07 15:40:13 +000046 AU.setPreservesCFG();
47 FunctionPass::getAnalysisUsage(AU);
48 AU.addRequired<AliasAnalysis>();
Chandler Carruth73523022014-01-13 13:07:17 +000049 AU.addRequired<DominatorTreeWrapperPass>();
Dan Gohman5d5b8b12010-05-07 15:40:13 +000050 AU.addRequired<LoopInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +000051 AU.addPreserved<DominatorTreeWrapperPass>();
Dan Gohman5d5b8b12010-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 Sands339bb612012-05-31 08:09:49 +000058 bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
Dan Gohman5d5b8b12010-05-07 15:40:13 +000059 };
60} // end anonymous namespace
Nadav Rotem465834c2012-07-24 10:51:42 +000061
Dan Gohman5d5b8b12010-05-07 15:40:13 +000062char Sinking::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000063INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
64INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chandler Carruth73523022014-01-13 13:07:17 +000065INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +000066INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
67INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
Dan Gohman5d5b8b12010-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 Rotem465834c2012-07-24 10:51:42 +000073bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
Dan Gohman5d5b8b12010-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.
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
86 // the PHI.
87 unsigned Num = PHINode::getIncomingValueNumForOperand(I.getOperandNo());
88 UseBlock = PN->getIncomingBlock(Num);
89 }
90 // Check that it dominates.
91 if (!DT->dominates(BB, UseBlock))
92 return false;
93 }
94 return true;
95}
96
97bool Sinking::runOnFunction(Function &F) {
Chandler Carruth73523022014-01-13 13:07:17 +000098 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Dan Gohman5d5b8b12010-05-07 15:40:13 +000099 LI = &getAnalysis<LoopInfo>();
100 AA = &getAnalysis<AliasAnalysis>();
101
Duncan Sands339bb612012-05-31 08:09:49 +0000102 bool MadeChange, EverMadeChange = false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000103
Duncan Sands339bb612012-05-31 08:09:49 +0000104 do {
105 MadeChange = false;
106 DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000107 // Process all basic blocks.
Nadav Rotem465834c2012-07-24 10:51:42 +0000108 for (Function::iterator I = F.begin(), E = F.end();
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000109 I != E; ++I)
110 MadeChange |= ProcessBlock(*I);
Duncan Sands339bb612012-05-31 08:09:49 +0000111 EverMadeChange |= MadeChange;
112 NumSinkIter++;
113 } while (MadeChange);
Nadav Rotem465834c2012-07-24 10:51:42 +0000114
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000115 return EverMadeChange;
116}
117
118bool 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;
121
122 // Don't bother sinking code out of unreachable blocks. In addition to being
Nadav Rotem465834c2012-07-24 10:51:42 +0000123 // unprofitable, it can also lead to infinite looping, because in an
124 // unreachable loop there may be nowhere to stop.
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000125 if (!DT->isReachableFromEntry(&BB)) return false;
126
127 bool MadeChange = false;
128
129 // Walk the basic block bottom-up. Remember if we saw a store.
130 BasicBlock::iterator I = BB.end();
131 --I;
132 bool ProcessedBegin = false;
133 SmallPtrSet<Instruction *, 8> Stores;
134 do {
135 Instruction *Inst = I; // The instruction to sink.
Nadav Rotem465834c2012-07-24 10:51:42 +0000136
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000137 // Predecrement I (if it's not begin) so that it isn't invalidated by
138 // sinking.
139 ProcessedBegin = I == BB.begin();
140 if (!ProcessedBegin)
141 --I;
142
143 if (isa<DbgInfoIntrinsic>(Inst))
144 continue;
145
146 if (SinkInstruction(Inst, Stores))
147 ++NumSunk, MadeChange = true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000148
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000149 // If we just processed the first instruction in the block, we're done.
150 } while (!ProcessedBegin);
Nadav Rotem465834c2012-07-24 10:51:42 +0000151
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000152 return MadeChange;
153}
154
155static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
156 SmallPtrSet<Instruction *, 8> &Stores) {
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000157
Eli Friedman71f5c2f2011-09-01 21:21:24 +0000158 if (Inst->mayWriteToMemory()) {
159 Stores.insert(Inst);
160 return false;
161 }
162
163 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
Dan Gohman65316d62010-11-11 21:50:19 +0000164 AliasAnalysis::Location Loc = AA->getLocation(L);
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000165 for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
166 E = Stores.end(); I != E; ++I)
Dan Gohman0cc4c752010-11-11 16:21:47 +0000167 if (AA->getModRefInfo(*I, Loc) & AliasAnalysis::Mod)
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000168 return false;
169 }
170
Dan Gohmanc3b4ea72010-11-11 16:20:28 +0000171 if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
172 return false;
173
174 return true;
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000175}
176
Duncan Sands339bb612012-05-31 08:09:49 +0000177/// IsAcceptableTarget - Return true if it is possible to sink the instruction
178/// in the specified basic block.
Nadav Rotem465834c2012-07-24 10:51:42 +0000179bool Sinking::IsAcceptableTarget(Instruction *Inst,
180 BasicBlock *SuccToSinkTo) const {
Duncan Sands339bb612012-05-31 08:09:49 +0000181 assert(Inst && "Instruction to be sunk is null");
182 assert(SuccToSinkTo && "Candidate sink target is null");
Nadav Rotem465834c2012-07-24 10:51:42 +0000183
Duncan Sands339bb612012-05-31 08:09:49 +0000184 // It is not possible to sink an instruction into its own block. This can
185 // happen with loops.
186 if (Inst->getParent() == SuccToSinkTo)
187 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000188
189 // If the block has multiple predecessors, this would introduce computation
Duncan Sands339bb612012-05-31 08:09:49 +0000190 // on different code paths. We could split the critical edge, but for now we
191 // just punt.
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
195 // other code paths.
196 if (!isSafeToSpeculativelyExecute(Inst))
197 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000198
Duncan Sands339bb612012-05-31 08:09:49 +0000199 // 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))
202 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000203
Duncan Sands339bb612012-05-31 08:09:49 +0000204 // Don't sink instructions into a loop.
Nadav Rotem465834c2012-07-24 10:51:42 +0000205 Loop *succ = LI->getLoopFor(SuccToSinkTo);
206 Loop *cur = LI->getLoopFor(Inst->getParent());
Duncan Sands339bb612012-05-31 08:09:49 +0000207 if (succ != 0 && succ != cur)
208 return false;
209 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000210
Duncan Sands339bb612012-05-31 08:09:49 +0000211 // Finally, check that all the uses of the instruction are actually
212 // dominated by the candidate
213 return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
214}
215
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000216/// SinkInstruction - Determine whether it is safe to sink the specified machine
217/// instruction out of its current block into a successor.
218bool 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))
222 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000223
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000224 // 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.
Nadav Rotem465834c2012-07-24 10:51:42 +0000231
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000232 // SuccToSinkTo - This is the successor to sink this instruction to, once we
233 // decide.
234 BasicBlock *SuccToSinkTo = 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000235
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000236 // Instructions can only be sunk if all their uses are in blocks
237 // dominated by one of the successors.
Duncan Sands339bb612012-05-31 08:09:49 +0000238 // Look at all the postdominators and see if we can sink it in one.
239 DomTreeNode *DTN = DT->getNode(Inst->getParent());
Nadav Rotem465834c2012-07-24 10:51:42 +0000240 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
Duncan Sands339bb612012-05-31 08:09:49 +0000241 I != E && SuccToSinkTo == 0; ++I) {
242 BasicBlock *Candidate = (*I)->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000243 if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
Duncan Sands339bb612012-05-31 08:09:49 +0000244 IsAcceptableTarget(Inst, Candidate))
245 SuccToSinkTo = Candidate;
246 }
247
Nadav Rotem465834c2012-07-24 10:51:42 +0000248 // If no suitable postdominator was found, look at all the successors and
Duncan Sands339bb612012-05-31 08:09:49 +0000249 // decide which one we should sink to, if any.
Nadav Rotem465834c2012-07-24 10:51:42 +0000250 for (succ_iterator I = succ_begin(Inst->getParent()),
Duncan Sands339bb612012-05-31 08:09:49 +0000251 E = succ_end(Inst->getParent()); I != E && SuccToSinkTo == 0; ++I) {
252 if (IsAcceptableTarget(Inst, *I))
253 SuccToSinkTo = *I;
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000254 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000255
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000256 // If we couldn't find a block to sink to, ignore this instruction.
257 if (SuccToSinkTo == 0)
258 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000259
Duncan Sands339bb612012-05-31 08:09:49 +0000260 DEBUG(dbgs() << "Sink" << *Inst << " (";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000261 Inst->getParent()->printAsOperand(dbgs(), false);
Duncan Sands339bb612012-05-31 08:09:49 +0000262 dbgs() << " -> ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000263 SuccToSinkTo->printAsOperand(dbgs(), false);
Duncan Sands339bb612012-05-31 08:09:49 +0000264 dbgs() << ")\n");
Nadav Rotem465834c2012-07-24 10:51:42 +0000265
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000266 // Move the instruction.
Duncan Sands339bb612012-05-31 08:09:49 +0000267 Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000268 return true;
269}