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