LLVM 24.0.0git
Sink.cpp
Go to the documentation of this file.
1//===-- Sink.cpp - Code Sinking -------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass moves instructions into successor blocks, when possible, so that
10// they aren't executed on paths where their results aren't needed.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/Statistic.h"
18#include "llvm/IR/Dominators.h"
21#include "llvm/Support/Debug.h"
24using namespace llvm;
25
26#define DEBUG_TYPE "sink"
27
28STATISTIC(NumSunk, "Number of instructions sunk");
29STATISTIC(NumSinkIter, "Number of sinking iterations");
30
33
34 if (Inst->mayWriteToMemory()) {
35 Stores.insert(Inst);
36 return false;
37 }
38
39 // Don't sink static alloca instructions. CodeGen assumes allocas outside the
40 // entry block are dynamically sized stack objects.
41 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
42 if (AI->isStaticAlloca())
43 return false;
44
45 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) {
47 for (Instruction *S : Stores)
48 if (isModSet(AA.getModRefInfo(S, Loc)))
49 return false;
50 }
51
52 if (Inst->isTerminator() || isa<PHINode>(Inst) || Inst->isEHPad() ||
53 Inst->mayThrow() || !Inst->willReturn())
54 return false;
55
56 if (auto *Call = dyn_cast<CallBase>(Inst)) {
57 // Convergent operations cannot be made control-dependent on additional
58 // values.
59 if (Call->isConvergent())
60 return false;
61
62 for (Instruction *S : Stores)
63 if (isModSet(AA.getModRefInfo(S, Call)))
64 return false;
65 }
66
67 return true;
68}
69
70/// IsAcceptableTarget - Return true if it is possible to sink the instruction
71/// in the specified basic block.
72static bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo,
73 DominatorTree &DT, LoopInfo &LI) {
74 assert(Inst && "Instruction to be sunk is null");
75 assert(SuccToSinkTo && "Candidate sink target is null");
76
77 // It's never legal to sink an instruction into an EH-pad block.
78 if (SuccToSinkTo->isEHPad())
79 return false;
80
81 // If the block has multiple predecessors, this would introduce computation
82 // on different code paths. We could split the critical edge, but for now we
83 // just punt.
84 // FIXME: Split critical edges if not backedges.
85 if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) {
86 // We cannot sink a load across a critical edge - there may be stores in
87 // other code paths.
88 if (Inst->mayReadFromMemory() &&
89 !Inst->hasMetadata(LLVMContext::MD_invariant_load))
90 return false;
91
92 // Don't sink instructions into a loop.
93 Loop *succ = LI.getLoopFor(SuccToSinkTo);
94 Loop *cur = LI.getLoopFor(Inst->getParent());
95 if (succ != nullptr && succ != cur)
96 return false;
97 }
98
99 return true;
100}
101
102/// SinkInstruction - Determine whether it is safe to sink the specified machine
103/// instruction out of its current block into a successor.
104static bool SinkInstruction(Instruction *Inst,
106 DominatorTree &DT, LoopInfo &LI, AAResults &AA) {
107
108 // Check if it's safe to move the instruction.
109 if (!isSafeToMove(Inst, AA, Stores))
110 return false;
111
112 // FIXME: This should include support for sinking instructions within the
113 // block they are currently in to shorten the live ranges. We often get
114 // instructions sunk into the top of a large block, but it would be better to
115 // also sink them down before their first use in the block. This xform has to
116 // be careful not to *increase* register pressure though, e.g. sinking
117 // "x = y + z" down if it kills y and z would increase the live ranges of y
118 // and z and only shrink the live range of x.
119
120 // SuccToSinkTo - This is the successor to sink this instruction to, once we
121 // decide.
122 BasicBlock *SuccToSinkTo = nullptr;
123
124 // Find the nearest common dominator of all users as the candidate.
125 BasicBlock *BB = Inst->getParent();
126 for (Use &U : Inst->uses()) {
127 Instruction *UseInst = cast<Instruction>(U.getUser());
128 BasicBlock *UseBlock = UseInst->getParent();
129 if (PHINode *PN = dyn_cast<PHINode>(UseInst)) {
130 // PHI nodes use the operand in the predecessor block, not the block with
131 // the PHI.
132 unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo());
133 UseBlock = PN->getIncomingBlock(Num);
134 }
135 // Don't worry about dead users.
136 if (!DT.isReachableFromEntry(UseBlock))
137 continue;
138
139 if (SuccToSinkTo)
140 SuccToSinkTo = DT.findNearestCommonDominator(SuccToSinkTo, UseBlock);
141 else
142 SuccToSinkTo = UseBlock;
143 }
144
145 if (SuccToSinkTo) {
146 // The nearest common dominator may be in a parent loop of BB, which may not
147 // be beneficial. Find an ancestor.
148 while (SuccToSinkTo != BB &&
149 !IsAcceptableTarget(Inst, SuccToSinkTo, DT, LI))
150 SuccToSinkTo = DT.getNode(SuccToSinkTo)->getIDom()->getBlock();
151 if (SuccToSinkTo == BB)
152 SuccToSinkTo = nullptr;
153 }
154
155 // If we couldn't find a block to sink to, ignore this instruction.
156 if (!SuccToSinkTo)
157 return false;
158
159 LLVM_DEBUG(dbgs() << "Sink" << *Inst << " (";
160 Inst->getParent()->printAsOperand(dbgs(), false); dbgs() << " -> ";
161 SuccToSinkTo->printAsOperand(dbgs(), false); dbgs() << ")\n");
162
163 // The current location of Inst dominates all uses, thus it must dominate
164 // SuccToSinkTo, which is on the IDom chain between the nearest common
165 // dominator to all uses and the current location.
166 assert(DT.dominates(BB, SuccToSinkTo) &&
167 "SuccToSinkTo must be dominated by current Inst location!");
168
169 // Move the instruction.
170 Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt());
171 return true;
172}
173
175 AAResults &AA) {
176 // Don't bother sinking code out of unreachable blocks. In addition to being
177 // unprofitable, it can also lead to infinite looping, because in an
178 // unreachable loop there may be nowhere to stop.
179 if (!DT.isReachableFromEntry(&BB)) return false;
180
181 bool MadeChange = false;
182
183 // Walk the basic block bottom-up. Remember if we saw a store.
185 --I;
186 bool ProcessedBegin = false;
188 do {
189 Instruction *Inst = &*I; // The instruction to sink.
190
191 // Predecrement I (if it's not begin) so that it isn't invalidated by
192 // sinking.
193 ProcessedBegin = I == BB.begin();
194 if (!ProcessedBegin)
195 --I;
196
197 if (isa<PseudoProbeInst>(Inst))
198 continue;
199
200 if (SinkInstruction(Inst, Stores, DT, LI, AA)) {
201 ++NumSunk;
202 MadeChange = true;
203 }
204
205 // If we just processed the first instruction in the block, we're done.
206 } while (!ProcessedBegin);
207
208 return MadeChange;
209}
210
212 LoopInfo &LI, AAResults &AA) {
213 bool MadeChange, EverMadeChange = false;
214
215 do {
216 MadeChange = false;
217 LLVM_DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n");
218 // Process all basic blocks.
219 for (BasicBlock &I : F)
220 MadeChange |= ProcessBlock(I, DT, LI, AA);
221 EverMadeChange |= MadeChange;
222 NumSinkIter++;
223 } while (MadeChange);
224
225 return EverMadeChange;
226}
227
229 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
230 auto &LI = AM.getResult<LoopAnalysis>(F);
231 auto &AA = AM.getResult<AAManager>(F);
232
233 if (!iterativelySinkInstructions(F, DT, LI, AA))
234 return PreservedAnalyses::all();
235
238 return PA;
239}
240
241namespace {
242 class SinkingLegacyPass : public FunctionPass {
243 public:
244 static char ID; // Pass identification
245 SinkingLegacyPass() : FunctionPass(ID) {
247 }
248
249 bool runOnFunction(Function &F) override {
250 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
251 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
252 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
253
254 return iterativelySinkInstructions(F, DT, LI, AA);
255 }
256
257 void getAnalysisUsage(AnalysisUsage &AU) const override {
258 AU.setPreservesCFG();
259 FunctionPass::getAnalysisUsage(AU);
260 AU.addRequired<AAResultsWrapperPass>();
261 AU.addRequired<DominatorTreeWrapperPass>();
262 AU.addRequired<LoopInfoWrapperPass>();
263 }
264 };
265} // end anonymous namespace
266
267char SinkingLegacyPass::ID = 0;
268INITIALIZE_PASS_BEGIN(SinkingLegacyPass, "sink", "Code sinking", false, false)
272INITIALIZE_PASS_END(SinkingLegacyPass, "sink", "Code sinking", false, false)
273
274FunctionPass *llvm::createSinkingPass() { return new SinkingLegacyPass(); }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool runOnFunction(Function &F, bool PostInlining)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static bool iterativelySinkInstructions(Function &F, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
Definition Sink.cpp:211
static bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo, DominatorTree &DT, LoopInfo &LI)
IsAcceptableTarget - Return true if it is possible to sink the instruction in the specified basic blo...
Definition Sink.cpp:72
static bool isSafeToMove(Instruction *Inst, AliasAnalysis &AA, SmallPtrSetImpl< Instruction * > &Stores)
Definition Sink.cpp:31
static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
Definition Sink.cpp:174
static bool SinkInstruction(Instruction *Inst, SmallPtrSetImpl< Instruction * > &Stores, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
SinkInstruction - Determine whether it is safe to sink the specified machine instruction out of its c...
Definition Sink.cpp:104
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
an instruction to allocate memory on the stack
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:278
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:689
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
LLVM_ABI bool mayThrow(bool IncludePhaseOneUnwind=false) const LLVM_READONLY
Return true if this instruction may throw an exception.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
bool isTerminator() const
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
LLVM_ABI bool willReturn() const LLVM_READONLY
Return true if the instruction will return (unwinding is considered as a form of returning control fl...
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:619
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static unsigned getIncomingValueNumForOperand(unsigned i)
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition Sink.cpp:228
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
iterator_range< use_iterator > uses()
Definition Value.h:382
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
Abstract Attribute helper functions.
Definition Attributor.h:165
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI void initializeSinkingLegacyPassPass(PassRegistry &)
LLVM_ABI FunctionPass * createSinkingPass()
Definition Sink.cpp:274
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.