blob: b544f0a39ea87dde1d45fdcd0215fb59f8e14ef8 [file] [log] [blame]
Philip Reames47cc6732015-02-04 00:37:33 +00001//===- PlaceSafepoints.cpp - Place GC Safepoints --------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Philip Reames47cc6732015-02-04 00:37:33 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Place garbage collection safepoints at appropriate locations in the IR. This
10// does not make relocation semantics or variable liveness explicit. That's
11// done by RewriteStatepointsForGC.
12//
Philip Reamesd4a912f2015-02-09 22:44:03 +000013// Terminology:
14// - A call is said to be "parseable" if there is a stack map generated for the
15// return PC of the call. A runtime can determine where values listed in the
16// deopt arguments and (after RewriteStatepointsForGC) gc arguments are located
17// on the stack when the code is suspended inside such a call. Every parse
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +000018// point is represented by a call wrapped in an gc.statepoint intrinsic.
Philip Reamesd4a912f2015-02-09 22:44:03 +000019// - A "poll" is an explicit check in the generated code to determine if the
20// runtime needs the generated code to cooperate by calling a helper routine
21// and thus suspending its execution at a known state. The call to the helper
22// routine will be parseable. The (gc & runtime specific) logic of a poll is
23// assumed to be provided in a function of the name "gc.safepoint_poll".
24//
25// We aim to insert polls such that running code can quickly be brought to a
26// well defined state for inspection by the collector. In the current
27// implementation, this is done via the insertion of poll sites at method entry
28// and the backedge of most loops. We try to avoid inserting more polls than
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000029// are necessary to ensure a finite period between poll sites. This is not
Philip Reamesd4a912f2015-02-09 22:44:03 +000030// because the poll itself is expensive in the generated code; it's not. Polls
31// do tend to impact the optimizer itself in negative ways; we'd like to avoid
32// perturbing the optimization of the method as much as we can.
33//
34// We also need to make most call sites parseable. The callee might execute a
35// poll (or otherwise be inspected by the GC). If so, the entire stack
36// (including the suspended frame of the current method) must be parseable.
37//
Philip Reames47cc6732015-02-04 00:37:33 +000038// This pass will insert:
Philip Reamesd4a912f2015-02-09 22:44:03 +000039// - Call parse points ("call safepoints") for any call which may need to
40// reach a safepoint during the execution of the callee function.
41// - Backedge safepoint polls and entry safepoint polls to ensure that
42// executing code reaches a safepoint poll in a finite amount of time.
Philip Reames47cc6732015-02-04 00:37:33 +000043//
Philip Reamesd4a912f2015-02-09 22:44:03 +000044// We do not currently support return statepoints, but adding them would not
45// be hard. They are not required for correctness - entry safepoints are an
46// alternative - but some GCs may prefer them. Patches welcome.
Philip Reames47cc6732015-02-04 00:37:33 +000047//
48//===----------------------------------------------------------------------===//
49
50#include "llvm/Pass.h"
Sanjoy Das360a4e42016-01-28 23:03:17 +000051
Philip Reames5708cca2015-05-12 20:43:48 +000052#include "llvm/ADT/SetVector.h"
Philip Reames47cc6732015-02-04 00:37:33 +000053#include "llvm/ADT/Statistic.h"
Philip Reames47cc6732015-02-04 00:37:33 +000054#include "llvm/Analysis/CFG.h"
Sanjoy Das360a4e42016-01-28 23:03:17 +000055#include "llvm/Analysis/ScalarEvolution.h"
Daniel Neilson2574d7c2017-07-27 16:49:39 +000056#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000057#include "llvm/Transforms/Utils/Local.h"
Philip Reames47cc6732015-02-04 00:37:33 +000058#include "llvm/IR/Dominators.h"
Philip Reames47cc6732015-02-04 00:37:33 +000059#include "llvm/IR/IntrinsicInst.h"
Sanjoy Das360a4e42016-01-28 23:03:17 +000060#include "llvm/IR/LegacyPassManager.h"
Philip Reames47cc6732015-02-04 00:37:33 +000061#include "llvm/IR/Statepoint.h"
Philip Reames47cc6732015-02-04 00:37:33 +000062#include "llvm/Support/CommandLine.h"
Sanjoy Das360a4e42016-01-28 23:03:17 +000063#include "llvm/Support/Debug.h"
Philip Reames47cc6732015-02-04 00:37:33 +000064#include "llvm/Transforms/Scalar.h"
65#include "llvm/Transforms/Utils/BasicBlockUtils.h"
66#include "llvm/Transforms/Utils/Cloning.h"
Philip Reames47cc6732015-02-04 00:37:33 +000067
68#define DEBUG_TYPE "safepoint-placement"
Sanjoy Dascd23fec2016-01-28 23:03:19 +000069
Philip Reames47cc6732015-02-04 00:37:33 +000070STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
Philip Reames47cc6732015-02-04 00:37:33 +000071STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
72
Sanjoy Dascd23fec2016-01-28 23:03:19 +000073STATISTIC(CallInLoop,
74 "Number of loops without safepoints due to calls in loop");
75STATISTIC(FiniteExecution,
76 "Number of loops without safepoints finite execution");
Philip Reames47cc6732015-02-04 00:37:33 +000077
78using namespace llvm;
79
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000080// Ignore opportunities to avoid placing safepoints on backedges, useful for
Philip Reames47cc6732015-02-04 00:37:33 +000081// validation
Philip Reames1f3e5c12015-02-20 23:32:03 +000082static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
83 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000084
Sanjoy Dasf75e15e2015-09-15 01:42:48 +000085/// How narrow does the trip count of a loop have to be to have to be considered
86/// "counted"? Counted loops do not get safepoints at backedges.
87static cl::opt<int> CountedLoopTripWidth("spp-counted-loop-trip-width",
88 cl::Hidden, cl::init(32));
Philip Reames47cc6732015-02-04 00:37:33 +000089
90// If true, split the backedge of a loop when placing the safepoint, otherwise
91// split the latch block itself. Both are useful to support for
92// experimentation, but in practice, it looks like splitting the backedge
93// optimizes better.
Philip Reames1f3e5c12015-02-20 23:32:03 +000094static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
95 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000096
Philip Reames47cc6732015-02-04 00:37:33 +000097namespace {
98
Philip Reames9f129042015-05-12 21:09:36 +000099/// An analysis pass whose purpose is to identify each of the backedges in
100/// the function which require a safepoint poll to be inserted.
101struct PlaceBackedgeSafepointsImpl : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000102 static char ID;
103
104 /// The output of the pass - gives a list of each backedge (described by
105 /// pointing at the branch) which need a poll inserted.
Chandler Carruthedb12a82018-10-15 10:04:59 +0000106 std::vector<Instruction *> PollLocations;
Philip Reames47cc6732015-02-04 00:37:33 +0000107
108 /// True unless we're running spp-no-calls in which case we need to disable
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000109 /// the call-dependent placement opts.
Philip Reames47cc6732015-02-04 00:37:33 +0000110 bool CallSafepointsEnabled;
Philip Reames9f129042015-05-12 21:09:36 +0000111
112 ScalarEvolution *SE = nullptr;
113 DominatorTree *DT = nullptr;
114 LoopInfo *LI = nullptr;
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000115 TargetLibraryInfo *TLI = nullptr;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000116
Philip Reames47cc6732015-02-04 00:37:33 +0000117 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
Philip Reames9f129042015-05-12 21:09:36 +0000118 : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
Philip Reames5a9685d2015-02-04 00:39:57 +0000119 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000120 }
121
Philip Reames9f129042015-05-12 21:09:36 +0000122 bool runOnLoop(Loop *);
123 void runOnLoopAndSubLoops(Loop *L) {
124 // Visit all the subloops
Benjamin Kramer135f7352016-06-26 12:28:59 +0000125 for (Loop *I : *L)
126 runOnLoopAndSubLoops(I);
Philip Reames9f129042015-05-12 21:09:36 +0000127 runOnLoop(L);
128 }
Justin Bogner383749a2015-05-12 21:49:47 +0000129
130 bool runOnFunction(Function &F) override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000131 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Philip Reames9f129042015-05-12 21:09:36 +0000132 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
133 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000134 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Benjamin Kramer135f7352016-06-26 12:28:59 +0000135 for (Loop *I : *LI) {
136 runOnLoopAndSubLoops(I);
Philip Reames9f129042015-05-12 21:09:36 +0000137 }
138 return false;
139 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000140
Philip Reames47cc6732015-02-04 00:37:33 +0000141 void getAnalysisUsage(AnalysisUsage &AU) const override {
Philip Reames57bdac92015-05-12 20:56:33 +0000142 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000143 AU.addRequired<ScalarEvolutionWrapperPass>();
Philip Reames9f129042015-05-12 21:09:36 +0000144 AU.addRequired<LoopInfoWrapperPass>();
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000145 AU.addRequired<TargetLibraryInfoWrapperPass>();
Philip Reames47cc6732015-02-04 00:37:33 +0000146 // We no longer modify the IR at all in this pass. Thus all
147 // analysis are preserved.
148 AU.setPreservesAll();
149 }
150};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000151}
Philip Reames47cc6732015-02-04 00:37:33 +0000152
Philip Reames1f3e5c12015-02-20 23:32:03 +0000153static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
154static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
155static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000156
157namespace {
Philip Reames7b981792015-05-12 21:21:18 +0000158struct PlaceSafepoints : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000159 static char ID; // Pass identification, replacement for typeid
160
Philip Reames7b981792015-05-12 21:21:18 +0000161 PlaceSafepoints() : FunctionPass(ID) {
Philip Reames47cc6732015-02-04 00:37:33 +0000162 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000163 }
Philip Reames7b981792015-05-12 21:21:18 +0000164 bool runOnFunction(Function &F) override;
Philip Reames47cc6732015-02-04 00:37:33 +0000165
166 void getAnalysisUsage(AnalysisUsage &AU) const override {
167 // We modify the graph wholesale (inlining, block insertion, etc). We
168 // preserve nothing at the moment. We could potentially preserve dom tree
169 // if that was worth doing
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000170 AU.addRequired<TargetLibraryInfoWrapperPass>();
Philip Reames47cc6732015-02-04 00:37:33 +0000171 }
172};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000173}
Philip Reames47cc6732015-02-04 00:37:33 +0000174
175// Insert a safepoint poll immediately before the given instruction. Does
176// not handle the parsability of state at the runtime call, that's the
177// callers job.
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000178static void
Philip Reames388402452015-05-26 21:03:23 +0000179InsertSafepointPoll(Instruction *InsertBefore,
Chandler Carruth31607342019-02-11 07:42:30 +0000180 std::vector<CallBase *> &ParsePointsNeeded /*rval*/,
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000181 const TargetLibraryInfo &TLI);
Philip Reames47cc6732015-02-04 00:37:33 +0000182
Chandler Carruth31607342019-02-11 07:42:30 +0000183static bool needsStatepoint(CallBase *Call, const TargetLibraryInfo &TLI) {
184 if (callsGCLeafFunction(Call, TLI))
Philip Reames47cc6732015-02-04 00:37:33 +0000185 return false;
Chandler Carruth31607342019-02-11 07:42:30 +0000186 if (auto *CI = dyn_cast<CallInst>(Call)) {
187 if (CI->isInlineAsm())
Philip Reames47cc6732015-02-04 00:37:33 +0000188 return false;
189 }
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000190
Chandler Carruth31607342019-02-11 07:42:30 +0000191 return !(isStatepoint(Call) || isGCRelocate(Call) || isGCResult(Call));
Philip Reames47cc6732015-02-04 00:37:33 +0000192}
193
Philip Reames47cc6732015-02-04 00:37:33 +0000194/// Returns true if this loop is known to contain a call safepoint which
195/// must unconditionally execute on any iteration of the loop which returns
196/// to the loop header via an edge from Pred. Returns a conservative correct
197/// answer; i.e. false is always valid.
198static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
199 BasicBlock *Pred,
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000200 DominatorTree &DT,
201 const TargetLibraryInfo &TLI) {
Philip Reames47cc6732015-02-04 00:37:33 +0000202 // In general, we're looking for any cut of the graph which ensures
203 // there's a call safepoint along every edge between Header and Pred.
204 // For the moment, we look only for the 'cuts' that consist of a single call
205 // instruction in a block which is dominated by the Header and dominates the
206 // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000207 // of such dominating blocks gets substantially more occurrences than just
Philip Reames47cc6732015-02-04 00:37:33 +0000208 // checking the Pred and Header blocks themselves. This may be due to the
209 // density of loop exit conditions caused by range and null checks.
210 // TODO: structure this as an analysis pass, cache the result for subloops,
211 // avoid dom tree recalculations
212 assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
213
214 BasicBlock *Current = Pred;
215 while (true) {
216 for (Instruction &I : *Current) {
Chandler Carruth31607342019-02-11 07:42:30 +0000217 if (auto *Call = dyn_cast<CallBase>(&I))
Philip Reames47cc6732015-02-04 00:37:33 +0000218 // Note: Technically, needing a safepoint isn't quite the right
219 // condition here. We should instead be checking if the target method
220 // has an
221 // unconditional poll. In practice, this is only a theoretical concern
222 // since we don't have any methods with conditional-only safepoint
223 // polls.
Chandler Carruth31607342019-02-11 07:42:30 +0000224 if (needsStatepoint(Call, TLI))
Philip Reames47cc6732015-02-04 00:37:33 +0000225 return true;
226 }
227
228 if (Current == Header)
229 break;
230 Current = DT.getNode(Current)->getIDom()->getBlock();
231 }
232
233 return false;
234}
235
236/// Returns true if this loop is known to terminate in a finite number of
237/// iterations. Note that this function may return false for a loop which
238/// does actual terminate in a finite constant number of iterations due to
239/// conservatism in the analysis.
240static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
Philip Reames5a9685d2015-02-04 00:39:57 +0000241 BasicBlock *Pred) {
Philip Reames47cc6732015-02-04 00:37:33 +0000242 // A conservative bound on the loop as a whole.
243 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
Sanjoy Dasf75e15e2015-09-15 01:42:48 +0000244 if (MaxTrips != SE->getCouldNotCompute() &&
245 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(
246 CountedLoopTripWidth))
247 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000248
249 // If this is a conditional branch to the header with the alternate path
250 // being outside the loop, we can ask questions about the execution frequency
251 // of the exit block.
252 if (L->isLoopExiting(Pred)) {
253 // This returns an exact expression only. TODO: We really only need an
254 // upper bound here, but SE doesn't expose that.
255 const SCEV *MaxExec = SE->getExitCount(L, Pred);
Sanjoy Dasf75e15e2015-09-15 01:42:48 +0000256 if (MaxExec != SE->getCouldNotCompute() &&
257 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(
258 CountedLoopTripWidth))
Philip Reames47cc6732015-02-04 00:37:33 +0000259 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000260 }
261
262 return /* not finite */ false;
263}
264
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000265static void scanOneBB(Instruction *Start, Instruction *End,
266 std::vector<CallInst *> &Calls,
267 DenseSet<BasicBlock *> &Seen,
268 std::vector<BasicBlock *> &Worklist) {
269 for (BasicBlock::iterator BBI(Start), BBE0 = Start->getParent()->end(),
270 BBE1 = BasicBlock::iterator(End);
271 BBI != BBE0 && BBI != BBE1; BBI++) {
272 if (CallInst *CI = dyn_cast<CallInst>(&*BBI))
273 Calls.push_back(CI);
274
Philip Reames47cc6732015-02-04 00:37:33 +0000275 // FIXME: This code does not handle invokes
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000276 assert(!isa<InvokeInst>(&*BBI) &&
Philip Reames47cc6732015-02-04 00:37:33 +0000277 "support for invokes in poll code needed");
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000278
Philip Reames47cc6732015-02-04 00:37:33 +0000279 // Only add the successor blocks if we reach the terminator instruction
280 // without encountering end first
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000281 if (BBI->isTerminator()) {
282 BasicBlock *BB = BBI->getParent();
Philip Reamesa29de872015-02-09 22:26:11 +0000283 for (BasicBlock *Succ : successors(BB)) {
Benjamin Kramer4dea8f52016-06-17 18:59:41 +0000284 if (Seen.insert(Succ).second) {
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000285 Worklist.push_back(Succ);
Philip Reames47cc6732015-02-04 00:37:33 +0000286 }
287 }
288 }
289 }
290}
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000291
292static void scanInlinedCode(Instruction *Start, Instruction *End,
293 std::vector<CallInst *> &Calls,
294 DenseSet<BasicBlock *> &Seen) {
295 Calls.clear();
296 std::vector<BasicBlock *> Worklist;
297 Seen.insert(Start->getParent());
298 scanOneBB(Start, End, Calls, Seen, Worklist);
299 while (!Worklist.empty()) {
300 BasicBlock *BB = Worklist.back();
301 Worklist.pop_back();
302 scanOneBB(&*BB->begin(), End, Calls, Seen, Worklist);
Philip Reames47cc6732015-02-04 00:37:33 +0000303 }
304}
305
Philip Reames9f129042015-05-12 21:09:36 +0000306bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) {
Philip Reames5708cca2015-05-12 20:43:48 +0000307 // Loop through all loop latches (branches controlling backedges). We need
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000308 // to place a safepoint on every backedge (potentially).
Philip Reames5708cca2015-05-12 20:43:48 +0000309 // Note: In common usage, there will be only one edge due to LoopSimplify
310 // having run sometime earlier in the pipeline, but this code must be correct
311 // w.r.t. loops with multiple backedges.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000312 BasicBlock *Header = L->getHeader();
Philip Reames5708cca2015-05-12 20:43:48 +0000313 SmallVector<BasicBlock*, 16> LoopLatches;
314 L->getLoopLatches(LoopLatches);
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000315 for (BasicBlock *Pred : LoopLatches) {
316 assert(L->contains(Pred));
Philip Reames47cc6732015-02-04 00:37:33 +0000317
318 // Make a policy decision about whether this loop needs a safepoint or
319 // not. Note that this is about unburdening the optimizer in loops, not
320 // avoiding the runtime cost of the actual safepoint.
321 if (!AllBackedges) {
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000322 if (mustBeFiniteCountedLoop(L, SE, Pred)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000323 LLVM_DEBUG(dbgs() << "skipping safepoint placement in finite loop\n");
Philip Reames47cc6732015-02-04 00:37:33 +0000324 FiniteExecution++;
325 continue;
326 }
327 if (CallSafepointsEnabled &&
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000328 containsUnconditionalCallSafepoint(L, Header, Pred, *DT, *TLI)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000329 // Note: This is only semantically legal since we won't do any further
330 // IPO or inlining before the actual call insertion.. If we hadn't, we
331 // might latter loose this call safepoint.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000332 LLVM_DEBUG(
333 dbgs()
334 << "skipping safepoint placement due to unconditional call\n");
Philip Reames47cc6732015-02-04 00:37:33 +0000335 CallInLoop++;
336 continue;
337 }
338 }
339
340 // TODO: We can create an inner loop which runs a finite number of
341 // iterations with an outer loop which contains a safepoint. This would
342 // not help runtime performance that much, but it might help our ability to
343 // optimize the inner loop.
344
Philip Reames47cc6732015-02-04 00:37:33 +0000345 // Safepoint insertion would involve creating a new basic block (as the
346 // target of the current backedge) which does the safepoint (of all live
347 // variables) and branches to the true header
Chandler Carruthedb12a82018-10-15 10:04:59 +0000348 Instruction *Term = Pred->getTerminator();
Philip Reames47cc6732015-02-04 00:37:33 +0000349
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000350 LLVM_DEBUG(dbgs() << "[LSP] terminator instruction: " << *Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000351
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000352 PollLocations.push_back(Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000353 }
354
Philip Reames5708cca2015-05-12 20:43:48 +0000355 return false;
Philip Reames47cc6732015-02-04 00:37:33 +0000356}
357
Philip Reamesd97cdf22015-05-19 23:40:11 +0000358/// Returns true if an entry safepoint is not required before this callsite in
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000359/// the caller function.
Chandler Carruth31607342019-02-11 07:42:30 +0000360static bool doesNotRequireEntrySafepointBefore(CallBase *Call) {
361 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call)) {
Philip Reamesd97cdf22015-05-19 23:40:11 +0000362 switch (II->getIntrinsicID()) {
363 case Intrinsic::experimental_gc_statepoint:
364 case Intrinsic::experimental_patchpoint_void:
365 case Intrinsic::experimental_patchpoint_i64:
366 // The can wrap an actual call which may grow the stack by an unbounded
367 // amount or run forever.
368 return false;
369 default:
370 // Most LLVM intrinsics are things which do not expand to actual calls, or
371 // at least if they do, are leaf functions that cause only finite stack
372 // growth. In particular, the optimizer likes to form things like memsets
373 // out of stores in the original IR. Another important example is
Reid Kleckner60381792015-07-07 22:25:32 +0000374 // llvm.localescape which must occur in the entry block. Inserting a
375 // safepoint before it is not legal since it could push the localescape
Philip Reamesd97cdf22015-05-19 23:40:11 +0000376 // out of the entry block.
377 return true;
378 }
379 }
380 return false;
381}
382
Philip Reames47cc6732015-02-04 00:37:33 +0000383static Instruction *findLocationForEntrySafepoint(Function &F,
384 DominatorTree &DT) {
385
386 // Conceptually, this poll needs to be on method entry, but in
387 // practice, we place it as late in the entry block as possible. We
388 // can place it as late as we want as long as it dominates all calls
389 // that can grow the stack. This, combined with backedge polls,
390 // give us all the progress guarantees we need.
391
Philip Reames47cc6732015-02-04 00:37:33 +0000392 // hasNextInstruction and nextInstruction are used to iterate
393 // through a "straight line" execution sequence.
394
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000395 auto HasNextInstruction = [](Instruction *I) {
396 if (!I->isTerminator())
Philip Reames47cc6732015-02-04 00:37:33 +0000397 return true;
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000398
Philip Reames47cc6732015-02-04 00:37:33 +0000399 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
400 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
401 };
402
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000403 auto NextInstruction = [&](Instruction *I) {
404 assert(HasNextInstruction(I) &&
Philip Reames47cc6732015-02-04 00:37:33 +0000405 "first check if there is a next instruction!");
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000406
407 if (I->isTerminator())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000408 return &I->getParent()->getUniqueSuccessor()->front();
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000409 return &*++I->getIterator();
Philip Reames47cc6732015-02-04 00:37:33 +0000410 };
411
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000412 Instruction *Cursor = nullptr;
413 for (Cursor = &F.getEntryBlock().front(); HasNextInstruction(Cursor);
414 Cursor = NextInstruction(Cursor)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000415
Philip Reamesd97cdf22015-05-19 23:40:11 +0000416 // We need to ensure a safepoint poll occurs before any 'real' call. The
417 // easiest way to ensure finite execution between safepoints in the face of
418 // recursive and mutually recursive functions is to enforce that each take
419 // a safepoint. Additionally, we need to ensure a poll before any call
420 // which can grow the stack by an unbounded amount. This isn't required
421 // for GC semantics per se, but is a common requirement for languages
422 // which detect stack overflow via guard pages and then throw exceptions.
Chandler Carruth31607342019-02-11 07:42:30 +0000423 if (auto *Call = dyn_cast<CallBase>(Cursor)) {
424 if (doesNotRequireEntrySafepointBefore(Call))
Philip Reamesd97cdf22015-05-19 23:40:11 +0000425 continue;
Philip Reames47cc6732015-02-04 00:37:33 +0000426 break;
427 }
428 }
429
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000430 assert((HasNextInstruction(Cursor) || Cursor->isTerminator()) &&
Philip Reames5a9685d2015-02-04 00:39:57 +0000431 "either we stopped because of a call, or because of terminator");
Philip Reames47cc6732015-02-04 00:37:33 +0000432
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000433 return Cursor;
Philip Reames47cc6732015-02-04 00:37:33 +0000434}
435
Benjamin Kramer82f86522015-06-07 16:36:28 +0000436static const char *const GCSafepointPollName = "gc.safepoint_poll";
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000437
438static bool isGCSafepointPoll(Function &F) {
439 return F.getName().equals(GCSafepointPollName);
440}
441
Philip Reames0b1b3872015-02-21 00:09:09 +0000442/// Returns true if this function should be rewritten to include safepoint
443/// polls and parseable call sites. The main point of this function is to be
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000444/// an extension point for custom logic.
Philip Reames0b1b3872015-02-21 00:09:09 +0000445static bool shouldRewriteFunction(Function &F) {
446 // TODO: This should check the GCStrategy
447 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +0000448 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000449 const StringRef StatepointExampleName("statepoint-example");
450 const StringRef CoreCLRName("coreclr");
451 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +0000452 (CoreCLRName == FunctionGCName);
Philip Reames0b1b3872015-02-21 00:09:09 +0000453 } else
454 return false;
455}
456
457// TODO: These should become properties of the GCStrategy, possibly with
458// command line overrides.
459static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
460static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
461static bool enableCallSafepoints(Function &F) { return !NoCall; }
462
Philip Reames47cc6732015-02-04 00:37:33 +0000463bool PlaceSafepoints::runOnFunction(Function &F) {
464 if (F.isDeclaration() || F.empty()) {
465 // This is a declaration, nothing to do. Must exit early to avoid crash in
466 // dom tree calculation
467 return false;
468 }
469
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000470 if (isGCSafepointPoll(F)) {
471 // Given we're inlining this inside of safepoint poll insertion, this
472 // doesn't make any sense. Note that we do make any contained calls
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000473 // parseable after we inline a poll.
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000474 return false;
475 }
476
Philip Reames0b1b3872015-02-21 00:09:09 +0000477 if (!shouldRewriteFunction(F))
478 return false;
479
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000480 const TargetLibraryInfo &TLI =
481 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
482
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000483 bool Modified = false;
Philip Reames47cc6732015-02-04 00:37:33 +0000484
485 // In various bits below, we rely on the fact that uses are reachable from
486 // defs. When there are basic blocks unreachable from the entry, dominance
487 // and reachablity queries return non-sensical results. Thus, we preprocess
488 // the function to ensure these properties hold.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000489 Modified |= removeUnreachableBlocks(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000490
491 // STEP 1 - Insert the safepoint polling locations. We do not need to
492 // actually insert parse points yet. That will be done for all polls and
493 // calls in a single pass.
494
Philip Reames47cc6732015-02-04 00:37:33 +0000495 DominatorTree DT;
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000496 DT.recalculate(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000497
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000498 SmallVector<Instruction *, 16> PollsNeeded;
Chandler Carruth31607342019-02-11 07:42:30 +0000499 std::vector<CallBase *> ParsePointNeeded;
Philip Reames47cc6732015-02-04 00:37:33 +0000500
Philip Reames0b1b3872015-02-21 00:09:09 +0000501 if (enableBackedgeSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000502 // Construct a pass manager to run the LoopPass backedge logic. We
503 // need the pass manager to handle scheduling all the loop passes
504 // appropriately. Doing this by hand is painful and just not worth messing
505 // with for the moment.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000506 legacy::FunctionPassManager FPM(F.getParent());
Philip Reames0b1b3872015-02-21 00:09:09 +0000507 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000508 auto *PBS = new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
Philip Reames47cc6732015-02-04 00:37:33 +0000509 FPM.add(PBS);
Philip Reames47cc6732015-02-04 00:37:33 +0000510 FPM.run(F);
511
512 // We preserve dominance information when inserting the poll, otherwise
513 // we'd have to recalculate this on every insert
514 DT.recalculate(F);
515
Philip Reames5708cca2015-05-12 20:43:48 +0000516 auto &PollLocations = PBS->PollLocations;
517
518 auto OrderByBBName = [](Instruction *a, Instruction *b) {
519 return a->getParent()->getName() < b->getParent()->getName();
520 };
521 // We need the order of list to be stable so that naming ends up stable
522 // when we split edges. This makes test cases much easier to write.
Fangrui Song0cac7262018-09-27 02:13:45 +0000523 llvm::sort(PollLocations, OrderByBBName);
Philip Reames5708cca2015-05-12 20:43:48 +0000524
525 // We can sometimes end up with duplicate poll locations. This happens if
526 // a single loop is visited more than once. The fact this happens seems
527 // wrong, but it does happen for the split-backedge.ll test case.
528 PollLocations.erase(std::unique(PollLocations.begin(),
529 PollLocations.end()),
530 PollLocations.end());
531
Philip Reames47cc6732015-02-04 00:37:33 +0000532 // Insert a poll at each point the analysis pass identified
Philip Reames89fe5702015-05-12 23:39:23 +0000533 // The poll location must be the terminator of a loop latch block.
Chandler Carruthedb12a82018-10-15 10:04:59 +0000534 for (Instruction *Term : PollLocations) {
Philip Reames47cc6732015-02-04 00:37:33 +0000535 // We are inserting a poll, the function is modified
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000536 Modified = true;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000537
Philip Reames47cc6732015-02-04 00:37:33 +0000538 if (SplitBackedge) {
539 // Split the backedge of the loop and insert the poll within that new
540 // basic block. This creates a loop with two latches per original
541 // latch (which is non-ideal), but this appears to be easier to
542 // optimize in practice than inserting the poll immediately before the
543 // latch test.
544
545 // Since this is a latch, at least one of the successors must dominate
546 // it. Its possible that we have a) duplicate edges to the same header
547 // and b) edges to distinct loop headers. We need to insert pools on
Philip Reames5708cca2015-05-12 20:43:48 +0000548 // each.
549 SetVector<BasicBlock *> Headers;
Philip Reames47cc6732015-02-04 00:37:33 +0000550 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
551 BasicBlock *Succ = Term->getSuccessor(i);
552 if (DT.dominates(Succ, Term->getParent())) {
553 Headers.insert(Succ);
554 }
555 }
556 assert(!Headers.empty() && "poll location is not a loop latch?");
557
558 // The split loop structure here is so that we only need to recalculate
559 // the dominator tree once. Alternatively, we could just keep it up to
560 // date and use a more natural merged loop.
Philip Reames5708cca2015-05-12 20:43:48 +0000561 SetVector<BasicBlock *> SplitBackedges;
Philip Reames47cc6732015-02-04 00:37:33 +0000562 for (BasicBlock *Header : Headers) {
Philip Reames89fe5702015-05-12 23:39:23 +0000563 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000564 PollsNeeded.push_back(NewBB->getTerminator());
Philip Reames47cc6732015-02-04 00:37:33 +0000565 NumBackedgeSafepoints++;
566 }
Philip Reames47cc6732015-02-04 00:37:33 +0000567 } else {
568 // Split the latch block itself, right before the terminator.
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000569 PollsNeeded.push_back(Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000570 NumBackedgeSafepoints++;
571 }
Philip Reames47cc6732015-02-04 00:37:33 +0000572 }
573 }
574
Philip Reames0b1b3872015-02-21 00:09:09 +0000575 if (enableEntrySafepoints(F)) {
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000576 if (Instruction *Location = findLocationForEntrySafepoint(F, DT)) {
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000577 PollsNeeded.push_back(Location);
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000578 Modified = true;
Philip Reames47cc6732015-02-04 00:37:33 +0000579 NumEntrySafepoints++;
Philip Reames47cc6732015-02-04 00:37:33 +0000580 }
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000581 // TODO: else we should assert that there was, in fact, a policy choice to
582 // not insert a entry safepoint poll.
Philip Reames47cc6732015-02-04 00:37:33 +0000583 }
584
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000585 // Now that we've identified all the needed safepoint poll locations, insert
586 // safepoint polls themselves.
587 for (Instruction *PollLocation : PollsNeeded) {
Chandler Carruth31607342019-02-11 07:42:30 +0000588 std::vector<CallBase *> RuntimeCalls;
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000589 InsertSafepointPoll(PollLocation, RuntimeCalls, TLI);
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000590 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
591 RuntimeCalls.end());
592 }
Sanjoy Das95639742016-01-22 21:02:55 +0000593
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000594 return Modified;
Philip Reames47cc6732015-02-04 00:37:33 +0000595}
596
597char PlaceBackedgeSafepointsImpl::ID = 0;
598char PlaceSafepoints::ID = 0;
599
Philip Reames7b981792015-05-12 21:21:18 +0000600FunctionPass *llvm::createPlaceSafepointsPass() {
601 return new PlaceSafepoints();
602}
Philip Reames47cc6732015-02-04 00:37:33 +0000603
604INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
605 "place-backedge-safepoints-impl",
606 "Place Backedge Safepoints", false, false)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000607INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Philip Reames57bdac92015-05-12 20:56:33 +0000608INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Philip Reames9f129042015-05-12 21:09:36 +0000609INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Philip Reames47cc6732015-02-04 00:37:33 +0000610INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
611 "place-backedge-safepoints-impl",
612 "Place Backedge Safepoints", false, false)
613
614INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
615 false, false)
616INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
617 false, false)
618
Philip Reames5a9685d2015-02-04 00:39:57 +0000619static void
Philip Reames388402452015-05-26 21:03:23 +0000620InsertSafepointPoll(Instruction *InsertBefore,
Chandler Carruth31607342019-02-11 07:42:30 +0000621 std::vector<CallBase *> &ParsePointsNeeded /*rval*/,
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000622 const TargetLibraryInfo &TLI) {
Philip Reames388402452015-05-26 21:03:23 +0000623 BasicBlock *OrigBB = InsertBefore->getParent();
624 Module *M = InsertBefore->getModule();
625 assert(M && "must be part of a module");
Philip Reames47cc6732015-02-04 00:37:33 +0000626
627 // Inline the safepoint poll implementation - this will get all the branch,
628 // control flow, etc.. Most importantly, it will introduce the actual slow
629 // path call - where we need to insert a safepoint (parsepoint).
Philip Reames388402452015-05-26 21:03:23 +0000630
631 auto *F = M->getFunction(GCSafepointPollName);
Manuel Jacobe3773d62015-12-29 21:57:55 +0000632 assert(F && "gc.safepoint_poll function is missing");
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000633 assert(F->getValueType() ==
Philip Reames388402452015-05-26 21:03:23 +0000634 FunctionType::get(Type::getVoidTy(M->getContext()), false) &&
635 "gc.safepoint_poll declared with wrong type");
Ramkumar Ramachandra3edf74f2015-02-09 23:02:10 +0000636 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
Philip Reames388402452015-05-26 21:03:23 +0000637 CallInst *PollCall = CallInst::Create(F, "", InsertBefore);
Philip Reames47cc6732015-02-04 00:37:33 +0000638
639 // Record some information about the call site we're replacing
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000640 BasicBlock::iterator Before(PollCall), After(PollCall);
641 bool IsBegin = false;
642 if (Before == OrigBB->begin())
643 IsBegin = true;
644 else
645 Before--;
Philip Reames47cc6732015-02-04 00:37:33 +0000646
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000647 After++;
648 assert(After != OrigBB->end() && "must have successor");
649
650 // Do the actual inlining
Philip Reames47cc6732015-02-04 00:37:33 +0000651 InlineFunctionInfo IFI;
Philip Reames388402452015-05-26 21:03:23 +0000652 bool InlineStatus = InlineFunction(PollCall, IFI);
653 assert(InlineStatus && "inline must succeed");
654 (void)InlineStatus; // suppress warning in release-asserts
Philip Reames47cc6732015-02-04 00:37:33 +0000655
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000656 // Check post-conditions
Philip Reames47cc6732015-02-04 00:37:33 +0000657 assert(IFI.StaticAllocas.empty() && "can't have allocs");
658
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000659 std::vector<CallInst *> Calls; // new calls
660 DenseSet<BasicBlock *> BBs; // new BBs + insertee
661
Philip Reames47cc6732015-02-04 00:37:33 +0000662 // Include only the newly inserted instructions, Note: begin may not be valid
663 // if we inserted to the beginning of the basic block
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000664 BasicBlock::iterator Start = IsBegin ? OrigBB->begin() : std::next(Before);
Philip Reames47cc6732015-02-04 00:37:33 +0000665
666 // If your poll function includes an unreachable at the end, that's not
667 // valid. Bugpoint likes to create this, so check for it.
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000668 assert(isPotentiallyReachable(&*Start, &*After) &&
Philip Reames47cc6732015-02-04 00:37:33 +0000669 "malformed poll function");
670
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000671 scanInlinedCode(&*Start, &*After, Calls, BBs);
672 assert(!Calls.empty() && "slow path not found for safepoint poll");
Philip Reames47cc6732015-02-04 00:37:33 +0000673
674 // Record the fact we need a parsable state at the runtime call contained in
675 // the poll function. This is required so that the runtime knows how to
676 // parse the last frame when we actually take the safepoint (i.e. execute
677 // the slow path)
678 assert(ParsePointsNeeded.empty());
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000679 for (auto *CI : Calls) {
Philip Reames47cc6732015-02-04 00:37:33 +0000680 // No safepoint needed or wanted
Daniel Neilson2574d7c2017-07-27 16:49:39 +0000681 if (!needsStatepoint(CI, TLI))
Philip Reames47cc6732015-02-04 00:37:33 +0000682 continue;
Philip Reames47cc6732015-02-04 00:37:33 +0000683
684 // These are likely runtime calls. Should we assert that via calling
685 // convention or something?
Chandler Carruth31607342019-02-11 07:42:30 +0000686 ParsePointsNeeded.push_back(CI);
Philip Reames47cc6732015-02-04 00:37:33 +0000687 }
Sanjoy Dascd23fec2016-01-28 23:03:19 +0000688 assert(ParsePointsNeeded.size() <= Calls.size());
Philip Reames47cc6732015-02-04 00:37:33 +0000689}