1 //===- PlaceSafepoints.cpp - Place GC Safepoints --------------------------===//
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 // Place garbage collection safepoints at appropriate locations in the IR. This
11 // does not make relocation semantics or variable liveness explicit. That's
12 // done by RewriteStatepointsForGC.
13 //
14 // Terminology:
15 // - A call is said to be "parseable" if there is a stack map generated for the
16 // return PC of the call. A runtime can determine where values listed in the
17 // deopt arguments and (after RewriteStatepointsForGC) gc arguments are located
18 // on the stack when the code is suspended inside such a call. Every parse
19 // point is represented by a call wrapped in an gc.statepoint intrinsic.
20 // - A "poll" is an explicit check in the generated code to determine if the
21 // runtime needs the generated code to cooperate by calling a helper routine
22 // and thus suspending its execution at a known state. The call to the helper
23 // routine will be parseable. The (gc & runtime specific) logic of a poll is
24 // assumed to be provided in a function of the name "gc.safepoint_poll".
25 //
26 // We aim to insert polls such that running code can quickly be brought to a
27 // well defined state for inspection by the collector. In the current
28 // implementation, this is done via the insertion of poll sites at method entry
29 // and the backedge of most loops. We try to avoid inserting more polls than
30 // are neccessary to ensure a finite period between poll sites. This is not
31 // because the poll itself is expensive in the generated code; it's not. Polls
32 // do tend to impact the optimizer itself in negative ways; we'd like to avoid
33 // perturbing the optimization of the method as much as we can.
34 //
35 // We also need to make most call sites parseable. The callee might execute a
36 // poll (or otherwise be inspected by the GC). If so, the entire stack
37 // (including the suspended frame of the current method) must be parseable.
38 //
39 // This pass will insert:
40 // - Call parse points ("call safepoints") for any call which may need to
41 // reach a safepoint during the execution of the callee function.
42 // - Backedge safepoint polls and entry safepoint polls to ensure that
43 // executing code reaches a safepoint poll in a finite amount of time.
44 //
45 // We do not currently support return statepoints, but adding them would not
46 // be hard. They are not required for correctness - entry safepoints are an
47 // alternative - but some GCs may prefer them. Patches welcome.
48 //
49 //===----------------------------------------------------------------------===//
50
51 #include "llvm/Pass.h"
52 #include "llvm/IR/LegacyPassManager.h"
53 #include "llvm/ADT/SetOperations.h"
54 #include "llvm/ADT/SetVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/StringRef.h"
57 #include "llvm/Analysis/LoopPass.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/ScalarEvolution.h"
60 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
61 #include "llvm/Analysis/CFG.h"
62 #include "llvm/Analysis/InstructionSimplify.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/CallSite.h"
65 #include "llvm/IR/Dominators.h"
66 #include "llvm/IR/Function.h"
67 #include "llvm/IR/IRBuilder.h"
68 #include "llvm/IR/InstIterator.h"
69 #include "llvm/IR/Instructions.h"
70 #include "llvm/IR/Intrinsics.h"
71 #include "llvm/IR/IntrinsicInst.h"
72 #include "llvm/IR/Module.h"
73 #include "llvm/IR/Statepoint.h"
74 #include "llvm/IR/Value.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/Support/Debug.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/raw_ostream.h"
79 #include "llvm/Transforms/Scalar.h"
80 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
81 #include "llvm/Transforms/Utils/Cloning.h"
82 #include "llvm/Transforms/Utils/Local.h"
83
84 #define DEBUG_TYPE "safepoint-placement"
85 STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
86 STATISTIC(NumCallSafepoints, "Number of call safepoints inserted");
87 STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
88
89 STATISTIC(CallInLoop, "Number of loops w/o safepoints due to calls in loop");
90 STATISTIC(FiniteExecution, "Number of loops w/o safepoints finite execution");
91
92 using namespace llvm;
93
94 // Ignore oppurtunities to avoid placing safepoints on backedges, useful for
95 // validation
96 static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
97 cl::init(false));
98
99 /// If true, do not place backedge safepoints in counted loops.
100 static cl::opt<bool> SkipCounted("spp-counted", cl::Hidden, cl::init(true));
101
102 // If true, split the backedge of a loop when placing the safepoint, otherwise
103 // split the latch block itself. Both are useful to support for
104 // experimentation, but in practice, it looks like splitting the backedge
105 // optimizes better.
106 static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
107 cl::init(false));
108
109 // Print tracing output
110 static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
111
112 namespace {
113
114 /// An analysis pass whose purpose is to identify each of the backedges in
115 /// the function which require a safepoint poll to be inserted.
116 struct PlaceBackedgeSafepointsImpl : public FunctionPass {
117 static char ID;
118
119 /// The output of the pass - gives a list of each backedge (described by
120 /// pointing at the branch) which need a poll inserted.
121 std::vector<TerminatorInst *> PollLocations;
122
123 /// True unless we're running spp-no-calls in which case we need to disable
124 /// the call dependend placement opts.
125 bool CallSafepointsEnabled;
126
127 ScalarEvolution *SE = nullptr;
128 DominatorTree *DT = nullptr;
129 LoopInfo *LI = nullptr;
130
PlaceBackedgeSafepointsImpl__anon4ed1fc630111::PlaceBackedgeSafepointsImpl131 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
132 : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
133 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
134 }
135
136 bool runOnLoop(Loop *);
runOnLoopAndSubLoops__anon4ed1fc630111::PlaceBackedgeSafepointsImpl137 void runOnLoopAndSubLoops(Loop *L) {
138 // Visit all the subloops
139 for (auto I = L->begin(), E = L->end(); I != E; I++)
140 runOnLoopAndSubLoops(*I);
141 runOnLoop(L);
142 }
143
runOnFunction__anon4ed1fc630111::PlaceBackedgeSafepointsImpl144 bool runOnFunction(Function &F) override {
145 SE = &getAnalysis<ScalarEvolution>();
146 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
147 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
148 for (auto I = LI->begin(), E = LI->end(); I != E; I++) {
149 runOnLoopAndSubLoops(*I);
150 }
151 return false;
152 }
153
getAnalysisUsage__anon4ed1fc630111::PlaceBackedgeSafepointsImpl154 void getAnalysisUsage(AnalysisUsage &AU) const override {
155 AU.addRequired<DominatorTreeWrapperPass>();
156 AU.addRequired<ScalarEvolution>();
157 AU.addRequired<LoopInfoWrapperPass>();
158 // We no longer modify the IR at all in this pass. Thus all
159 // analysis are preserved.
160 AU.setPreservesAll();
161 }
162 };
163 }
164
165 static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
166 static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
167 static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
168
169 namespace {
170 struct PlaceSafepoints : public FunctionPass {
171 static char ID; // Pass identification, replacement for typeid
172
PlaceSafepoints__anon4ed1fc630211::PlaceSafepoints173 PlaceSafepoints() : FunctionPass(ID) {
174 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
175 }
176 bool runOnFunction(Function &F) override;
177
getAnalysisUsage__anon4ed1fc630211::PlaceSafepoints178 void getAnalysisUsage(AnalysisUsage &AU) const override {
179 // We modify the graph wholesale (inlining, block insertion, etc). We
180 // preserve nothing at the moment. We could potentially preserve dom tree
181 // if that was worth doing
182 }
183 };
184 }
185
186 // Insert a safepoint poll immediately before the given instruction. Does
187 // not handle the parsability of state at the runtime call, that's the
188 // callers job.
189 static void
190 InsertSafepointPoll(Instruction *InsertBefore,
191 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
192
193 static bool isGCLeafFunction(const CallSite &CS);
194
needsStatepoint(const CallSite & CS)195 static bool needsStatepoint(const CallSite &CS) {
196 if (isGCLeafFunction(CS))
197 return false;
198 if (CS.isCall()) {
199 CallInst *call = cast<CallInst>(CS.getInstruction());
200 if (call->isInlineAsm())
201 return false;
202 }
203 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
204 return false;
205 }
206 return true;
207 }
208
209 static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P);
210
211 /// Returns true if this loop is known to contain a call safepoint which
212 /// must unconditionally execute on any iteration of the loop which returns
213 /// to the loop header via an edge from Pred. Returns a conservative correct
214 /// answer; i.e. false is always valid.
containsUnconditionalCallSafepoint(Loop * L,BasicBlock * Header,BasicBlock * Pred,DominatorTree & DT)215 static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
216 BasicBlock *Pred,
217 DominatorTree &DT) {
218 // In general, we're looking for any cut of the graph which ensures
219 // there's a call safepoint along every edge between Header and Pred.
220 // For the moment, we look only for the 'cuts' that consist of a single call
221 // instruction in a block which is dominated by the Header and dominates the
222 // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
223 // of such dominating blocks gets substaintially more occurences than just
224 // checking the Pred and Header blocks themselves. This may be due to the
225 // density of loop exit conditions caused by range and null checks.
226 // TODO: structure this as an analysis pass, cache the result for subloops,
227 // avoid dom tree recalculations
228 assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
229
230 BasicBlock *Current = Pred;
231 while (true) {
232 for (Instruction &I : *Current) {
233 if (auto CS = CallSite(&I))
234 // Note: Technically, needing a safepoint isn't quite the right
235 // condition here. We should instead be checking if the target method
236 // has an
237 // unconditional poll. In practice, this is only a theoretical concern
238 // since we don't have any methods with conditional-only safepoint
239 // polls.
240 if (needsStatepoint(CS))
241 return true;
242 }
243
244 if (Current == Header)
245 break;
246 Current = DT.getNode(Current)->getIDom()->getBlock();
247 }
248
249 return false;
250 }
251
252 /// Returns true if this loop is known to terminate in a finite number of
253 /// iterations. Note that this function may return false for a loop which
254 /// does actual terminate in a finite constant number of iterations due to
255 /// conservatism in the analysis.
mustBeFiniteCountedLoop(Loop * L,ScalarEvolution * SE,BasicBlock * Pred)256 static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
257 BasicBlock *Pred) {
258 // Only used when SkipCounted is off
259 const unsigned upperTripBound = 8192;
260
261 // A conservative bound on the loop as a whole.
262 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
263 if (MaxTrips != SE->getCouldNotCompute()) {
264 if (SE->getUnsignedRange(MaxTrips).getUnsignedMax().ult(upperTripBound))
265 return true;
266 if (SkipCounted &&
267 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(32))
268 return true;
269 }
270
271 // If this is a conditional branch to the header with the alternate path
272 // being outside the loop, we can ask questions about the execution frequency
273 // of the exit block.
274 if (L->isLoopExiting(Pred)) {
275 // This returns an exact expression only. TODO: We really only need an
276 // upper bound here, but SE doesn't expose that.
277 const SCEV *MaxExec = SE->getExitCount(L, Pred);
278 if (MaxExec != SE->getCouldNotCompute()) {
279 if (SE->getUnsignedRange(MaxExec).getUnsignedMax().ult(upperTripBound))
280 return true;
281 if (SkipCounted &&
282 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(32))
283 return true;
284 }
285 }
286
287 return /* not finite */ false;
288 }
289
scanOneBB(Instruction * start,Instruction * end,std::vector<CallInst * > & calls,std::set<BasicBlock * > & seen,std::vector<BasicBlock * > & worklist)290 static void scanOneBB(Instruction *start, Instruction *end,
291 std::vector<CallInst *> &calls,
292 std::set<BasicBlock *> &seen,
293 std::vector<BasicBlock *> &worklist) {
294 for (BasicBlock::iterator itr(start);
295 itr != start->getParent()->end() && itr != BasicBlock::iterator(end);
296 itr++) {
297 if (CallInst *CI = dyn_cast<CallInst>(&*itr)) {
298 calls.push_back(CI);
299 }
300 // FIXME: This code does not handle invokes
301 assert(!dyn_cast<InvokeInst>(&*itr) &&
302 "support for invokes in poll code needed");
303 // Only add the successor blocks if we reach the terminator instruction
304 // without encountering end first
305 if (itr->isTerminator()) {
306 BasicBlock *BB = itr->getParent();
307 for (BasicBlock *Succ : successors(BB)) {
308 if (seen.count(Succ) == 0) {
309 worklist.push_back(Succ);
310 seen.insert(Succ);
311 }
312 }
313 }
314 }
315 }
scanInlinedCode(Instruction * start,Instruction * end,std::vector<CallInst * > & calls,std::set<BasicBlock * > & seen)316 static void scanInlinedCode(Instruction *start, Instruction *end,
317 std::vector<CallInst *> &calls,
318 std::set<BasicBlock *> &seen) {
319 calls.clear();
320 std::vector<BasicBlock *> worklist;
321 seen.insert(start->getParent());
322 scanOneBB(start, end, calls, seen, worklist);
323 while (!worklist.empty()) {
324 BasicBlock *BB = worklist.back();
325 worklist.pop_back();
326 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
327 }
328 }
329
runOnLoop(Loop * L)330 bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) {
331 // Loop through all loop latches (branches controlling backedges). We need
332 // to place a safepoint on every backedge (potentially).
333 // Note: In common usage, there will be only one edge due to LoopSimplify
334 // having run sometime earlier in the pipeline, but this code must be correct
335 // w.r.t. loops with multiple backedges.
336 BasicBlock *header = L->getHeader();
337 SmallVector<BasicBlock*, 16> LoopLatches;
338 L->getLoopLatches(LoopLatches);
339 for (BasicBlock *pred : LoopLatches) {
340 assert(L->contains(pred));
341
342 // Make a policy decision about whether this loop needs a safepoint or
343 // not. Note that this is about unburdening the optimizer in loops, not
344 // avoiding the runtime cost of the actual safepoint.
345 if (!AllBackedges) {
346 if (mustBeFiniteCountedLoop(L, SE, pred)) {
347 if (TraceLSP)
348 errs() << "skipping safepoint placement in finite loop\n";
349 FiniteExecution++;
350 continue;
351 }
352 if (CallSafepointsEnabled &&
353 containsUnconditionalCallSafepoint(L, header, pred, *DT)) {
354 // Note: This is only semantically legal since we won't do any further
355 // IPO or inlining before the actual call insertion.. If we hadn't, we
356 // might latter loose this call safepoint.
357 if (TraceLSP)
358 errs() << "skipping safepoint placement due to unconditional call\n";
359 CallInLoop++;
360 continue;
361 }
362 }
363
364 // TODO: We can create an inner loop which runs a finite number of
365 // iterations with an outer loop which contains a safepoint. This would
366 // not help runtime performance that much, but it might help our ability to
367 // optimize the inner loop.
368
369 // Safepoint insertion would involve creating a new basic block (as the
370 // target of the current backedge) which does the safepoint (of all live
371 // variables) and branches to the true header
372 TerminatorInst *term = pred->getTerminator();
373
374 if (TraceLSP) {
375 errs() << "[LSP] terminator instruction: ";
376 term->dump();
377 }
378
379 PollLocations.push_back(term);
380 }
381
382 return false;
383 }
384
385 /// Returns true if an entry safepoint is not required before this callsite in
386 /// the caller function.
doesNotRequireEntrySafepointBefore(const CallSite & CS)387 static bool doesNotRequireEntrySafepointBefore(const CallSite &CS) {
388 Instruction *Inst = CS.getInstruction();
389 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
390 switch (II->getIntrinsicID()) {
391 case Intrinsic::experimental_gc_statepoint:
392 case Intrinsic::experimental_patchpoint_void:
393 case Intrinsic::experimental_patchpoint_i64:
394 // The can wrap an actual call which may grow the stack by an unbounded
395 // amount or run forever.
396 return false;
397 default:
398 // Most LLVM intrinsics are things which do not expand to actual calls, or
399 // at least if they do, are leaf functions that cause only finite stack
400 // growth. In particular, the optimizer likes to form things like memsets
401 // out of stores in the original IR. Another important example is
402 // llvm.localescape which must occur in the entry block. Inserting a
403 // safepoint before it is not legal since it could push the localescape
404 // out of the entry block.
405 return true;
406 }
407 }
408 return false;
409 }
410
findLocationForEntrySafepoint(Function & F,DominatorTree & DT)411 static Instruction *findLocationForEntrySafepoint(Function &F,
412 DominatorTree &DT) {
413
414 // Conceptually, this poll needs to be on method entry, but in
415 // practice, we place it as late in the entry block as possible. We
416 // can place it as late as we want as long as it dominates all calls
417 // that can grow the stack. This, combined with backedge polls,
418 // give us all the progress guarantees we need.
419
420 // hasNextInstruction and nextInstruction are used to iterate
421 // through a "straight line" execution sequence.
422
423 auto hasNextInstruction = [](Instruction *I) {
424 if (!I->isTerminator()) {
425 return true;
426 }
427 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
428 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
429 };
430
431 auto nextInstruction = [&hasNextInstruction](Instruction *I) {
432 assert(hasNextInstruction(I) &&
433 "first check if there is a next instruction!");
434 if (I->isTerminator()) {
435 return I->getParent()->getUniqueSuccessor()->begin();
436 } else {
437 return std::next(BasicBlock::iterator(I));
438 }
439 };
440
441 Instruction *cursor = nullptr;
442 for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor);
443 cursor = nextInstruction(cursor)) {
444
445 // We need to ensure a safepoint poll occurs before any 'real' call. The
446 // easiest way to ensure finite execution between safepoints in the face of
447 // recursive and mutually recursive functions is to enforce that each take
448 // a safepoint. Additionally, we need to ensure a poll before any call
449 // which can grow the stack by an unbounded amount. This isn't required
450 // for GC semantics per se, but is a common requirement for languages
451 // which detect stack overflow via guard pages and then throw exceptions.
452 if (auto CS = CallSite(cursor)) {
453 if (doesNotRequireEntrySafepointBefore(CS))
454 continue;
455 break;
456 }
457 }
458
459 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
460 "either we stopped because of a call, or because of terminator");
461
462 return cursor;
463 }
464
465 /// Identify the list of call sites which need to be have parseable state
findCallSafepoints(Function & F,std::vector<CallSite> & Found)466 static void findCallSafepoints(Function &F,
467 std::vector<CallSite> &Found /*rval*/) {
468 assert(Found.empty() && "must be empty!");
469 for (Instruction &I : inst_range(F)) {
470 Instruction *inst = &I;
471 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
472 CallSite CS(inst);
473
474 // No safepoint needed or wanted
475 if (!needsStatepoint(CS)) {
476 continue;
477 }
478
479 Found.push_back(CS);
480 }
481 }
482 }
483
484 /// Implement a unique function which doesn't require we sort the input
485 /// vector. Doing so has the effect of changing the output of a couple of
486 /// tests in ways which make them less useful in testing fused safepoints.
unique_unsorted(std::vector<T> & vec)487 template <typename T> static void unique_unsorted(std::vector<T> &vec) {
488 std::set<T> seen;
489 std::vector<T> tmp;
490 vec.reserve(vec.size());
491 std::swap(tmp, vec);
492 for (auto V : tmp) {
493 if (seen.insert(V).second) {
494 vec.push_back(V);
495 }
496 }
497 }
498
499 static const char *const GCSafepointPollName = "gc.safepoint_poll";
500
isGCSafepointPoll(Function & F)501 static bool isGCSafepointPoll(Function &F) {
502 return F.getName().equals(GCSafepointPollName);
503 }
504
505 /// Returns true if this function should be rewritten to include safepoint
506 /// polls and parseable call sites. The main point of this function is to be
507 /// an extension point for custom logic.
shouldRewriteFunction(Function & F)508 static bool shouldRewriteFunction(Function &F) {
509 // TODO: This should check the GCStrategy
510 if (F.hasGC()) {
511 const char *FunctionGCName = F.getGC();
512 const StringRef StatepointExampleName("statepoint-example");
513 const StringRef CoreCLRName("coreclr");
514 return (StatepointExampleName == FunctionGCName) ||
515 (CoreCLRName == FunctionGCName);
516 } else
517 return false;
518 }
519
520 // TODO: These should become properties of the GCStrategy, possibly with
521 // command line overrides.
enableEntrySafepoints(Function & F)522 static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
enableBackedgeSafepoints(Function & F)523 static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
enableCallSafepoints(Function & F)524 static bool enableCallSafepoints(Function &F) { return !NoCall; }
525
526 // Normalize basic block to make it ready to be target of invoke statepoint.
527 // Ensure that 'BB' does not have phi nodes. It may require spliting it.
normalizeForInvokeSafepoint(BasicBlock * BB,BasicBlock * InvokeParent)528 static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
529 BasicBlock *InvokeParent) {
530 BasicBlock *ret = BB;
531
532 if (!BB->getUniquePredecessor()) {
533 ret = SplitBlockPredecessors(BB, InvokeParent, "");
534 }
535
536 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
537 // from it
538 FoldSingleEntryPHINodes(ret);
539 assert(!isa<PHINode>(ret->begin()));
540
541 return ret;
542 }
543
runOnFunction(Function & F)544 bool PlaceSafepoints::runOnFunction(Function &F) {
545 if (F.isDeclaration() || F.empty()) {
546 // This is a declaration, nothing to do. Must exit early to avoid crash in
547 // dom tree calculation
548 return false;
549 }
550
551 if (isGCSafepointPoll(F)) {
552 // Given we're inlining this inside of safepoint poll insertion, this
553 // doesn't make any sense. Note that we do make any contained calls
554 // parseable after we inline a poll.
555 return false;
556 }
557
558 if (!shouldRewriteFunction(F))
559 return false;
560
561 bool modified = false;
562
563 // In various bits below, we rely on the fact that uses are reachable from
564 // defs. When there are basic blocks unreachable from the entry, dominance
565 // and reachablity queries return non-sensical results. Thus, we preprocess
566 // the function to ensure these properties hold.
567 modified |= removeUnreachableBlocks(F);
568
569 // STEP 1 - Insert the safepoint polling locations. We do not need to
570 // actually insert parse points yet. That will be done for all polls and
571 // calls in a single pass.
572
573 DominatorTree DT;
574 DT.recalculate(F);
575
576 SmallVector<Instruction *, 16> PollsNeeded;
577 std::vector<CallSite> ParsePointNeeded;
578
579 if (enableBackedgeSafepoints(F)) {
580 // Construct a pass manager to run the LoopPass backedge logic. We
581 // need the pass manager to handle scheduling all the loop passes
582 // appropriately. Doing this by hand is painful and just not worth messing
583 // with for the moment.
584 legacy::FunctionPassManager FPM(F.getParent());
585 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
586 PlaceBackedgeSafepointsImpl *PBS =
587 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
588 FPM.add(PBS);
589 FPM.run(F);
590
591 // We preserve dominance information when inserting the poll, otherwise
592 // we'd have to recalculate this on every insert
593 DT.recalculate(F);
594
595 auto &PollLocations = PBS->PollLocations;
596
597 auto OrderByBBName = [](Instruction *a, Instruction *b) {
598 return a->getParent()->getName() < b->getParent()->getName();
599 };
600 // We need the order of list to be stable so that naming ends up stable
601 // when we split edges. This makes test cases much easier to write.
602 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
603
604 // We can sometimes end up with duplicate poll locations. This happens if
605 // a single loop is visited more than once. The fact this happens seems
606 // wrong, but it does happen for the split-backedge.ll test case.
607 PollLocations.erase(std::unique(PollLocations.begin(),
608 PollLocations.end()),
609 PollLocations.end());
610
611 // Insert a poll at each point the analysis pass identified
612 // The poll location must be the terminator of a loop latch block.
613 for (TerminatorInst *Term : PollLocations) {
614 // We are inserting a poll, the function is modified
615 modified = true;
616
617 if (SplitBackedge) {
618 // Split the backedge of the loop and insert the poll within that new
619 // basic block. This creates a loop with two latches per original
620 // latch (which is non-ideal), but this appears to be easier to
621 // optimize in practice than inserting the poll immediately before the
622 // latch test.
623
624 // Since this is a latch, at least one of the successors must dominate
625 // it. Its possible that we have a) duplicate edges to the same header
626 // and b) edges to distinct loop headers. We need to insert pools on
627 // each.
628 SetVector<BasicBlock *> Headers;
629 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
630 BasicBlock *Succ = Term->getSuccessor(i);
631 if (DT.dominates(Succ, Term->getParent())) {
632 Headers.insert(Succ);
633 }
634 }
635 assert(!Headers.empty() && "poll location is not a loop latch?");
636
637 // The split loop structure here is so that we only need to recalculate
638 // the dominator tree once. Alternatively, we could just keep it up to
639 // date and use a more natural merged loop.
640 SetVector<BasicBlock *> SplitBackedges;
641 for (BasicBlock *Header : Headers) {
642 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
643 PollsNeeded.push_back(NewBB->getTerminator());
644 NumBackedgeSafepoints++;
645 }
646 } else {
647 // Split the latch block itself, right before the terminator.
648 PollsNeeded.push_back(Term);
649 NumBackedgeSafepoints++;
650 }
651 }
652 }
653
654 if (enableEntrySafepoints(F)) {
655 Instruction *Location = findLocationForEntrySafepoint(F, DT);
656 if (!Location) {
657 // policy choice not to insert?
658 } else {
659 PollsNeeded.push_back(Location);
660 modified = true;
661 NumEntrySafepoints++;
662 }
663 }
664
665 // Now that we've identified all the needed safepoint poll locations, insert
666 // safepoint polls themselves.
667 for (Instruction *PollLocation : PollsNeeded) {
668 std::vector<CallSite> RuntimeCalls;
669 InsertSafepointPoll(PollLocation, RuntimeCalls);
670 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
671 RuntimeCalls.end());
672 }
673 PollsNeeded.clear(); // make sure we don't accidentally use
674 // The dominator tree has been invalidated by the inlining performed in the
675 // above loop. TODO: Teach the inliner how to update the dom tree?
676 DT.recalculate(F);
677
678 if (enableCallSafepoints(F)) {
679 std::vector<CallSite> Calls;
680 findCallSafepoints(F, Calls);
681 NumCallSafepoints += Calls.size();
682 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
683 }
684
685 // Unique the vectors since we can end up with duplicates if we scan the call
686 // site for call safepoints after we add it for entry or backedge. The
687 // only reason we need tracking at all is that some functions might have
688 // polls but not call safepoints and thus we might miss marking the runtime
689 // calls for the polls. (This is useful in test cases!)
690 unique_unsorted(ParsePointNeeded);
691
692 // Any parse point (no matter what source) will be handled here
693
694 // We're about to start modifying the function
695 if (!ParsePointNeeded.empty())
696 modified = true;
697
698 // Now run through and insert the safepoints, but do _NOT_ update or remove
699 // any existing uses. We have references to live variables that need to
700 // survive to the last iteration of this loop.
701 std::vector<Value *> Results;
702 Results.reserve(ParsePointNeeded.size());
703 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
704 CallSite &CS = ParsePointNeeded[i];
705
706 // For invoke statepoints we need to remove all phi nodes at the normal
707 // destination block.
708 // Reason for this is that we can place gc_result only after last phi node
709 // in basic block. We will get malformed code after RAUW for the
710 // gc_result if one of this phi nodes uses result from the invoke.
711 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(CS.getInstruction())) {
712 normalizeForInvokeSafepoint(Invoke->getNormalDest(),
713 Invoke->getParent());
714 }
715
716 Value *GCResult = ReplaceWithStatepoint(CS, nullptr);
717 Results.push_back(GCResult);
718 }
719 assert(Results.size() == ParsePointNeeded.size());
720
721 // Adjust all users of the old call sites to use the new ones instead
722 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
723 CallSite &CS = ParsePointNeeded[i];
724 Value *GCResult = Results[i];
725 if (GCResult) {
726 // Can not RAUW for the invoke gc result in case of phi nodes preset.
727 assert(CS.isCall() || !isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin()));
728
729 // Replace all uses with the new call
730 CS.getInstruction()->replaceAllUsesWith(GCResult);
731 }
732
733 // Now that we've handled all uses, remove the original call itself
734 // Note: The insert point can't be the deleted instruction!
735 CS.getInstruction()->eraseFromParent();
736 }
737 return modified;
738 }
739
740 char PlaceBackedgeSafepointsImpl::ID = 0;
741 char PlaceSafepoints::ID = 0;
742
createPlaceSafepointsPass()743 FunctionPass *llvm::createPlaceSafepointsPass() {
744 return new PlaceSafepoints();
745 }
746
747 INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
748 "place-backedge-safepoints-impl",
749 "Place Backedge Safepoints", false, false)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)750 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
751 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
752 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
753 INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
754 "place-backedge-safepoints-impl",
755 "Place Backedge Safepoints", false, false)
756
757 INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
758 false, false)
759 INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
760 false, false)
761
762 static bool isGCLeafFunction(const CallSite &CS) {
763 Instruction *inst = CS.getInstruction();
764 if (isa<IntrinsicInst>(inst)) {
765 // Most LLVM intrinsics are things which can never take a safepoint.
766 // As a result, we don't need to have the stack parsable at the
767 // callsite. This is a highly useful optimization since intrinsic
768 // calls are fairly prevelent, particularly in debug builds.
769 return true;
770 }
771
772 // If this function is marked explicitly as a leaf call, we don't need to
773 // place a safepoint of it. In fact, for correctness we *can't* in many
774 // cases. Note: Indirect calls return Null for the called function,
775 // these obviously aren't runtime functions with attributes
776 // TODO: Support attributes on the call site as well.
777 const Function *F = CS.getCalledFunction();
778 bool isLeaf =
779 F &&
780 F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true");
781 if (isLeaf) {
782 return true;
783 }
784 return false;
785 }
786
787 static void
InsertSafepointPoll(Instruction * InsertBefore,std::vector<CallSite> & ParsePointsNeeded)788 InsertSafepointPoll(Instruction *InsertBefore,
789 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
790 BasicBlock *OrigBB = InsertBefore->getParent();
791 Module *M = InsertBefore->getModule();
792 assert(M && "must be part of a module");
793
794 // Inline the safepoint poll implementation - this will get all the branch,
795 // control flow, etc.. Most importantly, it will introduce the actual slow
796 // path call - where we need to insert a safepoint (parsepoint).
797
798 auto *F = M->getFunction(GCSafepointPollName);
799 assert(F->getType()->getElementType() ==
800 FunctionType::get(Type::getVoidTy(M->getContext()), false) &&
801 "gc.safepoint_poll declared with wrong type");
802 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
803 CallInst *PollCall = CallInst::Create(F, "", InsertBefore);
804
805 // Record some information about the call site we're replacing
806 BasicBlock::iterator before(PollCall), after(PollCall);
807 bool isBegin(false);
808 if (before == OrigBB->begin()) {
809 isBegin = true;
810 } else {
811 before--;
812 }
813 after++;
814 assert(after != OrigBB->end() && "must have successor");
815
816 // do the actual inlining
817 InlineFunctionInfo IFI;
818 bool InlineStatus = InlineFunction(PollCall, IFI);
819 assert(InlineStatus && "inline must succeed");
820 (void)InlineStatus; // suppress warning in release-asserts
821
822 // Check post conditions
823 assert(IFI.StaticAllocas.empty() && "can't have allocs");
824
825 std::vector<CallInst *> calls; // new calls
826 std::set<BasicBlock *> BBs; // new BBs + insertee
827 // Include only the newly inserted instructions, Note: begin may not be valid
828 // if we inserted to the beginning of the basic block
829 BasicBlock::iterator start;
830 if (isBegin) {
831 start = OrigBB->begin();
832 } else {
833 start = before;
834 start++;
835 }
836
837 // If your poll function includes an unreachable at the end, that's not
838 // valid. Bugpoint likes to create this, so check for it.
839 assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) &&
840 "malformed poll function");
841
842 scanInlinedCode(&*(start), &*(after), calls, BBs);
843 assert(!calls.empty() && "slow path not found for safepoint poll");
844
845 // Record the fact we need a parsable state at the runtime call contained in
846 // the poll function. This is required so that the runtime knows how to
847 // parse the last frame when we actually take the safepoint (i.e. execute
848 // the slow path)
849 assert(ParsePointsNeeded.empty());
850 for (size_t i = 0; i < calls.size(); i++) {
851
852 // No safepoint needed or wanted
853 if (!needsStatepoint(calls[i])) {
854 continue;
855 }
856
857 // These are likely runtime calls. Should we assert that via calling
858 // convention or something?
859 ParsePointsNeeded.push_back(CallSite(calls[i]));
860 }
861 assert(ParsePointsNeeded.size() <= calls.size());
862 }
863
864 /// Replaces the given call site (Call or Invoke) with a gc.statepoint
865 /// intrinsic with an empty deoptimization arguments list. This does
866 /// NOT do explicit relocation for GC support.
ReplaceWithStatepoint(const CallSite & CS,Pass * P)867 static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */
868 Pass *P) {
869 assert(CS.getInstruction()->getParent()->getParent()->getParent() &&
870 "must be set");
871
872 // TODO: technically, a pass is not allowed to get functions from within a
873 // function pass since it might trigger a new function addition. Refactor
874 // this logic out to the initialization of the pass. Doesn't appear to
875 // matter in practice.
876
877 // Then go ahead and use the builder do actually do the inserts. We insert
878 // immediately before the previous instruction under the assumption that all
879 // arguments will be available here. We can't insert afterwards since we may
880 // be replacing a terminator.
881 IRBuilder<> Builder(CS.getInstruction());
882
883 // Note: The gc args are not filled in at this time, that's handled by
884 // RewriteStatepointsForGC (which is currently under review).
885
886 // Create the statepoint given all the arguments
887 Instruction *Token = nullptr;
888
889 uint64_t ID;
890 uint32_t NumPatchBytes;
891
892 AttributeSet OriginalAttrs = CS.getAttributes();
893 Attribute AttrID =
894 OriginalAttrs.getAttribute(AttributeSet::FunctionIndex, "statepoint-id");
895 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
896 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
897
898 AttrBuilder AttrsToRemove;
899 bool HasID = AttrID.isStringAttribute() &&
900 !AttrID.getValueAsString().getAsInteger(10, ID);
901
902 if (HasID)
903 AttrsToRemove.addAttribute("statepoint-id");
904 else
905 ID = 0xABCDEF00;
906
907 bool HasNumPatchBytes =
908 AttrNumPatchBytes.isStringAttribute() &&
909 !AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
910
911 if (HasNumPatchBytes)
912 AttrsToRemove.addAttribute("statepoint-num-patch-bytes");
913 else
914 NumPatchBytes = 0;
915
916 OriginalAttrs = OriginalAttrs.removeAttributes(
917 CS.getInstruction()->getContext(), AttributeSet::FunctionIndex,
918 AttrsToRemove);
919
920 Value *StatepointTarget = NumPatchBytes == 0
921 ? CS.getCalledValue()
922 : ConstantPointerNull::get(cast<PointerType>(
923 CS.getCalledValue()->getType()));
924
925 if (CS.isCall()) {
926 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
927 CallInst *Call = Builder.CreateGCStatepointCall(
928 ID, NumPatchBytes, StatepointTarget,
929 makeArrayRef(CS.arg_begin(), CS.arg_end()), None, None,
930 "safepoint_token");
931 Call->setTailCall(ToReplace->isTailCall());
932 Call->setCallingConv(ToReplace->getCallingConv());
933
934 // In case if we can handle this set of attributes - set up function
935 // attributes directly on statepoint and return attributes later for
936 // gc_result intrinsic.
937 Call->setAttributes(OriginalAttrs.getFnAttributes());
938
939 Token = Call;
940
941 // Put the following gc_result and gc_relocate calls immediately after the
942 // the old call (which we're about to delete).
943 assert(ToReplace->getNextNode() && "not a terminator, must have next");
944 Builder.SetInsertPoint(ToReplace->getNextNode());
945 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
946 } else if (CS.isInvoke()) {
947 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
948
949 // Insert the new invoke into the old block. We'll remove the old one in a
950 // moment at which point this will become the new terminator for the
951 // original block.
952 Builder.SetInsertPoint(ToReplace->getParent());
953 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
954 ID, NumPatchBytes, StatepointTarget, ToReplace->getNormalDest(),
955 ToReplace->getUnwindDest(), makeArrayRef(CS.arg_begin(), CS.arg_end()),
956 None, None, "safepoint_token");
957
958 Invoke->setCallingConv(ToReplace->getCallingConv());
959
960 // In case if we can handle this set of attributes - set up function
961 // attributes directly on statepoint and return attributes later for
962 // gc_result intrinsic.
963 Invoke->setAttributes(OriginalAttrs.getFnAttributes());
964
965 Token = Invoke;
966
967 // We'll insert the gc.result into the normal block
968 BasicBlock *NormalDest = ToReplace->getNormalDest();
969 // Can not insert gc.result in case of phi nodes preset.
970 // Should have removed this cases prior to runnning this function
971 assert(!isa<PHINode>(NormalDest->begin()));
972 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
973 Builder.SetInsertPoint(IP);
974 } else {
975 llvm_unreachable("unexpect type of CallSite");
976 }
977 assert(Token);
978
979 // Handle the return value of the original call - update all uses to use a
980 // gc_result hanging off the statepoint node we just inserted
981
982 // Only add the gc_result iff there is actually a used result
983 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
984 std::string TakenName =
985 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
986 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), TakenName);
987 GCResult->setAttributes(OriginalAttrs.getRetAttributes());
988 return GCResult;
989 } else {
990 // No return value for the call.
991 return nullptr;
992 }
993 }
994