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