1 //===- PlaceSafepoints.cpp - Place GC Safepoints --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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".
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.
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.
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.
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.
49 //===----------------------------------------------------------------------===//
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/Analysis/LoopPass.h"
57 #include "llvm/Analysis/LoopInfo.h"
58 #include "llvm/Analysis/ScalarEvolution.h"
59 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
60 #include "llvm/Analysis/CFG.h"
61 #include "llvm/Analysis/InstructionSimplify.h"
62 #include "llvm/IR/BasicBlock.h"
63 #include "llvm/IR/CallSite.h"
64 #include "llvm/IR/Dominators.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/InstIterator.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Intrinsics.h"
70 #include "llvm/IR/IntrinsicInst.h"
71 #include "llvm/IR/Module.h"
72 #include "llvm/IR/Statepoint.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/Verifier.h"
75 #include "llvm/Support/Debug.h"
76 #include "llvm/Support/CommandLine.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/Scalar.h"
79 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
80 #include "llvm/Transforms/Utils/Cloning.h"
81 #include "llvm/Transforms/Utils/Local.h"
83 #define DEBUG_TYPE "safepoint-placement"
84 STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
85 STATISTIC(NumCallSafepoints, "Number of call safepoints inserted");
86 STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
88 STATISTIC(CallInLoop, "Number of loops w/o safepoints due to calls in loop");
89 STATISTIC(FiniteExecution, "Number of loops w/o safepoints finite execution");
93 // Ignore oppurtunities to avoid placing safepoints on backedges, useful for
95 static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
98 /// If true, do not place backedge safepoints in counted loops.
99 static cl::opt<bool> SkipCounted("spp-counted", cl::Hidden, cl::init(true));
101 // If true, split the backedge of a loop when placing the safepoint, otherwise
102 // split the latch block itself. Both are useful to support for
103 // experimentation, but in practice, it looks like splitting the backedge
105 static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
108 // Print tracing output
109 static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
113 /** An analysis pass whose purpose is to identify each of the backedges in
114 the function which require a safepoint poll to be inserted. */
115 struct PlaceBackedgeSafepointsImpl : public LoopPass {
118 /// The output of the pass - gives a list of each backedge (described by
119 /// pointing at the branch) which need a poll inserted.
120 std::vector<TerminatorInst *> PollLocations;
122 /// True unless we're running spp-no-calls in which case we need to disable
123 /// the call dependend placement opts.
124 bool CallSafepointsEnabled;
125 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
126 : LoopPass(ID), CallSafepointsEnabled(CallSafepoints) {
127 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
130 bool runOnLoop(Loop *, LPPassManager &LPM) override;
132 void getAnalysisUsage(AnalysisUsage &AU) const override {
133 AU.addRequired<DominatorTreeWrapperPass>();
134 AU.addRequired<ScalarEvolution>();
135 // We no longer modify the IR at all in this pass. Thus all
136 // analysis are preserved.
137 AU.setPreservesAll();
142 static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
143 static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
144 static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
147 struct PlaceSafepoints : public ModulePass {
148 static char ID; // Pass identification, replacement for typeid
150 PlaceSafepoints() : ModulePass(ID) {
151 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
153 bool runOnModule(Module &M) override {
154 bool modified = false;
155 for (Function &F : M) {
156 modified |= runOnFunction(F);
160 bool runOnFunction(Function &F);
162 void getAnalysisUsage(AnalysisUsage &AU) const override {
163 // We modify the graph wholesale (inlining, block insertion, etc). We
164 // preserve nothing at the moment. We could potentially preserve dom tree
165 // if that was worth doing
170 // Insert a safepoint poll immediately before the given instruction. Does
171 // not handle the parsability of state at the runtime call, that's the
174 InsertSafepointPoll(DominatorTree &DT, Instruction *after,
175 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
177 static bool isGCLeafFunction(const CallSite &CS);
179 static bool needsStatepoint(const CallSite &CS) {
180 if (isGCLeafFunction(CS))
183 CallInst *call = cast<CallInst>(CS.getInstruction());
184 if (call->isInlineAsm())
187 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
193 static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P);
195 /// Returns true if this loop is known to contain a call safepoint which
196 /// must unconditionally execute on any iteration of the loop which returns
197 /// to the loop header via an edge from Pred. Returns a conservative correct
198 /// answer; i.e. false is always valid.
199 static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
202 // 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
207 // of such dominating blocks gets substaintially more occurences than just
208 // 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?");
214 BasicBlock *Current = Pred;
216 for (Instruction &I : *Current) {
217 if (auto CS = CallSite(&I))
218 // Note: Technically, needing a safepoint isn't quite the right
219 // condition here. We should instead be checking if the target method
221 // unconditional poll. In practice, this is only a theoretical concern
222 // since we don't have any methods with conditional-only safepoint
224 if (needsStatepoint(CS))
228 if (Current == Header)
230 Current = DT.getNode(Current)->getIDom()->getBlock();
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.
240 static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
242 // Only used when SkipCounted is off
243 const unsigned upperTripBound = 8192;
245 // A conservative bound on the loop as a whole.
246 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
247 if (MaxTrips != SE->getCouldNotCompute()) {
248 if (SE->getUnsignedRange(MaxTrips).getUnsignedMax().ult(upperTripBound))
251 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(32))
255 // If this is a conditional branch to the header with the alternate path
256 // being outside the loop, we can ask questions about the execution frequency
257 // of the exit block.
258 if (L->isLoopExiting(Pred)) {
259 // This returns an exact expression only. TODO: We really only need an
260 // upper bound here, but SE doesn't expose that.
261 const SCEV *MaxExec = SE->getExitCount(L, Pred);
262 if (MaxExec != SE->getCouldNotCompute()) {
263 if (SE->getUnsignedRange(MaxExec).getUnsignedMax().ult(upperTripBound))
266 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(32))
271 return /* not finite */ false;
274 static void scanOneBB(Instruction *start, Instruction *end,
275 std::vector<CallInst *> &calls,
276 std::set<BasicBlock *> &seen,
277 std::vector<BasicBlock *> &worklist) {
278 for (BasicBlock::iterator itr(start);
279 itr != start->getParent()->end() && itr != BasicBlock::iterator(end);
281 if (CallInst *CI = dyn_cast<CallInst>(&*itr)) {
284 // FIXME: This code does not handle invokes
285 assert(!dyn_cast<InvokeInst>(&*itr) &&
286 "support for invokes in poll code needed");
287 // Only add the successor blocks if we reach the terminator instruction
288 // without encountering end first
289 if (itr->isTerminator()) {
290 BasicBlock *BB = itr->getParent();
291 for (BasicBlock *Succ : successors(BB)) {
292 if (seen.count(Succ) == 0) {
293 worklist.push_back(Succ);
300 static void scanInlinedCode(Instruction *start, Instruction *end,
301 std::vector<CallInst *> &calls,
302 std::set<BasicBlock *> &seen) {
304 std::vector<BasicBlock *> worklist;
305 seen.insert(start->getParent());
306 scanOneBB(start, end, calls, seen, worklist);
307 while (!worklist.empty()) {
308 BasicBlock *BB = worklist.back();
310 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
314 bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L, LPPassManager &LPM) {
315 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>();
316 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
318 // Loop through all loop latches (branches controlling backedges). We need
319 // to place a safepoint on every backedge (potentially).
320 // Note: In common usage, there will be only one edge due to LoopSimplify
321 // having run sometime earlier in the pipeline, but this code must be correct
322 // w.r.t. loops with multiple backedges.
323 BasicBlock *header = L->getHeader();
325 SmallVector<BasicBlock*, 16> LoopLatches;
326 L->getLoopLatches(LoopLatches);
327 for (BasicBlock *pred : LoopLatches) {
328 assert(L->contains(pred));
330 // Make a policy decision about whether this loop needs a safepoint or
331 // not. Note that this is about unburdening the optimizer in loops, not
332 // avoiding the runtime cost of the actual safepoint.
334 if (mustBeFiniteCountedLoop(L, SE, pred)) {
336 errs() << "skipping safepoint placement in finite loop\n";
340 if (CallSafepointsEnabled &&
341 containsUnconditionalCallSafepoint(L, header, pred, *DT)) {
342 // Note: This is only semantically legal since we won't do any further
343 // IPO or inlining before the actual call insertion.. If we hadn't, we
344 // might latter loose this call safepoint.
346 errs() << "skipping safepoint placement due to unconditional call\n";
352 // TODO: We can create an inner loop which runs a finite number of
353 // iterations with an outer loop which contains a safepoint. This would
354 // not help runtime performance that much, but it might help our ability to
355 // optimize the inner loop.
357 // Safepoint insertion would involve creating a new basic block (as the
358 // target of the current backedge) which does the safepoint (of all live
359 // variables) and branches to the true header
360 TerminatorInst *term = pred->getTerminator();
363 errs() << "[LSP] terminator instruction: ";
367 PollLocations.push_back(term);
373 static Instruction *findLocationForEntrySafepoint(Function &F,
376 // Conceptually, this poll needs to be on method entry, but in
377 // practice, we place it as late in the entry block as possible. We
378 // can place it as late as we want as long as it dominates all calls
379 // that can grow the stack. This, combined with backedge polls,
380 // give us all the progress guarantees we need.
382 // Due to the way the frontend generates IR, we may have a couple of initial
383 // basic blocks before the first bytecode. These will be single-entry
384 // single-exit blocks which conceptually are just part of the first 'real
385 // basic block'. Since we don't have deopt state until the first bytecode,
386 // walk forward until we've found the first unconditional branch or merge.
388 // hasNextInstruction and nextInstruction are used to iterate
389 // through a "straight line" execution sequence.
391 auto hasNextInstruction = [](Instruction *I) {
392 if (!I->isTerminator()) {
395 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
396 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
399 auto nextInstruction = [&hasNextInstruction](Instruction *I) {
400 assert(hasNextInstruction(I) &&
401 "first check if there is a next instruction!");
402 if (I->isTerminator()) {
403 return I->getParent()->getUniqueSuccessor()->begin();
405 return std::next(BasicBlock::iterator(I));
409 Instruction *cursor = nullptr;
410 for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor);
411 cursor = nextInstruction(cursor)) {
413 // We need to stop going forward as soon as we see a call that can
414 // grow the stack (i.e. the call target has a non-zero frame
416 if (CallSite(cursor)) {
417 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(cursor)) {
418 // llvm.assume(...) are not really calls.
419 if (II->getIntrinsicID() == Intrinsic::assume) {
422 // llvm.frameescape() intrinsic is not a real call. The intrinsic can
423 // exist only in the entry block.
424 // Inserting a statepoint before llvm.frameescape() may split the
425 // entry block, and push the intrinsic out of the entry block.
426 if (II->getIntrinsicID() == Intrinsic::frameescape) {
434 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
435 "either we stopped because of a call, or because of terminator");
437 if (cursor->isTerminator()) {
441 BasicBlock *BB = cursor->getParent();
442 SplitBlock(BB, cursor, nullptr);
444 // Note: SplitBlock modifies the DT. Simply passing a Pass (which is a
445 // module pass) is not enough.
448 // SplitBlock updates the DT
449 DEBUG(DT.verifyDomTree());
451 return BB->getTerminator();
454 /// Identify the list of call sites which need to be have parseable state
455 static void findCallSafepoints(Function &F,
456 std::vector<CallSite> &Found /*rval*/) {
457 assert(Found.empty() && "must be empty!");
458 for (Instruction &I : inst_range(F)) {
459 Instruction *inst = &I;
460 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
463 // No safepoint needed or wanted
464 if (!needsStatepoint(CS)) {
473 /// Implement a unique function which doesn't require we sort the input
474 /// vector. Doing so has the effect of changing the output of a couple of
475 /// tests in ways which make them less useful in testing fused safepoints.
476 template <typename T> static void unique_unsorted(std::vector<T> &vec) {
479 vec.reserve(vec.size());
482 if (seen.insert(V).second) {
488 static std::string GCSafepointPollName("gc.safepoint_poll");
490 static bool isGCSafepointPoll(Function &F) {
491 return F.getName().equals(GCSafepointPollName);
494 /// Returns true if this function should be rewritten to include safepoint
495 /// polls and parseable call sites. The main point of this function is to be
496 /// an extension point for custom logic.
497 static bool shouldRewriteFunction(Function &F) {
498 // TODO: This should check the GCStrategy
500 const std::string StatepointExampleName("statepoint-example");
501 return StatepointExampleName == F.getGC();
506 // TODO: These should become properties of the GCStrategy, possibly with
507 // command line overrides.
508 static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
509 static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
510 static bool enableCallSafepoints(Function &F) { return !NoCall; }
512 // Normalize basic block to make it ready to be target of invoke statepoint.
513 // Ensure that 'BB' does not have phi nodes. It may require spliting it.
514 static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
515 BasicBlock *InvokeParent) {
516 BasicBlock *ret = BB;
518 if (!BB->getUniquePredecessor()) {
519 ret = SplitBlockPredecessors(BB, InvokeParent, "");
522 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
524 FoldSingleEntryPHINodes(ret);
525 assert(!isa<PHINode>(ret->begin()));
530 bool PlaceSafepoints::runOnFunction(Function &F) {
531 if (F.isDeclaration() || F.empty()) {
532 // This is a declaration, nothing to do. Must exit early to avoid crash in
533 // dom tree calculation
537 if (isGCSafepointPoll(F)) {
538 // Given we're inlining this inside of safepoint poll insertion, this
539 // doesn't make any sense. Note that we do make any contained calls
540 // parseable after we inline a poll.
544 if (!shouldRewriteFunction(F))
547 bool modified = false;
549 // In various bits below, we rely on the fact that uses are reachable from
550 // defs. When there are basic blocks unreachable from the entry, dominance
551 // and reachablity queries return non-sensical results. Thus, we preprocess
552 // the function to ensure these properties hold.
553 modified |= removeUnreachableBlocks(F);
555 // STEP 1 - Insert the safepoint polling locations. We do not need to
556 // actually insert parse points yet. That will be done for all polls and
557 // calls in a single pass.
559 // Note: With the migration, we need to recompute this for each 'pass'. Once
560 // we merge these, we'll do it once before the analysis
563 std::vector<CallSite> ParsePointNeeded;
565 if (enableBackedgeSafepoints(F)) {
566 // Construct a pass manager to run the LoopPass backedge logic. We
567 // need the pass manager to handle scheduling all the loop passes
568 // appropriately. Doing this by hand is painful and just not worth messing
569 // with for the moment.
570 legacy::FunctionPassManager FPM(F.getParent());
571 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
572 PlaceBackedgeSafepointsImpl *PBS =
573 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
577 // We preserve dominance information when inserting the poll, otherwise
578 // we'd have to recalculate this on every insert
581 auto &PollLocations = PBS->PollLocations;
583 auto OrderByBBName = [](Instruction *a, Instruction *b) {
584 return a->getParent()->getName() < b->getParent()->getName();
586 // We need the order of list to be stable so that naming ends up stable
587 // when we split edges. This makes test cases much easier to write.
588 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
590 // We can sometimes end up with duplicate poll locations. This happens if
591 // a single loop is visited more than once. The fact this happens seems
592 // wrong, but it does happen for the split-backedge.ll test case.
593 PollLocations.erase(std::unique(PollLocations.begin(),
594 PollLocations.end()),
595 PollLocations.end());
597 // Insert a poll at each point the analysis pass identified
598 for (size_t i = 0; i < PollLocations.size(); i++) {
599 // We are inserting a poll, the function is modified
602 // The poll location must be the terminator of a loop latch block.
603 TerminatorInst *Term = PollLocations[i];
605 std::vector<CallSite> ParsePoints;
607 // Split the backedge of the loop and insert the poll within that new
608 // basic block. This creates a loop with two latches per original
609 // latch (which is non-ideal), but this appears to be easier to
610 // optimize in practice than inserting the poll immediately before the
613 // Since this is a latch, at least one of the successors must dominate
614 // it. Its possible that we have a) duplicate edges to the same header
615 // and b) edges to distinct loop headers. We need to insert pools on
617 SetVector<BasicBlock *> Headers;
618 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
619 BasicBlock *Succ = Term->getSuccessor(i);
620 if (DT.dominates(Succ, Term->getParent())) {
621 Headers.insert(Succ);
624 assert(!Headers.empty() && "poll location is not a loop latch?");
626 // The split loop structure here is so that we only need to recalculate
627 // the dominator tree once. Alternatively, we could just keep it up to
628 // date and use a more natural merged loop.
629 SetVector<BasicBlock *> SplitBackedges;
630 for (BasicBlock *Header : Headers) {
631 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, nullptr);
632 SplitBackedges.insert(NewBB);
635 for (BasicBlock *NewBB : SplitBackedges) {
636 std::vector<CallSite> RuntimeCalls;
637 InsertSafepointPoll(DT, NewBB->getTerminator(), RuntimeCalls);
638 NumBackedgeSafepoints++;
639 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
644 // Split the latch block itself, right before the terminator.
645 std::vector<CallSite> RuntimeCalls;
646 InsertSafepointPoll(DT, Term, RuntimeCalls);
647 NumBackedgeSafepoints++;
648 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
652 // Record the parse points for later use
653 ParsePointNeeded.insert(ParsePointNeeded.end(), ParsePoints.begin(),
658 if (enableEntrySafepoints(F)) {
660 Instruction *term = findLocationForEntrySafepoint(F, DT);
662 // policy choice not to insert?
664 std::vector<CallSite> RuntimeCalls;
665 InsertSafepointPoll(DT, term, RuntimeCalls);
667 NumEntrySafepoints++;
668 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
673 if (enableCallSafepoints(F)) {
675 std::vector<CallSite> Calls;
676 findCallSafepoints(F, Calls);
677 NumCallSafepoints += Calls.size();
678 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
681 // Unique the vectors since we can end up with duplicates if we scan the call
682 // site for call safepoints after we add it for entry or backedge. The
683 // only reason we need tracking at all is that some functions might have
684 // polls but not call safepoints and thus we might miss marking the runtime
685 // calls for the polls. (This is useful in test cases!)
686 unique_unsorted(ParsePointNeeded);
688 // Any parse point (no matter what source) will be handled here
689 DT.recalculate(F); // Needed?
691 // We're about to start modifying the function
692 if (!ParsePointNeeded.empty())
695 // Now run through and insert the safepoints, but do _NOT_ update or remove
696 // any existing uses. We have references to live variables that need to
697 // survive to the last iteration of this loop.
698 std::vector<Value *> Results;
699 Results.reserve(ParsePointNeeded.size());
700 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
701 CallSite &CS = ParsePointNeeded[i];
703 // For invoke statepoints we need to remove all phi nodes at the normal
704 // destination block.
705 // Reason for this is that we can place gc_result only after last phi node
706 // in basic block. We will get malformed code after RAUW for the
707 // gc_result if one of this phi nodes uses result from the invoke.
708 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(CS.getInstruction())) {
709 normalizeForInvokeSafepoint(Invoke->getNormalDest(),
710 Invoke->getParent());
713 Value *GCResult = ReplaceWithStatepoint(CS, nullptr);
714 Results.push_back(GCResult);
716 assert(Results.size() == ParsePointNeeded.size());
718 // Adjust all users of the old call sites to use the new ones instead
719 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
720 CallSite &CS = ParsePointNeeded[i];
721 Value *GCResult = Results[i];
723 // Can not RAUW for the gc result in case of phi nodes preset.
724 assert(!isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin()));
726 // Replace all uses with the new call
727 CS.getInstruction()->replaceAllUsesWith(GCResult);
730 // Now that we've handled all uses, remove the original call itself
731 // Note: The insert point can't be the deleted instruction!
732 CS.getInstruction()->eraseFromParent();
737 char PlaceBackedgeSafepointsImpl::ID = 0;
738 char PlaceSafepoints::ID = 0;
740 ModulePass *llvm::createPlaceSafepointsPass() { return new PlaceSafepoints(); }
742 INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
743 "place-backedge-safepoints-impl",
744 "Place Backedge Safepoints", false, false)
745 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
746 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
747 INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
748 "place-backedge-safepoints-impl",
749 "Place Backedge Safepoints", false, false)
751 INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
753 INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
756 static bool isGCLeafFunction(const CallSite &CS) {
757 Instruction *inst = CS.getInstruction();
758 if (isa<IntrinsicInst>(inst)) {
759 // Most LLVM intrinsics are things which can never take a safepoint.
760 // As a result, we don't need to have the stack parsable at the
761 // callsite. This is a highly useful optimization since intrinsic
762 // calls are fairly prevelent, particularly in debug builds.
766 // If this function is marked explicitly as a leaf call, we don't need to
767 // place a safepoint of it. In fact, for correctness we *can't* in many
768 // cases. Note: Indirect calls return Null for the called function,
769 // these obviously aren't runtime functions with attributes
770 // TODO: Support attributes on the call site as well.
771 const Function *F = CS.getCalledFunction();
774 F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true");
782 InsertSafepointPoll(DominatorTree &DT, Instruction *term,
783 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
784 Module *M = term->getParent()->getParent()->getParent();
787 // Inline the safepoint poll implementation - this will get all the branch,
788 // control flow, etc.. Most importantly, it will introduce the actual slow
789 // path call - where we need to insert a safepoint (parsepoint).
790 FunctionType *ftype =
791 FunctionType::get(Type::getVoidTy(M->getContext()), false);
792 assert(ftype && "null?");
793 // Note: This cast can fail if there's a function of the same name with a
794 // different type inserted previously
796 dyn_cast<Function>(M->getOrInsertFunction("gc.safepoint_poll", ftype));
797 assert(F && "void @gc.safepoint_poll() must be defined");
798 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
799 CallInst *poll = CallInst::Create(F, "", term);
801 // Record some information about the call site we're replacing
802 BasicBlock *OrigBB = term->getParent();
803 BasicBlock::iterator before(poll), after(poll);
805 if (before == term->getParent()->begin()) {
811 assert(after != poll->getParent()->end() && "must have successor");
812 assert(DT.dominates(before, after) && "trivially true");
814 // do the actual inlining
815 InlineFunctionInfo IFI;
816 bool inlineStatus = InlineFunction(poll, IFI);
817 assert(inlineStatus && "inline must succeed");
818 (void)inlineStatus; // suppress warning in release-asserts
820 // Check post conditions
821 assert(IFI.StaticAllocas.empty() && "can't have allocs");
823 std::vector<CallInst *> calls; // new calls
824 std::set<BasicBlock *> BBs; // new BBs + insertee
825 // Include only the newly inserted instructions, Note: begin may not be valid
826 // if we inserted to the beginning of the basic block
827 BasicBlock::iterator start;
829 start = OrigBB->begin();
835 // If your poll function includes an unreachable at the end, that's not
836 // valid. Bugpoint likes to create this, so check for it.
837 assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) &&
838 "malformed poll function");
840 scanInlinedCode(&*(start), &*(after), calls, BBs);
842 // Recompute since we've invalidated cached data. Conceptually we
843 // shouldn't need to do this, but implementation wise we appear to. Needed
844 // so we can insert safepoints correctly.
845 // TODO: update more cheaply
846 DT.recalculate(*after->getParent()->getParent());
848 assert(!calls.empty() && "slow path not found for safepoint poll");
850 // Record the fact we need a parsable state at the runtime call contained in
851 // the poll function. This is required so that the runtime knows how to
852 // parse the last frame when we actually take the safepoint (i.e. execute
854 assert(ParsePointsNeeded.empty());
855 for (size_t i = 0; i < calls.size(); i++) {
857 // No safepoint needed or wanted
858 if (!needsStatepoint(calls[i])) {
862 // These are likely runtime calls. Should we assert that via calling
863 // convention or something?
864 ParsePointsNeeded.push_back(CallSite(calls[i]));
866 assert(ParsePointsNeeded.size() <= calls.size());
869 /// Replaces the given call site (Call or Invoke) with a gc.statepoint
870 /// intrinsic with an empty deoptimization arguments list. This does
871 /// NOT do explicit relocation for GC support.
872 static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */
874 assert(CS.getInstruction()->getParent()->getParent()->getParent() &&
877 // TODO: technically, a pass is not allowed to get functions from within a
878 // function pass since it might trigger a new function addition. Refactor
879 // this logic out to the initialization of the pass. Doesn't appear to
880 // matter in practice.
882 // Then go ahead and use the builder do actually do the inserts. We insert
883 // immediately before the previous instruction under the assumption that all
884 // arguments will be available here. We can't insert afterwards since we may
885 // be replacing a terminator.
886 IRBuilder<> Builder(CS.getInstruction());
888 // Note: The gc args are not filled in at this time, that's handled by
889 // RewriteStatepointsForGC (which is currently under review).
891 // Create the statepoint given all the arguments
892 Instruction *Token = nullptr;
893 AttributeSet OriginalAttrs;
896 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
897 CallInst *Call = Builder.CreateGCStatepointCall(
898 CS.getCalledValue(), makeArrayRef(CS.arg_begin(), CS.arg_end()), None,
899 None, "safepoint_token");
900 Call->setTailCall(ToReplace->isTailCall());
901 Call->setCallingConv(ToReplace->getCallingConv());
903 // Before we have to worry about GC semantics, all attributes are legal
904 // TODO: handle param attributes
905 OriginalAttrs = ToReplace->getAttributes();
907 // In case if we can handle this set of attributes - set up function
908 // attributes directly on statepoint and return attributes later for
909 // gc_result intrinsic.
910 Call->setAttributes(OriginalAttrs.getFnAttributes());
914 // Put the following gc_result and gc_relocate calls immediately after the
915 // the old call (which we're about to delete).
916 assert(ToReplace->getNextNode() && "not a terminator, must have next");
917 Builder.SetInsertPoint(ToReplace->getNextNode());
918 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
919 } else if (CS.isInvoke()) {
920 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
922 // Insert the new invoke into the old block. We'll remove the old one in a
923 // moment at which point this will become the new terminator for the
925 Builder.SetInsertPoint(ToReplace->getParent());
926 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
927 CS.getCalledValue(), ToReplace->getNormalDest(),
928 ToReplace->getUnwindDest(), makeArrayRef(CS.arg_begin(), CS.arg_end()),
929 Builder.getInt32(0), None, "safepoint_token");
931 // Currently we will fail on parameter attributes and on certain
932 // function attributes.
933 OriginalAttrs = ToReplace->getAttributes();
935 // In case if we can handle this set of attributes - set up function
936 // attributes directly on statepoint and return attributes later for
937 // gc_result intrinsic.
938 Invoke->setAttributes(OriginalAttrs.getFnAttributes());
942 // We'll insert the gc.result into the normal block
943 BasicBlock *NormalDest = ToReplace->getNormalDest();
944 // Can not insert gc.result in case of phi nodes preset.
945 // Should have removed this cases prior to runnning this function
946 assert(!isa<PHINode>(NormalDest->begin()));
947 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
948 Builder.SetInsertPoint(IP);
950 llvm_unreachable("unexpect type of CallSite");
954 // Handle the return value of the original call - update all uses to use a
955 // gc_result hanging off the statepoint node we just inserted
957 // Only add the gc_result iff there is actually a used result
958 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
959 std::string TakenName =
960 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
961 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), TakenName);
962 GCResult->setAttributes(OriginalAttrs.getRetAttributes());
965 // No return value for the call.