Add a pass for constructing gc.statepoint sequences w/explicit relocations
[oota-llvm.git] / lib / Transforms / Scalar / RewriteStatepointsForGC.cpp
1 //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
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 // Rewrite an existing set of gc.statepoints such that they make potential
11 // relocations performed by the garbage collector explicit in the IR.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Pass.h"
16 #include "llvm/Analysis/CFG.h"
17 #include "llvm/ADT/SetOperations.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/InstIterator.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Statepoint.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
40
41 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
42
43 using namespace llvm;
44
45 // Print tracing output
46 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
47                               cl::init(false));
48
49 // Print the liveset found at the insert location
50 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
51                                   cl::init(false));
52 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size",
53                                       cl::Hidden, cl::init(false));
54 // Print out the base pointers for debugging
55 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers",
56                                        cl::Hidden, cl::init(false));
57
58 struct RewriteStatepointsForGC : public FunctionPass {
59   static char ID; // Pass identification, replacement for typeid
60
61   RewriteStatepointsForGC() : FunctionPass(ID) {
62     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
63   }
64   bool runOnFunction(Function &F) override;
65
66   void getAnalysisUsage(AnalysisUsage &AU) const override {
67     // We add and rewrite a bunch of instructions, but don't really do much
68     // else.  We could in theory preserve a lot more analyses here.
69     AU.addRequired<DominatorTreeWrapperPass>();
70   }
71 };
72
73 char RewriteStatepointsForGC::ID = 0;
74
75 FunctionPass *llvm::createRewriteStatepointsForGCPass() {
76   return new RewriteStatepointsForGC();
77 }
78
79 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
80                       "Make relocations explicit at statepoints", false, false)
81 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
82 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
83                     "Make relocations explicit at statepoints", false, false)
84
85 namespace {
86 // The type of the internal cache used inside the findBasePointers family
87 // of functions.  From the callers perspective, this is an opaque type and
88 // should not be inspected.
89 //
90 // In the actual implementation this caches two relations:
91 // - The base relation itself (i.e. this pointer is based on that one)
92 // - The base defining value relation (i.e. before base_phi insertion)
93 // Generally, after the execution of a full findBasePointer call, only the
94 // base relation will remain.  Internally, we add a mixture of the two
95 // types, then update all the second type to the first type
96 typedef std::map<Value *, Value *> DefiningValueMapTy;
97 }
98
99 namespace {
100 struct PartiallyConstructedSafepointRecord {
101   /// The set of values known to be live accross this safepoint
102   std::set<llvm::Value *> liveset;
103
104   /// Mapping from live pointers to a base-defining-value
105   std::map<llvm::Value *, llvm::Value *> base_pairs;
106
107   /// Any new values which were added to the IR during base pointer analysis
108   /// for this safepoint
109   std::set<llvm::Value *> newInsertedDefs;
110
111   /// The bounds of the inserted code for the safepoint
112   std::pair<Instruction *, Instruction *> safepoint;
113
114   // Instruction to which exceptional gc relocates are attached
115   // Makes it easier to iterate through them during relocationViaAlloca.
116   Instruction *exceptional_relocates_token;
117
118   /// The result of the safepointing call (or nullptr)
119   Value *result;
120 };
121 }
122
123 // TODO: Once we can get to the GCStrategy, this becomes
124 // Optional<bool> isGCManagedPointer(const Value *V) const override {
125
126 static bool isGCPointerType(const Type *T) {
127   if (const PointerType *PT = dyn_cast<PointerType>(T))
128     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
129     // GC managed heap.  We know that a pointer into this heap needs to be
130     // updated and that no other pointer does.
131     return (1 == PT->getAddressSpace());
132   return false;
133 }
134
135 /// Return true if the Value is a gc reference type which is potentially used
136 /// after the instruction 'loc'.  This is only used with the edge reachability
137 /// liveness code.  Note: It is assumed the V dominates loc.
138 static bool isLiveGCReferenceAt(Value &V, Instruction *loc, DominatorTree &DT,
139                                 LoopInfo *LI) {
140   if (!isGCPointerType(V.getType()))
141     return false;
142
143   if (V.use_empty())
144     return false;
145
146   // Given assumption that V dominates loc, this may be live
147   return true;
148 }
149 static bool isAggWhichContainsGCPtrType(Type *Ty) {
150   if (VectorType *VT = dyn_cast<VectorType>(Ty))
151     return isGCPointerType(VT->getScalarType());
152   else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
153     return isGCPointerType(AT->getElementType()) ||
154            isAggWhichContainsGCPtrType(AT->getElementType());
155   } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
156     bool UnsupportedType = false;
157     for (Type *SubType : ST->subtypes())
158       UnsupportedType |= isGCPointerType(SubType) || isAggWhichContainsGCPtrType(SubType);
159     return UnsupportedType;
160   } else
161     return false;
162 }
163
164 // Conservatively identifies any definitions which might be live at the
165 // given instruction. The  analysis is performed immediately before the
166 // given instruction. Values defined by that instruction are not considered
167 // live.  Values used by that instruction are considered live.
168 //
169 // preconditions: valid IR graph, term is either a terminator instruction or
170 // a call instruction, pred is the basic block of term, DT, LI are valid
171 //
172 // side effects: none, does not mutate IR
173 //
174 //  postconditions: populates liveValues as discussed above
175 static void findLiveGCValuesAtInst(Instruction *term, BasicBlock *pred,
176                                    DominatorTree &DT, LoopInfo *LI,
177                                    std::set<llvm::Value *> &liveValues) {
178   liveValues.clear();
179
180   assert(isa<CallInst>(term) || isa<InvokeInst>(term) || term->isTerminator());
181
182   Function *F = pred->getParent();
183
184   auto is_live_gc_reference =
185       [&](Value &V) { return isLiveGCReferenceAt(V, term, DT, LI); };
186
187   // Are there any gc pointer arguments live over this point?  This needs to be
188   // special cased since arguments aren't defined in basic blocks.
189   for (Argument &arg : F->args()) {
190     assert(!isAggWhichContainsGCPtrType(arg.getType()) &&
191            "support for FCA unimplemented");
192
193     if (is_live_gc_reference(arg)) {
194       liveValues.insert(&arg);
195     }
196   }
197
198   // Walk through all dominating blocks - the ones which can contain
199   // definitions used in this block - and check to see if any of the values
200   // they define are used in locations potentially reachable from the
201   // interesting instruction.
202   BasicBlock *BBI = pred;
203   while (true) {
204     if (TraceLSP) {
205       errs() << "[LSP] Looking at dominating block " << pred->getName() << "\n";
206     }
207     assert(DT.dominates(BBI, pred));
208     assert(isPotentiallyReachable(BBI, pred, &DT) &&
209            "dominated block must be reachable");
210
211     // Walk through the instructions in dominating blocks and keep any
212     // that have a use potentially reachable from the block we're
213     // considering putting the safepoint in
214     for (Instruction &inst : *BBI) {
215       if (TraceLSP) {
216         errs() << "[LSP] Looking at instruction ";
217         inst.dump();
218       }
219
220       if (pred == BBI && (&inst) == term) {
221         if (TraceLSP) {
222           errs() << "[LSP] stopped because we encountered the safepoint "
223                     "instruction.\n";
224         }
225
226         // If we're in the block which defines the interesting instruction,
227         // we don't want to include any values as live which are defined
228         // _after_ the interesting line or as part of the line itself
229         // i.e. "term" is the call instruction for a call safepoint, the
230         // results of the call should not be considered live in that stackmap
231         break;
232       }
233
234       assert(!isAggWhichContainsGCPtrType(inst.getType()) &&
235              "support for FCA unimplemented");
236
237       if (is_live_gc_reference(inst)) {
238         if (TraceLSP) {
239           errs() << "[LSP] found live value for this safepoint ";
240           inst.dump();
241           term->dump();
242         }
243         liveValues.insert(&inst);
244       }
245     }
246     if (!DT.getNode(BBI)->getIDom()) {
247       assert(BBI == &F->getEntryBlock() &&
248              "failed to find a dominator for something other than "
249              "the entry block");
250       break;
251     }
252     BBI = DT.getNode(BBI)->getIDom()->getBlock();
253   }
254 }
255
256 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
257   if (a->hasName() && b->hasName()) {
258     return -1 == a->getName().compare(b->getName());
259   } else if (a->hasName() && !b->hasName()) {
260     return true;
261   } else if (!a->hasName() && b->hasName()) {
262     return false;
263   } else {
264     // Better than nothing, but not stable
265     return a < b;
266   }
267 }
268
269 /// Find the initial live set. Note that due to base pointer
270 /// insertion, the live set may be incomplete.
271 static void
272 analyzeParsePointLiveness(DominatorTree &DT, const CallSite &CS,
273                           PartiallyConstructedSafepointRecord &result) {
274   Instruction *inst = CS.getInstruction();
275
276   BasicBlock *BB = inst->getParent();
277   std::set<Value *> liveset;
278   findLiveGCValuesAtInst(inst, BB, DT, nullptr, liveset);
279
280   if (PrintLiveSet) {
281     // Note: This output is used by several of the test cases
282     // The order of elemtns in a set is not stable, put them in a vec and sort
283     // by name
284     std::vector<Value *> temp;
285     temp.insert(temp.end(), liveset.begin(), liveset.end());
286     std::sort(temp.begin(), temp.end(), order_by_name);
287     errs() << "Live Variables:\n";
288     for (Value *V : temp) {
289       errs() << " " << V->getName(); // no newline
290       V->dump();
291     }
292   }
293   if (PrintLiveSetSize) {
294     errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
295     errs() << "Number live values: " << liveset.size() << "\n";
296   }
297   result.liveset = liveset;
298 }
299
300 /// True iff this value is the null pointer constant (of any pointer type)
301 static bool isNullConstant(Value *V) {
302   return isa<Constant>(V) && isa<PointerType>(V->getType()) &&
303          cast<Constant>(V)->isNullValue();
304 }
305
306 /// Helper function for findBasePointer - Will return a value which either a)
307 /// defines the base pointer for the input or b) blocks the simple search
308 /// (i.e. a PHI or Select of two derived pointers)
309 static Value *findBaseDefiningValue(Value *I) {
310   assert(I->getType()->isPointerTy() &&
311          "Illegal to ask for the base pointer of a non-pointer type");
312
313   // There are instructions which can never return gc pointer values.  Sanity
314   // check
315   // that this is actually true.
316   assert(!isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
317          !isa<ShuffleVectorInst>(I) && "Vector types are not gc pointers");
318   assert((!isa<Instruction>(I) || isa<InvokeInst>(I) ||
319           !cast<Instruction>(I)->isTerminator()) &&
320          "With the exception of invoke terminators don't define values");
321   assert(!isa<StoreInst>(I) && !isa<FenceInst>(I) &&
322          "Can't be definitions to start with");
323   assert(!isa<ICmpInst>(I) && !isa<FCmpInst>(I) &&
324          "Comparisons don't give ops");
325   // There's a bunch of instructions which just don't make sense to apply to
326   // a pointer.  The only valid reason for this would be pointer bit
327   // twiddling which we're just not going to support.
328   assert((!isa<Instruction>(I) || !cast<Instruction>(I)->isBinaryOp()) &&
329          "Binary ops on pointer values are meaningless.  Unless your "
330          "bit-twiddling which we don't support");
331
332   if (Argument *Arg = dyn_cast<Argument>(I)) {
333     // An incoming argument to the function is a base pointer
334     // We should have never reached here if this argument isn't an gc value
335     assert(Arg->getType()->isPointerTy() &&
336            "Base for pointer must be another pointer");
337     return Arg;
338   }
339
340   if (GlobalVariable *global = dyn_cast<GlobalVariable>(I)) {
341     // base case
342     assert(global->getType()->isPointerTy() &&
343            "Base for pointer must be another pointer");
344     return global;
345   }
346
347   // inlining could possibly introduce phi node that contains
348   // undef if callee has multiple returns
349   if (UndefValue *undef = dyn_cast<UndefValue>(I)) {
350     assert(undef->getType()->isPointerTy() &&
351            "Base for pointer must be another pointer");
352     return undef; // utterly meaningless, but useful for dealing with
353                   // partially optimized code.
354   }
355
356   // Due to inheritance, this must be _after_ the global variable and undef
357   // checks
358   if (Constant *con = dyn_cast<Constant>(I)) {
359     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
360            "order of checks wrong!");
361     // Note: Finding a constant base for something marked for relocation
362     // doesn't really make sense.  The most likely case is either a) some
363     // screwed up the address space usage or b) your validating against
364     // compiled C++ code w/o the proper separation.  The only real exception
365     // is a null pointer.  You could have generic code written to index of
366     // off a potentially null value and have proven it null.  We also use
367     // null pointers in dead paths of relocation phis (which we might later
368     // want to find a base pointer for).
369     assert(con->getType()->isPointerTy() &&
370            "Base for pointer must be another pointer");
371     assert(con->isNullValue() && "null is the only case which makes sense");
372     return con;
373   }
374
375   if (CastInst *CI = dyn_cast<CastInst>(I)) {
376     Value *def = CI->stripPointerCasts();
377     assert(def->getType()->isPointerTy() &&
378            "Base for pointer must be another pointer");
379     if (isa<CastInst>(def)) {
380       // If we find a cast instruction here, it means we've found a cast
381       // which is not simply a pointer cast (i.e. an inttoptr).  We don't
382       // know how to handle int->ptr conversion.
383       llvm_unreachable("Can not find the base pointers for an inttoptr cast");
384     }
385     assert(!isa<CastInst>(def) && "shouldn't find another cast here");
386     return findBaseDefiningValue(def);
387   }
388
389   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
390     if (LI->getType()->isPointerTy()) {
391       Value *Op = LI->getOperand(0);
392       // Has to be a pointer to an gc object, or possibly an array of such?
393       assert(Op->getType()->isPointerTy());
394       return LI; // The value loaded is an gc base itself
395     }
396   }
397   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
398     Value *Op = GEP->getOperand(0);
399     if (Op->getType()->isPointerTy()) {
400       return findBaseDefiningValue(Op); // The base of this GEP is the base
401     }
402   }
403
404   if (AllocaInst *alloc = dyn_cast<AllocaInst>(I)) {
405     // An alloca represents a conceptual stack slot.  It's the slot itself
406     // that the GC needs to know about, not the value in the slot.
407     assert(alloc->getType()->isPointerTy() &&
408            "Base for pointer must be another pointer");
409     return alloc;
410   }
411
412   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
413     switch (II->getIntrinsicID()) {
414     default:
415       // fall through to general call handling
416       break;
417     case Intrinsic::experimental_gc_statepoint:
418     case Intrinsic::experimental_gc_result_float:
419     case Intrinsic::experimental_gc_result_int:
420       llvm_unreachable("these don't produce pointers");
421     case Intrinsic::experimental_gc_result_ptr:
422       // This is just a special case of the CallInst check below to handle a
423       // statepoint with deopt args which hasn't been rewritten for GC yet.
424       // TODO: Assert that the statepoint isn't rewritten yet.
425       return II;
426     case Intrinsic::experimental_gc_relocate: {
427       // Rerunning safepoint insertion after safepoints are already
428       // inserted is not supported.  It could probably be made to work,
429       // but why are you doing this?  There's no good reason.
430       llvm_unreachable("repeat safepoint insertion is not supported");
431     }
432     case Intrinsic::gcroot:
433       // Currently, this mechanism hasn't been extended to work with gcroot.
434       // There's no reason it couldn't be, but I haven't thought about the
435       // implications much.
436       llvm_unreachable(
437           "interaction with the gcroot mechanism is not supported");
438     }
439   }
440   // We assume that functions in the source language only return base
441   // pointers.  This should probably be generalized via attributes to support
442   // both source language and internal functions.
443   if (CallInst *call = dyn_cast<CallInst>(I)) {
444     assert(call->getType()->isPointerTy() &&
445            "Base for pointer must be another pointer");
446     return call;
447   }
448   if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
449     assert(invoke->getType()->isPointerTy() &&
450            "Base for pointer must be another pointer");
451     return invoke;
452   }
453
454   // I have absolutely no idea how to implement this part yet.  It's not
455   // neccessarily hard, I just haven't really looked at it yet.
456   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
457
458   if (AtomicCmpXchgInst *cas = dyn_cast<AtomicCmpXchgInst>(I)) {
459     // A CAS is effectively a atomic store and load combined under a
460     // predicate.  From the perspective of base pointers, we just treat it
461     // like a load.  We loaded a pointer from a address in memory, that value
462     // had better be a valid base pointer.
463     return cas->getPointerOperand();
464   }
465   if (AtomicRMWInst *atomic = dyn_cast<AtomicRMWInst>(I)) {
466     assert(AtomicRMWInst::Xchg == atomic->getOperation() &&
467            "All others are binary ops which don't apply to base pointers");
468     // semantically, a load, store pair.  Treat it the same as a standard load
469     return atomic->getPointerOperand();
470   }
471
472   // The aggregate ops.  Aggregates can either be in the heap or on the
473   // stack, but in either case, this is simply a field load.  As a result,
474   // this is a defining definition of the base just like a load is.
475   if (ExtractValueInst *ev = dyn_cast<ExtractValueInst>(I)) {
476     return ev;
477   }
478
479   // We should never see an insert vector since that would require we be
480   // tracing back a struct value not a pointer value.
481   assert(!isa<InsertValueInst>(I) &&
482          "Base pointer for a struct is meaningless");
483
484   // The last two cases here don't return a base pointer.  Instead, they
485   // return a value which dynamically selects from amoung several base
486   // derived pointers (each with it's own base potentially).  It's the job of
487   // the caller to resolve these.
488   if (SelectInst *select = dyn_cast<SelectInst>(I)) {
489     return select;
490   }
491   if (PHINode *phi = dyn_cast<PHINode>(I)) {
492     return phi;
493   }
494
495   errs() << "unknown type: " << *I << "\n";
496   llvm_unreachable("unknown type");
497   return nullptr;
498 }
499
500 /// Returns the base defining value for this value.
501 Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &cache) {
502   if (cache.find(I) == cache.end()) {
503     cache[I] = findBaseDefiningValue(I);
504   }
505   assert(cache.find(I) != cache.end());
506
507   if (TraceLSP) {
508     errs() << "fBDV-cached: " << I->getName() << " -> " << cache[I]->getName()
509            << "\n";
510   }
511   return cache[I];
512 }
513
514 /// Return a base pointer for this value if known.  Otherwise, return it's
515 /// base defining value.
516 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &cache) {
517   Value *def = findBaseDefiningValueCached(I, cache);
518   if (cache.count(def)) {
519     // Either a base-of relation, or a self reference.  Caller must check.
520     return cache[def];
521   }
522   // Only a BDV available
523   return def;
524 }
525
526 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
527 /// is it known to be a base pointer?  Or do we need to continue searching.
528 static bool isKnownBaseResult(Value *v) {
529   if (!isa<PHINode>(v) && !isa<SelectInst>(v)) {
530     // no recursion possible
531     return true;
532   }
533   if (cast<Instruction>(v)->getMetadata("is_base_value")) {
534     // This is a previously inserted base phi or select.  We know
535     // that this is a base value.
536     return true;
537   }
538
539   // We need to keep searching
540   return false;
541 }
542
543 // TODO: find a better name for this
544 namespace {
545 class PhiState {
546 public:
547   enum Status { Unknown, Base, Conflict };
548
549   PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
550     assert(status != Base || b);
551   }
552   PhiState(Value *b) : status(Base), base(b) {}
553   PhiState() : status(Unknown), base(nullptr) {}
554   PhiState(const PhiState &other) : status(other.status), base(other.base) {
555     assert(status != Base || base);
556   }
557
558   Status getStatus() const { return status; }
559   Value *getBase() const { return base; }
560
561   bool isBase() const { return getStatus() == Base; }
562   bool isUnknown() const { return getStatus() == Unknown; }
563   bool isConflict() const { return getStatus() == Conflict; }
564
565   bool operator==(const PhiState &other) const {
566     return base == other.base && status == other.status;
567   }
568
569   bool operator!=(const PhiState &other) const { return !(*this == other); }
570
571   void dump() {
572     errs() << status << " (" << base << " - "
573            << (base ? base->getName() : "nullptr") << "): ";
574   }
575
576 private:
577   Status status;
578   Value *base; // non null only if status == base
579 };
580
581 // Values of type PhiState form a lattice, and this is a helper
582 // class that implementes the meet operation.  The meat of the meet
583 // operation is implemented in MeetPhiStates::pureMeet
584 class MeetPhiStates {
585 public:
586   // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
587   explicit MeetPhiStates(const std::map<Value *, PhiState> &phiStates)
588       : phiStates(phiStates) {}
589
590   // Destructively meet the current result with the base V.  V can
591   // either be a merge instruction (SelectInst / PHINode), in which
592   // case its status is looked up in the phiStates map; or a regular
593   // SSA value, in which case it is assumed to be a base.
594   void meetWith(Value *V) {
595     PhiState otherState = getStateForBDV(V);
596     assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
597             MeetPhiStates::pureMeet(currentResult, otherState)) &&
598            "math is wrong: meet does not commute!");
599     currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
600   }
601
602   PhiState getResult() const { return currentResult; }
603
604 private:
605   const std::map<Value *, PhiState> &phiStates;
606   PhiState currentResult;
607
608   /// Return a phi state for a base defining value.  We'll generate a new
609   /// base state for known bases and expect to find a cached state otherwise
610   PhiState getStateForBDV(Value *baseValue) {
611     if (isKnownBaseResult(baseValue)) {
612       return PhiState(baseValue);
613     } else {
614       return lookupFromMap(baseValue);
615     }
616   }
617
618   PhiState lookupFromMap(Value *V) {
619     auto I = phiStates.find(V);
620     assert(I != phiStates.end() && "lookup failed!");
621     return I->second;
622   }
623
624   static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
625     switch (stateA.getStatus()) {
626     case PhiState::Unknown:
627       return stateB;
628
629     case PhiState::Base:
630       assert(stateA.getBase() && "can't be null");
631       if (stateB.isUnknown()) {
632         return stateA;
633       } else if (stateB.isBase()) {
634         if (stateA.getBase() == stateB.getBase()) {
635           assert(stateA == stateB && "equality broken!");
636           return stateA;
637         }
638         return PhiState(PhiState::Conflict);
639       } else {
640         assert(stateB.isConflict() && "only three states!");
641         return PhiState(PhiState::Conflict);
642       }
643
644     case PhiState::Conflict:
645       return stateA;
646     }
647     assert(false && "only three states!");
648   }
649 };
650 }
651 /// For a given value or instruction, figure out what base ptr it's derived
652 /// from.  For gc objects, this is simply itself.  On success, returns a value
653 /// which is the base pointer.  (This is reliable and can be used for
654 /// relocation.)  On failure, returns nullptr.
655 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache,
656                               std::set<llvm::Value *> &newInsertedDefs) {
657   Value *def = findBaseOrBDV(I, cache);
658
659   if (isKnownBaseResult(def)) {
660     return def;
661   }
662
663   // Here's the rough algorithm:
664   // - For every SSA value, construct a mapping to either an actual base
665   //   pointer or a PHI which obscures the base pointer.
666   // - Construct a mapping from PHI to unknown TOP state.  Use an
667   //   optimistic algorithm to propagate base pointer information.  Lattice
668   //   looks like:
669   //   UNKNOWN
670   //   b1 b2 b3 b4
671   //   CONFLICT
672   //   When algorithm terminates, all PHIs will either have a single concrete
673   //   base or be in a conflict state.
674   // - For every conflict, insert a dummy PHI node without arguments.  Add
675   //   these to the base[Instruction] = BasePtr mapping.  For every
676   //   non-conflict, add the actual base.
677   //  - For every conflict, add arguments for the base[a] of each input
678   //   arguments.
679   //
680   // Note: A simpler form of this would be to add the conflict form of all
681   // PHIs without running the optimistic algorithm.  This would be
682   // analougous to pessimistic data flow and would likely lead to an
683   // overall worse solution.
684
685   std::map<Value *, PhiState> states;
686   states[def] = PhiState();
687   // Recursively fill in all phis & selects reachable from the initial one
688   // for which we don't already know a definite base value for
689   // PERF: Yes, this is as horribly inefficient as it looks.
690   bool done = false;
691   while (!done) {
692     done = true;
693     for (auto Pair : states) {
694       Value *v = Pair.first;
695       assert(!isKnownBaseResult(v) && "why did it get added?");
696       if (PHINode *phi = dyn_cast<PHINode>(v)) {
697         unsigned NumPHIValues = phi->getNumIncomingValues();
698         assert(NumPHIValues > 0 && "zero input phis are illegal");
699         for (unsigned i = 0; i != NumPHIValues; ++i) {
700           Value *InVal = phi->getIncomingValue(i);
701           Value *local = findBaseOrBDV(InVal, cache);
702           if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
703             states[local] = PhiState();
704             done = false;
705           }
706         }
707       } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
708         Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
709         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
710           states[local] = PhiState();
711           done = false;
712         }
713         local = findBaseOrBDV(sel->getFalseValue(), cache);
714         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
715           states[local] = PhiState();
716           done = false;
717         }
718       }
719     }
720   }
721
722   if (TraceLSP) {
723     errs() << "States after initialization:\n";
724     for (auto Pair : states) {
725       Instruction *v = cast<Instruction>(Pair.first);
726       PhiState state = Pair.second;
727       state.dump();
728       v->dump();
729     }
730   }
731
732   // TODO: come back and revisit the state transitions around inputs which
733   // have reached conflict state.  The current version seems too conservative.
734
735   bool progress = true;
736   size_t oldSize = 0;
737   while (progress) {
738     oldSize = states.size();
739     progress = false;
740     for (auto Pair : states) {
741       MeetPhiStates calculateMeet(states);
742       Value *v = Pair.first;
743       assert(!isKnownBaseResult(v) && "why did it get added?");
744       assert(isa<SelectInst>(v) || isa<PHINode>(v));
745       if (SelectInst *select = dyn_cast<SelectInst>(v)) {
746         calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
747         calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
748       } else if (PHINode *phi = dyn_cast<PHINode>(v)) {
749         for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
750           calculateMeet.meetWith(
751               findBaseOrBDV(phi->getIncomingValue(i), cache));
752         }
753       } else {
754         llvm_unreachable("no such state expected");
755       }
756
757       PhiState oldState = states[v];
758       PhiState newState = calculateMeet.getResult();
759       if (oldState != newState) {
760         progress = true;
761         states[v] = newState;
762       }
763     }
764
765     assert(oldSize <= states.size());
766     assert(oldSize == states.size() || progress);
767   }
768
769   if (TraceLSP) {
770     errs() << "States after meet iteration:\n";
771     for (auto Pair : states) {
772       Instruction *v = cast<Instruction>(Pair.first);
773       PhiState state = Pair.second;
774       state.dump();
775       v->dump();
776     }
777   }
778
779   // Insert Phis for all conflicts
780   for (auto Pair : states) {
781     Instruction *v = cast<Instruction>(Pair.first);
782     PhiState state = Pair.second;
783     assert(!isKnownBaseResult(v) && "why did it get added?");
784     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
785     if (state.isConflict()) {
786       if (isa<PHINode>(v)) {
787         int num_preds =
788             std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
789         assert(num_preds > 0 && "how did we reach here");
790         PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
791         newInsertedDefs.insert(phi);
792         // Add metadata marking this as a base value
793         auto *const_1 = ConstantInt::get(
794             Type::getInt32Ty(
795                 v->getParent()->getParent()->getParent()->getContext()),
796             1);
797         auto MDConst = ConstantAsMetadata::get(const_1);
798         MDNode *md = MDNode::get(
799             v->getParent()->getParent()->getParent()->getContext(), MDConst);
800         phi->setMetadata("is_base_value", md);
801         states[v] = PhiState(PhiState::Conflict, phi);
802       } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
803         // The undef will be replaced later
804         UndefValue *undef = UndefValue::get(sel->getType());
805         SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
806                                                  undef, "base_select", sel);
807         newInsertedDefs.insert(basesel);
808         // Add metadata marking this as a base value
809         auto *const_1 = ConstantInt::get(
810             Type::getInt32Ty(
811                 v->getParent()->getParent()->getParent()->getContext()),
812             1);
813         auto MDConst = ConstantAsMetadata::get(const_1);
814         MDNode *md = MDNode::get(
815             v->getParent()->getParent()->getParent()->getContext(), MDConst);
816         basesel->setMetadata("is_base_value", md);
817         states[v] = PhiState(PhiState::Conflict, basesel);
818       } else {
819         assert(false);
820       }
821     }
822   }
823
824   // Fixup all the inputs of the new PHIs
825   for (auto Pair : states) {
826     Instruction *v = cast<Instruction>(Pair.first);
827     PhiState state = Pair.second;
828
829     assert(!isKnownBaseResult(v) && "why did it get added?");
830     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
831     if (state.isConflict()) {
832       if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
833         PHINode *phi = cast<PHINode>(v);
834         unsigned NumPHIValues = phi->getNumIncomingValues();
835         for (unsigned i = 0; i < NumPHIValues; i++) {
836           Value *InVal = phi->getIncomingValue(i);
837           BasicBlock *InBB = phi->getIncomingBlock(i);
838
839           // If we've already seen InBB, add the same incoming value
840           // we added for it earlier.  The IR verifier requires phi
841           // nodes with multiple entries from the same basic block
842           // to have the same incoming value for each of those
843           // entries.  If we don't do this check here and basephi
844           // has a different type than base, we'll end up adding two
845           // bitcasts (and hence two distinct values) as incoming
846           // values for the same basic block.
847
848           int blockIndex = basephi->getBasicBlockIndex(InBB);
849           if (blockIndex != -1) {
850             Value *oldBase = basephi->getIncomingValue(blockIndex);
851             basephi->addIncoming(oldBase, InBB);
852 #ifndef NDEBUG
853             Value *base = findBaseOrBDV(InVal, cache);
854             if (!isKnownBaseResult(base)) {
855               // Either conflict or base.
856               assert(states.count(base));
857               base = states[base].getBase();
858               assert(base != nullptr && "unknown PhiState!");
859               assert(newInsertedDefs.count(base) &&
860                      "should have already added this in a prev. iteration!");
861             }
862
863             // In essense this assert states: the only way two
864             // values incoming from the same basic block may be
865             // different is by being different bitcasts of the same
866             // value.  A cleanup that remains TODO is changing
867             // findBaseOrBDV to return an llvm::Value of the correct
868             // type (and still remain pure).  This will remove the
869             // need to add bitcasts.
870             assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
871                    "sanity -- findBaseOrBDV should be pure!");
872 #endif
873             continue;
874           }
875
876           // Find either the defining value for the PHI or the normal base for
877           // a non-phi node
878           Value *base = findBaseOrBDV(InVal, cache);
879           if (!isKnownBaseResult(base)) {
880             // Either conflict or base.
881             assert(states.count(base));
882             base = states[base].getBase();
883             assert(base != nullptr && "unknown PhiState!");
884           }
885           assert(base && "can't be null");
886           // Must use original input BB since base may not be Instruction
887           // The cast is needed since base traversal may strip away bitcasts
888           if (base->getType() != basephi->getType()) {
889             base = new BitCastInst(base, basephi->getType(), "cast",
890                                    InBB->getTerminator());
891             newInsertedDefs.insert(base);
892           }
893           basephi->addIncoming(base, InBB);
894         }
895         assert(basephi->getNumIncomingValues() == NumPHIValues);
896       } else if (SelectInst *basesel = dyn_cast<SelectInst>(state.getBase())) {
897         SelectInst *sel = cast<SelectInst>(v);
898         // Operand 1 & 2 are true, false path respectively. TODO: refactor to
899         // something more safe and less hacky.
900         for (int i = 1; i <= 2; i++) {
901           Value *InVal = sel->getOperand(i);
902           // Find either the defining value for the PHI or the normal base for
903           // a non-phi node
904           Value *base = findBaseOrBDV(InVal, cache);
905           if (!isKnownBaseResult(base)) {
906             // Either conflict or base.
907             assert(states.count(base));
908             base = states[base].getBase();
909             assert(base != nullptr && "unknown PhiState!");
910           }
911           assert(base && "can't be null");
912           // Must use original input BB since base may not be Instruction
913           // The cast is needed since base traversal may strip away bitcasts
914           if (base->getType() != basesel->getType()) {
915             base = new BitCastInst(base, basesel->getType(), "cast", basesel);
916             newInsertedDefs.insert(base);
917           }
918           basesel->setOperand(i, base);
919         }
920       } else {
921         assert(false && "unexpected type");
922       }
923     }
924   }
925
926   // Cache all of our results so we can cheaply reuse them
927   // NOTE: This is actually two caches: one of the base defining value
928   // relation and one of the base pointer relation!  FIXME
929   for (auto item : states) {
930     Value *v = item.first;
931     Value *base = item.second.getBase();
932     assert(v && base);
933     assert(!isKnownBaseResult(v) && "why did it get added?");
934
935     if (TraceLSP) {
936       std::string fromstr =
937           cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
938                          : "none";
939       errs() << "Updating base value cache"
940              << " for: " << (v->hasName() ? v->getName() : "")
941              << " from: " << fromstr
942              << " to: " << (base->hasName() ? base->getName() : "") << "\n";
943     }
944
945     assert(isKnownBaseResult(base) &&
946            "must be something we 'know' is a base pointer");
947     if (cache.count(v)) {
948       // Once we transition from the BDV relation being store in the cache to
949       // the base relation being stored, it must be stable
950       assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
951              "base relation should be stable");
952     }
953     cache[v] = base;
954   }
955   assert(cache.find(def) != cache.end());
956   return cache[def];
957 }
958
959 // For a set of live pointers (base and/or derived), identify the base
960 // pointer of the object which they are derived from.  This routine will
961 // mutate the IR graph as needed to make the 'base' pointer live at the
962 // definition site of 'derived'.  This ensures that any use of 'derived' can
963 // also use 'base'.  This may involve the insertion of a number of
964 // additional PHI nodes.
965 //
966 // preconditions: live is a set of pointer type Values
967 //
968 // side effects: may insert PHI nodes into the existing CFG, will preserve
969 // CFG, will not remove or mutate any existing nodes
970 //
971 // post condition: base_pairs contains one (derived, base) pair for every
972 // pointer in live.  Note that derived can be equal to base if the original
973 // pointer was a base pointer.
974 static void findBasePointers(const std::set<llvm::Value *> &live,
975                              std::map<llvm::Value *, llvm::Value *> &base_pairs,
976                              DominatorTree *DT, DefiningValueMapTy &DVCache,
977                              std::set<llvm::Value *> &newInsertedDefs) {
978   for (Value *ptr : live) {
979     Value *base = findBasePointer(ptr, DVCache, newInsertedDefs);
980     assert(base && "failed to find base pointer");
981     base_pairs[ptr] = base;
982     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
983             DT->dominates(cast<Instruction>(base)->getParent(),
984                           cast<Instruction>(ptr)->getParent())) &&
985            "The base we found better dominate the derived pointer");
986
987     if (isNullConstant(base))
988       // If you see this trip and like to live really dangerously, the code
989       // should be correct, just with idioms the verifier can't handle.  You
990       // can try disabling the verifier at your own substaintial risk.
991       llvm_unreachable("the relocation code needs adjustment to handle the"
992                        "relocation of a null pointer constant without causing"
993                        "false positives in the safepoint ir verifier.");
994   }
995 }
996
997 /// Find the required based pointers (and adjust the live set) for the given
998 /// parse point.
999 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1000                              const CallSite &CS,
1001                              PartiallyConstructedSafepointRecord &result) {
1002   std::map<llvm::Value *, llvm::Value *> base_pairs;
1003   std::set<llvm::Value *> newInsertedDefs;
1004   findBasePointers(result.liveset, base_pairs, &DT, DVCache, newInsertedDefs);
1005
1006   if (PrintBasePointers) {
1007     errs() << "Base Pairs (w/o Relocation):\n";
1008     for (auto Pair : base_pairs) {
1009       errs() << " derived %" << Pair.first->getName() << " base %"
1010              << Pair.second->getName() << "\n";
1011     }
1012   }
1013
1014   result.base_pairs = base_pairs;
1015   result.newInsertedDefs = newInsertedDefs;
1016 }
1017
1018 /// Check for liveness of items in the insert defs and add them to the live
1019 /// and base pointer sets
1020 static void fixupLiveness(DominatorTree &DT, const CallSite &CS,
1021                           const std::set<Value *> &allInsertedDefs,
1022                           PartiallyConstructedSafepointRecord &result) {
1023   Instruction *inst = CS.getInstruction();
1024
1025   std::set<llvm::Value *> liveset = result.liveset;
1026   std::map<llvm::Value *, llvm::Value *> base_pairs = result.base_pairs;
1027
1028   auto is_live_gc_reference =
1029       [&](Value &V) { return isLiveGCReferenceAt(V, inst, DT, nullptr); };
1030
1031   // For each new definition, check to see if a) the definition dominates the
1032   // instruction we're interested in, and b) one of the uses of that definition
1033   // is edge-reachable from the instruction we're interested in.  This is the
1034   // same definition of liveness we used in the intial liveness analysis
1035   for (Value *newDef : allInsertedDefs) {
1036     if (liveset.count(newDef)) {
1037       // already live, no action needed
1038       continue;
1039     }
1040
1041     // PERF: Use DT to check instruction domination might not be good for
1042     // compilation time, and we could change to optimal solution if this
1043     // turn to be a issue
1044     if (!DT.dominates(cast<Instruction>(newDef), inst)) {
1045       // can't possibly be live at inst
1046       continue;
1047     }
1048
1049     if (is_live_gc_reference(*newDef)) {
1050       // Add the live new defs into liveset and base_pairs
1051       liveset.insert(newDef);
1052       base_pairs[newDef] = newDef;
1053     }
1054   }
1055
1056   result.liveset = liveset;
1057   result.base_pairs = base_pairs;
1058 }
1059
1060 static void fixupLiveReferences(
1061     Function &F, DominatorTree &DT, Pass *P,
1062     const std::set<llvm::Value *> &allInsertedDefs,
1063     std::vector<CallSite> &toUpdate,
1064     std::vector<struct PartiallyConstructedSafepointRecord> &records) {
1065   for (size_t i = 0; i < records.size(); i++) {
1066     struct PartiallyConstructedSafepointRecord &info = records[i];
1067     CallSite &CS = toUpdate[i];
1068     fixupLiveness(DT, CS, allInsertedDefs, info);
1069   }
1070 }
1071
1072 // Normalize basic block to make it ready to be target of invoke statepoint.
1073 // It means spliting it to have single predecessor. Return newly created BB
1074 // ready to be successor of invoke statepoint.
1075 static BasicBlock *normalizeBBForInvokeSafepoint(BasicBlock *BB,
1076                                                  BasicBlock *InvokeParent,
1077                                                  Pass *P) {
1078   BasicBlock *ret = BB;
1079
1080   if (!BB->getUniquePredecessor()) {
1081     ret = SplitBlockPredecessors(BB, InvokeParent, "");
1082   }
1083
1084   // Another requirement for such basic blocks is to not have any phi nodes.
1085   // Since we just ensured that new BB will have single predecessor,
1086   // all phi nodes in it will have one value. Here it would be naturall place
1087   // to
1088   // remove them all. But we can not do this because we are risking to remove
1089   // one of the values stored in liveset of another statepoint. We will do it
1090   // later after placing all safepoints.
1091
1092   return ret;
1093 }
1094
1095 static void
1096 VerifySafepointBounds(const std::pair<Instruction *, Instruction *> &bounds) {
1097   assert(bounds.first->getParent() && bounds.second->getParent() &&
1098          "both must belong to basic blocks");
1099   if (bounds.first->getParent() == bounds.second->getParent()) {
1100     // This is a call safepoint
1101     // TODO: scan the range to find the statepoint
1102     // TODO: check that the following instruction is not a gc_relocate or
1103     // gc_result
1104   } else {
1105     // This is an invoke safepoint
1106     InvokeInst *invoke = dyn_cast<InvokeInst>(bounds.first);
1107     assert(invoke && "only continues over invokes!");
1108     assert(invoke->getNormalDest() == bounds.second->getParent() &&
1109            "safepoint should continue into normal exit block");
1110   }
1111 }
1112
1113 static int find_index(const SmallVectorImpl<Value *> &livevec, Value *val) {
1114   auto itr = std::find(livevec.begin(), livevec.end(), val);
1115   assert(livevec.end() != itr);
1116   size_t index = std::distance(livevec.begin(), itr);
1117   assert(index < livevec.size());
1118   return index;
1119 }
1120
1121 // Create new attribute set containing only attributes which can be transfered
1122 // from original call to the safepoint.
1123 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1124   AttributeSet ret;
1125
1126   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1127     unsigned index = AS.getSlotIndex(Slot);
1128
1129     if (index == AttributeSet::ReturnIndex ||
1130         index == AttributeSet::FunctionIndex) {
1131
1132       for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1133            ++it) {
1134         Attribute attr = *it;
1135
1136         // Do not allow certain attributes - just skip them
1137         // Safepoint can not be read only or read none.
1138         if (attr.hasAttribute(Attribute::ReadNone) ||
1139             attr.hasAttribute(Attribute::ReadOnly))
1140           continue;
1141
1142         ret = ret.addAttributes(
1143             AS.getContext(), index,
1144             AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1145       }
1146     }
1147
1148     // Just skip parameter attributes for now
1149   }
1150
1151   return ret;
1152 }
1153
1154 /// Helper function to place all gc relocates necessary for the given
1155 /// statepoint.
1156 /// Inputs:
1157 ///   liveVariables - list of variables to be relocated.
1158 ///   liveStart - index of the first live variable.
1159 ///   basePtrs - base pointers.
1160 ///   statepointToken - statepoint instruction to which relocates should be
1161 ///   bound.
1162 ///   Builder - Llvm IR builder to be used to construct new calls.
1163 /// Returns array with newly created relocates.
1164 static std::vector<llvm::Instruction *>
1165 CreateGCRelocates(const SmallVectorImpl<llvm::Value *> &liveVariables,
1166                   const int liveStart,
1167                   const SmallVectorImpl<llvm::Value *> &basePtrs,
1168                   Instruction *statepointToken, IRBuilder<> Builder) {
1169
1170   std::vector<llvm::Instruction *> newDefs;
1171
1172   Module *M = statepointToken->getParent()->getParent()->getParent();
1173
1174   for (unsigned i = 0; i < liveVariables.size(); i++) {
1175     // We generate a (potentially) unique declaration for every pointer type
1176     // combination.  This results is some blow up the function declarations in
1177     // the IR, but removes the need for argument bitcasts which shrinks the IR
1178     // greatly and makes it much more readable.
1179     std::vector<Type *> types;                    // one per 'any' type
1180     types.push_back(liveVariables[i]->getType()); // result type
1181     Value *gc_relocate_decl = Intrinsic::getDeclaration(
1182         M, Intrinsic::experimental_gc_relocate, types);
1183
1184     // Generate the gc.relocate call and save the result
1185     Value *baseIdx =
1186         ConstantInt::get(Type::getInt32Ty(M->getContext()),
1187                          liveStart + find_index(liveVariables, basePtrs[i]));
1188     Value *liveIdx = ConstantInt::get(
1189         Type::getInt32Ty(M->getContext()),
1190         liveStart + find_index(liveVariables, liveVariables[i]));
1191
1192     // only specify a debug name if we can give a useful one
1193     Value *reloc = Builder.CreateCall3(
1194         gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1195         liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1196                                     : "");
1197     // Trick CodeGen into thinking there are lots of free registers at this
1198     // fake call.
1199     cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1200
1201     newDefs.push_back(cast<Instruction>(reloc));
1202   }
1203   assert(newDefs.size() == liveVariables.size() &&
1204          "missing or extra redefinition at safepoint");
1205
1206   return newDefs;
1207 }
1208
1209 static void
1210 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1211                            const SmallVectorImpl<llvm::Value *> &basePtrs,
1212                            const SmallVectorImpl<llvm::Value *> &liveVariables,
1213                            Pass *P,
1214                            PartiallyConstructedSafepointRecord &result) {
1215   assert(basePtrs.size() == liveVariables.size());
1216   assert(isStatepoint(CS) &&
1217          "This method expects to be rewriting a statepoint");
1218
1219   BasicBlock *BB = CS.getInstruction()->getParent();
1220   assert(BB);
1221   Function *F = BB->getParent();
1222   assert(F && "must be set");
1223   Module *M = F->getParent();
1224   assert(M && "must be set");
1225
1226   // We're not changing the function signature of the statepoint since the gc
1227   // arguments go into the var args section.
1228   Function *gc_statepoint_decl = CS.getCalledFunction();
1229
1230   // Then go ahead and use the builder do actually do the inserts.  We insert
1231   // immediately before the previous instruction under the assumption that all
1232   // arguments will be available here.  We can't insert afterwards since we may
1233   // be replacing a terminator.
1234   Instruction *insertBefore = CS.getInstruction();
1235   IRBuilder<> Builder(insertBefore);
1236   // Copy all of the arguments from the original statepoint - this includes the
1237   // target, call args, and deopt args
1238   std::vector<llvm::Value *> args;
1239   args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1240   // TODO: Clear the 'needs rewrite' flag
1241
1242   // add all the pointers to be relocated (gc arguments)
1243   // Capture the start of the live variable list for use in the gc_relocates
1244   const int live_start = args.size();
1245   args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1246
1247   // Create the statepoint given all the arguments
1248   Instruction *token = nullptr;
1249   AttributeSet return_attributes;
1250   if (CS.isCall()) {
1251     CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1252     CallInst *call =
1253         Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1254     call->setTailCall(toReplace->isTailCall());
1255     call->setCallingConv(toReplace->getCallingConv());
1256
1257     // Currently we will fail on parameter attributes and on certain
1258     // function attributes.
1259     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1260     // In case if we can handle this set of sttributes - set up function attrs
1261     // directly on statepoint and return attrs later for gc_result intrinsic.
1262     call->setAttributes(new_attrs.getFnAttributes());
1263     return_attributes = new_attrs.getRetAttributes();
1264
1265     token = call;
1266
1267     // Put the following gc_result and gc_relocate calls immediately after the
1268     // the old call (which we're about to delete)
1269     BasicBlock::iterator next(toReplace);
1270     assert(BB->end() != next && "not a terminator, must have next");
1271     next++;
1272     Instruction *IP = &*(next);
1273     Builder.SetInsertPoint(IP);
1274     Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1275
1276   } else if (CS.isInvoke()) {
1277     InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1278
1279     // Insert the new invoke into the old block.  We'll remove the old one in a
1280     // moment at which point this will become the new terminator for the
1281     // original block.
1282     InvokeInst *invoke = InvokeInst::Create(
1283         gc_statepoint_decl, toReplace->getNormalDest(),
1284         toReplace->getUnwindDest(), args, "", toReplace->getParent());
1285     invoke->setCallingConv(toReplace->getCallingConv());
1286
1287     // Currently we will fail on parameter attributes and on certain
1288     // function attributes.
1289     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1290     // In case if we can handle this set of sttributes - set up function attrs
1291     // directly on statepoint and return attrs later for gc_result intrinsic.
1292     invoke->setAttributes(new_attrs.getFnAttributes());
1293     return_attributes = new_attrs.getRetAttributes();
1294
1295     token = invoke;
1296
1297     // Generate gc relocates in exceptional path
1298     BasicBlock *unwindBlock = normalizeBBForInvokeSafepoint(
1299         toReplace->getUnwindDest(), invoke->getParent(), P);
1300
1301     Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1302     Builder.SetInsertPoint(IP);
1303     Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1304
1305     // Extract second element from landingpad return value. We will attach
1306     // exceptional gc relocates to it.
1307     const unsigned idx = 1;
1308     Instruction *exceptional_token =
1309         cast<Instruction>(Builder.CreateExtractValue(
1310             unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1311     result.exceptional_relocates_token = exceptional_token;
1312
1313     // Just throw away return value. We will use the one we got for normal
1314     // block.
1315     (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1316                             exceptional_token, Builder);
1317
1318     // Generate gc relocates and returns for normal block
1319     BasicBlock *normalDest = normalizeBBForInvokeSafepoint(
1320         toReplace->getNormalDest(), invoke->getParent(), P);
1321
1322     IP = &*(normalDest->getFirstInsertionPt());
1323     Builder.SetInsertPoint(IP);
1324
1325     // gc relocates will be generated later as if it were regular call
1326     // statepoint
1327   } else {
1328     llvm_unreachable("unexpect type of CallSite");
1329   }
1330   assert(token);
1331
1332   // Take the name of the original value call if it had one.
1333   token->takeName(CS.getInstruction());
1334
1335   // The GCResult is already inserted, we just need to find it
1336   Instruction *gc_result = nullptr;
1337   /* scope */ {
1338     Instruction *toReplace = CS.getInstruction();
1339     assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1340            "only valid use before rewrite is gc.result");
1341     if (toReplace->hasOneUse()) {
1342       Instruction *GCResult = cast<Instruction>(*toReplace->user_begin());
1343       assert(isGCResult(GCResult));
1344       gc_result = GCResult;
1345     }
1346   }
1347
1348   // Update the gc.result of the original statepoint (if any) to use the newly
1349   // inserted statepoint.  This is safe to do here since the token can't be
1350   // considered a live reference.
1351   CS.getInstruction()->replaceAllUsesWith(token);
1352
1353   // Second, create a gc.relocate for every live variable
1354   std::vector<llvm::Instruction *> newDefs =
1355       CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1356
1357   // Need to pass through the last part of the safepoint block so that we
1358   // don't accidentally update uses in a following gc.relocate which is
1359   // still conceptually part of the same safepoint.  Gah.
1360   Instruction *last = nullptr;
1361   if (!newDefs.empty()) {
1362     last = newDefs.back();
1363   } else if (gc_result) {
1364     last = gc_result;
1365   } else {
1366     last = token;
1367   }
1368   assert(last && "can't be null");
1369   const auto bounds = std::make_pair(token, last);
1370
1371   // Sanity check our results - this is slightly non-trivial due to invokes
1372   VerifySafepointBounds(bounds);
1373
1374   result.safepoint = bounds;
1375 }
1376
1377 namespace {
1378 struct name_ordering {
1379   Value *base;
1380   Value *derived;
1381   bool operator()(name_ordering const &a, name_ordering const &b) {
1382     return -1 == a.derived->getName().compare(b.derived->getName());
1383   }
1384 };
1385 }
1386 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1387                            SmallVectorImpl<Value *> &livevec) {
1388   assert(basevec.size() == livevec.size());
1389
1390   std::vector<name_ordering> temp;
1391   for (size_t i = 0; i < basevec.size(); i++) {
1392     name_ordering v;
1393     v.base = basevec[i];
1394     v.derived = livevec[i];
1395     temp.push_back(v);
1396   }
1397   std::sort(temp.begin(), temp.end(), name_ordering());
1398   for (size_t i = 0; i < basevec.size(); i++) {
1399     basevec[i] = temp[i].base;
1400     livevec[i] = temp[i].derived;
1401   }
1402 }
1403
1404 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1405 // which make the relocations happening at this safepoint explicit.
1406 // 
1407 // WARNING: Does not do any fixup to adjust users of the original live
1408 // values.  That's the callers responsibility.
1409 static void
1410 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1411                        PartiallyConstructedSafepointRecord &result) {
1412   std::set<llvm::Value *> liveset = result.liveset;
1413   std::map<llvm::Value *, llvm::Value *> base_pairs = result.base_pairs;
1414
1415   // Convert to vector for efficient cross referencing.
1416   SmallVector<Value *, 64> basevec, livevec;
1417   livevec.reserve(liveset.size());
1418   basevec.reserve(liveset.size());
1419   for (Value *L : liveset) {
1420     livevec.push_back(L);
1421
1422     assert(base_pairs.find(L) != base_pairs.end());
1423     Value *base = base_pairs[L];
1424     basevec.push_back(base);
1425   }
1426   assert(livevec.size() == basevec.size());
1427
1428   // To make the output IR slightly more stable (for use in diffs), ensure a
1429   // fixed order of the values in the safepoint (by sorting the value name).
1430   // The order is otherwise meaningless.
1431   stablize_order(basevec, livevec);
1432
1433   // Do the actual rewriting and delete the old statepoint
1434   makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1435   CS.getInstruction()->eraseFromParent();
1436 }
1437
1438 // Helper function for the relocationViaAlloca.
1439 // It receives iterator to the statepoint gc relocates and emits store to the
1440 // assigned
1441 // location (via allocaMap) for the each one of them.
1442 // Add visited values into the visitedLiveValues set we will later use them
1443 // for sanity check.
1444 static void
1445 insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1446                        DenseMap<Value *, Value *> &allocaMap,
1447                        DenseSet<Value *> &visitedLiveValues) {
1448
1449   for (User *U : gcRelocs) {
1450     if (!isa<IntrinsicInst>(U))
1451       continue;
1452
1453     IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1454
1455     // We only care about relocates
1456     if (relocatedValue->getIntrinsicID() !=
1457         Intrinsic::experimental_gc_relocate) {
1458       continue;
1459     }
1460
1461     GCRelocateOperands relocateOperands(relocatedValue);
1462     Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1463     assert(allocaMap.count(originalValue));
1464     Value *alloca = allocaMap[originalValue];
1465
1466     // Emit store into the related alloca
1467     StoreInst *store = new StoreInst(relocatedValue, alloca);
1468     store->insertAfter(relocatedValue);
1469
1470 #ifndef NDEBUG
1471     visitedLiveValues.insert(originalValue);
1472 #endif
1473   }
1474 }
1475
1476 /// do all the relocation update via allocas and mem2reg
1477 static void relocationViaAlloca(
1478     Function &F, DominatorTree &DT, const std::vector<Value *> &live,
1479     const std::vector<struct PartiallyConstructedSafepointRecord> &records) {
1480 #ifndef NDEBUG
1481   int initialAllocaNum = 0;
1482
1483   // record initial number of allocas
1484   for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1485        itr++) {
1486     if (isa<AllocaInst>(*itr))
1487       initialAllocaNum++;
1488   }
1489 #endif
1490
1491   // TODO-PERF: change data structures, reserve
1492   DenseMap<Value *, Value *> allocaMap;
1493   SmallVector<AllocaInst *, 200> PromotableAllocas;
1494   PromotableAllocas.reserve(live.size());
1495
1496   // emit alloca for each live gc pointer
1497   for (unsigned i = 0; i < live.size(); i++) {
1498     Value *liveValue = live[i];
1499     AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1500                                         F.getEntryBlock().getFirstNonPHI());
1501     allocaMap[liveValue] = alloca;
1502     PromotableAllocas.push_back(alloca);
1503   }
1504
1505   // The next two loops are part of the same conceptual operation.  We need to
1506   // insert a store to the alloca after the original def and at each
1507   // redefinition.  We need to insert a load before each use.  These are split
1508   // into distinct loops for performance reasons.
1509
1510   // update gc pointer after each statepoint
1511   // either store a relocated value or null (if no relocated value found for
1512   // this gc pointer and it is not a gc_result)
1513   // this must happen before we update the statepoint with load of alloca
1514   // otherwise we lose the link between statepoint and old def
1515   for (size_t i = 0; i < records.size(); i++) {
1516     const struct PartiallyConstructedSafepointRecord &info = records[i];
1517     Value *statepoint = info.safepoint.first;
1518
1519     // This will be used for consistency check
1520     DenseSet<Value *> visitedLiveValues;
1521
1522     // Insert stores for normal statepoint gc relocates
1523     insertRelocationStores(statepoint->users(), allocaMap, visitedLiveValues);
1524
1525     // In case if it was invoke statepoint
1526     // we will insert stores for exceptional path gc relocates.
1527     if (isa<InvokeInst>(statepoint)) {
1528       insertRelocationStores(info.exceptional_relocates_token->users(),
1529                              allocaMap, visitedLiveValues);
1530     }
1531
1532 #ifndef NDEBUG
1533     // For consistency check store null's into allocas for values that are not
1534     // relocated
1535     // by this statepoint.
1536     for (auto Pair : allocaMap) {
1537       Value *def = Pair.first;
1538       Value *alloca = Pair.second;
1539
1540       // This value was relocated
1541       if (visitedLiveValues.count(def)) {
1542         continue;
1543       }
1544       // Result should not be relocated
1545       if (def == info.result) {
1546         continue;
1547       }
1548
1549       Constant *CPN =
1550           ConstantPointerNull::get(cast<PointerType>(def->getType()));
1551       StoreInst *store = new StoreInst(CPN, alloca);
1552       store->insertBefore(info.safepoint.second);
1553     }
1554 #endif
1555   }
1556   // update use with load allocas and add store for gc_relocated
1557   for (auto Pair : allocaMap) {
1558     Value *def = Pair.first;
1559     Value *alloca = Pair.second;
1560
1561     // we pre-record the uses of allocas so that we dont have to worry about
1562     // later update
1563     // that change the user information.
1564     SmallVector<Instruction *, 20> uses;
1565     // PERF: trade a linear scan for repeated reallocation
1566     uses.reserve(std::distance(def->user_begin(), def->user_end()));
1567     for (User *U : def->users()) {
1568       if (!isa<ConstantExpr>(U)) {
1569         // If the def has a ConstantExpr use, then the def is either a
1570         // ConstantExpr use itself or null.  In either case
1571         // (recursively in the first, directly in the second), the oop
1572         // it is ultimately dependent on is null and this particular
1573         // use does not need to be fixed up.
1574         uses.push_back(cast<Instruction>(U));
1575       }
1576     }
1577
1578     std::sort(uses.begin(), uses.end());
1579     auto last = std::unique(uses.begin(), uses.end());
1580     uses.erase(last, uses.end());
1581
1582     for (Instruction *use : uses) {
1583       if (isa<PHINode>(use)) {
1584         PHINode *phi = cast<PHINode>(use);
1585         for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1586           if (def == phi->getIncomingValue(i)) {
1587             LoadInst *load = new LoadInst(
1588                 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1589             phi->setIncomingValue(i, load);
1590           }
1591         }
1592       } else {
1593         LoadInst *load = new LoadInst(alloca, "", use);
1594         use->replaceUsesOfWith(def, load);
1595       }
1596     }
1597
1598     // emit store for the initial gc value
1599     // store must be inserted after load, otherwise store will be in alloca's
1600     // use list and an extra load will be inserted before it
1601     StoreInst *store = new StoreInst(def, alloca);
1602     if (isa<Instruction>(def)) {
1603       store->insertAfter(cast<Instruction>(def));
1604     } else {
1605       assert((isa<Argument>(def) || isa<GlobalVariable>(def) ||
1606               (isa<Constant>(def) && cast<Constant>(def)->isNullValue())) &&
1607              "Must be argument or global");
1608       store->insertAfter(cast<Instruction>(alloca));
1609     }
1610   }
1611
1612   assert(PromotableAllocas.size() == live.size() &&
1613          "we must have the same allocas with lives");
1614   if (!PromotableAllocas.empty()) {
1615     // apply mem2reg to promote alloca to SSA
1616     PromoteMemToReg(PromotableAllocas, DT);
1617   }
1618
1619 #ifndef NDEBUG
1620   for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1621        itr++) {
1622     if (isa<AllocaInst>(*itr))
1623       initialAllocaNum--;
1624   }
1625   assert(initialAllocaNum == 0 && "We must not introduce any extra allocas");
1626 #endif
1627 }
1628
1629 /// Implement a unique function which doesn't require we sort the input
1630 /// vector.  Doing so has the effect of changing the output of a couple of
1631 /// tests in ways which make them less useful in testing fused safepoints.
1632 template <typename T> static void unique_unsorted(std::vector<T> &vec) {
1633   DenseSet<T> seen;
1634   std::vector<T> tmp;
1635   vec.reserve(vec.size());
1636   std::swap(tmp, vec);
1637   for (auto V : tmp) {
1638     if (seen.insert(V).second) {
1639       vec.push_back(V);
1640     }
1641   }
1642 }
1643
1644 static Function *getUseHolder(Module &M) {
1645   FunctionType *ftype =
1646       FunctionType::get(Type::getVoidTy(M.getContext()), true);
1647   Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype));
1648   return Func;
1649 }
1650
1651 /// Insert holders so that each Value is obviously live through the entire
1652 /// liftetime of the call.
1653 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1654                                  std::vector<CallInst *> &holders) {
1655   Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1656   Function *Func = getUseHolder(*M);
1657   if (CS.isCall()) {
1658     // For call safepoints insert dummy calls right after safepoint
1659     BasicBlock::iterator next(CS.getInstruction());
1660     next++;
1661     CallInst *base_holder = CallInst::Create(Func, Values, "", next);
1662     holders.push_back(base_holder);
1663   } else if (CS.isInvoke()) {
1664     // For invoke safepooints insert dummy calls both in normal and
1665     // exceptional destination blocks
1666     InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1667     CallInst *normal_holder = CallInst::Create(
1668         Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt());
1669     CallInst *unwind_holder = CallInst::Create(
1670         Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt());
1671     holders.push_back(normal_holder);
1672     holders.push_back(unwind_holder);
1673   } else {
1674     assert(false && "Unsupported");
1675   }
1676 }
1677
1678 static void findLiveReferences(
1679     Function &F, DominatorTree &DT, Pass *P, std::vector<CallSite> &toUpdate,
1680     std::vector<struct PartiallyConstructedSafepointRecord> &records) {
1681   for (size_t i = 0; i < records.size(); i++) {
1682     struct PartiallyConstructedSafepointRecord &info = records[i];
1683     CallSite &CS = toUpdate[i];
1684     analyzeParsePointLiveness(DT, CS, info);
1685   }
1686 }
1687
1688 static void addBasesAsLiveValues(std::set<Value *> &liveset,
1689                                  std::map<Value *, Value *> &base_pairs) {
1690   // Identify any base pointers which are used in this safepoint, but not
1691   // themselves relocated.  We need to relocate them so that later inserted
1692   // safepoints can get the properly relocated base register.
1693   DenseSet<Value *> missing;
1694   for (Value *L : liveset) {
1695     assert(base_pairs.find(L) != base_pairs.end());
1696     Value *base = base_pairs[L];
1697     assert(base);
1698     if (liveset.find(base) == liveset.end()) {
1699       assert(base_pairs.find(base) == base_pairs.end());
1700       // uniqued by set insert
1701       missing.insert(base);
1702     }
1703   }
1704
1705   // Note that we want these at the end of the list, otherwise
1706   // register placement gets screwed up once we lower to STATEPOINT
1707   // instructions.  This is an utter hack, but there doesn't seem to be a
1708   // better one.
1709   for (Value *base : missing) {
1710     assert(base);
1711     liveset.insert(base);
1712     base_pairs[base] = base;
1713   }
1714   assert(liveset.size() == base_pairs.size());
1715 }
1716
1717 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
1718                               std::vector<CallSite> &toUpdate) {
1719 #ifndef NDEBUG
1720   // sanity check the input
1721   std::set<CallSite> uniqued;
1722   uniqued.insert(toUpdate.begin(), toUpdate.end());
1723   assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1724
1725   for (size_t i = 0; i < toUpdate.size(); i++) {
1726     CallSite &CS = toUpdate[i];
1727     assert(CS.getInstruction()->getParent()->getParent() == &F);
1728     assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1729   }
1730 #endif
1731
1732   // A list of dummy calls added to the IR to keep various values obviously
1733   // live in the IR.  We'll remove all of these when done.
1734   std::vector<CallInst *> holders;
1735
1736   // Insert a dummy call with all of the arguments to the vm_state we'll need
1737   // for the actual safepoint insertion.  This ensures reference arguments in
1738   // the deopt argument list are considered live through the safepoint (and
1739   // thus makes sure they get relocated.)
1740   for (size_t i = 0; i < toUpdate.size(); i++) {
1741     CallSite &CS = toUpdate[i];
1742     Statepoint StatepointCS(CS);
1743
1744     SmallVector<Value *, 64> DeoptValues;
1745     for (Use &U : StatepointCS.vm_state_args()) {
1746       Value *Arg = cast<Value>(&U);
1747       if (isGCPointerType(Arg->getType()))
1748         DeoptValues.push_back(Arg);
1749     }
1750     insertUseHolderAfter(CS, DeoptValues, holders);
1751   }
1752
1753   std::vector<struct PartiallyConstructedSafepointRecord> records;
1754   records.reserve(toUpdate.size());
1755   for (size_t i = 0; i < toUpdate.size(); i++) {
1756     struct PartiallyConstructedSafepointRecord info;
1757     records.push_back(info);
1758   }
1759   assert(records.size() == toUpdate.size());
1760
1761   // A) Identify all gc pointers which are staticly live at the given call
1762   // site.
1763   findLiveReferences(F, DT, P, toUpdate, records);
1764
1765   // B) Find the base pointers for each live pointer
1766   /* scope for caching */ {
1767     // Cache the 'defining value' relation used in the computation and
1768     // insertion of base phis and selects.  This ensures that we don't insert
1769     // large numbers of duplicate base_phis.
1770     DefiningValueMapTy DVCache;
1771
1772     for (size_t i = 0; i < records.size(); i++) {
1773       struct PartiallyConstructedSafepointRecord &info = records[i];
1774       CallSite &CS = toUpdate[i];
1775       findBasePointers(DT, DVCache, CS, info);
1776     }
1777   } // end of cache scope
1778
1779   // The base phi insertion logic (for any safepoint) may have inserted new
1780   // instructions which are now live at some safepoint.  The simplest such
1781   // example is:
1782   // loop:
1783   //   phi a  <-- will be a new base_phi here
1784   //   safepoint 1 <-- that needs to be live here
1785   //   gep a + 1
1786   //   safepoint 2
1787   //   br loop
1788   std::set<llvm::Value *> allInsertedDefs;
1789   for (size_t i = 0; i < records.size(); i++) {
1790     struct PartiallyConstructedSafepointRecord &info = records[i];
1791     allInsertedDefs.insert(info.newInsertedDefs.begin(),
1792                            info.newInsertedDefs.end());
1793   }
1794
1795   // We insert some dummy calls after each safepoint to definitely hold live
1796   // the base pointers which were identified for that safepoint.  We'll then
1797   // ask liveness for _every_ base inserted to see what is now live.  Then we
1798   // remove the dummy calls.
1799   holders.reserve(holders.size() + records.size());
1800   for (size_t i = 0; i < records.size(); i++) {
1801     struct PartiallyConstructedSafepointRecord &info = records[i];
1802     CallSite &CS = toUpdate[i];
1803
1804     SmallVector<Value *, 128> Bases;
1805     for (auto Pair : info.base_pairs) {
1806       Bases.push_back(Pair.second);
1807     }
1808     insertUseHolderAfter(CS, Bases, holders);
1809   }
1810
1811   // Add the bases explicitly to the live vector set.  This may result in a few
1812   // extra relocations, but the base has to be available whenever a pointer
1813   // derived from it is used.  Thus, we need it to be part of the statepoint's
1814   // gc arguments list.  TODO: Introduce an explicit notion (in the following
1815   // code) of the GC argument list as seperate from the live Values at a
1816   // given statepoint.
1817   for (size_t i = 0; i < records.size(); i++) {
1818     struct PartiallyConstructedSafepointRecord &info = records[i];
1819     addBasesAsLiveValues(info.liveset, info.base_pairs);
1820   }
1821
1822   // If we inserted any new values, we need to adjust our notion of what is
1823   // live at a particular safepoint.
1824   if (!allInsertedDefs.empty()) {
1825     fixupLiveReferences(F, DT, P, allInsertedDefs, toUpdate, records);
1826   }
1827   if (PrintBasePointers) {
1828     for (size_t i = 0; i < records.size(); i++) {
1829       struct PartiallyConstructedSafepointRecord &info = records[i];
1830       errs() << "Base Pairs: (w/Relocation)\n";
1831       for (auto Pair : info.base_pairs) {
1832         errs() << " derived %" << Pair.first->getName() << " base %"
1833                << Pair.second->getName() << "\n";
1834       }
1835     }
1836   }
1837   for (size_t i = 0; i < holders.size(); i++) {
1838     holders[i]->eraseFromParent();
1839     holders[i] = nullptr;
1840   }
1841   holders.clear();
1842
1843   // Now run through and replace the existing statepoints with new ones with
1844   // the live variables listed.  We do not yet update uses of the values being
1845   // relocated. We have references to live variables that need to
1846   // survive to the last iteration of this loop.  (By construction, the
1847   // previous statepoint can not be a live variable, thus we can and remove
1848   // the old statepoint calls as we go.)
1849   for (size_t i = 0; i < records.size(); i++) {
1850     struct PartiallyConstructedSafepointRecord &info = records[i];
1851     CallSite &CS = toUpdate[i];
1852     makeStatepointExplicit(DT, CS, P, info);
1853   }
1854   toUpdate.clear(); // prevent accident use of invalid CallSites
1855
1856   // In case if we inserted relocates in a different basic block than the
1857   // original safepoint (this can happen for invokes). We need to be sure that
1858   // original values were not used in any of the phi nodes at the
1859   // beginning of basic block containing them. Because we know that all such
1860   // blocks will have single predecessor we can safely assume that all phi
1861   // nodes have single entry (because of normalizeBBForInvokeSafepoint).
1862   // Just remove them all here.
1863   for (size_t i = 0; i < records.size(); i++) {
1864     Instruction *I = records[i].safepoint.first;
1865
1866     if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
1867       FoldSingleEntryPHINodes(invoke->getNormalDest());
1868       assert(!isa<PHINode>(invoke->getNormalDest()->begin()));
1869
1870       FoldSingleEntryPHINodes(invoke->getUnwindDest());
1871       assert(!isa<PHINode>(invoke->getUnwindDest()->begin()));
1872     }
1873   }
1874
1875   // Do all the fixups of the original live variables to their relocated selves
1876   std::vector<Value *> live;
1877   for (size_t i = 0; i < records.size(); i++) {
1878     struct PartiallyConstructedSafepointRecord &info = records[i];
1879     // We can't simply save the live set from the original insertion.  One of
1880     // the live values might be the result of a call which needs a safepoint.
1881     // That Value* no longer exists and we need to use the new gc_result.
1882     // Thankfully, the liveset is embedded in the statepoint (and updated), so
1883     // we just grab that.
1884     Statepoint statepoint(info.safepoint.first);
1885     live.insert(live.end(), statepoint.gc_args_begin(),
1886                 statepoint.gc_args_end());
1887   }
1888   unique_unsorted(live);
1889
1890   // sanity check
1891   for (auto ptr : live) {
1892     assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1893   }
1894
1895   relocationViaAlloca(F, DT, live, records);
1896   return !records.empty();
1897 }
1898
1899 /// Returns true if this function should be rewritten by this pass.  The main
1900 /// point of this function is as an extension point for custom logic.
1901 static bool shouldRewriteStatepointsIn(Function &F) {
1902   // TODO: This should check the GCStrategy
1903   return true;
1904 }
1905
1906 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1907   // Nothing to do for declarations.
1908   if (F.isDeclaration() || F.empty())
1909     return false;
1910
1911   // Policy choice says not to rewrite - the most common reason is that we're
1912   // compiling code without a GCStrategy.
1913   if (!shouldRewriteStatepointsIn(F))
1914     return false;
1915
1916   // Gather all the statepoints which need rewritten.
1917   std::vector<CallSite> ParsePointNeeded;
1918   for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1919        itr++) {
1920     // TODO: only the ones with the flag set!
1921     if (isStatepoint(*itr))
1922       ParsePointNeeded.push_back(CallSite(&*itr));
1923   }
1924
1925   // Return early if no work to do.
1926   if (ParsePointNeeded.empty())
1927     return false;
1928
1929   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1930   return insertParsePoints(F, DT, this, ParsePointNeeded);
1931 }