blob: b5124b7adc4aef0ef3880c9135828aa53574dea1 [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
19// point is represented by a call wrapped in an gc.statepoint intrinsic.
20// - A "poll" is an explicit check in the generated code to determine if the
21// runtime needs the generated code to cooperate by calling a helper routine
22// and thus suspending its execution at a known state. The call to the helper
23// routine will be parseable. The (gc & runtime specific) logic of a poll is
24// assumed to be provided in a function of the name "gc.safepoint_poll".
25//
26// We aim to insert polls such that running code can quickly be brought to a
27// well defined state for inspection by the collector. In the current
28// implementation, this is done via the insertion of poll sites at method entry
29// and the backedge of most loops. We try to avoid inserting more polls than
30// are neccessary to ensure a finite period between poll sites. This is not
31// because the poll itself is expensive in the generated code; it's not. Polls
32// do tend to impact the optimizer itself in negative ways; we'd like to avoid
33// perturbing the optimization of the method as much as we can.
34//
35// We also need to make most call sites parseable. The callee might execute a
36// poll (or otherwise be inspected by the GC). If so, the entire stack
37// (including the suspended frame of the current method) must be parseable.
38//
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"
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"
82
83#define DEBUG_TYPE "safepoint-placement"
84STATISTIC(NumEntrySafepoints, "Number of entry safepoints inserted");
85STATISTIC(NumCallSafepoints, "Number of call safepoints inserted");
86STATISTIC(NumBackedgeSafepoints, "Number of backedge safepoints inserted");
87
88STATISTIC(CallInLoop, "Number of loops w/o safepoints due to calls in loop");
89STATISTIC(FiniteExecution, "Number of loops w/o safepoints finite execution");
90
91using namespace llvm;
92
93// Ignore oppurtunities to avoid placing safepoints on backedges, useful for
94// validation
Philip Reames1f3e5c12015-02-20 23:32:03 +000095static cl::opt<bool> AllBackedges("spp-all-backedges", cl::Hidden,
96 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +000097
98/// If true, do not place backedge safepoints in counted loops.
Philip Reames1f3e5c12015-02-20 23:32:03 +000099static cl::opt<bool> SkipCounted("spp-counted", cl::Hidden, cl::init(true));
Philip Reames47cc6732015-02-04 00:37:33 +0000100
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
104// optimizes better.
Philip Reames1f3e5c12015-02-20 23:32:03 +0000105static cl::opt<bool> SplitBackedge("spp-split-backedge", cl::Hidden,
106 cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000107
108// Print tracing output
Philip Reames1f3e5c12015-02-20 23:32:03 +0000109static cl::opt<bool> TraceLSP("spp-trace", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000110
111namespace {
112
Philip Reames9f129042015-05-12 21:09:36 +0000113/// An analysis pass whose purpose is to identify each of the backedges in
114/// the function which require a safepoint poll to be inserted.
115struct PlaceBackedgeSafepointsImpl : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000116 static char ID;
117
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;
121
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;
Philip Reames9f129042015-05-12 21:09:36 +0000125
126 ScalarEvolution *SE = nullptr;
127 DominatorTree *DT = nullptr;
128 LoopInfo *LI = nullptr;
129
Philip Reames47cc6732015-02-04 00:37:33 +0000130 PlaceBackedgeSafepointsImpl(bool CallSafepoints = false)
Philip Reames9f129042015-05-12 21:09:36 +0000131 : FunctionPass(ID), CallSafepointsEnabled(CallSafepoints) {
Philip Reames5a9685d2015-02-04 00:39:57 +0000132 initializePlaceBackedgeSafepointsImplPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000133 }
134
Philip Reames9f129042015-05-12 21:09:36 +0000135 bool runOnLoop(Loop *);
136 void runOnLoopAndSubLoops(Loop *L) {
137 // Visit all the subloops
138 for (auto I = L->begin(), E = L->end(); I != E; I++)
139 runOnLoopAndSubLoops(*I);
140 runOnLoop(L);
141 }
Justin Bogner383749a2015-05-12 21:49:47 +0000142
143 bool runOnFunction(Function &F) override {
Philip Reames9f129042015-05-12 21:09:36 +0000144 SE = &getAnalysis<ScalarEvolution>();
145 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
146 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
147 for (auto I = LI->begin(), E = LI->end(); I != E; I++) {
148 runOnLoopAndSubLoops(*I);
149 }
150 return false;
151 }
152
Philip Reames47cc6732015-02-04 00:37:33 +0000153 void getAnalysisUsage(AnalysisUsage &AU) const override {
Philip Reames57bdac92015-05-12 20:56:33 +0000154 AU.addRequired<DominatorTreeWrapperPass>();
Philip Reames47cc6732015-02-04 00:37:33 +0000155 AU.addRequired<ScalarEvolution>();
Philip Reames9f129042015-05-12 21:09:36 +0000156 AU.addRequired<LoopInfoWrapperPass>();
Philip Reames47cc6732015-02-04 00:37:33 +0000157 // We no longer modify the IR at all in this pass. Thus all
158 // analysis are preserved.
159 AU.setPreservesAll();
160 }
161};
162}
163
Philip Reames1f3e5c12015-02-20 23:32:03 +0000164static cl::opt<bool> NoEntry("spp-no-entry", cl::Hidden, cl::init(false));
165static cl::opt<bool> NoCall("spp-no-call", cl::Hidden, cl::init(false));
166static cl::opt<bool> NoBackedge("spp-no-backedge", cl::Hidden, cl::init(false));
Philip Reames47cc6732015-02-04 00:37:33 +0000167
168namespace {
Philip Reames7b981792015-05-12 21:21:18 +0000169struct PlaceSafepoints : public FunctionPass {
Philip Reames47cc6732015-02-04 00:37:33 +0000170 static char ID; // Pass identification, replacement for typeid
171
Philip Reames7b981792015-05-12 21:21:18 +0000172 PlaceSafepoints() : FunctionPass(ID) {
Philip Reames47cc6732015-02-04 00:37:33 +0000173 initializePlaceSafepointsPass(*PassRegistry::getPassRegistry());
Philip Reames47cc6732015-02-04 00:37:33 +0000174 }
Philip Reames7b981792015-05-12 21:21:18 +0000175 bool runOnFunction(Function &F) override;
Philip Reames47cc6732015-02-04 00:37:33 +0000176
177 void getAnalysisUsage(AnalysisUsage &AU) const override {
178 // We modify the graph wholesale (inlining, block insertion, etc). We
179 // preserve nothing at the moment. We could potentially preserve dom tree
180 // if that was worth doing
181 }
182};
183}
184
185// Insert a safepoint poll immediately before the given instruction. Does
186// not handle the parsability of state at the runtime call, that's the
187// callers job.
Philip Reames5a9685d2015-02-04 00:39:57 +0000188static void
189InsertSafepointPoll(DominatorTree &DT, Instruction *after,
190 std::vector<CallSite> &ParsePointsNeeded /*rval*/);
Philip Reames47cc6732015-02-04 00:37:33 +0000191
192static bool isGCLeafFunction(const CallSite &CS);
193
194static bool needsStatepoint(const CallSite &CS) {
195 if (isGCLeafFunction(CS))
196 return false;
197 if (CS.isCall()) {
198 CallInst *call = cast<CallInst>(CS.getInstruction());
199 if (call->isInlineAsm())
200 return false;
201 }
202 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS)) {
203 return false;
204 }
205 return true;
206}
207
Philip Reames5a9685d2015-02-04 00:39:57 +0000208static Value *ReplaceWithStatepoint(const CallSite &CS, Pass *P);
Philip Reames47cc6732015-02-04 00:37:33 +0000209
210/// Returns true if this loop is known to contain a call safepoint which
211/// must unconditionally execute on any iteration of the loop which returns
212/// to the loop header via an edge from Pred. Returns a conservative correct
213/// answer; i.e. false is always valid.
214static bool containsUnconditionalCallSafepoint(Loop *L, BasicBlock *Header,
215 BasicBlock *Pred,
216 DominatorTree &DT) {
217 // In general, we're looking for any cut of the graph which ensures
218 // there's a call safepoint along every edge between Header and Pred.
219 // For the moment, we look only for the 'cuts' that consist of a single call
220 // instruction in a block which is dominated by the Header and dominates the
221 // loop latch (Pred) block. Somewhat surprisingly, walking the entire chain
222 // of such dominating blocks gets substaintially more occurences than just
223 // checking the Pred and Header blocks themselves. This may be due to the
224 // density of loop exit conditions caused by range and null checks.
225 // TODO: structure this as an analysis pass, cache the result for subloops,
226 // avoid dom tree recalculations
227 assert(DT.dominates(Header, Pred) && "loop latch not dominated by header?");
228
229 BasicBlock *Current = Pred;
230 while (true) {
231 for (Instruction &I : *Current) {
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000232 if (auto CS = CallSite(&I))
Philip Reames47cc6732015-02-04 00:37:33 +0000233 // Note: Technically, needing a safepoint isn't quite the right
234 // condition here. We should instead be checking if the target method
235 // has an
236 // unconditional poll. In practice, this is only a theoretical concern
237 // since we don't have any methods with conditional-only safepoint
238 // polls.
239 if (needsStatepoint(CS))
240 return true;
241 }
242
243 if (Current == Header)
244 break;
245 Current = DT.getNode(Current)->getIDom()->getBlock();
246 }
247
248 return false;
249}
250
251/// Returns true if this loop is known to terminate in a finite number of
252/// iterations. Note that this function may return false for a loop which
253/// does actual terminate in a finite constant number of iterations due to
254/// conservatism in the analysis.
255static bool mustBeFiniteCountedLoop(Loop *L, ScalarEvolution *SE,
Philip Reames5a9685d2015-02-04 00:39:57 +0000256 BasicBlock *Pred) {
Philip Reames47cc6732015-02-04 00:37:33 +0000257 // Only used when SkipCounted is off
258 const unsigned upperTripBound = 8192;
259
260 // A conservative bound on the loop as a whole.
261 const SCEV *MaxTrips = SE->getMaxBackedgeTakenCount(L);
262 if (MaxTrips != SE->getCouldNotCompute()) {
263 if (SE->getUnsignedRange(MaxTrips).getUnsignedMax().ult(upperTripBound))
264 return true;
265 if (SkipCounted &&
266 SE->getUnsignedRange(MaxTrips).getUnsignedMax().isIntN(32))
267 return true;
268 }
269
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);
277 if (MaxExec != SE->getCouldNotCompute()) {
278 if (SE->getUnsignedRange(MaxExec).getUnsignedMax().ult(upperTripBound))
279 return true;
280 if (SkipCounted &&
281 SE->getUnsignedRange(MaxExec).getUnsignedMax().isIntN(32))
282 return true;
283 }
284 }
285
286 return /* not finite */ false;
287}
288
289static void scanOneBB(Instruction *start, Instruction *end,
Philip Reames5a9685d2015-02-04 00:39:57 +0000290 std::vector<CallInst *> &calls,
291 std::set<BasicBlock *> &seen,
292 std::vector<BasicBlock *> &worklist) {
Philip Reames47cc6732015-02-04 00:37:33 +0000293 for (BasicBlock::iterator itr(start);
294 itr != start->getParent()->end() && itr != BasicBlock::iterator(end);
295 itr++) {
296 if (CallInst *CI = dyn_cast<CallInst>(&*itr)) {
297 calls.push_back(CI);
298 }
299 // FIXME: This code does not handle invokes
300 assert(!dyn_cast<InvokeInst>(&*itr) &&
301 "support for invokes in poll code needed");
302 // Only add the successor blocks if we reach the terminator instruction
303 // without encountering end first
304 if (itr->isTerminator()) {
305 BasicBlock *BB = itr->getParent();
Philip Reamesa29de872015-02-09 22:26:11 +0000306 for (BasicBlock *Succ : successors(BB)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000307 if (seen.count(Succ) == 0) {
308 worklist.push_back(Succ);
309 seen.insert(Succ);
310 }
311 }
312 }
313 }
314}
315static void scanInlinedCode(Instruction *start, Instruction *end,
Philip Reames5a9685d2015-02-04 00:39:57 +0000316 std::vector<CallInst *> &calls,
317 std::set<BasicBlock *> &seen) {
Philip Reames47cc6732015-02-04 00:37:33 +0000318 calls.clear();
319 std::vector<BasicBlock *> worklist;
320 seen.insert(start->getParent());
321 scanOneBB(start, end, calls, seen, worklist);
322 while (!worklist.empty()) {
323 BasicBlock *BB = worklist.back();
324 worklist.pop_back();
325 scanOneBB(&*BB->begin(), end, calls, seen, worklist);
326 }
327}
328
Philip Reames9f129042015-05-12 21:09:36 +0000329bool PlaceBackedgeSafepointsImpl::runOnLoop(Loop *L) {
Philip Reames5708cca2015-05-12 20:43:48 +0000330 // Loop through all loop latches (branches controlling backedges). We need
331 // to place a safepoint on every backedge (potentially).
332 // Note: In common usage, there will be only one edge due to LoopSimplify
333 // having run sometime earlier in the pipeline, but this code must be correct
334 // w.r.t. loops with multiple backedges.
Philip Reames47cc6732015-02-04 00:37:33 +0000335 BasicBlock *header = L->getHeader();
Philip Reames5708cca2015-05-12 20:43:48 +0000336 SmallVector<BasicBlock*, 16> LoopLatches;
337 L->getLoopLatches(LoopLatches);
338 for (BasicBlock *pred : LoopLatches) {
339 assert(L->contains(pred));
Philip Reames47cc6732015-02-04 00:37:33 +0000340
341 // Make a policy decision about whether this loop needs a safepoint or
342 // not. Note that this is about unburdening the optimizer in loops, not
343 // avoiding the runtime cost of the actual safepoint.
344 if (!AllBackedges) {
345 if (mustBeFiniteCountedLoop(L, SE, pred)) {
346 if (TraceLSP)
347 errs() << "skipping safepoint placement in finite loop\n";
348 FiniteExecution++;
349 continue;
350 }
351 if (CallSafepointsEnabled &&
Philip Reames57bdac92015-05-12 20:56:33 +0000352 containsUnconditionalCallSafepoint(L, header, pred, *DT)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000353 // Note: This is only semantically legal since we won't do any further
354 // IPO or inlining before the actual call insertion.. If we hadn't, we
355 // might latter loose this call safepoint.
356 if (TraceLSP)
357 errs() << "skipping safepoint placement due to unconditional call\n";
358 CallInLoop++;
359 continue;
360 }
361 }
362
363 // TODO: We can create an inner loop which runs a finite number of
364 // iterations with an outer loop which contains a safepoint. This would
365 // not help runtime performance that much, but it might help our ability to
366 // optimize the inner loop.
367
Philip Reames47cc6732015-02-04 00:37:33 +0000368 // Safepoint insertion would involve creating a new basic block (as the
369 // target of the current backedge) which does the safepoint (of all live
370 // variables) and branches to the true header
371 TerminatorInst *term = pred->getTerminator();
372
373 if (TraceLSP) {
374 errs() << "[LSP] terminator instruction: ";
375 term->dump();
376 }
377
378 PollLocations.push_back(term);
379 }
380
Philip Reames5708cca2015-05-12 20:43:48 +0000381 return false;
Philip Reames47cc6732015-02-04 00:37:33 +0000382}
383
384static Instruction *findLocationForEntrySafepoint(Function &F,
385 DominatorTree &DT) {
386
387 // Conceptually, this poll needs to be on method entry, but in
388 // practice, we place it as late in the entry block as possible. We
389 // can place it as late as we want as long as it dominates all calls
390 // that can grow the stack. This, combined with backedge polls,
391 // give us all the progress guarantees we need.
392
393 // Due to the way the frontend generates IR, we may have a couple of initial
394 // basic blocks before the first bytecode. These will be single-entry
395 // single-exit blocks which conceptually are just part of the first 'real
396 // basic block'. Since we don't have deopt state until the first bytecode,
397 // walk forward until we've found the first unconditional branch or merge.
398
399 // hasNextInstruction and nextInstruction are used to iterate
400 // through a "straight line" execution sequence.
401
402 auto hasNextInstruction = [](Instruction *I) {
403 if (!I->isTerminator()) {
404 return true;
405 }
406 BasicBlock *nextBB = I->getParent()->getUniqueSuccessor();
407 return nextBB && (nextBB->getUniquePredecessor() != nullptr);
408 };
409
410 auto nextInstruction = [&hasNextInstruction](Instruction *I) {
411 assert(hasNextInstruction(I) &&
412 "first check if there is a next instruction!");
413 if (I->isTerminator()) {
414 return I->getParent()->getUniqueSuccessor()->begin();
415 } else {
416 return std::next(BasicBlock::iterator(I));
417 }
418 };
419
420 Instruction *cursor = nullptr;
421 for (cursor = F.getEntryBlock().begin(); hasNextInstruction(cursor);
422 cursor = nextInstruction(cursor)) {
423
Philip Reames47cc6732015-02-04 00:37:33 +0000424 // We need to stop going forward as soon as we see a call that can
425 // grow the stack (i.e. the call target has a non-zero frame
426 // size).
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000427 if (CallSite(cursor)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000428 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(cursor)) {
429 // llvm.assume(...) are not really calls.
430 if (II->getIntrinsicID() == Intrinsic::assume) {
431 continue;
432 }
Philip Reames2e78fa42015-04-26 19:41:23 +0000433 // llvm.frameescape() intrinsic is not a real call. The intrinsic can
434 // exist only in the entry block.
435 // Inserting a statepoint before llvm.frameescape() may split the
436 // entry block, and push the intrinsic out of the entry block.
437 if (II->getIntrinsicID() == Intrinsic::frameescape) {
438 continue;
439 }
Philip Reames47cc6732015-02-04 00:37:33 +0000440 }
441 break;
442 }
443 }
444
Philip Reames5a9685d2015-02-04 00:39:57 +0000445 assert((hasNextInstruction(cursor) || cursor->isTerminator()) &&
446 "either we stopped because of a call, or because of terminator");
Philip Reames47cc6732015-02-04 00:37:33 +0000447
448 if (cursor->isTerminator()) {
449 return cursor;
450 }
451
452 BasicBlock *BB = cursor->getParent();
453 SplitBlock(BB, cursor, nullptr);
454
455 // Note: SplitBlock modifies the DT. Simply passing a Pass (which is a
456 // module pass) is not enough.
457 DT.recalculate(F);
Adam Nemete340f852015-05-06 08:18:41 +0000458
Philip Reames47cc6732015-02-04 00:37:33 +0000459 // SplitBlock updates the DT
Adam Nemete340f852015-05-06 08:18:41 +0000460 DEBUG(DT.verifyDomTree());
Philip Reames47cc6732015-02-04 00:37:33 +0000461
462 return BB->getTerminator();
463}
464
465/// Identify the list of call sites which need to be have parseable state
466static void findCallSafepoints(Function &F,
467 std::vector<CallSite> &Found /*rval*/) {
468 assert(Found.empty() && "must be empty!");
Philip Reamesa29de872015-02-09 22:26:11 +0000469 for (Instruction &I : inst_range(F)) {
470 Instruction *inst = &I;
Philip Reames47cc6732015-02-04 00:37:33 +0000471 if (isa<CallInst>(inst) || isa<InvokeInst>(inst)) {
472 CallSite CS(inst);
473
474 // No safepoint needed or wanted
475 if (!needsStatepoint(CS)) {
476 continue;
477 }
478
479 Found.push_back(CS);
480 }
481 }
482}
483
484/// Implement a unique function which doesn't require we sort the input
485/// vector. Doing so has the effect of changing the output of a couple of
486/// tests in ways which make them less useful in testing fused safepoints.
487template <typename T> static void unique_unsorted(std::vector<T> &vec) {
488 std::set<T> seen;
489 std::vector<T> tmp;
490 vec.reserve(vec.size());
491 std::swap(tmp, vec);
492 for (auto V : tmp) {
493 if (seen.insert(V).second) {
494 vec.push_back(V);
495 }
496 }
497}
498
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000499static std::string GCSafepointPollName("gc.safepoint_poll");
500
501static bool isGCSafepointPoll(Function &F) {
502 return F.getName().equals(GCSafepointPollName);
503}
504
Philip Reames0b1b3872015-02-21 00:09:09 +0000505/// Returns true if this function should be rewritten to include safepoint
506/// polls and parseable call sites. The main point of this function is to be
507/// an extension point for custom logic.
508static bool shouldRewriteFunction(Function &F) {
509 // TODO: This should check the GCStrategy
510 if (F.hasGC()) {
511 const std::string StatepointExampleName("statepoint-example");
512 return StatepointExampleName == F.getGC();
513 } else
514 return false;
515}
516
517// TODO: These should become properties of the GCStrategy, possibly with
518// command line overrides.
519static bool enableEntrySafepoints(Function &F) { return !NoEntry; }
520static bool enableBackedgeSafepoints(Function &F) { return !NoBackedge; }
521static bool enableCallSafepoints(Function &F) { return !NoCall; }
522
Igor Laevsky5e23e162015-05-08 11:59:09 +0000523// Normalize basic block to make it ready to be target of invoke statepoint.
524// Ensure that 'BB' does not have phi nodes. It may require spliting it.
525static BasicBlock *normalizeForInvokeSafepoint(BasicBlock *BB,
526 BasicBlock *InvokeParent) {
527 BasicBlock *ret = BB;
528
529 if (!BB->getUniquePredecessor()) {
530 ret = SplitBlockPredecessors(BB, InvokeParent, "");
531 }
532
533 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
534 // from it
535 FoldSingleEntryPHINodes(ret);
536 assert(!isa<PHINode>(ret->begin()));
537
538 return ret;
539}
Philip Reames0b1b3872015-02-21 00:09:09 +0000540
Philip Reames47cc6732015-02-04 00:37:33 +0000541bool PlaceSafepoints::runOnFunction(Function &F) {
542 if (F.isDeclaration() || F.empty()) {
543 // This is a declaration, nothing to do. Must exit early to avoid crash in
544 // dom tree calculation
545 return false;
546 }
547
Philip Reames7e7dc3e2015-02-10 00:04:53 +0000548 if (isGCSafepointPoll(F)) {
549 // Given we're inlining this inside of safepoint poll insertion, this
550 // doesn't make any sense. Note that we do make any contained calls
551 // parseable after we inline a poll.
552 return false;
553 }
554
Philip Reames0b1b3872015-02-21 00:09:09 +0000555 if (!shouldRewriteFunction(F))
556 return false;
557
Philip Reames47cc6732015-02-04 00:37:33 +0000558 bool modified = false;
559
560 // In various bits below, we rely on the fact that uses are reachable from
561 // defs. When there are basic blocks unreachable from the entry, dominance
562 // and reachablity queries return non-sensical results. Thus, we preprocess
563 // the function to ensure these properties hold.
564 modified |= removeUnreachableBlocks(F);
565
566 // STEP 1 - Insert the safepoint polling locations. We do not need to
567 // actually insert parse points yet. That will be done for all polls and
568 // calls in a single pass.
569
570 // Note: With the migration, we need to recompute this for each 'pass'. Once
571 // we merge these, we'll do it once before the analysis
572 DominatorTree DT;
573
574 std::vector<CallSite> ParsePointNeeded;
575
Philip Reames0b1b3872015-02-21 00:09:09 +0000576 if (enableBackedgeSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000577 // Construct a pass manager to run the LoopPass backedge logic. We
578 // need the pass manager to handle scheduling all the loop passes
579 // appropriately. Doing this by hand is painful and just not worth messing
580 // with for the moment.
Chandler Carruth30d69c22015-02-13 10:01:29 +0000581 legacy::FunctionPassManager FPM(F.getParent());
Philip Reames0b1b3872015-02-21 00:09:09 +0000582 bool CanAssumeCallSafepoints = enableCallSafepoints(F);
Philip Reames47cc6732015-02-04 00:37:33 +0000583 PlaceBackedgeSafepointsImpl *PBS =
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000584 new PlaceBackedgeSafepointsImpl(CanAssumeCallSafepoints);
Philip Reames47cc6732015-02-04 00:37:33 +0000585 FPM.add(PBS);
Philip Reames47cc6732015-02-04 00:37:33 +0000586 FPM.run(F);
587
588 // We preserve dominance information when inserting the poll, otherwise
589 // we'd have to recalculate this on every insert
590 DT.recalculate(F);
591
Philip Reames5708cca2015-05-12 20:43:48 +0000592 auto &PollLocations = PBS->PollLocations;
593
594 auto OrderByBBName = [](Instruction *a, Instruction *b) {
595 return a->getParent()->getName() < b->getParent()->getName();
596 };
597 // We need the order of list to be stable so that naming ends up stable
598 // when we split edges. This makes test cases much easier to write.
599 std::sort(PollLocations.begin(), PollLocations.end(), OrderByBBName);
600
601 // We can sometimes end up with duplicate poll locations. This happens if
602 // a single loop is visited more than once. The fact this happens seems
603 // wrong, but it does happen for the split-backedge.ll test case.
604 PollLocations.erase(std::unique(PollLocations.begin(),
605 PollLocations.end()),
606 PollLocations.end());
607
Philip Reames47cc6732015-02-04 00:37:33 +0000608 // Insert a poll at each point the analysis pass identified
Philip Reames5708cca2015-05-12 20:43:48 +0000609 for (size_t i = 0; i < PollLocations.size(); i++) {
Philip Reames47cc6732015-02-04 00:37:33 +0000610 // We are inserting a poll, the function is modified
611 modified = true;
612
613 // The poll location must be the terminator of a loop latch block.
Philip Reames5708cca2015-05-12 20:43:48 +0000614 TerminatorInst *Term = PollLocations[i];
Philip Reames47cc6732015-02-04 00:37:33 +0000615
616 std::vector<CallSite> ParsePoints;
617 if (SplitBackedge) {
618 // Split the backedge of the loop and insert the poll within that new
619 // basic block. This creates a loop with two latches per original
620 // latch (which is non-ideal), but this appears to be easier to
621 // optimize in practice than inserting the poll immediately before the
622 // latch test.
623
624 // Since this is a latch, at least one of the successors must dominate
625 // it. Its possible that we have a) duplicate edges to the same header
626 // and b) edges to distinct loop headers. We need to insert pools on
Philip Reames5708cca2015-05-12 20:43:48 +0000627 // each.
628 SetVector<BasicBlock *> Headers;
Philip Reames47cc6732015-02-04 00:37:33 +0000629 for (unsigned i = 0; i < Term->getNumSuccessors(); i++) {
630 BasicBlock *Succ = Term->getSuccessor(i);
631 if (DT.dominates(Succ, Term->getParent())) {
632 Headers.insert(Succ);
633 }
634 }
635 assert(!Headers.empty() && "poll location is not a loop latch?");
636
637 // The split loop structure here is so that we only need to recalculate
638 // the dominator tree once. Alternatively, we could just keep it up to
639 // date and use a more natural merged loop.
Philip Reames5708cca2015-05-12 20:43:48 +0000640 SetVector<BasicBlock *> SplitBackedges;
Philip Reames47cc6732015-02-04 00:37:33 +0000641 for (BasicBlock *Header : Headers) {
642 BasicBlock *NewBB = SplitEdge(Term->getParent(), Header, nullptr);
643 SplitBackedges.insert(NewBB);
644 }
645 DT.recalculate(F);
646 for (BasicBlock *NewBB : SplitBackedges) {
Philip Reames5708cca2015-05-12 20:43:48 +0000647 std::vector<CallSite> RuntimeCalls;
648 InsertSafepointPoll(DT, NewBB->getTerminator(), RuntimeCalls);
Philip Reames47cc6732015-02-04 00:37:33 +0000649 NumBackedgeSafepoints++;
Philip Reames5708cca2015-05-12 20:43:48 +0000650 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
651 RuntimeCalls.end());
Philip Reames47cc6732015-02-04 00:37:33 +0000652 }
653
654 } else {
655 // Split the latch block itself, right before the terminator.
Philip Reames5708cca2015-05-12 20:43:48 +0000656 std::vector<CallSite> RuntimeCalls;
657 InsertSafepointPoll(DT, Term, RuntimeCalls);
Philip Reames47cc6732015-02-04 00:37:33 +0000658 NumBackedgeSafepoints++;
Philip Reames5708cca2015-05-12 20:43:48 +0000659 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
660 RuntimeCalls.end());
Philip Reames47cc6732015-02-04 00:37:33 +0000661 }
662
Philip Reames47cc6732015-02-04 00:37:33 +0000663 // Record the parse points for later use
664 ParsePointNeeded.insert(ParsePointNeeded.end(), ParsePoints.begin(),
665 ParsePoints.end());
666 }
667 }
668
Philip Reames0b1b3872015-02-21 00:09:09 +0000669 if (enableEntrySafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000670 DT.recalculate(F);
671 Instruction *term = findLocationForEntrySafepoint(F, DT);
672 if (!term) {
673 // policy choice not to insert?
674 } else {
675 std::vector<CallSite> RuntimeCalls;
676 InsertSafepointPoll(DT, term, RuntimeCalls);
677 modified = true;
678 NumEntrySafepoints++;
679 ParsePointNeeded.insert(ParsePointNeeded.end(), RuntimeCalls.begin(),
680 RuntimeCalls.end());
681 }
682 }
683
Philip Reames0b1b3872015-02-21 00:09:09 +0000684 if (enableCallSafepoints(F)) {
Philip Reames47cc6732015-02-04 00:37:33 +0000685 DT.recalculate(F);
686 std::vector<CallSite> Calls;
687 findCallSafepoints(F, Calls);
688 NumCallSafepoints += Calls.size();
Philip Reames5a9685d2015-02-04 00:39:57 +0000689 ParsePointNeeded.insert(ParsePointNeeded.end(), Calls.begin(), Calls.end());
Philip Reames47cc6732015-02-04 00:37:33 +0000690 }
691
692 // Unique the vectors since we can end up with duplicates if we scan the call
693 // site for call safepoints after we add it for entry or backedge. The
694 // only reason we need tracking at all is that some functions might have
695 // polls but not call safepoints and thus we might miss marking the runtime
696 // calls for the polls. (This is useful in test cases!)
697 unique_unsorted(ParsePointNeeded);
698
699 // Any parse point (no matter what source) will be handled here
700 DT.recalculate(F); // Needed?
701
702 // We're about to start modifying the function
703 if (!ParsePointNeeded.empty())
704 modified = true;
705
706 // Now run through and insert the safepoints, but do _NOT_ update or remove
707 // any existing uses. We have references to live variables that need to
708 // survive to the last iteration of this loop.
709 std::vector<Value *> Results;
710 Results.reserve(ParsePointNeeded.size());
711 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
712 CallSite &CS = ParsePointNeeded[i];
Igor Laevsky5e23e162015-05-08 11:59:09 +0000713
714 // For invoke statepoints we need to remove all phi nodes at the normal
715 // destination block.
716 // Reason for this is that we can place gc_result only after last phi node
717 // in basic block. We will get malformed code after RAUW for the
718 // gc_result if one of this phi nodes uses result from the invoke.
719 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(CS.getInstruction())) {
720 normalizeForInvokeSafepoint(Invoke->getNormalDest(),
721 Invoke->getParent());
722 }
723
Philip Reames47cc6732015-02-04 00:37:33 +0000724 Value *GCResult = ReplaceWithStatepoint(CS, nullptr);
725 Results.push_back(GCResult);
726 }
727 assert(Results.size() == ParsePointNeeded.size());
728
729 // Adjust all users of the old call sites to use the new ones instead
730 for (size_t i = 0; i < ParsePointNeeded.size(); i++) {
731 CallSite &CS = ParsePointNeeded[i];
732 Value *GCResult = Results[i];
733 if (GCResult) {
Igor Laevsky5e23e162015-05-08 11:59:09 +0000734 // Can not RAUW for the gc result in case of phi nodes preset.
735 assert(!isa<PHINode>(cast<Instruction>(GCResult)->getParent()->begin()));
Philip Reames47cc6732015-02-04 00:37:33 +0000736
737 // Replace all uses with the new call
738 CS.getInstruction()->replaceAllUsesWith(GCResult);
739 }
740
741 // Now that we've handled all uses, remove the original call itself
742 // Note: The insert point can't be the deleted instruction!
743 CS.getInstruction()->eraseFromParent();
744 }
745 return modified;
746}
747
748char PlaceBackedgeSafepointsImpl::ID = 0;
749char PlaceSafepoints::ID = 0;
750
Philip Reames7b981792015-05-12 21:21:18 +0000751FunctionPass *llvm::createPlaceSafepointsPass() {
752 return new PlaceSafepoints();
753}
Philip Reames47cc6732015-02-04 00:37:33 +0000754
755INITIALIZE_PASS_BEGIN(PlaceBackedgeSafepointsImpl,
756 "place-backedge-safepoints-impl",
757 "Place Backedge Safepoints", false, false)
758INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Philip Reames57bdac92015-05-12 20:56:33 +0000759INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Philip Reames9f129042015-05-12 21:09:36 +0000760INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Philip Reames47cc6732015-02-04 00:37:33 +0000761INITIALIZE_PASS_END(PlaceBackedgeSafepointsImpl,
762 "place-backedge-safepoints-impl",
763 "Place Backedge Safepoints", false, false)
764
765INITIALIZE_PASS_BEGIN(PlaceSafepoints, "place-safepoints", "Place Safepoints",
766 false, false)
767INITIALIZE_PASS_END(PlaceSafepoints, "place-safepoints", "Place Safepoints",
768 false, false)
769
770static bool isGCLeafFunction(const CallSite &CS) {
771 Instruction *inst = CS.getInstruction();
Aaron Ballman94d4d332015-02-05 13:52:42 +0000772 if (isa<IntrinsicInst>(inst)) {
Aaron Ballman1b072b32015-02-05 13:40:04 +0000773 // Most LLVM intrinsics are things which can never take a safepoint.
774 // As a result, we don't need to have the stack parsable at the
775 // callsite. This is a highly useful optimization since intrinsic
776 // calls are fairly prevelent, particularly in debug builds.
777 return true;
Philip Reames47cc6732015-02-04 00:37:33 +0000778 }
779
780 // If this function is marked explicitly as a leaf call, we don't need to
781 // place a safepoint of it. In fact, for correctness we *can't* in many
782 // cases. Note: Indirect calls return Null for the called function,
783 // these obviously aren't runtime functions with attributes
784 // TODO: Support attributes on the call site as well.
785 const Function *F = CS.getCalledFunction();
786 bool isLeaf =
787 F &&
788 F->getFnAttribute("gc-leaf-function").getValueAsString().equals("true");
789 if (isLeaf) {
790 return true;
791 }
792 return false;
793}
794
Philip Reames5a9685d2015-02-04 00:39:57 +0000795static void
796InsertSafepointPoll(DominatorTree &DT, Instruction *term,
797 std::vector<CallSite> &ParsePointsNeeded /*rval*/) {
Philip Reames47cc6732015-02-04 00:37:33 +0000798 Module *M = term->getParent()->getParent()->getParent();
799 assert(M);
800
801 // Inline the safepoint poll implementation - this will get all the branch,
802 // control flow, etc.. Most importantly, it will introduce the actual slow
803 // path call - where we need to insert a safepoint (parsepoint).
804 FunctionType *ftype =
805 FunctionType::get(Type::getVoidTy(M->getContext()), false);
806 assert(ftype && "null?");
807 // Note: This cast can fail if there's a function of the same name with a
808 // different type inserted previously
809 Function *F =
810 dyn_cast<Function>(M->getOrInsertFunction("gc.safepoint_poll", ftype));
Ramkumar Ramachandra3edf74f2015-02-09 23:02:10 +0000811 assert(F && "void @gc.safepoint_poll() must be defined");
812 assert(!F->empty() && "gc.safepoint_poll must be a non-empty function");
Philip Reames47cc6732015-02-04 00:37:33 +0000813 CallInst *poll = CallInst::Create(F, "", term);
814
815 // Record some information about the call site we're replacing
816 BasicBlock *OrigBB = term->getParent();
817 BasicBlock::iterator before(poll), after(poll);
818 bool isBegin(false);
819 if (before == term->getParent()->begin()) {
820 isBegin = true;
821 } else {
822 before--;
823 }
824 after++;
825 assert(after != poll->getParent()->end() && "must have successor");
826 assert(DT.dominates(before, after) && "trivially true");
827
828 // do the actual inlining
829 InlineFunctionInfo IFI;
830 bool inlineStatus = InlineFunction(poll, IFI);
831 assert(inlineStatus && "inline must succeed");
Philip Reames72634d62015-02-04 05:11:20 +0000832 (void)inlineStatus; // suppress warning in release-asserts
Philip Reames47cc6732015-02-04 00:37:33 +0000833
834 // Check post conditions
835 assert(IFI.StaticAllocas.empty() && "can't have allocs");
836
837 std::vector<CallInst *> calls; // new calls
838 std::set<BasicBlock *> BBs; // new BBs + insertee
839 // Include only the newly inserted instructions, Note: begin may not be valid
840 // if we inserted to the beginning of the basic block
841 BasicBlock::iterator start;
842 if (isBegin) {
843 start = OrigBB->begin();
844 } else {
845 start = before;
846 start++;
847 }
848
849 // If your poll function includes an unreachable at the end, that's not
850 // valid. Bugpoint likes to create this, so check for it.
851 assert(isPotentiallyReachable(&*start, &*after, nullptr, nullptr) &&
852 "malformed poll function");
853
854 scanInlinedCode(&*(start), &*(after), calls, BBs);
855
856 // Recompute since we've invalidated cached data. Conceptually we
857 // shouldn't need to do this, but implementation wise we appear to. Needed
858 // so we can insert safepoints correctly.
859 // TODO: update more cheaply
860 DT.recalculate(*after->getParent()->getParent());
861
862 assert(!calls.empty() && "slow path not found for safepoint poll");
863
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
867 // the slow path)
868 assert(ParsePointsNeeded.empty());
869 for (size_t i = 0; i < calls.size(); i++) {
870
871 // No safepoint needed or wanted
872 if (!needsStatepoint(calls[i])) {
873 continue;
874 }
875
876 // These are likely runtime calls. Should we assert that via calling
877 // convention or something?
878 ParsePointsNeeded.push_back(CallSite(calls[i]));
879 }
880 assert(ParsePointsNeeded.size() <= calls.size());
881}
882
Philip Reames47cc6732015-02-04 00:37:33 +0000883/// 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.
886static Value *ReplaceWithStatepoint(const CallSite &CS, /* to replace */
887 Pass *P) {
NAKAMURA Takumi2a5bd542015-05-07 10:18:46 +0000888 assert(CS.getInstruction()->getParent()->getParent()->getParent() &&
889 "must be set");
Philip Reames47cc6732015-02-04 00:37:33 +0000890
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.
895
Philip Reames47cc6732015-02-04 00:37:33 +0000896 // 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.
Sanjoy Das93abd812015-05-06 23:53:19 +0000900 IRBuilder<> Builder(CS.getInstruction());
Philip Reamesb1ed02f2015-02-09 21:48:05 +0000901
902 // Note: The gc args are not filled in at this time, that's handled by
903 // RewriteStatepointsForGC (which is currently under review).
904
Philip Reames47cc6732015-02-04 00:37:33 +0000905 // Create the statepoint given all the arguments
Sanjoy Das93abd812015-05-06 23:53:19 +0000906 Instruction *Token = nullptr;
Sanjoy Dasabf15602015-05-06 23:53:21 +0000907 AttributeSet OriginalAttrs;
908
Philip Reames47cc6732015-02-04 00:37:33 +0000909 if (CS.isCall()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000910 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Dasabe1c682015-05-06 23:53:09 +0000911 CallInst *Call = Builder.CreateGCStatepointCall(
Ramkumar Ramachandra3408f3e2015-02-26 00:35:56 +0000912 CS.getCalledValue(), makeArrayRef(CS.arg_begin(), CS.arg_end()), None,
913 None, "safepoint_token");
Sanjoy Das93abd812015-05-06 23:53:19 +0000914 Call->setTailCall(ToReplace->isTailCall());
915 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reames47cc6732015-02-04 00:37:33 +0000916
917 // Before we have to worry about GC semantics, all attributes are legal
Philip Reames47cc6732015-02-04 00:37:33 +0000918 // TODO: handle param attributes
Sanjoy Dasabf15602015-05-06 23:53:21 +0000919 OriginalAttrs = ToReplace->getAttributes();
920
921 // In case if we can handle this set of attributes - set up function
922 // attributes directly on statepoint and return attributes later for
923 // gc_result intrinsic.
924 Call->setAttributes(OriginalAttrs.getFnAttributes());
Philip Reames47cc6732015-02-04 00:37:33 +0000925
Sanjoy Das93abd812015-05-06 23:53:19 +0000926 Token = Call;
Philip Reames47cc6732015-02-04 00:37:33 +0000927
928 // Put the following gc_result and gc_relocate calls immediately after the
Sanjoy Dasabf15602015-05-06 23:53:21 +0000929 // the old call (which we're about to delete).
930 assert(ToReplace->getNextNode() && "not a terminator, must have next");
931 Builder.SetInsertPoint(ToReplace->getNextNode());
932 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
Philip Reames47cc6732015-02-04 00:37:33 +0000933 } else if (CS.isInvoke()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000934 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reames47cc6732015-02-04 00:37:33 +0000935
936 // Insert the new invoke into the old block. We'll remove the old one in a
937 // moment at which point this will become the new terminator for the
938 // original block.
Sanjoy Das93abd812015-05-06 23:53:19 +0000939 Builder.SetInsertPoint(ToReplace->getParent());
940 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
941 CS.getCalledValue(), ToReplace->getNormalDest(),
942 ToReplace->getUnwindDest(), makeArrayRef(CS.arg_begin(), CS.arg_end()),
Sanjoy Dasabe1c682015-05-06 23:53:09 +0000943 Builder.getInt32(0), None, "safepoint_token");
Philip Reames47cc6732015-02-04 00:37:33 +0000944
945 // Currently we will fail on parameter attributes and on certain
946 // function attributes.
Sanjoy Dasabf15602015-05-06 23:53:21 +0000947 OriginalAttrs = ToReplace->getAttributes();
948
949 // In case if we can handle this set of attributes - set up function
950 // attributes directly on statepoint and return attributes later for
951 // gc_result intrinsic.
Sanjoy Das93abd812015-05-06 23:53:19 +0000952 Invoke->setAttributes(OriginalAttrs.getFnAttributes());
Philip Reames47cc6732015-02-04 00:37:33 +0000953
Sanjoy Das93abd812015-05-06 23:53:19 +0000954 Token = Invoke;
Philip Reames47cc6732015-02-04 00:37:33 +0000955
956 // We'll insert the gc.result into the normal block
Igor Laevsky5e23e162015-05-08 11:59:09 +0000957 BasicBlock *NormalDest = ToReplace->getNormalDest();
958 // Can not insert gc.result in case of phi nodes preset.
959 // Should have removed this cases prior to runnning this function
960 assert(!isa<PHINode>(NormalDest->begin()));
961 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
962 Builder.SetInsertPoint(IP);
Philip Reames47cc6732015-02-04 00:37:33 +0000963 } else {
964 llvm_unreachable("unexpect type of CallSite");
965 }
Sanjoy Das93abd812015-05-06 23:53:19 +0000966 assert(Token);
Philip Reames47cc6732015-02-04 00:37:33 +0000967
968 // Handle the return value of the original call - update all uses to use a
969 // gc_result hanging off the statepoint node we just inserted
970
971 // Only add the gc_result iff there is actually a used result
972 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
Sanjoy Das93abd812015-05-06 23:53:19 +0000973 std::string TakenName =
974 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
975 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), TakenName);
Sanjoy Dasabf15602015-05-06 23:53:21 +0000976 GCResult->setAttributes(OriginalAttrs.getRetAttributes());
Sanjoy Das93abd812015-05-06 23:53:19 +0000977 return GCResult;
Philip Reames47cc6732015-02-04 00:37:33 +0000978 } else {
979 // No return value for the call.
980 return nullptr;
981 }
982}