xref: /llvm-project/llvm/lib/Transforms/Scalar/Sink.cpp (revision 7a08381403b54cd8998f3c922f18b65867e3c07c)
1 //===-- 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 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/IR/CFG.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "sink"
30 
31 STATISTIC(NumSunk, "Number of instructions sunk");
32 STATISTIC(NumSinkIter, "Number of sinking iterations");
33 
34 namespace {
35   class Sinking : public FunctionPass {
36     DominatorTree *DT;
37     LoopInfo *LI;
38     AliasAnalysis *AA;
39 
40   public:
41     static char ID; // Pass identification
42     Sinking() : FunctionPass(ID) {
43       initializeSinkingPass(*PassRegistry::getPassRegistry());
44     }
45 
46     bool runOnFunction(Function &F) override;
47 
48     void getAnalysisUsage(AnalysisUsage &AU) const override {
49       AU.setPreservesCFG();
50       FunctionPass::getAnalysisUsage(AU);
51       AU.addRequired<AAResultsWrapperPass>();
52       AU.addRequired<DominatorTreeWrapperPass>();
53       AU.addRequired<LoopInfoWrapperPass>();
54       AU.addPreserved<DominatorTreeWrapperPass>();
55       AU.addPreserved<LoopInfoWrapperPass>();
56     }
57   private:
58     bool ProcessBlock(BasicBlock &BB);
59     bool SinkInstruction(Instruction *I, SmallPtrSetImpl<Instruction*> &Stores);
60     bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const;
61     bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const;
62   };
63 } // end anonymous namespace
64 
65 char Sinking::ID = 0;
66 INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false)
67 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
68 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
69 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
70 INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false)
71 
72 FunctionPass *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.
76 bool Sinking::AllUsesDominatedByBlock(Instruction *Inst,
77                                       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.
82   for (Use &U : Inst->uses()) {
83     // Determine the block of the use.
84     Instruction *UseInst = cast<Instruction>(U.getUser());
85     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.
89       unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
90       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 
99 bool Sinking::runOnFunction(Function &F) {
100   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
101   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
102   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
103 
104   bool MadeChange, EverMadeChange = false;
105 
106   do {
107     MadeChange = false;
108     DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
109     // Process all basic blocks.
110     for (Function::iterator I = F.begin(), E = F.end();
111          I != E; ++I)
112       MadeChange |= ProcessBlock(*I);
113     EverMadeChange |= MadeChange;
114     NumSinkIter++;
115   } while (MadeChange);
116 
117   return EverMadeChange;
118 }
119 
120 bool Sinking::ProcessBlock(BasicBlock &BB) {
121   // Can't sink anything out of a block that has less than two successors.
122   if (BB.getTerminator()->getNumSuccessors() <= 1) return false;
123 
124   // Don't bother sinking code out of unreachable blocks. In addition to being
125   // unprofitable, it can also lead to infinite looping, because in an
126   // unreachable loop there may be nowhere to stop.
127   if (!DT->isReachableFromEntry(&BB)) return false;
128 
129   bool MadeChange = false;
130 
131   // Walk the basic block bottom-up.  Remember if we saw a store.
132   BasicBlock::iterator I = BB.end();
133   --I;
134   bool ProcessedBegin = false;
135   SmallPtrSet<Instruction *, 8> Stores;
136   do {
137     Instruction *Inst = &*I; // The instruction to sink.
138 
139     // Predecrement I (if it's not begin) so that it isn't invalidated by
140     // sinking.
141     ProcessedBegin = I == BB.begin();
142     if (!ProcessedBegin)
143       --I;
144 
145     if (isa<DbgInfoIntrinsic>(Inst))
146       continue;
147 
148     if (SinkInstruction(Inst, Stores)) {
149       ++NumSunk;
150       MadeChange = true;
151     }
152 
153     // If we just processed the first instruction in the block, we're done.
154   } while (!ProcessedBegin);
155 
156   return MadeChange;
157 }
158 
159 static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA,
160                          SmallPtrSetImpl<Instruction *> &Stores) {
161 
162   if (Inst->mayWriteToMemory()) {
163     Stores.insert(Inst);
164     return false;
165   }
166 
167   if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
168     MemoryLocation Loc = MemoryLocation::get(L);
169     for (Instruction *S : Stores)
170       if (AA->getModRefInfo(S, Loc) & MRI_Mod)
171         return false;
172   }
173 
174   if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst) || Inst->isEHPad() ||
175       Inst->mayThrow())
176     return false;
177 
178   // Convergent operations cannot be made control-dependent on additional
179   // values.
180   if (auto CS = CallSite(Inst)) {
181     if (CS.hasFnAttr(Attribute::Convergent))
182       return false;
183   }
184 
185   return true;
186 }
187 
188 /// IsAcceptableTarget - Return true if it is possible to sink the instruction
189 /// in the specified basic block.
190 bool Sinking::IsAcceptableTarget(Instruction *Inst,
191                                  BasicBlock *SuccToSinkTo) const {
192   assert(Inst && "Instruction to be sunk is null");
193   assert(SuccToSinkTo && "Candidate sink target is null");
194 
195   // It is not possible to sink an instruction into its own block.  This can
196   // happen with loops.
197   if (Inst->getParent() == SuccToSinkTo)
198     return false;
199 
200   // It's never legal to sink an instruction into a block which terminates in an
201   // EH-pad.
202   if (SuccToSinkTo->getTerminator()->isExceptional())
203     return false;
204 
205   // If the block has multiple predecessors, this would introduce computation
206   // on different code paths.  We could split the critical edge, but for now we
207   // just punt.
208   // FIXME: Split critical edges if not backedges.
209   if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
210     // We cannot sink a load across a critical edge - there may be stores in
211     // other code paths.
212     if (!isSafeToSpeculativelyExecute(Inst))
213       return false;
214 
215     // We don't want to sink across a critical edge if we don't dominate the
216     // successor. We could be introducing calculations to new code paths.
217     if (!DT->dominates(Inst->getParent(), SuccToSinkTo))
218       return false;
219 
220     // Don't sink instructions into a loop.
221     Loop *succ = LI->getLoopFor(SuccToSinkTo);
222     Loop *cur = LI->getLoopFor(Inst->getParent());
223     if (succ != nullptr && succ != cur)
224       return false;
225   }
226 
227   // Finally, check that all the uses of the instruction are actually
228   // dominated by the candidate
229   return AllUsesDominatedByBlock(Inst, SuccToSinkTo);
230 }
231 
232 /// SinkInstruction - Determine whether it is safe to sink the specified machine
233 /// instruction out of its current block into a successor.
234 bool Sinking::SinkInstruction(Instruction *Inst,
235                               SmallPtrSetImpl<Instruction *> &Stores) {
236 
237   // Don't sink static alloca instructions.  CodeGen assumes allocas outside the
238   // entry block are dynamically sized stack objects.
239   if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
240     if (AI->isStaticAlloca())
241       return false;
242 
243   // Check if it's safe to move the instruction.
244   if (!isSafeToMove(Inst, AA, Stores))
245     return false;
246 
247   // FIXME: This should include support for sinking instructions within the
248   // block they are currently in to shorten the live ranges.  We often get
249   // instructions sunk into the top of a large block, but it would be better to
250   // also sink them down before their first use in the block.  This xform has to
251   // be careful not to *increase* register pressure though, e.g. sinking
252   // "x = y + z" down if it kills y and z would increase the live ranges of y
253   // and z and only shrink the live range of x.
254 
255   // SuccToSinkTo - This is the successor to sink this instruction to, once we
256   // decide.
257   BasicBlock *SuccToSinkTo = nullptr;
258 
259   // Instructions can only be sunk if all their uses are in blocks
260   // dominated by one of the successors.
261   // Look at all the postdominators and see if we can sink it in one.
262   DomTreeNode *DTN = DT->getNode(Inst->getParent());
263   for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end();
264       I != E && SuccToSinkTo == nullptr; ++I) {
265     BasicBlock *Candidate = (*I)->getBlock();
266     if ((*I)->getIDom()->getBlock() == Inst->getParent() &&
267         IsAcceptableTarget(Inst, Candidate))
268       SuccToSinkTo = Candidate;
269   }
270 
271   // If no suitable postdominator was found, look at all the successors and
272   // decide which one we should sink to, if any.
273   for (succ_iterator I = succ_begin(Inst->getParent()),
274       E = succ_end(Inst->getParent()); I != E && !SuccToSinkTo; ++I) {
275     if (IsAcceptableTarget(Inst, *I))
276       SuccToSinkTo = *I;
277   }
278 
279   // If we couldn't find a block to sink to, ignore this instruction.
280   if (!SuccToSinkTo)
281     return false;
282 
283   DEBUG(dbgs() << "Sink" << *Inst << " (";
284         Inst->getParent()->printAsOperand(dbgs(), false);
285         dbgs() << " -> ";
286         SuccToSinkTo->printAsOperand(dbgs(), false);
287         dbgs() << ")\n");
288 
289   // Move the instruction.
290   Inst->moveBefore(&*SuccToSinkTo->getFirstInsertionPt());
291   return true;
292 }
293