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