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