blob: 2f4e23a7488b453521de0094489186fcbb68f4bb [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
Dan Gohman5d5b8b12010-05-07 15:40:13 +000015#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman5d5b8b12010-05-07 15:40:13 +000018#include "llvm/Analysis/LoopInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000019#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000020#include "llvm/IR/CFG.h"
Hal Finkel511fea72014-07-10 16:07:11 +000021#include "llvm/IR/DataLayout.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
Chandler Carruth964daaa2014-04-22 02:55:47 +000028#define DEBUG_TYPE "sink"
29
Dan Gohman5d5b8b12010-05-07 15:40:13 +000030STATISTIC(NumSunk, "Number of instructions sunk");
Duncan Sands339bb612012-05-31 08:09:49 +000031STATISTIC(NumSinkIter, "Number of sinking iterations");
Dan Gohman5d5b8b12010-05-07 15:40:13 +000032
33namespace {
34 class Sinking : public FunctionPass {
35 DominatorTree *DT;
36 LoopInfo *LI;
37 AliasAnalysis *AA;
Hal Finkel511fea72014-07-10 16:07:11 +000038 const DataLayout *DL;
Dan Gohman5d5b8b12010-05-07 15:40:13 +000039
40 public:
41 static char ID; // Pass identification
Owen Anderson6c18d1a2010-10-19 17:21:58 +000042 Sinking() : FunctionPass(ID) {
43 initializeSinkingPass(*PassRegistry::getPassRegistry());
44 }
Nadav Rotem465834c2012-07-24 10:51:42 +000045
Craig Topper3e4c6972014-03-05 09:10:37 +000046 bool runOnFunction(Function &F) override;
Nadav Rotem465834c2012-07-24 10:51:42 +000047
Craig Topper3e4c6972014-03-05 09:10:37 +000048 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman5d5b8b12010-05-07 15:40:13 +000049 AU.setPreservesCFG();
50 FunctionPass::getAnalysisUsage(AU);
51 AU.addRequired<AliasAnalysis>();
Chandler Carruth73523022014-01-13 13:07:17 +000052 AU.addRequired<DominatorTreeWrapperPass>();
Dan Gohman5d5b8b12010-05-07 15:40:13 +000053 AU.addRequired<LoopInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +000054 AU.addPreserved<DominatorTreeWrapperPass>();
Dan Gohman5d5b8b12010-05-07 15:40:13 +000055 AU.addPreserved<LoopInfo>();
56 }
57 private:
58 bool ProcessBlock(BasicBlock &BB);
Craig Topper71b7b682014-08-21 05:55:13 +000059 bool SinkInstruction(Instruction *I, SmallPtrSetImpl<Instruction*> &Stores);
Dan Gohman5d5b8b12010-05-07 15:40:13 +000060 bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
Duncan Sands339bb612012-05-31 08:09:49 +000061 bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
Dan Gohman5d5b8b12010-05-07 15:40:13 +000062 };
63} // end anonymous namespace
Nadav Rotem465834c2012-07-24 10:51:42 +000064
Dan Gohman5d5b8b12010-05-07 15:40:13 +000065char Sinking::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000066INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
67INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chandler Carruth73523022014-01-13 13:07:17 +000068INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +000069INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
70INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
Dan Gohman5d5b8b12010-05-07 15:40:13 +000071
72FunctionPass *llvm::createSinkingPass() { return new Sinking(); }
73
74/// AllUsesDominatedByBlock - Return true if all uses of the specified value
75/// occur in blocks dominated by the specified block.
Nadav Rotem465834c2012-07-24 10:51:42 +000076bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
Dan Gohman5d5b8b12010-05-07 15:40:13 +000077 BasicBlock *BB) const {
78 // Ignoring debug uses is necessary so debug info doesn't affect the code.
79 // This may leave a referencing dbg_value in the original block, before
80 // the definition of the vreg. Dwarf generator handles this although the
81 // user might not get the right info at runtime.
Chandler Carruthcdf47882014-03-09 03:16:01 +000082 for (Use &U : Inst->uses()) {
Dan Gohman5d5b8b12010-05-07 15:40:13 +000083 // Determine the block of the use.
Chandler Carruthcdf47882014-03-09 03:16:01 +000084 Instruction *UseInst = cast<Instruction>(U.getUser());
Dan Gohman5d5b8b12010-05-07 15:40:13 +000085 BasicBlock *UseBlock = UseInst->getParent();
86 if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
87 // PHI nodes use the operand in the predecessor block, not the block with
88 // the PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +000089 unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
Dan Gohman5d5b8b12010-05-07 15:40:13 +000090 UseBlock = PN->getIncomingBlock(Num);
91 }
92 // Check that it dominates.
93 if (!DT->dominates(BB, UseBlock))
94 return false;
95 }
96 return true;
97}
98
99bool Sinking::runOnFunction(Function &F) {
Chandler Carruth73523022014-01-13 13:07:17 +0000100 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000101 LI = &getAnalysis<LoopInfo>();
102 AA = &getAnalysis<AliasAnalysis>();
Hal Finkel511fea72014-07-10 16:07:11 +0000103 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
104 DL = DLP ? &DLP->getDataLayout() : nullptr;
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000105
Duncan Sands339bb612012-05-31 08:09:49 +0000106 bool MadeChange, EverMadeChange = false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000107
Duncan Sands339bb612012-05-31 08:09:49 +0000108 do {
109 MadeChange = false;
110 DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000111 // Process all basic blocks.
Nadav Rotem465834c2012-07-24 10:51:42 +0000112 for (Function::iterator I = F.begin(), E = F.end();
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000113 I != E; ++I)
114 MadeChange |= ProcessBlock(*I);
Duncan Sands339bb612012-05-31 08:09:49 +0000115 EverMadeChange |= MadeChange;
116 NumSinkIter++;
117 } while (MadeChange);
Nadav Rotem465834c2012-07-24 10:51:42 +0000118
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000119 return EverMadeChange;
120}
121
122bool Sinking::ProcessBlock(BasicBlock &BB) {
123 // Can't sink anything out of a block that has less than two successors.
124 if (BB.getTerminator()->getNumSuccessors() <= 1 || BB.empty()) return false;
125
126 // Don't bother sinking code out of unreachable blocks. In addition to being
Nadav Rotem465834c2012-07-24 10:51:42 +0000127 // unprofitable, it can also lead to infinite looping, because in an
128 // unreachable loop there may be nowhere to stop.
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000129 if (!DT->isReachableFromEntry(&BB)) return false;
130
131 bool MadeChange = false;
132
133 // Walk the basic block bottom-up. Remember if we saw a store.
134 BasicBlock::iterator I = BB.end();
135 --I;
136 bool ProcessedBegin = false;
137 SmallPtrSet<Instruction *, 8> Stores;
138 do {
139 Instruction *Inst = I; // The instruction to sink.
Nadav Rotem465834c2012-07-24 10:51:42 +0000140
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000141 // Predecrement I (if it's not begin) so that it isn't invalidated by
142 // sinking.
143 ProcessedBegin = I == BB.begin();
144 if (!ProcessedBegin)
145 --I;
146
147 if (isa<DbgInfoIntrinsic>(Inst))
148 continue;
149
150 if (SinkInstruction(Inst, Stores))
151 ++NumSunk, MadeChange = true;
Nadav Rotem465834c2012-07-24 10:51:42 +0000152
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000153 // If we just processed the first instruction in the block, we're done.
154 } while (!ProcessedBegin);
Nadav Rotem465834c2012-07-24 10:51:42 +0000155
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000156 return MadeChange;
157}
158
159static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
Craig Topper71b7b682014-08-21 05:55:13 +0000160 SmallPtrSetImpl<Instruction *> &Stores) {
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000161
Eli Friedman71f5c2f2011-09-01 21:21:24 +0000162 if (Inst->mayWriteToMemory()) {
163 Stores.insert(Inst);
164 return false;
165 }
166
167 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
Dan Gohman65316d62010-11-11 21:50:19 +0000168 AliasAnalysis::Location Loc = AA->getLocation(L);
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000169 for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(),
170 E = Stores.end(); I != E; ++I)
Dan Gohman0cc4c752010-11-11 16:21:47 +0000171 if (AA->getModRefInfo(*I, Loc) & AliasAnalysis::Mod)
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000172 return false;
173 }
174
Dan Gohmanc3b4ea72010-11-11 16:20:28 +0000175 if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst))
176 return false;
177
178 return true;
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000179}
180
Duncan Sands339bb612012-05-31 08:09:49 +0000181/// IsAcceptableTarget - Return true if it is possible to sink the instruction
182/// in the specified basic block.
Nadav Rotem465834c2012-07-24 10:51:42 +0000183bool Sinking::IsAcceptableTarget(Instruction *Inst,
184 BasicBlock *SuccToSinkTo) const {
Duncan Sands339bb612012-05-31 08:09:49 +0000185 assert(Inst && "Instruction to be sunk is null");
186 assert(SuccToSinkTo && "Candidate sink target is null");
Nadav Rotem465834c2012-07-24 10:51:42 +0000187
Duncan Sands339bb612012-05-31 08:09:49 +0000188 // It is not possible to sink an instruction into its own block. This can
189 // happen with loops.
190 if (Inst->getParent() == SuccToSinkTo)
191 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000192
193 // If the block has multiple predecessors, this would introduce computation
Duncan Sands339bb612012-05-31 08:09:49 +0000194 // on different code paths. We could split the critical edge, but for now we
195 // just punt.
196 // FIXME: Split critical edges if not backedges.
197 if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
198 // We cannot sink a load across a critical edge - there may be stores in
199 // other code paths.
Hal Finkel511fea72014-07-10 16:07:11 +0000200 if (!isSafeToSpeculativelyExecute(Inst, DL))
Duncan Sands339bb612012-05-31 08:09:49 +0000201 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000202
Duncan Sands339bb612012-05-31 08:09:49 +0000203 // We don't want to sink across a critical edge if we don't dominate the
204 // successor. We could be introducing calculations to new code paths.
205 if (!DT->dominates(Inst->getParent(), SuccToSinkTo))
206 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000207
Duncan Sands339bb612012-05-31 08:09:49 +0000208 // Don't sink instructions into a loop.
Nadav Rotem465834c2012-07-24 10:51:42 +0000209 Loop *succ = LI->getLoopFor(SuccToSinkTo);
210 Loop *cur = LI->getLoopFor(Inst->getParent());
Craig Topperf40110f2014-04-25 05:29:35 +0000211 if (succ != nullptr && succ != cur)
Duncan Sands339bb612012-05-31 08:09:49 +0000212 return false;
213 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000214
Duncan Sands339bb612012-05-31 08:09:49 +0000215 // Finally, check that all the uses of the instruction are actually
216 // dominated by the candidate
217 return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
218}
219
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000220/// SinkInstruction - Determine whether it is safe to sink the specified machine
221/// instruction out of its current block into a successor.
222bool Sinking::SinkInstruction(Instruction *Inst,
Craig Topper71b7b682014-08-21 05:55:13 +0000223 SmallPtrSetImpl<Instruction *> &Stores) {
Tom Stellardedfd81d2014-03-21 15:51:51 +0000224
225 // Don't sink static alloca instructions. CodeGen assumes allocas outside the
226 // entry block are dynamically sized stack objects.
227 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
228 if (AI->isStaticAlloca())
229 return false;
230
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000231 // Check if it's safe to move the instruction.
232 if (!isSafeToMove(Inst, AA, Stores))
233 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000234
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000235 // FIXME: This should include support for sinking instructions within the
236 // block they are currently in to shorten the live ranges. We often get
237 // instructions sunk into the top of a large block, but it would be better to
238 // also sink them down before their first use in the block. This xform has to
239 // be careful not to *increase* register pressure though, e.g. sinking
240 // "x = y + z" down if it kills y and z would increase the live ranges of y
241 // and z and only shrink the live range of x.
Nadav Rotem465834c2012-07-24 10:51:42 +0000242
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000243 // SuccToSinkTo - This is the successor to sink this instruction to, once we
244 // decide.
Craig Topperf40110f2014-04-25 05:29:35 +0000245 BasicBlock *SuccToSinkTo = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000246
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000247 // Instructions can only be sunk if all their uses are in blocks
248 // dominated by one of the successors.
Duncan Sands339bb612012-05-31 08:09:49 +0000249 // Look at all the postdominators and see if we can sink it in one.
250 DomTreeNode *DTN = DT->getNode(Inst->getParent());
Nadav Rotem465834c2012-07-24 10:51:42 +0000251 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
Craig Topperf40110f2014-04-25 05:29:35 +0000252 I != E && SuccToSinkTo == nullptr; ++I) {
Duncan Sands339bb612012-05-31 08:09:49 +0000253 BasicBlock *Candidate = (*I)->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000254 if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
Duncan Sands339bb612012-05-31 08:09:49 +0000255 IsAcceptableTarget(Inst, Candidate))
256 SuccToSinkTo = Candidate;
257 }
258
Nadav Rotem465834c2012-07-24 10:51:42 +0000259 // If no suitable postdominator was found, look at all the successors and
Duncan Sands339bb612012-05-31 08:09:49 +0000260 // decide which one we should sink to, if any.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000261 for (succ_iterator I = succ_begin(Inst->getParent()),
262 E = succ_end(Inst->getParent()); I != E && !SuccToSinkTo; ++I) {
263 if (IsAcceptableTarget(Inst, *I))
264 SuccToSinkTo = *I;
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000265 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000266
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000267 // If we couldn't find a block to sink to, ignore this instruction.
Craig Topperf40110f2014-04-25 05:29:35 +0000268 if (!SuccToSinkTo)
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000269 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000270
Duncan Sands339bb612012-05-31 08:09:49 +0000271 DEBUG(dbgs() << "Sink" << *Inst << " (";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000272 Inst->getParent()->printAsOperand(dbgs(), false);
Duncan Sands339bb612012-05-31 08:09:49 +0000273 dbgs() << " -> ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000274 SuccToSinkTo->printAsOperand(dbgs(), false);
Duncan Sands339bb612012-05-31 08:09:49 +0000275 dbgs() << ")\n");
Nadav Rotem465834c2012-07-24 10:51:42 +0000276
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000277 // Move the instruction.
Duncan Sands339bb612012-05-31 08:09:49 +0000278 Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
Dan Gohman5d5b8b12010-05-07 15:40:13 +0000279 return true;
280}