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/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"
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");
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");
94 // Ignore oppurtunities to avoid placing safepoints on backedges, useful for
96 static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
99 /// If true, do not place backedge safepoints in counted loops.
100 static cl::opt<bool> SkipCounted("spp-counted", cl::Hidden, cl::init(true));
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
106 static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
109 // Print tracing output
110 static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
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 {
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;
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;
127 ScalarEvolution *SE = nullptr;
128 DominatorTree *DT = nullptr;
129 LoopInfo *LI = nullptr;
131 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
132 : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
133 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
136 bool runOnLoop(Loop *);
137 void runOnLoopAndSubLoops(Loop *L) {
138 // Visit all the subloops
139 for (auto I = L->begin(), E = L->end(); I != E; I++)
140 runOnLoopAndSubLoops(*I);
144 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);
154 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();
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));
170 struct PlaceSafepoints : public FunctionPass {
171 static char ID; // Pass identification, replacement for typeid
173 PlaceSafepoints() : FunctionPass(ID) {
174 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
176 bool runOnFunction(Function &F) override;
178 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
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
190 InsertSafepointPoll(Instruction *after,
191 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
193 static bool isGCLeafFunction(const CallSite &CS);
195 static bool needsStatepoint(const CallSite &CS) {
196 if (isGCLeafFunction(CS))
199 CallInst *call = cast<CallInst>(CS.getInstruction());
200 if (call->isInlineAsm())
203 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
209 static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P);
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.
215 static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
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?");
230 BasicBlock *Current = Pred;
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
237 // unconditional poll. In practice, this is only a theoretical concern
238 // since we don't have any methods with conditional-only safepoint
240 if (needsStatepoint(CS))
244 if (Current == Header)
246 Current = DT.getNode(Current)->getIDom()->getBlock();
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.
256 static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
258 // Only used when SkipCounted is off
259 const unsigned upperTripBound = 8192;
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))
267 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(32))
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))
282 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(32))
287 return /* not finite */ false;
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);
297 if (CallInst *CI = dyn_cast<CallInst>(&*itr)) {
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);
316 static void scanInlinedCode(Instruction *start, Instruction *end,
317 std::vector<CallInst *> &calls,
318 std::set<BasicBlock *> &seen) {
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();
326 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
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));
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.
346 if (mustBeFiniteCountedLoop(L, SE, pred)) {
348 errs() << "skipping safepoint placement in finite loop\n";
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.
358 errs() << "skipping safepoint placement due to unconditional call\n";
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.
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();
375 errs() << "[LSP] terminator instruction: ";
379 PollLocations.push_back(term);
385 /// Returns true if an entry safepoint is not required before this callsite in
386 /// the caller function.
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.
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.frameescape which must occur in the entry block. Inserting a
403 // safepoint before it is not legal since it could push the frameescape
404 // out of the entry block.
411 static Instruction *findLocationForEntrySafepoint(Function &F,
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.
420 // Due to the way the frontend generates IR, we may have a couple of initial
421 // basic blocks before the first bytecode. These will be single-entry
422 // single-exit blocks which conceptually are just part of the first 'real
423 // basic block'. Since we don't have deopt state until the first bytecode,
424 // walk forward until we've found the first unconditional branch or merge.
426 // hasNextInstruction and nextInstruction are used to iterate
427 // through a "straight line" execution sequence.
429 auto hasNextInstruction = [](Instruction *I) {
430 if (!I->isTerminator()) {
433 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
434 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
437 auto nextInstruction = [&hasNextInstruction](Instruction *I) {
438 assert(hasNextInstruction(I) &&
439 "first check if there is a next instruction!");
440 if (I->isTerminator()) {
441 return I->getParent()->getUniqueSuccessor()->begin();
443 return std::next(BasicBlock::iterator(I));
447 Instruction *cursor = nullptr;
448 for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor);
449 cursor = nextInstruction(cursor)) {
451 // We need to ensure a safepoint poll occurs before any 'real' call. The
452 // easiest way to ensure finite execution between safepoints in the face of
453 // recursive and mutually recursive functions is to enforce that each take
454 // a safepoint. Additionally, we need to ensure a poll before any call
455 // which can grow the stack by an unbounded amount. This isn't required
456 // for GC semantics per se, but is a common requirement for languages
457 // which detect stack overflow via guard pages and then throw exceptions.
458 if (auto CS = CallSite(cursor)) {
459 if (doesNotRequireEntrySafepointBefore(CS))
465 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
466 "either we stopped because of a call, or because of terminator");
468 if (cursor->isTerminator()) {
472 BasicBlock *BB = cursor->getParent();
473 SplitBlock(BB, cursor, &DT);
475 // SplitBlock updates the DT
476 DEBUG(DT.verifyDomTree());
478 return BB->getTerminator();
481 /// Identify the list of call sites which need to be have parseable state
482 static void findCallSafepoints(Function &F,
483 std::vector<CallSite> &Found /*rval*/) {
484 assert(Found.empty() && "must be empty!");
485 for (Instruction &I : inst_range(F)) {
486 Instruction *inst = &I;
487 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
490 // No safepoint needed or wanted
491 if (!needsStatepoint(CS)) {
500 /// Implement a unique function which doesn't require we sort the input
501 /// vector. Doing so has the effect of changing the output of a couple of
502 /// tests in ways which make them less useful in testing fused safepoints.
503 template <typename T> static void unique_unsorted(std::vector<T> &vec) {
506 vec.reserve(vec.size());
509 if (seen.insert(V).second) {
515 static std::string GCSafepointPollName("gc.safepoint_poll");
517 static bool isGCSafepointPoll(Function &F) {
518 return F.getName().equals(GCSafepointPollName);
521 /// Returns true if this function should be rewritten to include safepoint
522 /// polls and parseable call sites. The main point of this function is to be
523 /// an extension point for custom logic.
524 static bool shouldRewriteFunction(Function &F) {
525 // TODO: This should check the GCStrategy
527 const char *FunctionGCName = F.getGC();
\r
528 const StringRef StatepointExampleName("statepoint-example");
\r
529 const StringRef CoreCLRName("coreclr");
\r
530 return (StatepointExampleName == FunctionGCName) ||
\r
531 (CoreCLRName == FunctionGCName);
536 // TODO: These should become properties of the GCStrategy, possibly with
537 // command line overrides.
538 static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
539 static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
540 static bool enableCallSafepoints(Function &F) { return !NoCall; }
542 // Normalize basic block to make it ready to be target of invoke statepoint.
543 // Ensure that 'BB' does not have phi nodes. It may require spliting it.
544 static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
545 BasicBlock *InvokeParent) {
546 BasicBlock *ret = BB;
548 if (!BB->getUniquePredecessor()) {
549 ret = SplitBlockPredecessors(BB, InvokeParent, "");
552 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
554 FoldSingleEntryPHINodes(ret);
555 assert(!isa<PHINode>(ret->begin()));
560 bool PlaceSafepoints::runOnFunction(Function &F) {
561 if (F.isDeclaration() || F.empty()) {
562 // This is a declaration, nothing to do. Must exit early to avoid crash in
563 // dom tree calculation
567 if (isGCSafepointPoll(F)) {
568 // Given we're inlining this inside of safepoint poll insertion, this
569 // doesn't make any sense. Note that we do make any contained calls
570 // parseable after we inline a poll.
574 if (!shouldRewriteFunction(F))
577 bool modified = false;
579 // In various bits below, we rely on the fact that uses are reachable from
580 // defs. When there are basic blocks unreachable from the entry, dominance
581 // and reachablity queries return non-sensical results. Thus, we preprocess
582 // the function to ensure these properties hold.
583 modified |= removeUnreachableBlocks(F);
585 // STEP 1 - Insert the safepoint polling locations. We do not need to
586 // actually insert parse points yet. That will be done for all polls and
587 // calls in a single pass.
592 SmallVector<Instruction *, 16> PollsNeeded;
593 std::vector<CallSite> ParsePointNeeded;
595 if (enableBackedgeSafepoints(F)) {
596 // Construct a pass manager to run the LoopPass backedge logic. We
597 // need the pass manager to handle scheduling all the loop passes
598 // appropriately. Doing this by hand is painful and just not worth messing
599 // with for the moment.
600 legacy::FunctionPassManager FPM(F.getParent());
601 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
602 PlaceBackedgeSafepointsImpl *PBS =
603 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
607 // We preserve dominance information when inserting the poll, otherwise
608 // we'd have to recalculate this on every insert
611 auto &PollLocations = PBS->PollLocations;
613 auto OrderByBBName = [](Instruction *a, Instruction *b) {
614 return a->getParent()->getName() < b->getParent()->getName();
616 // We need the order of list to be stable so that naming ends up stable
617 // when we split edges. This makes test cases much easier to write.
618 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
620 // We can sometimes end up with duplicate poll locations. This happens if
621 // a single loop is visited more than once. The fact this happens seems
622 // wrong, but it does happen for the split-backedge.ll test case.
623 PollLocations.erase(std::unique(PollLocations.begin(),
624 PollLocations.end()),
625 PollLocations.end());
627 // Insert a poll at each point the analysis pass identified
628 // The poll location must be the terminator of a loop latch block.
629 for (TerminatorInst *Term : PollLocations) {
630 // We are inserting a poll, the function is modified
634 // Split the backedge of the loop and insert the poll within that new
635 // basic block. This creates a loop with two latches per original
636 // latch (which is non-ideal), but this appears to be easier to
637 // optimize in practice than inserting the poll immediately before the
640 // Since this is a latch, at least one of the successors must dominate
641 // it. Its possible that we have a) duplicate edges to the same header
642 // and b) edges to distinct loop headers. We need to insert pools on
644 SetVector<BasicBlock *> Headers;
645 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
646 BasicBlock *Succ = Term->getSuccessor(i);
647 if (DT.dominates(Succ, Term->getParent())) {
648 Headers.insert(Succ);
651 assert(!Headers.empty() && "poll location is not a loop latch?");
653 // The split loop structure here is so that we only need to recalculate
654 // the dominator tree once. Alternatively, we could just keep it up to
655 // date and use a more natural merged loop.
656 SetVector<BasicBlock *> SplitBackedges;
657 for (BasicBlock *Header : Headers) {
658 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
659 PollsNeeded.push_back(NewBB->getTerminator());
660 NumBackedgeSafepoints++;
663 // Split the latch block itself, right before the terminator.
664 PollsNeeded.push_back(Term);
665 NumBackedgeSafepoints++;
670 if (enableEntrySafepoints(F)) {
671 Instruction *Location = findLocationForEntrySafepoint(F, DT);
673 // policy choice not to insert?
675 PollsNeeded.push_back(Location);
677 NumEntrySafepoints++;
681 // Now that we've identified all the needed safepoint poll locations, insert
682 // safepoint polls themselves.
683 for (Instruction *PollLocation : PollsNeeded) {
684 std::vector<CallSite> RuntimeCalls;
685 InsertSafepointPoll(PollLocation, RuntimeCalls);
686 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
689 PollsNeeded.clear(); // make sure we don't accidentally use
690 // The dominator tree has been invalidated by the inlining performed in the
691 // above loop. TODO: Teach the inliner how to update the dom tree?
694 if (enableCallSafepoints(F)) {
695 std::vector<CallSite> Calls;
696 findCallSafepoints(F, Calls);
697 NumCallSafepoints += Calls.size();
698 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
701 // Unique the vectors since we can end up with duplicates if we scan the call
702 // site for call safepoints after we add it for entry or backedge. The
703 // only reason we need tracking at all is that some functions might have
704 // polls but not call safepoints and thus we might miss marking the runtime
705 // calls for the polls. (This is useful in test cases!)
706 unique_unsorted(ParsePointNeeded);
708 // Any parse point (no matter what source) will be handled here
710 // We're about to start modifying the function
711 if (!ParsePointNeeded.empty())
714 // Now run through and insert the safepoints, but do _NOT_ update or remove
715 // any existing uses. We have references to live variables that need to
716 // survive to the last iteration of this loop.
717 std::vector<Value *> Results;
718 Results.reserve(ParsePointNeeded.size());
719 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
720 CallSite &CS = ParsePointNeeded[i];
722 // For invoke statepoints we need to remove all phi nodes at the normal
723 // destination block.
724 // Reason for this is that we can place gc_result only after last phi node
725 // in basic block. We will get malformed code after RAUW for the
726 // gc_result if one of this phi nodes uses result from the invoke.
727 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(CS.getInstruction())) {
728 normalizeForInvokeSafepoint(Invoke->getNormalDest(),
729 Invoke->getParent());
732 Value *GCResult = ReplaceWithStatepoint(CS, nullptr);
733 Results.push_back(GCResult);
735 assert(Results.size() == ParsePointNeeded.size());
737 // Adjust all users of the old call sites to use the new ones instead
738 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
739 CallSite &CS = ParsePointNeeded[i];
740 Value *GCResult = Results[i];
742 // Can not RAUW for the invoke gc result in case of phi nodes preset.
743 assert(CS.isCall() || !isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin()));
745 // Replace all uses with the new call
746 CS.getInstruction()->replaceAllUsesWith(GCResult);
749 // Now that we've handled all uses, remove the original call itself
750 // Note: The insert point can't be the deleted instruction!
751 CS.getInstruction()->eraseFromParent();
756 char PlaceBackedgeSafepointsImpl::ID = 0;
757 char PlaceSafepoints::ID = 0;
759 FunctionPass *llvm::createPlaceSafepointsPass() {
760 return new PlaceSafepoints();
763 INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
764 "place-backedge-safepoints-impl",
765 "Place Backedge Safepoints", false, false)
766 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
767 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
768 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
769 INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
770 "place-backedge-safepoints-impl",
771 "Place Backedge Safepoints", false, false)
773 INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
775 INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
778 static bool isGCLeafFunction(const CallSite &CS) {
779 Instruction *inst = CS.getInstruction();
780 if (isa<IntrinsicInst>(inst)) {
781 // Most LLVM intrinsics are things which can never take a safepoint.
782 // As a result, we don't need to have the stack parsable at the
783 // callsite. This is a highly useful optimization since intrinsic
784 // calls are fairly prevelent, particularly in debug builds.
788 // If this function is marked explicitly as a leaf call, we don't need to
789 // place a safepoint of it. In fact, for correctness we *can't* in many
790 // cases. Note: Indirect calls return Null for the called function,
791 // these obviously aren't runtime functions with attributes
792 // TODO: Support attributes on the call site as well.
793 const Function *F = CS.getCalledFunction();
796 F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true");
804 InsertSafepointPoll(Instruction *term,
805 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
806 Module *M = term->getParent()->getParent()->getParent();
809 // Inline the safepoint poll implementation - this will get all the branch,
810 // control flow, etc.. Most importantly, it will introduce the actual slow
811 // path call - where we need to insert a safepoint (parsepoint).
812 FunctionType *ftype =
813 FunctionType::get(Type::getVoidTy(M->getContext()), false);
814 assert(ftype && "null?");
815 // Note: This cast can fail if there's a function of the same name with a
816 // different type inserted previously
818 dyn_cast<Function>(M->getOrInsertFunction("gc.safepoint_poll", ftype));
819 assert(F && "void @gc.safepoint_poll() must be defined");
820 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
821 CallInst *poll = CallInst::Create(F, "", term);
823 // Record some information about the call site we're replacing
824 BasicBlock *OrigBB = term->getParent();
825 BasicBlock::iterator before(poll), after(poll);
827 if (before == term->getParent()->begin()) {
833 assert(after != poll->getParent()->end() && "must have successor");
835 // do the actual inlining
836 InlineFunctionInfo IFI;
837 bool inlineStatus = InlineFunction(poll, IFI);
838 assert(inlineStatus && "inline must succeed");
839 (void)inlineStatus; // suppress warning in release-asserts
841 // Check post conditions
842 assert(IFI.StaticAllocas.empty() && "can't have allocs");
844 std::vector<CallInst *> calls; // new calls
845 std::set<BasicBlock *> BBs; // new BBs + insertee
846 // Include only the newly inserted instructions, Note: begin may not be valid
847 // if we inserted to the beginning of the basic block
848 BasicBlock::iterator start;
850 start = OrigBB->begin();
856 // If your poll function includes an unreachable at the end, that's not
857 // valid. Bugpoint likes to create this, so check for it.
858 assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) &&
859 "malformed poll function");
861 scanInlinedCode(&*(start), &*(after), calls, BBs);
862 assert(!calls.empty() && "slow path not found for safepoint poll");
864 // Record the fact we need a parsable state at the runtime call contained in
865 // the poll function. This is required so that the runtime knows how to
866 // parse the last frame when we actually take the safepoint (i.e. execute
868 assert(ParsePointsNeeded.empty());
869 for (size_t i = 0; i < calls.size(); i++) {
871 // No safepoint needed or wanted
872 if (!needsStatepoint(calls[i])) {
876 // These are likely runtime calls. Should we assert that via calling
877 // convention or something?
878 ParsePointsNeeded.push_back(CallSite(calls[i]));
880 assert(ParsePointsNeeded.size() <= calls.size());
883 /// Replaces the given call site (Call or Invoke) with a gc.statepoint
884 /// intrinsic with an empty deoptimization arguments list. This does
885 /// NOT do explicit relocation for GC support.
886 static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */
888 assert(CS.getInstruction()->getParent()->getParent()->getParent() &&
891 // TODO: technically, a pass is not allowed to get functions from within a
892 // function pass since it might trigger a new function addition. Refactor
893 // this logic out to the initialization of the pass. Doesn't appear to
894 // matter in practice.
896 // Then go ahead and use the builder do actually do the inserts. We insert
897 // immediately before the previous instruction under the assumption that all
898 // arguments will be available here. We can't insert afterwards since we may
899 // be replacing a terminator.
900 IRBuilder<> Builder(CS.getInstruction());
902 // Note: The gc args are not filled in at this time, that's handled by
903 // RewriteStatepointsForGC (which is currently under review).
905 // Create the statepoint given all the arguments
906 Instruction *Token = nullptr;
909 uint32_t NumPatchBytes;
911 AttributeSet OriginalAttrs = CS.getAttributes();
913 OriginalAttrs.getAttribute(AttributeSet::FunctionIndex, "statepoint-id");
914 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
915 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
917 AttrBuilder AttrsToRemove;
918 bool HasID = AttrID.isStringAttribute() &&
919 !AttrID.getValueAsString().getAsInteger(10, ID);
922 AttrsToRemove.addAttribute("statepoint-id");
926 bool HasNumPatchBytes =
927 AttrNumPatchBytes.isStringAttribute() &&
928 !AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
930 if (HasNumPatchBytes)
931 AttrsToRemove.addAttribute("statepoint-num-patch-bytes");
935 OriginalAttrs = OriginalAttrs.removeAttributes(
936 CS.getInstruction()->getContext(), AttributeSet::FunctionIndex,
939 Value *StatepointTarget = NumPatchBytes == 0
940 ? CS.getCalledValue()
941 : ConstantPointerNull::get(cast<PointerType>(
942 CS.getCalledValue()->getType()));
945 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
946 CallInst *Call = Builder.CreateGCStatepointCall(
947 ID, NumPatchBytes, StatepointTarget,
948 makeArrayRef(CS.arg_begin(), CS.arg_end()), None, None,
950 Call->setTailCall(ToReplace->isTailCall());
951 Call->setCallingConv(ToReplace->getCallingConv());
953 // In case if we can handle this set of attributes - set up function
954 // attributes directly on statepoint and return attributes later for
955 // gc_result intrinsic.
956 Call->setAttributes(OriginalAttrs.getFnAttributes());
960 // Put the following gc_result and gc_relocate calls immediately after the
961 // the old call (which we're about to delete).
962 assert(ToReplace->getNextNode() && "not a terminator, must have next");
963 Builder.SetInsertPoint(ToReplace->getNextNode());
964 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
965 } else if (CS.isInvoke()) {
966 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
968 // Insert the new invoke into the old block. We'll remove the old one in a
969 // moment at which point this will become the new terminator for the
971 Builder.SetInsertPoint(ToReplace->getParent());
972 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
973 ID, NumPatchBytes, StatepointTarget, ToReplace->getNormalDest(),
974 ToReplace->getUnwindDest(), makeArrayRef(CS.arg_begin(), CS.arg_end()),
975 None, None, "safepoint_token");
977 Invoke->setCallingConv(ToReplace->getCallingConv());
979 // In case if we can handle this set of attributes - set up function
980 // attributes directly on statepoint and return attributes later for
981 // gc_result intrinsic.
982 Invoke->setAttributes(OriginalAttrs.getFnAttributes());
986 // We'll insert the gc.result into the normal block
987 BasicBlock *NormalDest = ToReplace->getNormalDest();
988 // Can not insert gc.result in case of phi nodes preset.
989 // Should have removed this cases prior to runnning this function
990 assert(!isa<PHINode>(NormalDest->begin()));
991 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
992 Builder.SetInsertPoint(IP);
994 llvm_unreachable("unexpect type of CallSite");
998 // Handle the return value of the original call - update all uses to use a
999 // gc_result hanging off the statepoint node we just inserted
1001 // Only add the gc_result iff there is actually a used result
1002 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1003 std::string TakenName =
1004 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1005 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), TakenName);
1006 GCResult->setAttributes(OriginalAttrs.getRetAttributes());
1009 // No return value for the call.