blob: 63e8115bea60e9cd8410a96f3de37d0a9c19a271 [file] [log] [blame]
Philip Reames47cc6732015-02-04 00:37:33 +00001//===- 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//
Philip Reamesd4a912f2015-02-09 22:44:03 +000014// 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
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +000019// point is represented by a call wrapped in an gc.statepoint intrinsic.
Philip Reamesd4a912f2015-02-09 22:44:03 +000020// - 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
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000030// are necessary to ensure a finite period between poll sites. This is not
Philip Reamesd4a912f2015-02-09 22:44:03 +000031// 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//
Philip Reames47cc6732015-02-04 00:37:33 +000039// This pass will insert:
Philip Reamesd4a912f2015-02-09 22:44:03 +000040// - 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.
Philip Reames47cc6732015-02-04 00:37:33 +000044//
Philip Reamesd4a912f2015-02-09 22:44:03 +000045// 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.
Philip Reames47cc6732015-02-04 00:37:33 +000048//
49//===----------------------------------------------------------------------===//
50
51#include "llvm/Pass.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000052#include "llvm/IR/LegacyPassManager.h"
Philip Reames47cc6732015-02-04 00:37:33 +000053#include "llvm/ADT/SetOperations.h"
Philip Reames5708cca2015-05-12 20:43:48 +000054#include "llvm/ADT/SetVector.h"
Philip Reames47cc6732015-02-04 00:37:33 +000055#include "llvm/ADT/Statistic.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000056#include "llvm/ADT/StringRef.h"
Philip Reames47cc6732015-02-04 00:37:33 +000057#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"
85STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
86STATISTIC(NumCallSafepoints, "Number of call safepoints inserted");
87STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
88
89STATISTIC(CallInLoop, "Number of loops w/o safepoints due to calls in loop");
90STATISTIC(FiniteExecution, "Number of loops w/o safepoints finite execution");
91
92using namespace llvm;
93
Benjamin Kramerdf005cb2015-08-08 18:27:36 +000094// Ignore opportunities to avoid placing safepoints on backedges, useful for
Philip Reames47cc6732015-02-04 00:37:33 +000095// validation
Philip Reames1f3e5c12015-02-20 23:32:03 +000096static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
97 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000098
Sanjoy Dasf75e15e2015-09-15 01:42:48 +000099/// How narrow does the trip count of a loop have to be to have to be considered
100/// "counted"? Counted loops do not get safepoints at backedges.
101static cl::opt<int> CountedLoopTripWidth("spp-counted-loop-trip-width",
102 cl::Hidden, cl::init(32));
Philip Reames47cc6732015-02-04 00:37:33 +0000103
104// If true, split the backedge of a loop when placing the safepoint, otherwise
105// split the latch block itself. Both are useful to support for
106// experimentation, but in practice, it looks like splitting the backedge
107// optimizes better.
Philip Reames1f3e5c12015-02-20 23:32:03 +0000108static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
109 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000110
Sanjoy Das95639742016-01-22 21:02:55 +0000111// If true, don't wrap calls (the ones present in the IR, and the ones
112// introduced due to polls) in gc.statepoint.
113static cl::opt<bool> NoStatepoints("spp-no-statepoints", cl::Hidden,
114 cl::init(false));
115
Philip Reames47cc6732015-02-04 00:37:33 +0000116// Print tracing output
Philip Reames1f3e5c12015-02-20 23:32:03 +0000117static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000118
119namespace {
120
Philip Reames9f129042015-05-12 21:09:36 +0000121/// An analysis pass whose purpose is to identify each of the backedges in
122/// the function which require a safepoint poll to be inserted.
123struct PlaceBackedgeSafepointsImpl : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000124 static char ID;
125
126 /// The output of the pass - gives a list of each backedge (described by
127 /// pointing at the branch) which need a poll inserted.
128 std::vector<TerminatorInst *> PollLocations;
129
130 /// True unless we're running spp-no-calls in which case we need to disable
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000131 /// the call-dependent placement opts.
Philip Reames47cc6732015-02-04 00:37:33 +0000132 bool CallSafepointsEnabled;
Philip Reames9f129042015-05-12 21:09:36 +0000133
134 ScalarEvolution *SE = nullptr;
135 DominatorTree *DT = nullptr;
136 LoopInfo *LI = nullptr;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000137
Philip Reames47cc6732015-02-04 00:37:33 +0000138 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
Philip Reames9f129042015-05-12 21:09:36 +0000139 : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
Philip Reames5a9685d2015-02-04 00:39:57 +0000140 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000141 }
142
Philip Reames9f129042015-05-12 21:09:36 +0000143 bool runOnLoop(Loop *);
144 void runOnLoopAndSubLoops(Loop *L) {
145 // Visit all the subloops
146 for (auto I = L->begin(), E = L->end(); I != E; I++)
147 runOnLoopAndSubLoops(*I);
148 runOnLoop(L);
149 }
Justin Bogner383749a2015-05-12 21:49:47 +0000150
151 bool runOnFunction(Function &F) override {
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000152 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Philip Reames9f129042015-05-12 21:09:36 +0000153 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
154 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
155 for (auto I = LI->begin(), E = LI->end(); I != E; I++) {
156 runOnLoopAndSubLoops(*I);
157 }
158 return false;
159 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000160
Philip Reames47cc6732015-02-04 00:37:33 +0000161 void getAnalysisUsage(AnalysisUsage &AU) const override {
Philip Reames57bdac92015-05-12 20:56:33 +0000162 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000163 AU.addRequired<ScalarEvolutionWrapperPass>();
Philip Reames9f129042015-05-12 21:09:36 +0000164 AU.addRequired<LoopInfoWrapperPass>();
Philip Reames47cc6732015-02-04 00:37:33 +0000165 // We no longer modify the IR at all in this pass. Thus all
166 // analysis are preserved.
167 AU.setPreservesAll();
168 }
169};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000170}
Philip Reames47cc6732015-02-04 00:37:33 +0000171
Philip Reames1f3e5c12015-02-20 23:32:03 +0000172static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
173static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
174static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000175
176namespace {
Philip Reames7b981792015-05-12 21:21:18 +0000177struct PlaceSafepoints : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000178 static char ID; // Pass identification, replacement for typeid
179
Philip Reames7b981792015-05-12 21:21:18 +0000180 PlaceSafepoints() : FunctionPass(ID) {
Philip Reames47cc6732015-02-04 00:37:33 +0000181 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000182 }
Philip Reames7b981792015-05-12 21:21:18 +0000183 bool runOnFunction(Function &F) override;
Philip Reames47cc6732015-02-04 00:37:33 +0000184
185 void getAnalysisUsage(AnalysisUsage &AU) const override {
186 // We modify the graph wholesale (inlining, block insertion, etc). We
187 // preserve nothing at the moment. We could potentially preserve dom tree
188 // if that was worth doing
189 }
190};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000191}
Philip Reames47cc6732015-02-04 00:37:33 +0000192
193// Insert a safepoint poll immediately before the given instruction. Does
194// not handle the parsability of state at the runtime call, that's the
195// callers job.
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000196static void
Philip Reames388402452015-05-26 21:03:23 +0000197InsertSafepointPoll(Instruction *InsertBefore,
Philip Reames5a9685d2015-02-04 00:39:57 +0000198 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
Philip Reames47cc6732015-02-04 00:37:33 +0000199
Philip Reames47cc6732015-02-04 00:37:33 +0000200static bool needsStatepoint(const CallSite &CS) {
Sanjoy Dasc21a05a2015-10-08 23:18:30 +0000201 if (callsGCLeafFunction(CS))
Philip Reames47cc6732015-02-04 00:37:33 +0000202 return false;
203 if (CS.isCall()) {
204 CallInst *call = cast<CallInst>(CS.getInstruction());
205 if (call->isInlineAsm())
206 return false;
207 }
208 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
209 return false;
210 }
211 return true;
212}
213
Justin Bogner843fb202015-12-15 19:40:57 +0000214static Value *ReplaceWithStatepoint(const CallSite &CS);
Philip Reames47cc6732015-02-04 00:37:33 +0000215
216/// Returns true if this loop is known to contain a call safepoint which
217/// must unconditionally execute on any iteration of the loop which returns
218/// to the loop header via an edge from Pred. Returns a conservative correct
219/// answer; i.e. false is always valid.
220static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
221 BasicBlock *Pred,
222 DominatorTree &DT) {
223 // In general, we're looking for any cut of the graph which ensures
224 // there's a call safepoint along every edge between Header and Pred.
225 // For the moment, we look only for the 'cuts' that consist of a single call
226 // instruction in a block which is dominated by the Header and dominates the
227 // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000228 // of such dominating blocks gets substantially more occurrences than just
Philip Reames47cc6732015-02-04 00:37:33 +0000229 // checking the Pred and Header blocks themselves. This may be due to the
230 // density of loop exit conditions caused by range and null checks.
231 // TODO: structure this as an analysis pass, cache the result for subloops,
232 // avoid dom tree recalculations
233 assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
234
235 BasicBlock *Current = Pred;
236 while (true) {
237 for (Instruction &I : *Current) {
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000238 if (auto CS = CallSite(&I))
Philip Reames47cc6732015-02-04 00:37:33 +0000239 // Note: Technically, needing a safepoint isn't quite the right
240 // condition here. We should instead be checking if the target method
241 // has an
242 // unconditional poll. In practice, this is only a theoretical concern
243 // since we don't have any methods with conditional-only safepoint
244 // polls.
245 if (needsStatepoint(CS))
246 return true;
247 }
248
249 if (Current == Header)
250 break;
251 Current = DT.getNode(Current)->getIDom()->getBlock();
252 }
253
254 return false;
255}
256
257/// Returns true if this loop is known to terminate in a finite number of
258/// iterations. Note that this function may return false for a loop which
259/// does actual terminate in a finite constant number of iterations due to
260/// conservatism in the analysis.
261static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
Philip Reames5a9685d2015-02-04 00:39:57 +0000262 BasicBlock *Pred) {
Philip Reames47cc6732015-02-04 00:37:33 +0000263 // A conservative bound on the loop as a whole.
264 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
Sanjoy Dasf75e15e2015-09-15 01:42:48 +0000265 if (MaxTrips != SE->getCouldNotCompute() &&
266 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(
267 CountedLoopTripWidth))
268 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000269
270 // If this is a conditional branch to the header with the alternate path
271 // being outside the loop, we can ask questions about the execution frequency
272 // of the exit block.
273 if (L->isLoopExiting(Pred)) {
274 // This returns an exact expression only. TODO: We really only need an
275 // upper bound here, but SE doesn't expose that.
276 const SCEV *MaxExec = SE->getExitCount(L, Pred);
Sanjoy Dasf75e15e2015-09-15 01:42:48 +0000277 if (MaxExec != SE->getCouldNotCompute() &&
278 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(
279 CountedLoopTripWidth))
Philip Reames47cc6732015-02-04 00:37:33 +0000280 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000281 }
282
283 return /* not finite */ false;
284}
285
286static void scanOneBB(Instruction *start, Instruction *end,
Philip Reames5a9685d2015-02-04 00:39:57 +0000287 std::vector<CallInst *> &calls,
288 std::set<BasicBlock *> &seen,
289 std::vector<BasicBlock *> &worklist) {
Philip Reames47cc6732015-02-04 00:37:33 +0000290 for (BasicBlock::iterator itr(start);
291 itr != start->getParent()->end() && itr != BasicBlock::iterator(end);
292 itr++) {
293 if (CallInst *CI = dyn_cast<CallInst>(&*itr)) {
294 calls.push_back(CI);
295 }
296 // FIXME: This code does not handle invokes
297 assert(!dyn_cast<InvokeInst>(&*itr) &&
298 "support for invokes in poll code needed");
299 // Only add the successor blocks if we reach the terminator instruction
300 // without encountering end first
301 if (itr->isTerminator()) {
302 BasicBlock *BB = itr->getParent();
Philip Reamesa29de872015-02-09 22:26:11 +0000303 for (BasicBlock *Succ : successors(BB)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000304 if (seen.count(Succ) == 0) {
305 worklist.push_back(Succ);
306 seen.insert(Succ);
307 }
308 }
309 }
310 }
311}
312static void scanInlinedCode(Instruction *start, Instruction *end,
Philip Reames5a9685d2015-02-04 00:39:57 +0000313 std::vector<CallInst *> &calls,
314 std::set<BasicBlock *> &seen) {
Philip Reames47cc6732015-02-04 00:37:33 +0000315 calls.clear();
316 std::vector<BasicBlock *> worklist;
317 seen.insert(start->getParent());
318 scanOneBB(start, end, calls, seen, worklist);
319 while (!worklist.empty()) {
320 BasicBlock *BB = worklist.back();
321 worklist.pop_back();
322 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
323 }
324}
325
Philip Reames9f129042015-05-12 21:09:36 +0000326bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) {
Philip Reames5708cca2015-05-12 20:43:48 +0000327 // Loop through all loop latches (branches controlling backedges). We need
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000328 // to place a safepoint on every backedge (potentially).
Philip Reames5708cca2015-05-12 20:43:48 +0000329 // Note: In common usage, there will be only one edge due to LoopSimplify
330 // having run sometime earlier in the pipeline, but this code must be correct
331 // w.r.t. loops with multiple backedges.
Philip Reames47cc6732015-02-04 00:37:33 +0000332 BasicBlock *header = L->getHeader();
Philip Reames5708cca2015-05-12 20:43:48 +0000333 SmallVector<BasicBlock*, 16> LoopLatches;
334 L->getLoopLatches(LoopLatches);
335 for (BasicBlock *pred : LoopLatches) {
336 assert(L->contains(pred));
Philip Reames47cc6732015-02-04 00:37:33 +0000337
338 // Make a policy decision about whether this loop needs a safepoint or
339 // not. Note that this is about unburdening the optimizer in loops, not
340 // avoiding the runtime cost of the actual safepoint.
341 if (!AllBackedges) {
342 if (mustBeFiniteCountedLoop(L, SE, pred)) {
343 if (TraceLSP)
344 errs() << "skipping safepoint placement in finite loop\n";
345 FiniteExecution++;
346 continue;
347 }
348 if (CallSafepointsEnabled &&
Philip Reames57bdac92015-05-12 20:56:33 +0000349 containsUnconditionalCallSafepoint(L, header, pred, *DT)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000350 // Note: This is only semantically legal since we won't do any further
351 // IPO or inlining before the actual call insertion.. If we hadn't, we
352 // might latter loose this call safepoint.
353 if (TraceLSP)
354 errs() << "skipping safepoint placement due to unconditional call\n";
355 CallInLoop++;
356 continue;
357 }
358 }
359
360 // TODO: We can create an inner loop which runs a finite number of
361 // iterations with an outer loop which contains a safepoint. This would
362 // not help runtime performance that much, but it might help our ability to
363 // optimize the inner loop.
364
Philip Reames47cc6732015-02-04 00:37:33 +0000365 // Safepoint insertion would involve creating a new basic block (as the
366 // target of the current backedge) which does the safepoint (of all live
367 // variables) and branches to the true header
368 TerminatorInst *term = pred->getTerminator();
369
370 if (TraceLSP) {
371 errs() << "[LSP] terminator instruction: ";
372 term->dump();
373 }
374
375 PollLocations.push_back(term);
376 }
377
Philip Reames5708cca2015-05-12 20:43:48 +0000378 return false;
Philip Reames47cc6732015-02-04 00:37:33 +0000379}
380
Philip Reamesd97cdf22015-05-19 23:40:11 +0000381/// Returns true if an entry safepoint is not required before this callsite in
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000382/// the caller function.
Philip Reamesd97cdf22015-05-19 23:40:11 +0000383static bool doesNotRequireEntrySafepointBefore(const CallSite &CS) {
384 Instruction *Inst = CS.getInstruction();
385 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
386 switch (II->getIntrinsicID()) {
387 case Intrinsic::experimental_gc_statepoint:
388 case Intrinsic::experimental_patchpoint_void:
389 case Intrinsic::experimental_patchpoint_i64:
390 // The can wrap an actual call which may grow the stack by an unbounded
391 // amount or run forever.
392 return false;
393 default:
394 // Most LLVM intrinsics are things which do not expand to actual calls, or
395 // at least if they do, are leaf functions that cause only finite stack
396 // growth. In particular, the optimizer likes to form things like memsets
397 // out of stores in the original IR. Another important example is
Reid Kleckner60381792015-07-07 22:25:32 +0000398 // llvm.localescape which must occur in the entry block. Inserting a
399 // safepoint before it is not legal since it could push the localescape
Philip Reamesd97cdf22015-05-19 23:40:11 +0000400 // out of the entry block.
401 return true;
402 }
403 }
404 return false;
405}
406
Philip Reames47cc6732015-02-04 00:37:33 +0000407static Instruction *findLocationForEntrySafepoint(Function &F,
408 DominatorTree &DT) {
409
410 // Conceptually, this poll needs to be on method entry, but in
411 // practice, we place it as late in the entry block as possible. We
412 // can place it as late as we want as long as it dominates all calls
413 // that can grow the stack. This, combined with backedge polls,
414 // give us all the progress guarantees we need.
415
Philip Reames47cc6732015-02-04 00:37:33 +0000416 // hasNextInstruction and nextInstruction are used to iterate
417 // through a "straight line" execution sequence.
418
419 auto hasNextInstruction = [](Instruction *I) {
420 if (!I->isTerminator()) {
421 return true;
422 }
423 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
424 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
425 };
426
427 auto nextInstruction = [&hasNextInstruction](Instruction *I) {
428 assert(hasNextInstruction(I) &&
429 "first check if there is a next instruction!");
430 if (I->isTerminator()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000431 return &I->getParent()->getUniqueSuccessor()->front();
Philip Reames47cc6732015-02-04 00:37:33 +0000432 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000433 return &*++I->getIterator();
Philip Reames47cc6732015-02-04 00:37:33 +0000434 }
435 };
436
437 Instruction *cursor = nullptr;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000438 for (cursor = &F.getEntryBlock().front(); hasNextInstruction(cursor);
Philip Reames47cc6732015-02-04 00:37:33 +0000439 cursor = nextInstruction(cursor)) {
440
Philip Reamesd97cdf22015-05-19 23:40:11 +0000441 // We need to ensure a safepoint poll occurs before any 'real' call. The
442 // easiest way to ensure finite execution between safepoints in the face of
443 // recursive and mutually recursive functions is to enforce that each take
444 // a safepoint. Additionally, we need to ensure a poll before any call
445 // which can grow the stack by an unbounded amount. This isn't required
446 // for GC semantics per se, but is a common requirement for languages
447 // which detect stack overflow via guard pages and then throw exceptions.
448 if (auto CS = CallSite(cursor)) {
449 if (doesNotRequireEntrySafepointBefore(CS))
450 continue;
Philip Reames47cc6732015-02-04 00:37:33 +0000451 break;
452 }
453 }
454
Philip Reames5a9685d2015-02-04 00:39:57 +0000455 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
456 "either we stopped because of a call, or because of terminator");
Philip Reames47cc6732015-02-04 00:37:33 +0000457
Philip Reames52e7a592015-05-26 21:16:42 +0000458 return cursor;
Philip Reames47cc6732015-02-04 00:37:33 +0000459}
460
461/// Identify the list of call sites which need to be have parseable state
462static void findCallSafepoints(Function &F,
463 std::vector<CallSite> &Found /*rval*/) {
464 assert(Found.empty() && "must be empty!");
Nico Rieck78199512015-08-06 19:10:45 +0000465 for (Instruction &I : instructions(F)) {
Philip Reamesa29de872015-02-09 22:26:11 +0000466 Instruction *inst = &I;
Philip Reames47cc6732015-02-04 00:37:33 +0000467 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
468 CallSite CS(inst);
469
470 // No safepoint needed or wanted
471 if (!needsStatepoint(CS)) {
472 continue;
473 }
474
475 Found.push_back(CS);
476 }
477 }
478}
479
480/// Implement a unique function which doesn't require we sort the input
481/// vector. Doing so has the effect of changing the output of a couple of
482/// tests in ways which make them less useful in testing fused safepoints.
483template <typename T> static void unique_unsorted(std::vector<T> &vec) {
484 std::set<T> seen;
485 std::vector<T> tmp;
486 vec.reserve(vec.size());
487 std::swap(tmp, vec);
488 for (auto V : tmp) {
489 if (seen.insert(V).second) {
490 vec.push_back(V);
491 }
492 }
493}
494
Benjamin Kramer82f86522015-06-07 16:36:28 +0000495static const char *const GCSafepointPollName = "gc.safepoint_poll";
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000496
497static bool isGCSafepointPoll(Function &F) {
498 return F.getName().equals(GCSafepointPollName);
499}
500
Philip Reames0b1b3872015-02-21 00:09:09 +0000501/// Returns true if this function should be rewritten to include safepoint
502/// polls and parseable call sites. The main point of this function is to be
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000503/// an extension point for custom logic.
Philip Reames0b1b3872015-02-21 00:09:09 +0000504static bool shouldRewriteFunction(Function &F) {
505 // TODO: This should check the GCStrategy
506 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +0000507 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000508 const StringRef StatepointExampleName("statepoint-example");
509 const StringRef CoreCLRName("coreclr");
510 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +0000511 (CoreCLRName == FunctionGCName);
Philip Reames0b1b3872015-02-21 00:09:09 +0000512 } else
513 return false;
514}
515
516// TODO: These should become properties of the GCStrategy, possibly with
517// command line overrides.
518static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
519static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
520static bool enableCallSafepoints(Function &F) { return !NoCall; }
521
Igor Laevsky5e23e162015-05-08 11:59:09 +0000522// Normalize basic block to make it ready to be target of invoke statepoint.
523// Ensure that 'BB' does not have phi nodes. It may require spliting it.
524static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
525 BasicBlock *InvokeParent) {
526 BasicBlock *ret = BB;
527
528 if (!BB->getUniquePredecessor()) {
529 ret = SplitBlockPredecessors(BB, InvokeParent, "");
530 }
531
532 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
533 // from it
534 FoldSingleEntryPHINodes(ret);
535 assert(!isa<PHINode>(ret->begin()));
536
537 return ret;
538}
Philip Reames0b1b3872015-02-21 00:09:09 +0000539
Philip Reames47cc6732015-02-04 00:37:33 +0000540bool PlaceSafepoints::runOnFunction(Function &F) {
541 if (F.isDeclaration() || F.empty()) {
542 // This is a declaration, nothing to do. Must exit early to avoid crash in
543 // dom tree calculation
544 return false;
545 }
546
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000547 if (isGCSafepointPoll(F)) {
548 // Given we're inlining this inside of safepoint poll insertion, this
549 // doesn't make any sense. Note that we do make any contained calls
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000550 // parseable after we inline a poll.
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000551 return false;
552 }
553
Philip Reames0b1b3872015-02-21 00:09:09 +0000554 if (!shouldRewriteFunction(F))
555 return false;
556
Philip Reames47cc6732015-02-04 00:37:33 +0000557 bool modified = false;
558
559 // In various bits below, we rely on the fact that uses are reachable from
560 // defs. When there are basic blocks unreachable from the entry, dominance
561 // and reachablity queries return non-sensical results. Thus, we preprocess
562 // the function to ensure these properties hold.
563 modified |= removeUnreachableBlocks(F);
564
565 // STEP 1 - Insert the safepoint polling locations. We do not need to
566 // actually insert parse points yet. That will be done for all polls and
567 // calls in a single pass.
568
Philip Reames47cc6732015-02-04 00:37:33 +0000569 DominatorTree DT;
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000570 DT.recalculate(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000571
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000572 SmallVector<Instruction *, 16> PollsNeeded;
Philip Reames47cc6732015-02-04 00:37:33 +0000573 std::vector<CallSite> ParsePointNeeded;
574
Philip Reames0b1b3872015-02-21 00:09:09 +0000575 if (enableBackedgeSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000576 // Construct a pass manager to run the LoopPass backedge logic. We
577 // need the pass manager to handle scheduling all the loop passes
578 // appropriately. Doing this by hand is painful and just not worth messing
579 // with for the moment.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000580 legacy::FunctionPassManager FPM(F.getParent());
Philip Reames0b1b3872015-02-21 00:09:09 +0000581 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000582 PlaceBackedgeSafepointsImpl *PBS =
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000583 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
Philip Reames47cc6732015-02-04 00:37:33 +0000584 FPM.add(PBS);
Philip Reames47cc6732015-02-04 00:37:33 +0000585 FPM.run(F);
586
587 // We preserve dominance information when inserting the poll, otherwise
588 // we'd have to recalculate this on every insert
589 DT.recalculate(F);
590
Philip Reames5708cca2015-05-12 20:43:48 +0000591 auto &PollLocations = PBS->PollLocations;
592
593 auto OrderByBBName = [](Instruction *a, Instruction *b) {
594 return a->getParent()->getName() < b->getParent()->getName();
595 };
596 // We need the order of list to be stable so that naming ends up stable
597 // when we split edges. This makes test cases much easier to write.
598 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
599
600 // We can sometimes end up with duplicate poll locations. This happens if
601 // a single loop is visited more than once. The fact this happens seems
602 // wrong, but it does happen for the split-backedge.ll test case.
603 PollLocations.erase(std::unique(PollLocations.begin(),
604 PollLocations.end()),
605 PollLocations.end());
606
Philip Reames47cc6732015-02-04 00:37:33 +0000607 // Insert a poll at each point the analysis pass identified
Philip Reames89fe5702015-05-12 23:39:23 +0000608 // The poll location must be the terminator of a loop latch block.
609 for (TerminatorInst *Term : PollLocations) {
Philip Reames47cc6732015-02-04 00:37:33 +0000610 // We are inserting a poll, the function is modified
611 modified = true;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000612
Philip Reames47cc6732015-02-04 00:37:33 +0000613 if (SplitBackedge) {
614 // Split the backedge of the loop and insert the poll within that new
615 // basic block. This creates a loop with two latches per original
616 // latch (which is non-ideal), but this appears to be easier to
617 // optimize in practice than inserting the poll immediately before the
618 // latch test.
619
620 // Since this is a latch, at least one of the successors must dominate
621 // it. Its possible that we have a) duplicate edges to the same header
622 // and b) edges to distinct loop headers. We need to insert pools on
Philip Reames5708cca2015-05-12 20:43:48 +0000623 // each.
624 SetVector<BasicBlock *> Headers;
Philip Reames47cc6732015-02-04 00:37:33 +0000625 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
626 BasicBlock *Succ = Term->getSuccessor(i);
627 if (DT.dominates(Succ, Term->getParent())) {
628 Headers.insert(Succ);
629 }
630 }
631 assert(!Headers.empty() && "poll location is not a loop latch?");
632
633 // The split loop structure here is so that we only need to recalculate
634 // the dominator tree once. Alternatively, we could just keep it up to
635 // date and use a more natural merged loop.
Philip Reames5708cca2015-05-12 20:43:48 +0000636 SetVector<BasicBlock *> SplitBackedges;
Philip Reames47cc6732015-02-04 00:37:33 +0000637 for (BasicBlock *Header : Headers) {
Philip Reames89fe5702015-05-12 23:39:23 +0000638 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, &DT);
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000639 PollsNeeded.push_back(NewBB->getTerminator());
Philip Reames47cc6732015-02-04 00:37:33 +0000640 NumBackedgeSafepoints++;
641 }
Philip Reames47cc6732015-02-04 00:37:33 +0000642 } else {
643 // Split the latch block itself, right before the terminator.
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000644 PollsNeeded.push_back(Term);
Philip Reames47cc6732015-02-04 00:37:33 +0000645 NumBackedgeSafepoints++;
646 }
Philip Reames47cc6732015-02-04 00:37:33 +0000647 }
648 }
649
Philip Reames0b1b3872015-02-21 00:09:09 +0000650 if (enableEntrySafepoints(F)) {
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000651 Instruction *Location = findLocationForEntrySafepoint(F, DT);
652 if (!Location) {
Philip Reames47cc6732015-02-04 00:37:33 +0000653 // policy choice not to insert?
654 } else {
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000655 PollsNeeded.push_back(Location);
Philip Reames47cc6732015-02-04 00:37:33 +0000656 modified = true;
657 NumEntrySafepoints++;
Philip Reames47cc6732015-02-04 00:37:33 +0000658 }
659 }
660
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000661 // Now that we've identified all the needed safepoint poll locations, insert
662 // safepoint polls themselves.
663 for (Instruction *PollLocation : PollsNeeded) {
664 std::vector<CallSite> RuntimeCalls;
665 InsertSafepointPoll(PollLocation, RuntimeCalls);
666 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
667 RuntimeCalls.end());
668 }
Sanjoy Das95639742016-01-22 21:02:55 +0000669
670 // If we've been asked to not wrap the calls with gc.statepoint, then we're
671 // done. In the near future, this option will be "constant folded" to true,
672 // and the code below that deals with insert gc.statepoint calls will be
673 // removed. Wrapping potentially safepointing calls in gc.statepoint will
674 // then become the responsibility of the RewriteStatepointsForGC pass.
675 if (NoStatepoints)
676 return modified;
677
Philip Reames4d1a3ef2015-05-13 00:32:23 +0000678 PollsNeeded.clear(); // make sure we don't accidentally use
679 // The dominator tree has been invalidated by the inlining performed in the
680 // above loop. TODO: Teach the inliner how to update the dom tree?
681 DT.recalculate(F);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000682
Philip Reames0b1b3872015-02-21 00:09:09 +0000683 if (enableCallSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000684 std::vector<CallSite> Calls;
685 findCallSafepoints(F, Calls);
686 NumCallSafepoints += Calls.size();
Philip Reames5a9685d2015-02-04 00:39:57 +0000687 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
Philip Reames47cc6732015-02-04 00:37:33 +0000688 }
689
690 // Unique the vectors since we can end up with duplicates if we scan the call
691 // site for call safepoints after we add it for entry or backedge. The
692 // only reason we need tracking at all is that some functions might have
693 // polls but not call safepoints and thus we might miss marking the runtime
694 // calls for the polls. (This is useful in test cases!)
695 unique_unsorted(ParsePointNeeded);
696
697 // Any parse point (no matter what source) will be handled here
Philip Reames47cc6732015-02-04 00:37:33 +0000698
699 // We're about to start modifying the function
700 if (!ParsePointNeeded.empty())
701 modified = true;
702
703 // Now run through and insert the safepoints, but do _NOT_ update or remove
704 // any existing uses. We have references to live variables that need to
705 // survive to the last iteration of this loop.
706 std::vector<Value *> Results;
707 Results.reserve(ParsePointNeeded.size());
708 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
709 CallSite &CS = ParsePointNeeded[i];
Igor Laevsky5e23e162015-05-08 11:59:09 +0000710
711 // For invoke statepoints we need to remove all phi nodes at the normal
712 // destination block.
713 // Reason for this is that we can place gc_result only after last phi node
714 // in basic block. We will get malformed code after RAUW for the
715 // gc_result if one of this phi nodes uses result from the invoke.
716 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(CS.getInstruction())) {
717 normalizeForInvokeSafepoint(Invoke->getNormalDest(),
718 Invoke->getParent());
719 }
720
Justin Bogner843fb202015-12-15 19:40:57 +0000721 Value *GCResult = ReplaceWithStatepoint(CS);
Philip Reames47cc6732015-02-04 00:37:33 +0000722 Results.push_back(GCResult);
723 }
724 assert(Results.size() == ParsePointNeeded.size());
725
726 // Adjust all users of the old call sites to use the new ones instead
727 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
728 CallSite &CS = ParsePointNeeded[i];
729 Value *GCResult = Results[i];
730 if (GCResult) {
Chen Li74ca2a82015-05-18 19:02:25 +0000731 // Can not RAUW for the invoke gc result in case of phi nodes preset.
732 assert(CS.isCall() || !isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin()));
Philip Reames47cc6732015-02-04 00:37:33 +0000733
734 // Replace all uses with the new call
735 CS.getInstruction()->replaceAllUsesWith(GCResult);
736 }
737
738 // Now that we've handled all uses, remove the original call itself
739 // Note: The insert point can't be the deleted instruction!
740 CS.getInstruction()->eraseFromParent();
741 }
742 return modified;
743}
744
745char PlaceBackedgeSafepointsImpl::ID = 0;
746char PlaceSafepoints::ID = 0;
747
Philip Reames7b981792015-05-12 21:21:18 +0000748FunctionPass *llvm::createPlaceSafepointsPass() {
749 return new PlaceSafepoints();
750}
Philip Reames47cc6732015-02-04 00:37:33 +0000751
752INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
753 "place-backedge-safepoints-impl",
754 "Place Backedge Safepoints", false, false)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000755INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Philip Reames57bdac92015-05-12 20:56:33 +0000756INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Philip Reames9f129042015-05-12 21:09:36 +0000757INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Philip Reames47cc6732015-02-04 00:37:33 +0000758INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
759 "place-backedge-safepoints-impl",
760 "Place Backedge Safepoints", false, false)
761
762INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
763 false, false)
764INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
765 false, false)
766
Philip Reames5a9685d2015-02-04 00:39:57 +0000767static void
Philip Reames388402452015-05-26 21:03:23 +0000768InsertSafepointPoll(Instruction *InsertBefore,
Philip Reames5a9685d2015-02-04 00:39:57 +0000769 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
Philip Reames388402452015-05-26 21:03:23 +0000770 BasicBlock *OrigBB = InsertBefore->getParent();
771 Module *M = InsertBefore->getModule();
772 assert(M && "must be part of a module");
Philip Reames47cc6732015-02-04 00:37:33 +0000773
774 // Inline the safepoint poll implementation - this will get all the branch,
775 // control flow, etc.. Most importantly, it will introduce the actual slow
776 // path call - where we need to insert a safepoint (parsepoint).
Philip Reames388402452015-05-26 21:03:23 +0000777
778 auto *F = M->getFunction(GCSafepointPollName);
Manuel Jacobe3773d62015-12-29 21:57:55 +0000779 assert(F && "gc.safepoint_poll function is missing");
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000780 assert(F->getValueType() ==
Philip Reames388402452015-05-26 21:03:23 +0000781 FunctionType::get(Type::getVoidTy(M->getContext()), false) &&
782 "gc.safepoint_poll declared with wrong type");
Ramkumar Ramachandra3edf74f2015-02-09 23:02:10 +0000783 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
Philip Reames388402452015-05-26 21:03:23 +0000784 CallInst *PollCall = CallInst::Create(F, "", InsertBefore);
Philip Reames47cc6732015-02-04 00:37:33 +0000785
786 // Record some information about the call site we're replacing
Philip Reames388402452015-05-26 21:03:23 +0000787 BasicBlock::iterator before(PollCall), after(PollCall);
Philip Reames47cc6732015-02-04 00:37:33 +0000788 bool isBegin(false);
Philip Reames388402452015-05-26 21:03:23 +0000789 if (before == OrigBB->begin()) {
Philip Reames47cc6732015-02-04 00:37:33 +0000790 isBegin = true;
791 } else {
792 before--;
793 }
794 after++;
Philip Reames388402452015-05-26 21:03:23 +0000795 assert(after != OrigBB->end() && "must have successor");
Philip Reames47cc6732015-02-04 00:37:33 +0000796
797 // do the actual inlining
798 InlineFunctionInfo IFI;
Philip Reames388402452015-05-26 21:03:23 +0000799 bool InlineStatus = InlineFunction(PollCall, IFI);
800 assert(InlineStatus && "inline must succeed");
801 (void)InlineStatus; // suppress warning in release-asserts
Philip Reames47cc6732015-02-04 00:37:33 +0000802
803 // Check post conditions
804 assert(IFI.StaticAllocas.empty() && "can't have allocs");
805
806 std::vector<CallInst *> calls; // new calls
807 std::set<BasicBlock *> BBs; // new BBs + insertee
808 // Include only the newly inserted instructions, Note: begin may not be valid
809 // if we inserted to the beginning of the basic block
810 BasicBlock::iterator start;
811 if (isBegin) {
812 start = OrigBB->begin();
813 } else {
814 start = before;
815 start++;
816 }
817
818 // If your poll function includes an unreachable at the end, that's not
819 // valid. Bugpoint likes to create this, so check for it.
820 assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) &&
821 "malformed poll function");
822
823 scanInlinedCode(&*(start), &*(after), calls, BBs);
Philip Reames47cc6732015-02-04 00:37:33 +0000824 assert(!calls.empty() && "slow path not found for safepoint poll");
825
826 // Record the fact we need a parsable state at the runtime call contained in
827 // the poll function. This is required so that the runtime knows how to
828 // parse the last frame when we actually take the safepoint (i.e. execute
829 // the slow path)
830 assert(ParsePointsNeeded.empty());
831 for (size_t i = 0; i < calls.size(); i++) {
832
833 // No safepoint needed or wanted
834 if (!needsStatepoint(calls[i])) {
835 continue;
836 }
837
838 // These are likely runtime calls. Should we assert that via calling
839 // convention or something?
840 ParsePointsNeeded.push_back(CallSite(calls[i]));
841 }
842 assert(ParsePointsNeeded.size() <= calls.size());
843}
844
Philip Reames47cc6732015-02-04 00:37:33 +0000845/// Replaces the given call site (Call or Invoke) with a gc.statepoint
846/// intrinsic with an empty deoptimization arguments list. This does
847/// NOT do explicit relocation for GC support.
Justin Bogner843fb202015-12-15 19:40:57 +0000848static Value *ReplaceWithStatepoint(const CallSite &CS /* to replace */) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000849 assert(CS.getInstruction()->getModule() && "must be set");
Philip Reames47cc6732015-02-04 00:37:33 +0000850
851 // TODO: technically, a pass is not allowed to get functions from within a
852 // function pass since it might trigger a new function addition. Refactor
853 // this logic out to the initialization of the pass. Doesn't appear to
854 // matter in practice.
855
Philip Reames47cc6732015-02-04 00:37:33 +0000856 // Then go ahead and use the builder do actually do the inserts. We insert
857 // immediately before the previous instruction under the assumption that all
858 // arguments will be available here. We can't insert afterwards since we may
859 // be replacing a terminator.
Sanjoy Das93abd812015-05-06 23:53:19 +0000860 IRBuilder<> Builder(CS.getInstruction());
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000861
862 // Note: The gc args are not filled in at this time, that's handled by
863 // RewriteStatepointsForGC (which is currently under review).
864
Philip Reames47cc6732015-02-04 00:37:33 +0000865 // Create the statepoint given all the arguments
Sanjoy Das93abd812015-05-06 23:53:19 +0000866 Instruction *Token = nullptr;
Sanjoy Dasba74e642015-05-13 20:11:31 +0000867
868 uint64_t ID;
869 uint32_t NumPatchBytes;
870
871 AttributeSet OriginalAttrs = CS.getAttributes();
872 Attribute AttrID =
873 OriginalAttrs.getAttribute(AttributeSet::FunctionIndex, "statepoint-id");
874 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
875 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
876
877 AttrBuilder AttrsToRemove;
878 bool HasID = AttrID.isStringAttribute() &&
879 !AttrID.getValueAsString().getAsInteger(10, ID);
880
881 if (HasID)
882 AttrsToRemove.addAttribute("statepoint-id");
883 else
884 ID = 0xABCDEF00;
885
886 bool HasNumPatchBytes =
887 AttrNumPatchBytes.isStringAttribute() &&
888 !AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
889
890 if (HasNumPatchBytes)
891 AttrsToRemove.addAttribute("statepoint-num-patch-bytes");
892 else
893 NumPatchBytes = 0;
894
895 OriginalAttrs = OriginalAttrs.removeAttributes(
896 CS.getInstruction()->getContext(), AttributeSet::FunctionIndex,
897 AttrsToRemove);
898
Philip Reames47cc6732015-02-04 00:37:33 +0000899 if (CS.isCall()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000900 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Dasabe1c682015-05-06 23:53:09 +0000901 CallInst *Call = Builder.CreateGCStatepointCall(
Sanjoy Dascfe41f02015-07-28 23:50:30 +0000902 ID, NumPatchBytes, CS.getCalledValue(),
Sanjoy Dasba74e642015-05-13 20:11:31 +0000903 makeArrayRef(CS.arg_begin(), CS.arg_end()), None, None,
904 "safepoint_token");
Sanjoy Das93abd812015-05-06 23:53:19 +0000905 Call->setTailCall(ToReplace->isTailCall());
906 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reames47cc6732015-02-04 00:37:33 +0000907
Sanjoy Dasabf15602015-05-06 23:53:21 +0000908 // In case if we can handle this set of attributes - set up function
909 // attributes directly on statepoint and return attributes later for
910 // gc_result intrinsic.
911 Call->setAttributes(OriginalAttrs.getFnAttributes());
Philip Reames47cc6732015-02-04 00:37:33 +0000912
Sanjoy Das93abd812015-05-06 23:53:19 +0000913 Token = Call;
Philip Reames47cc6732015-02-04 00:37:33 +0000914
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000915 // Put the following gc_result and gc_relocate calls immediately after
Sanjoy Dasabf15602015-05-06 23:53:21 +0000916 // the old call (which we're about to delete).
917 assert(ToReplace->getNextNode() && "not a terminator, must have next");
918 Builder.SetInsertPoint(ToReplace->getNextNode());
919 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
Philip Reames47cc6732015-02-04 00:37:33 +0000920 } else if (CS.isInvoke()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000921 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reames47cc6732015-02-04 00:37:33 +0000922
923 // Insert the new invoke into the old block. We'll remove the old one in a
924 // moment at which point this will become the new terminator for the
925 // original block.
Sanjoy Das93abd812015-05-06 23:53:19 +0000926 Builder.SetInsertPoint(ToReplace->getParent());
927 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
Sanjoy Dascfe41f02015-07-28 23:50:30 +0000928 ID, NumPatchBytes, CS.getCalledValue(), ToReplace->getNormalDest(),
Sanjoy Das93abd812015-05-06 23:53:19 +0000929 ToReplace->getUnwindDest(), makeArrayRef(CS.arg_begin(), CS.arg_end()),
Sanjoy Das80458102015-05-15 00:26:15 +0000930 None, None, "safepoint_token");
Philip Reames47cc6732015-02-04 00:37:33 +0000931
Sanjoy Das2c266142015-05-15 00:26:21 +0000932 Invoke->setCallingConv(ToReplace->getCallingConv());
933
Sanjoy Dasabf15602015-05-06 23:53:21 +0000934 // 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.
Sanjoy Das93abd812015-05-06 23:53:19 +0000937 Invoke->setAttributes(OriginalAttrs.getFnAttributes());
Philip Reames47cc6732015-02-04 00:37:33 +0000938
Sanjoy Das93abd812015-05-06 23:53:19 +0000939 Token = Invoke;
Philip Reames47cc6732015-02-04 00:37:33 +0000940
941 // We'll insert the gc.result into the normal block
Igor Laevsky5e23e162015-05-08 11:59:09 +0000942 BasicBlock *NormalDest = ToReplace->getNormalDest();
943 // Can not insert gc.result in case of phi nodes preset.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000944 // Should have removed this cases prior to running this function
Igor Laevsky5e23e162015-05-08 11:59:09 +0000945 assert(!isa<PHINode>(NormalDest->begin()));
946 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
947 Builder.SetInsertPoint(IP);
Philip Reames47cc6732015-02-04 00:37:33 +0000948 } else {
949 llvm_unreachable("unexpect type of CallSite");
950 }
Sanjoy Das93abd812015-05-06 23:53:19 +0000951 assert(Token);
Philip Reames47cc6732015-02-04 00:37:33 +0000952
953 // Handle the return value of the original call - update all uses to use a
954 // gc_result hanging off the statepoint node we just inserted
955
956 // Only add the gc_result iff there is actually a used result
957 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000958 std::string TakenName =
959 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
960 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), TakenName);
Sanjoy Dasabf15602015-05-06 23:53:21 +0000961 GCResult->setAttributes(OriginalAttrs.getRetAttributes());
Sanjoy Das93abd812015-05-06 23:53:19 +0000962 return GCResult;
Philip Reames47cc6732015-02-04 00:37:33 +0000963 } else {
964 // No return value for the call.
965 return nullptr;
966 }
967}