[RewriteStatepointsForGC] Reduce the number of new instructions for base pointers
[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/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/TargetTransformInfo.h"
19 #include "llvm/ADT/SetOperations.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InstIterator.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/MDBuilder.h"
35 #include "llvm/IR/Statepoint.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Transforms/Utils/Cloning.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
45
46 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
47
48 using namespace llvm;
49
50 // Print tracing output
51 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
52                               cl::init(false));
53
54 // Print the liveset found at the insert location
55 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
56                                   cl::init(false));
57 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
58                                       cl::init(false));
59 // Print out the base pointers for debugging
60 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
61                                        cl::init(false));
62
63 // Cost threshold measuring when it is profitable to rematerialize value instead
64 // of relocating it
65 static cl::opt<unsigned>
66 RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
67                            cl::init(6));
68
69 #ifdef XDEBUG
70 static bool ClobberNonLive = true;
71 #else
72 static bool ClobberNonLive = false;
73 #endif
74 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
75                                                   cl::location(ClobberNonLive),
76                                                   cl::Hidden);
77
78 namespace {
79 struct RewriteStatepointsForGC : public ModulePass {
80   static char ID; // Pass identification, replacement for typeid
81
82   RewriteStatepointsForGC() : ModulePass(ID) {
83     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
84   }
85   bool runOnFunction(Function &F);
86   bool runOnModule(Module &M) override {
87     bool Changed = false;
88     for (Function &F : M)
89       Changed |= runOnFunction(F);
90
91     if (Changed) {
92       // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
93       // returns true for at least one function in the module.  Since at least
94       // one function changed, we know that the precondition is satisfied.
95       stripDereferenceabilityInfo(M);
96     }
97
98     return Changed;
99   }
100
101   void getAnalysisUsage(AnalysisUsage &AU) const override {
102     // We add and rewrite a bunch of instructions, but don't really do much
103     // else.  We could in theory preserve a lot more analyses here.
104     AU.addRequired<DominatorTreeWrapperPass>();
105     AU.addRequired<TargetTransformInfoWrapperPass>();
106   }
107
108   /// The IR fed into RewriteStatepointsForGC may have had attributes implying
109   /// dereferenceability that are no longer valid/correct after
110   /// RewriteStatepointsForGC has run.  This is because semantically, after
111   /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
112   /// heap.  stripDereferenceabilityInfo (conservatively) restores correctness
113   /// by erasing all attributes in the module that externally imply
114   /// dereferenceability.
115   ///
116   void stripDereferenceabilityInfo(Module &M);
117
118   // Helpers for stripDereferenceabilityInfo
119   void stripDereferenceabilityInfoFromBody(Function &F);
120   void stripDereferenceabilityInfoFromPrototype(Function &F);
121 };
122 } // namespace
123
124 char RewriteStatepointsForGC::ID = 0;
125
126 ModulePass *llvm::createRewriteStatepointsForGCPass() {
127   return new RewriteStatepointsForGC();
128 }
129
130 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
131                       "Make relocations explicit at statepoints", false, false)
132 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
133 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
134                     "Make relocations explicit at statepoints", false, false)
135
136 namespace {
137 struct GCPtrLivenessData {
138   /// Values defined in this block.
139   DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
140   /// Values used in this block (and thus live); does not included values
141   /// killed within this block.
142   DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
143
144   /// Values live into this basic block (i.e. used by any
145   /// instruction in this basic block or ones reachable from here)
146   DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
147
148   /// Values live out of this basic block (i.e. live into
149   /// any successor block)
150   DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
151 };
152
153 // The type of the internal cache used inside the findBasePointers family
154 // of functions.  From the callers perspective, this is an opaque type and
155 // should not be inspected.
156 //
157 // In the actual implementation this caches two relations:
158 // - The base relation itself (i.e. this pointer is based on that one)
159 // - The base defining value relation (i.e. before base_phi insertion)
160 // Generally, after the execution of a full findBasePointer call, only the
161 // base relation will remain.  Internally, we add a mixture of the two
162 // types, then update all the second type to the first type
163 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
164 typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
165 typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
166
167 struct PartiallyConstructedSafepointRecord {
168   /// The set of values known to be live across this safepoint
169   StatepointLiveSetTy liveset;
170
171   /// Mapping from live pointers to a base-defining-value
172   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
173
174   /// The *new* gc.statepoint instruction itself.  This produces the token
175   /// that normal path gc.relocates and the gc.result are tied to.
176   Instruction *StatepointToken;
177
178   /// Instruction to which exceptional gc relocates are attached
179   /// Makes it easier to iterate through them during relocationViaAlloca.
180   Instruction *UnwindToken;
181
182   /// Record live values we are rematerialized instead of relocating.
183   /// They are not included into 'liveset' field.
184   /// Maps rematerialized copy to it's original value.
185   RematerializedValueMapTy RematerializedValues;
186 };
187 }
188
189 /// Compute the live-in set for every basic block in the function
190 static void computeLiveInValues(DominatorTree &DT, Function &F,
191                                 GCPtrLivenessData &Data);
192
193 /// Given results from the dataflow liveness computation, find the set of live
194 /// Values at a particular instruction.
195 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
196                               StatepointLiveSetTy &out);
197
198 // TODO: Once we can get to the GCStrategy, this becomes
199 // Optional<bool> isGCManagedPointer(const Value *V) const override {
200
201 static bool isGCPointerType(Type *T) {
202   if (auto *PT = dyn_cast<PointerType>(T))
203     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
204     // GC managed heap.  We know that a pointer into this heap needs to be
205     // updated and that no other pointer does.
206     return (1 == PT->getAddressSpace());
207   return false;
208 }
209
210 // Return true if this type is one which a) is a gc pointer or contains a GC
211 // pointer and b) is of a type this code expects to encounter as a live value.
212 // (The insertion code will assert that a type which matches (a) and not (b)
213 // is not encountered.)
214 static bool isHandledGCPointerType(Type *T) {
215   // We fully support gc pointers
216   if (isGCPointerType(T))
217     return true;
218   // We partially support vectors of gc pointers. The code will assert if it
219   // can't handle something.
220   if (auto VT = dyn_cast<VectorType>(T))
221     if (isGCPointerType(VT->getElementType()))
222       return true;
223   return false;
224 }
225
226 #ifndef NDEBUG
227 /// Returns true if this type contains a gc pointer whether we know how to
228 /// handle that type or not.
229 static bool containsGCPtrType(Type *Ty) {
230   if (isGCPointerType(Ty))
231     return true;
232   if (VectorType *VT = dyn_cast<VectorType>(Ty))
233     return isGCPointerType(VT->getScalarType());
234   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
235     return containsGCPtrType(AT->getElementType());
236   if (StructType *ST = dyn_cast<StructType>(Ty))
237     return std::any_of(
238         ST->subtypes().begin(), ST->subtypes().end(),
239         [](Type *SubType) { return containsGCPtrType(SubType); });
240   return false;
241 }
242
243 // Returns true if this is a type which a) is a gc pointer or contains a GC
244 // pointer and b) is of a type which the code doesn't expect (i.e. first class
245 // aggregates).  Used to trip assertions.
246 static bool isUnhandledGCPointerType(Type *Ty) {
247   return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
248 }
249 #endif
250
251 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
252   if (a->hasName() && b->hasName()) {
253     return -1 == a->getName().compare(b->getName());
254   } else if (a->hasName() && !b->hasName()) {
255     return true;
256   } else if (!a->hasName() && b->hasName()) {
257     return false;
258   } else {
259     // Better than nothing, but not stable
260     return a < b;
261   }
262 }
263
264 // Conservatively identifies any definitions which might be live at the
265 // given instruction. The  analysis is performed immediately before the
266 // given instruction. Values defined by that instruction are not considered
267 // live.  Values used by that instruction are considered live.
268 static void analyzeParsePointLiveness(
269     DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
270     const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
271   Instruction *inst = CS.getInstruction();
272
273   StatepointLiveSetTy liveset;
274   findLiveSetAtInst(inst, OriginalLivenessData, liveset);
275
276   if (PrintLiveSet) {
277     // Note: This output is used by several of the test cases
278     // The order of elements in a set is not stable, put them in a vec and sort
279     // by name
280     SmallVector<Value *, 64> temp;
281     temp.insert(temp.end(), liveset.begin(), liveset.end());
282     std::sort(temp.begin(), temp.end(), order_by_name);
283     errs() << "Live Variables:\n";
284     for (Value *V : temp) {
285       errs() << " " << V->getName(); // no newline
286       V->dump();
287     }
288   }
289   if (PrintLiveSetSize) {
290     errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
291     errs() << "Number live values: " << liveset.size() << "\n";
292   }
293   result.liveset = liveset;
294 }
295
296 static Value *findBaseDefiningValue(Value *I);
297
298 /// Return a base defining value for the 'Index' element of the given vector
299 /// instruction 'I'.  If Index is null, returns a BDV for the entire vector
300 /// 'I'.  As an optimization, this method will try to determine when the 
301 /// element is known to already be a base pointer.  If this can be established,
302 /// the second value in the returned pair will be true.  Note that either a
303 /// vector or a pointer typed value can be returned.  For the former, the
304 /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
305 /// If the later, the return pointer is a BDV (or possibly a base) for the
306 /// particular element in 'I'.  
307 static std::pair<Value *, bool>
308 findBaseDefiningValueOfVector(Value *I, Value *Index = nullptr) {
309   assert(I->getType()->isVectorTy() &&
310          cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
311          "Illegal to ask for the base pointer of a non-pointer type");
312
313   // Each case parallels findBaseDefiningValue below, see that code for
314   // detailed motivation.
315
316   if (isa<Argument>(I))
317     // An incoming argument to the function is a base pointer
318     return std::make_pair(I, true);
319
320   // We shouldn't see the address of a global as a vector value?
321   assert(!isa<GlobalVariable>(I) &&
322          "unexpected global variable found in base of vector");
323
324   // inlining could possibly introduce phi node that contains
325   // undef if callee has multiple returns
326   if (isa<UndefValue>(I))
327     // utterly meaningless, but useful for dealing with partially optimized
328     // code.
329     return std::make_pair(I, true);
330
331   // Due to inheritance, this must be _after_ the global variable and undef
332   // checks
333   if (Constant *Con = dyn_cast<Constant>(I)) {
334     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
335            "order of checks wrong!");
336     assert(Con->isNullValue() && "null is the only case which makes sense");
337     return std::make_pair(Con, true);
338   }
339   
340   if (isa<LoadInst>(I))
341     return std::make_pair(I, true);
342   
343   // For an insert element, we might be able to look through it if we know
344   // something about the indexes.
345   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
346     if (Index) {
347       Value *InsertIndex = IEI->getOperand(2);
348       // This index is inserting the value, look for its BDV
349       if (InsertIndex == Index)
350         return std::make_pair(findBaseDefiningValue(IEI->getOperand(1)), false);
351       // Both constant, and can't be equal per above. This insert is definitely
352       // not relevant, look back at the rest of the vector and keep trying.
353       if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
354         return findBaseDefiningValueOfVector(IEI->getOperand(0), Index);
355     }
356     
357     // We don't know whether this vector contains entirely base pointers or
358     // not.  To be conservatively correct, we treat it as a BDV and will
359     // duplicate code as needed to construct a parallel vector of bases.
360     return std::make_pair(IEI, false);
361   }
362
363   if (isa<ShuffleVectorInst>(I))
364     // We don't know whether this vector contains entirely base pointers or
365     // not.  To be conservatively correct, we treat it as a BDV and will
366     // duplicate code as needed to construct a parallel vector of bases.
367     // TODO: There a number of local optimizations which could be applied here
368     // for particular sufflevector patterns.
369     return std::make_pair(I, false);
370
371   // A PHI or Select is a base defining value.  The outer findBasePointer
372   // algorithm is responsible for constructing a base value for this BDV.
373   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
374          "unknown vector instruction - no base found for vector element");
375   return std::make_pair(I, false);
376 }
377
378 static bool isKnownBaseResult(Value *V);
379
380 /// Helper function for findBasePointer - Will return a value which either a)
381 /// defines the base pointer for the input, b) blocks the simple search
382 /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
383 /// from pointer to vector type or back.
384 static Value *findBaseDefiningValue(Value *I) {
385   if (I->getType()->isVectorTy())
386     return findBaseDefiningValueOfVector(I).first;
387   
388   assert(I->getType()->isPointerTy() &&
389          "Illegal to ask for the base pointer of a non-pointer type");
390
391   if (isa<Argument>(I))
392     // An incoming argument to the function is a base pointer
393     // We should have never reached here if this argument isn't an gc value
394     return I;
395
396   if (isa<GlobalVariable>(I))
397     // base case
398     return I;
399
400   // inlining could possibly introduce phi node that contains
401   // undef if callee has multiple returns
402   if (isa<UndefValue>(I))
403     // utterly meaningless, but useful for dealing with
404     // partially optimized code.
405     return I;
406
407   // Due to inheritance, this must be _after_ the global variable and undef
408   // checks
409   if (Constant *Con = dyn_cast<Constant>(I)) {
410     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
411            "order of checks wrong!");
412     // Note: Finding a constant base for something marked for relocation
413     // doesn't really make sense.  The most likely case is either a) some
414     // screwed up the address space usage or b) your validating against
415     // compiled C++ code w/o the proper separation.  The only real exception
416     // is a null pointer.  You could have generic code written to index of
417     // off a potentially null value and have proven it null.  We also use
418     // null pointers in dead paths of relocation phis (which we might later
419     // want to find a base pointer for).
420     assert(isa<ConstantPointerNull>(Con) &&
421            "null is the only case which makes sense");
422     return Con;
423   }
424
425   if (CastInst *CI = dyn_cast<CastInst>(I)) {
426     Value *Def = CI->stripPointerCasts();
427     // If we find a cast instruction here, it means we've found a cast which is
428     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
429     // handle int->ptr conversion.
430     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
431     return findBaseDefiningValue(Def);
432   }
433
434   if (isa<LoadInst>(I))
435     return I; // The value loaded is an gc base itself
436
437   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
438     // The base of this GEP is the base
439     return findBaseDefiningValue(GEP->getPointerOperand());
440
441   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
442     switch (II->getIntrinsicID()) {
443     case Intrinsic::experimental_gc_result_ptr:
444     default:
445       // fall through to general call handling
446       break;
447     case Intrinsic::experimental_gc_statepoint:
448     case Intrinsic::experimental_gc_result_float:
449     case Intrinsic::experimental_gc_result_int:
450       llvm_unreachable("these don't produce pointers");
451     case Intrinsic::experimental_gc_relocate: {
452       // Rerunning safepoint insertion after safepoints are already
453       // inserted is not supported.  It could probably be made to work,
454       // but why are you doing this?  There's no good reason.
455       llvm_unreachable("repeat safepoint insertion is not supported");
456     }
457     case Intrinsic::gcroot:
458       // Currently, this mechanism hasn't been extended to work with gcroot.
459       // There's no reason it couldn't be, but I haven't thought about the
460       // implications much.
461       llvm_unreachable(
462           "interaction with the gcroot mechanism is not supported");
463     }
464   }
465   // We assume that functions in the source language only return base
466   // pointers.  This should probably be generalized via attributes to support
467   // both source language and internal functions.
468   if (isa<CallInst>(I) || isa<InvokeInst>(I))
469     return I;
470
471   // I have absolutely no idea how to implement this part yet.  It's not
472   // necessarily hard, I just haven't really looked at it yet.
473   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
474
475   if (isa<AtomicCmpXchgInst>(I))
476     // A CAS is effectively a atomic store and load combined under a
477     // predicate.  From the perspective of base pointers, we just treat it
478     // like a load.
479     return I;
480
481   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
482                                    "binary ops which don't apply to pointers");
483
484   // The aggregate ops.  Aggregates can either be in the heap or on the
485   // stack, but in either case, this is simply a field load.  As a result,
486   // this is a defining definition of the base just like a load is.
487   if (isa<ExtractValueInst>(I))
488     return I;
489
490   // We should never see an insert vector since that would require we be
491   // tracing back a struct value not a pointer value.
492   assert(!isa<InsertValueInst>(I) &&
493          "Base pointer for a struct is meaningless");
494
495   // An extractelement produces a base result exactly when it's input does.
496   // We may need to insert a parallel instruction to extract the appropriate
497   // element out of the base vector corresponding to the input. Given this,
498   // it's analogous to the phi and select case even though it's not a merge.
499   if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
500     Value *VectorOperand = EEI->getVectorOperand();
501     Value *Index = EEI->getIndexOperand();
502     std::pair<Value *, bool> pair =
503       findBaseDefiningValueOfVector(VectorOperand, Index);
504     Value *VectorBase = pair.first;
505     if (VectorBase->getType()->isPointerTy())
506       // We found a BDV for this specific element with the vector.  This is an
507       // optimization, but in practice it covers most of the useful cases
508       // created via scalarization. Note: The peephole optimization here is
509       // currently needed for correctness since the general algorithm doesn't
510       // yet handle insertelements.  That will change shortly.
511       return VectorBase;
512     else {
513       assert(VectorBase->getType()->isVectorTy());
514       // Otherwise, we have an instruction which potentially produces a
515       // derived pointer and we need findBasePointers to clone code for us
516       // such that we can create an instruction which produces the
517       // accompanying base pointer.
518       return EEI;
519     }
520   }
521
522   // The last two cases here don't return a base pointer.  Instead, they
523   // return a value which dynamically selects from among several base
524   // derived pointers (each with it's own base potentially).  It's the job of
525   // the caller to resolve these.
526   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
527          "missing instruction case in findBaseDefiningValing");
528   return I;
529 }
530
531 /// Returns the base defining value for this value.
532 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
533   Value *&Cached = Cache[I];
534   if (!Cached) {
535     Cached = findBaseDefiningValue(I);
536     DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
537                  << Cached->getName() << "\n");
538   }
539   assert(Cache[I] != nullptr);
540   return Cached;
541 }
542
543 /// Return a base pointer for this value if known.  Otherwise, return it's
544 /// base defining value.
545 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
546   Value *Def = findBaseDefiningValueCached(I, Cache);
547   auto Found = Cache.find(Def);
548   if (Found != Cache.end()) {
549     // Either a base-of relation, or a self reference.  Caller must check.
550     return Found->second;
551   }
552   // Only a BDV available
553   return Def;
554 }
555
556 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
557 /// is it known to be a base pointer?  Or do we need to continue searching.
558 static bool isKnownBaseResult(Value *V) {
559   if (!isa<PHINode>(V) && !isa<SelectInst>(V) && !isa<ExtractElementInst>(V)) {
560     // no recursion possible
561     return true;
562   }
563   if (isa<Instruction>(V) &&
564       cast<Instruction>(V)->getMetadata("is_base_value")) {
565     // This is a previously inserted base phi or select.  We know
566     // that this is a base value.
567     return true;
568   }
569
570   // We need to keep searching
571   return false;
572 }
573
574 namespace {
575 /// Models the state of a single base defining value in the findBasePointer
576 /// algorithm for determining where a new instruction is needed to propagate
577 /// the base of this BDV.
578 class BDVState {
579 public:
580   enum Status { Unknown, Base, Conflict };
581
582   BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
583     assert(status != Base || b);
584   }
585   explicit BDVState(Value *b) : status(Base), base(b) {}
586   BDVState() : status(Unknown), base(nullptr) {}
587
588   Status getStatus() const { return status; }
589   Value *getBase() const { return base; }
590
591   bool isBase() const { return getStatus() == Base; }
592   bool isUnknown() const { return getStatus() == Unknown; }
593   bool isConflict() const { return getStatus() == Conflict; }
594
595   bool operator==(const BDVState &other) const {
596     return base == other.base && status == other.status;
597   }
598
599   bool operator!=(const BDVState &other) const { return !(*this == other); }
600
601   LLVM_DUMP_METHOD
602   void dump() const { print(dbgs()); dbgs() << '\n'; }
603   
604   void print(raw_ostream &OS) const {
605     OS << status << " (" << base << " - "
606        << (base ? base->getName() : "nullptr") << "): ";
607   }
608
609 private:
610   Status status;
611   Value *base; // non null only if status == base
612 };
613
614 inline raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
615   State.print(OS);
616   return OS;
617 }
618
619
620 typedef DenseMap<Value *, BDVState> ConflictStateMapTy;
621 // Values of type BDVState form a lattice, and this is a helper
622 // class that implementes the meet operation.  The meat of the meet
623 // operation is implemented in MeetBDVStates::pureMeet
624 class MeetBDVStates {
625 public:
626   /// Initializes the currentResult to the TOP state so that if can be met with
627   /// any other state to produce that state.
628   MeetBDVStates() {}
629
630   // Destructively meet the current result with the given BDVState
631   void meetWith(BDVState otherState) {
632     currentResult = meet(otherState, currentResult);
633   }
634
635   BDVState getResult() const { return currentResult; }
636
637 private:
638   BDVState currentResult;
639
640   /// Perform a meet operation on two elements of the BDVState lattice.
641   static BDVState meet(BDVState LHS, BDVState RHS) {
642     assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
643            "math is wrong: meet does not commute!");
644     BDVState Result = pureMeet(LHS, RHS);
645     DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
646                  << " produced " << Result << "\n");
647     return Result;
648   }
649
650   static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
651     switch (stateA.getStatus()) {
652     case BDVState::Unknown:
653       return stateB;
654
655     case BDVState::Base:
656       assert(stateA.getBase() && "can't be null");
657       if (stateB.isUnknown())
658         return stateA;
659
660       if (stateB.isBase()) {
661         if (stateA.getBase() == stateB.getBase()) {
662           assert(stateA == stateB && "equality broken!");
663           return stateA;
664         }
665         return BDVState(BDVState::Conflict);
666       }
667       assert(stateB.isConflict() && "only three states!");
668       return BDVState(BDVState::Conflict);
669
670     case BDVState::Conflict:
671       return stateA;
672     }
673     llvm_unreachable("only three states!");
674   }
675 };
676 }
677 /// For a given value or instruction, figure out what base ptr it's derived
678 /// from.  For gc objects, this is simply itself.  On success, returns a value
679 /// which is the base pointer.  (This is reliable and can be used for
680 /// relocation.)  On failure, returns nullptr.
681 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
682   Value *def = findBaseOrBDV(I, cache);
683
684   if (isKnownBaseResult(def)) {
685     return def;
686   }
687
688   // Here's the rough algorithm:
689   // - For every SSA value, construct a mapping to either an actual base
690   //   pointer or a PHI which obscures the base pointer.
691   // - Construct a mapping from PHI to unknown TOP state.  Use an
692   //   optimistic algorithm to propagate base pointer information.  Lattice
693   //   looks like:
694   //   UNKNOWN
695   //   b1 b2 b3 b4
696   //   CONFLICT
697   //   When algorithm terminates, all PHIs will either have a single concrete
698   //   base or be in a conflict state.
699   // - For every conflict, insert a dummy PHI node without arguments.  Add
700   //   these to the base[Instruction] = BasePtr mapping.  For every
701   //   non-conflict, add the actual base.
702   //  - For every conflict, add arguments for the base[a] of each input
703   //   arguments.
704   //
705   // Note: A simpler form of this would be to add the conflict form of all
706   // PHIs without running the optimistic algorithm.  This would be
707   // analogous to pessimistic data flow and would likely lead to an
708   // overall worse solution.
709
710 #ifndef NDEBUG
711   auto isExpectedBDVType = [](Value *BDV) {
712     return isa<PHINode>(BDV) || isa<SelectInst>(BDV) || isa<ExtractElementInst>(BDV);
713   };
714 #endif
715
716   // Once populated, will contain a mapping from each potentially non-base BDV
717   // to a lattice value (described above) which corresponds to that BDV.
718   ConflictStateMapTy states;
719   // Recursively fill in all phis & selects reachable from the initial one
720   // for which we don't already know a definite base value for
721   /* scope */ {
722     DenseSet<Value *> Visited;
723     SmallVector<Value*, 16> Worklist;
724     Worklist.push_back(def);
725     Visited.insert(def);
726     while (!Worklist.empty()) {
727       Value *Current = Worklist.pop_back_val();
728       assert(!isKnownBaseResult(Current) && "why did it get added?");
729
730       auto visitIncomingValue = [&](Value *InVal) {
731         Value *Base = findBaseOrBDV(InVal, cache);
732         if (isKnownBaseResult(Base))
733           // Known bases won't need new instructions introduced and can be
734           // ignored safely
735           return;
736         assert(isExpectedBDVType(Base) && "the only non-base values "
737                "we see should be base defining values");
738         if (Visited.insert(Base).second)
739           Worklist.push_back(Base);
740       };
741       if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
742         for (Value *InVal : Phi->incoming_values())
743           visitIncomingValue(InVal);
744       } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
745         visitIncomingValue(Sel->getTrueValue());
746         visitIncomingValue(Sel->getFalseValue());
747       } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
748         visitIncomingValue(EE->getVectorOperand());
749       } else {
750         // There are two classes of instructions we know we don't handle.
751         assert(isa<ShuffleVectorInst>(Current) ||
752                isa<InsertElementInst>(Current));
753         llvm_unreachable("unimplemented instruction case");
754       }
755     }
756     // The frontier of visited instructions are the ones we might need to
757     // duplicate, so fill in the starting state for the optimistic algorithm
758     // that follows.
759     for (Value *BDV : Visited) {
760       states[BDV] = BDVState();
761     }
762   }
763
764   if (TraceLSP) {
765     errs() << "States after initialization:\n";
766     for (auto Pair : states)
767       dbgs() << " " << Pair.second << " for " << *Pair.first << "\n";
768   }
769
770   // TODO: come back and revisit the state transitions around inputs which
771   // have reached conflict state.  The current version seems too conservative.
772
773   // Return a phi state for a base defining value.  We'll generate a new
774   // base state for known bases and expect to find a cached state otherwise.
775   auto getStateForBDV = [&](Value *baseValue) {
776     if (isKnownBaseResult(baseValue))
777       return BDVState(baseValue);
778     auto I = states.find(baseValue);
779     assert(I != states.end() && "lookup failed!");
780     return I->second;
781   };
782
783   bool progress = true;
784   while (progress) {
785 #ifndef NDEBUG
786     size_t oldSize = states.size();
787 #endif
788     progress = false;
789     // We're only changing keys in this loop, thus safe to keep iterators
790     for (auto Pair : states) {
791       Value *v = Pair.first;
792       assert(!isKnownBaseResult(v) && "why did it get added?");
793
794       // Given an input value for the current instruction, return a BDVState
795       // instance which represents the BDV of that value.
796       auto getStateForInput = [&](Value *V) mutable {
797         Value *BDV = findBaseOrBDV(V, cache);
798         return getStateForBDV(BDV);
799       };
800
801       MeetBDVStates calculateMeet;
802       if (SelectInst *select = dyn_cast<SelectInst>(v)) {
803         calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
804         calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
805       } else if (PHINode *Phi = dyn_cast<PHINode>(v)) {
806         for (Value *Val : Phi->incoming_values())
807           calculateMeet.meetWith(getStateForInput(Val));
808       } else {
809         // The 'meet' for an extractelement is slightly trivial, but it's still
810         // useful in that it drives us to conflict if our input is.
811         auto *EE = cast<ExtractElementInst>(v);
812         calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
813       }
814
815
816       BDVState oldState = states[v];
817       BDVState newState = calculateMeet.getResult();
818       if (oldState != newState) {
819         progress = true;
820         states[v] = newState;
821       }
822     }
823
824     assert(oldSize <= states.size());
825     assert(oldSize == states.size() || progress);
826   }
827
828   if (TraceLSP) {
829     errs() << "States after meet iteration:\n";
830     for (auto Pair : states)
831       dbgs() << " " << Pair.second << " for " << *Pair.first << "\n";
832   }
833
834   // Insert Phis for all conflicts
835   // We want to keep naming deterministic in the loop that follows, so
836   // sort the keys before iteration.  This is useful in allowing us to
837   // write stable tests. Note that there is no invalidation issue here.
838   SmallVector<Value *, 16> Keys;
839   Keys.reserve(states.size());
840   for (auto Pair : states) {
841     Value *V = Pair.first;
842     Keys.push_back(V);
843   }
844   std::sort(Keys.begin(), Keys.end(), order_by_name);
845   // TODO: adjust naming patterns to avoid this order of iteration dependency
846   for (Value *V : Keys) {
847     Instruction *I = cast<Instruction>(V);
848     BDVState State = states[I];
849     assert(!isKnownBaseResult(I) && "why did it get added?");
850     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
851
852     // extractelement instructions are a bit special in that we may need to
853     // insert an extract even when we know an exact base for the instruction.
854     // The problem is that we need to convert from a vector base to a scalar
855     // base for the particular indice we're interested in.
856     if (State.isBase() && isa<ExtractElementInst>(I) &&
857         isa<VectorType>(State.getBase()->getType())) {
858       auto *EE = cast<ExtractElementInst>(I);
859       // TODO: In many cases, the new instruction is just EE itself.  We should
860       // exploit this, but can't do it here since it would break the invariant
861       // about the BDV not being known to be a base.
862       auto *BaseInst = ExtractElementInst::Create(State.getBase(),
863                                                   EE->getIndexOperand(),
864                                                   "base_ee", EE);
865       BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
866       states[I] = BDVState(BDVState::Base, BaseInst);
867     }
868     
869     if (!State.isConflict())
870       continue;
871
872     /// Create and insert a new instruction which will represent the base of
873     /// the given instruction 'I'.
874     auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
875       if (isa<PHINode>(I)) {
876         BasicBlock *BB = I->getParent();
877         int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
878         assert(NumPreds > 0 && "how did we reach here");
879         std::string Name = I->hasName() ?
880            (I->getName() + ".base").str() : "base_phi";
881         return PHINode::Create(I->getType(), NumPreds, Name, I);
882       } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
883         // The undef will be replaced later
884         UndefValue *Undef = UndefValue::get(Sel->getType());
885         std::string Name = I->hasName() ?
886           (I->getName() + ".base").str() : "base_select";
887         return SelectInst::Create(Sel->getCondition(), Undef,
888                                   Undef, Name, Sel);
889       } else {
890         auto *EE = cast<ExtractElementInst>(I);
891         UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
892         std::string Name = I->hasName() ?
893           (I->getName() + ".base").str() : "base_ee";
894         return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
895                                           EE);
896       }
897     };
898     Instruction *BaseInst = MakeBaseInstPlaceholder(I);
899     // Add metadata marking this as a base value
900     BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
901     states[I] = BDVState(BDVState::Conflict, BaseInst);
902   }
903
904   // Fixup all the inputs of the new PHIs
905   for (auto Pair : states) {
906     Instruction *v = cast<Instruction>(Pair.first);
907     BDVState state = Pair.second;
908
909     assert(!isKnownBaseResult(v) && "why did it get added?");
910     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
911     if (!state.isConflict())
912       continue;
913
914     if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
915       PHINode *phi = cast<PHINode>(v);
916       unsigned NumPHIValues = phi->getNumIncomingValues();
917       for (unsigned i = 0; i < NumPHIValues; i++) {
918         Value *InVal = phi->getIncomingValue(i);
919         BasicBlock *InBB = phi->getIncomingBlock(i);
920
921         // If we've already seen InBB, add the same incoming value
922         // we added for it earlier.  The IR verifier requires phi
923         // nodes with multiple entries from the same basic block
924         // to have the same incoming value for each of those
925         // entries.  If we don't do this check here and basephi
926         // has a different type than base, we'll end up adding two
927         // bitcasts (and hence two distinct values) as incoming
928         // values for the same basic block.
929
930         int blockIndex = basephi->getBasicBlockIndex(InBB);
931         if (blockIndex != -1) {
932           Value *oldBase = basephi->getIncomingValue(blockIndex);
933           basephi->addIncoming(oldBase, InBB);
934 #ifndef NDEBUG
935           Value *base = findBaseOrBDV(InVal, cache);
936           if (!isKnownBaseResult(base)) {
937             // Either conflict or base.
938             assert(states.count(base));
939             base = states[base].getBase();
940             assert(base != nullptr && "unknown BDVState!");
941           }
942
943           // In essence this assert states: the only way two
944           // values incoming from the same basic block may be
945           // different is by being different bitcasts of the same
946           // value.  A cleanup that remains TODO is changing
947           // findBaseOrBDV to return an llvm::Value of the correct
948           // type (and still remain pure).  This will remove the
949           // need to add bitcasts.
950           assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
951                  "sanity -- findBaseOrBDV should be pure!");
952 #endif
953           continue;
954         }
955
956         // Find either the defining value for the PHI or the normal base for
957         // a non-phi node
958         Value *base = findBaseOrBDV(InVal, cache);
959         if (!isKnownBaseResult(base)) {
960           // Either conflict or base.
961           assert(states.count(base));
962           base = states[base].getBase();
963           assert(base != nullptr && "unknown BDVState!");
964         }
965         assert(base && "can't be null");
966         // Must use original input BB since base may not be Instruction
967         // The cast is needed since base traversal may strip away bitcasts
968         if (base->getType() != basephi->getType()) {
969           base = new BitCastInst(base, basephi->getType(), "cast",
970                                  InBB->getTerminator());
971         }
972         basephi->addIncoming(base, InBB);
973       }
974       assert(basephi->getNumIncomingValues() == NumPHIValues);
975     } else if (SelectInst *basesel = dyn_cast<SelectInst>(state.getBase())) {
976       SelectInst *sel = cast<SelectInst>(v);
977       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
978       // something more safe and less hacky.
979       for (int i = 1; i <= 2; i++) {
980         Value *InVal = sel->getOperand(i);
981         // Find either the defining value for the PHI or the normal base for
982         // a non-phi node
983         Value *base = findBaseOrBDV(InVal, cache);
984         if (!isKnownBaseResult(base)) {
985           // Either conflict or base.
986           assert(states.count(base));
987           base = states[base].getBase();
988           assert(base != nullptr && "unknown BDVState!");
989         }
990         assert(base && "can't be null");
991         // Must use original input BB since base may not be Instruction
992         // The cast is needed since base traversal may strip away bitcasts
993         if (base->getType() != basesel->getType()) {
994           base = new BitCastInst(base, basesel->getType(), "cast", basesel);
995         }
996         basesel->setOperand(i, base);
997       }
998     } else {
999       auto *BaseEE = cast<ExtractElementInst>(state.getBase());
1000       Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
1001       Value *Base = findBaseOrBDV(InVal, cache);
1002       if (!isKnownBaseResult(Base)) {
1003         // Either conflict or base.
1004         assert(states.count(Base));
1005         Base = states[Base].getBase();
1006         assert(Base != nullptr && "unknown BDVState!");
1007       }
1008       assert(Base && "can't be null");
1009       BaseEE->setOperand(0, Base);
1010     }
1011   }
1012
1013   // Now that we're done with the algorithm, see if we can optimize the 
1014   // results slightly by reducing the number of new instructions needed. 
1015   // Arguably, this should be integrated into the algorithm above, but 
1016   // doing as a post process step is easier to reason about for the moment.
1017   DenseMap<Value *, Value *> ReverseMap;
1018   SmallPtrSet<Instruction *, 16> NewInsts;
1019   SmallSetVector<Instruction *, 16> Worklist;
1020   for (auto Item : states) {
1021     Value *V = Item.first;
1022     Value *Base = Item.second.getBase();
1023     assert(V && Base);
1024     assert(!isKnownBaseResult(V) && "why did it get added?");
1025     assert(isKnownBaseResult(Base) &&
1026            "must be something we 'know' is a base pointer");
1027     if (!Item.second.isConflict())
1028       continue;
1029
1030     ReverseMap[Base] = V;
1031     if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1032       NewInsts.insert(BaseI);
1033       Worklist.insert(BaseI);
1034     }
1035   }
1036   auto PushNewUsers = [&](Instruction *I) {
1037     for (User *U : I->users())
1038       if (auto *UI = dyn_cast<Instruction>(U))
1039         if (NewInsts.count(UI))
1040           Worklist.insert(UI);
1041   };
1042   const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1043   while (!Worklist.empty()) {
1044     Instruction *BaseI = Worklist.pop_back_val();
1045     Value *Bdv = ReverseMap[BaseI];
1046     if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1047       if (BaseI->isIdenticalTo(BdvI)) {
1048         DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
1049         PushNewUsers(BaseI);
1050         BaseI->replaceAllUsesWith(Bdv);
1051         BaseI->eraseFromParent();
1052         states[Bdv] = BDVState(BDVState::Conflict, Bdv);
1053         NewInsts.erase(BaseI);
1054         ReverseMap.erase(BaseI);
1055         continue;
1056       }
1057     if (Value *V = SimplifyInstruction(BaseI, DL)) {
1058       DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
1059       PushNewUsers(BaseI);
1060       BaseI->replaceAllUsesWith(V);
1061       BaseI->eraseFromParent();
1062       states[Bdv] = BDVState(BDVState::Conflict, V);
1063       NewInsts.erase(BaseI);
1064       ReverseMap.erase(BaseI);
1065       continue;
1066     }
1067   }
1068
1069   // Cache all of our results so we can cheaply reuse them
1070   // NOTE: This is actually two caches: one of the base defining value
1071   // relation and one of the base pointer relation!  FIXME
1072   for (auto item : states) {
1073     Value *v = item.first;
1074     Value *base = item.second.getBase();
1075     assert(v && base);
1076
1077     if (TraceLSP) {
1078       std::string fromstr =
1079           cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
1080                          : "none";
1081       errs() << "Updating base value cache"
1082              << " for: " << (v->hasName() ? v->getName() : "")
1083              << " from: " << fromstr
1084              << " to: " << (base->hasName() ? base->getName() : "") << "\n";
1085     }
1086
1087     if (cache.count(v)) {
1088       // Once we transition from the BDV relation being store in the cache to
1089       // the base relation being stored, it must be stable
1090       assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
1091              "base relation should be stable");
1092     }
1093     cache[v] = base;
1094   }
1095   assert(cache.find(def) != cache.end());
1096   return cache[def];
1097 }
1098
1099 // For a set of live pointers (base and/or derived), identify the base
1100 // pointer of the object which they are derived from.  This routine will
1101 // mutate the IR graph as needed to make the 'base' pointer live at the
1102 // definition site of 'derived'.  This ensures that any use of 'derived' can
1103 // also use 'base'.  This may involve the insertion of a number of
1104 // additional PHI nodes.
1105 //
1106 // preconditions: live is a set of pointer type Values
1107 //
1108 // side effects: may insert PHI nodes into the existing CFG, will preserve
1109 // CFG, will not remove or mutate any existing nodes
1110 //
1111 // post condition: PointerToBase contains one (derived, base) pair for every
1112 // pointer in live.  Note that derived can be equal to base if the original
1113 // pointer was a base pointer.
1114 static void
1115 findBasePointers(const StatepointLiveSetTy &live,
1116                  DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
1117                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
1118   // For the naming of values inserted to be deterministic - which makes for
1119   // much cleaner and more stable tests - we need to assign an order to the
1120   // live values.  DenseSets do not provide a deterministic order across runs.
1121   SmallVector<Value *, 64> Temp;
1122   Temp.insert(Temp.end(), live.begin(), live.end());
1123   std::sort(Temp.begin(), Temp.end(), order_by_name);
1124   for (Value *ptr : Temp) {
1125     Value *base = findBasePointer(ptr, DVCache);
1126     assert(base && "failed to find base pointer");
1127     PointerToBase[ptr] = base;
1128     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1129             DT->dominates(cast<Instruction>(base)->getParent(),
1130                           cast<Instruction>(ptr)->getParent())) &&
1131            "The base we found better dominate the derived pointer");
1132
1133     // If you see this trip and like to live really dangerously, the code should
1134     // be correct, just with idioms the verifier can't handle.  You can try
1135     // disabling the verifier at your own substantial risk.
1136     assert(!isa<ConstantPointerNull>(base) &&
1137            "the relocation code needs adjustment to handle the relocation of "
1138            "a null pointer constant without causing false positives in the "
1139            "safepoint ir verifier.");
1140   }
1141 }
1142
1143 /// Find the required based pointers (and adjust the live set) for the given
1144 /// parse point.
1145 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1146                              const CallSite &CS,
1147                              PartiallyConstructedSafepointRecord &result) {
1148   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1149   findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
1150
1151   if (PrintBasePointers) {
1152     // Note: Need to print these in a stable order since this is checked in
1153     // some tests.
1154     errs() << "Base Pairs (w/o Relocation):\n";
1155     SmallVector<Value *, 64> Temp;
1156     Temp.reserve(PointerToBase.size());
1157     for (auto Pair : PointerToBase) {
1158       Temp.push_back(Pair.first);
1159     }
1160     std::sort(Temp.begin(), Temp.end(), order_by_name);
1161     for (Value *Ptr : Temp) {
1162       Value *Base = PointerToBase[Ptr];
1163       errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1164              << "\n";
1165     }
1166   }
1167
1168   result.PointerToBase = PointerToBase;
1169 }
1170
1171 /// Given an updated version of the dataflow liveness results, update the
1172 /// liveset and base pointer maps for the call site CS.
1173 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1174                                   const CallSite &CS,
1175                                   PartiallyConstructedSafepointRecord &result);
1176
1177 static void recomputeLiveInValues(
1178     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1179     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1180   // TODO-PERF: reuse the original liveness, then simply run the dataflow
1181   // again.  The old values are still live and will help it stabilize quickly.
1182   GCPtrLivenessData RevisedLivenessData;
1183   computeLiveInValues(DT, F, RevisedLivenessData);
1184   for (size_t i = 0; i < records.size(); i++) {
1185     struct PartiallyConstructedSafepointRecord &info = records[i];
1186     const CallSite &CS = toUpdate[i];
1187     recomputeLiveInValues(RevisedLivenessData, CS, info);
1188   }
1189 }
1190
1191 // When inserting gc.relocate calls, we need to ensure there are no uses
1192 // of the original value between the gc.statepoint and the gc.relocate call.
1193 // One case which can arise is a phi node starting one of the successor blocks.
1194 // We also need to be able to insert the gc.relocates only on the path which
1195 // goes through the statepoint.  We might need to split an edge to make this
1196 // possible.
1197 static BasicBlock *
1198 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1199                             DominatorTree &DT) {
1200   BasicBlock *Ret = BB;
1201   if (!BB->getUniquePredecessor()) {
1202     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1203   }
1204
1205   // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1206   // from it
1207   FoldSingleEntryPHINodes(Ret);
1208   assert(!isa<PHINode>(Ret->begin()));
1209
1210   // At this point, we can safely insert a gc.relocate as the first instruction
1211   // in Ret if needed.
1212   return Ret;
1213 }
1214
1215 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1216   auto itr = std::find(livevec.begin(), livevec.end(), val);
1217   assert(livevec.end() != itr);
1218   size_t index = std::distance(livevec.begin(), itr);
1219   assert(index < livevec.size());
1220   return index;
1221 }
1222
1223 // Create new attribute set containing only attributes which can be transferred
1224 // from original call to the safepoint.
1225 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1226   AttributeSet ret;
1227
1228   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1229     unsigned index = AS.getSlotIndex(Slot);
1230
1231     if (index == AttributeSet::ReturnIndex ||
1232         index == AttributeSet::FunctionIndex) {
1233
1234       for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1235            ++it) {
1236         Attribute attr = *it;
1237
1238         // Do not allow certain attributes - just skip them
1239         // Safepoint can not be read only or read none.
1240         if (attr.hasAttribute(Attribute::ReadNone) ||
1241             attr.hasAttribute(Attribute::ReadOnly))
1242           continue;
1243
1244         ret = ret.addAttributes(
1245             AS.getContext(), index,
1246             AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1247       }
1248     }
1249
1250     // Just skip parameter attributes for now
1251   }
1252
1253   return ret;
1254 }
1255
1256 /// Helper function to place all gc relocates necessary for the given
1257 /// statepoint.
1258 /// Inputs:
1259 ///   liveVariables - list of variables to be relocated.
1260 ///   liveStart - index of the first live variable.
1261 ///   basePtrs - base pointers.
1262 ///   statepointToken - statepoint instruction to which relocates should be
1263 ///   bound.
1264 ///   Builder - Llvm IR builder to be used to construct new calls.
1265 static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1266                               const int LiveStart,
1267                               ArrayRef<llvm::Value *> BasePtrs,
1268                               Instruction *StatepointToken,
1269                               IRBuilder<> Builder) {
1270   if (LiveVariables.empty())
1271     return;
1272   
1273   // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1274   // unique declarations for each pointer type, but this proved problematic
1275   // because the intrinsic mangling code is incomplete and fragile.  Since
1276   // we're moving towards a single unified pointer type anyways, we can just
1277   // cast everything to an i8* of the right address space.  A bitcast is added
1278   // later to convert gc_relocate to the actual value's type. 
1279   Module *M = StatepointToken->getModule();
1280   auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1281   Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1282   Value *GCRelocateDecl =
1283     Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
1284
1285   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1286     // Generate the gc.relocate call and save the result
1287     Value *BaseIdx =
1288       Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1289     Value *LiveIdx =
1290       Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
1291
1292     // only specify a debug name if we can give a useful one
1293     CallInst *Reloc = Builder.CreateCall(
1294         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1295         LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
1296                                     : "");
1297     // Trick CodeGen into thinking there are lots of free registers at this
1298     // fake call.
1299     Reloc->setCallingConv(CallingConv::Cold);
1300   }
1301 }
1302
1303 static void
1304 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1305                            const SmallVectorImpl<llvm::Value *> &basePtrs,
1306                            const SmallVectorImpl<llvm::Value *> &liveVariables,
1307                            Pass *P,
1308                            PartiallyConstructedSafepointRecord &result) {
1309   assert(basePtrs.size() == liveVariables.size());
1310   assert(isStatepoint(CS) &&
1311          "This method expects to be rewriting a statepoint");
1312
1313   BasicBlock *BB = CS.getInstruction()->getParent();
1314   assert(BB);
1315   Function *F = BB->getParent();
1316   assert(F && "must be set");
1317   Module *M = F->getParent();
1318   (void)M;
1319   assert(M && "must be set");
1320
1321   // We're not changing the function signature of the statepoint since the gc
1322   // arguments go into the var args section.
1323   Function *gc_statepoint_decl = CS.getCalledFunction();
1324
1325   // Then go ahead and use the builder do actually do the inserts.  We insert
1326   // immediately before the previous instruction under the assumption that all
1327   // arguments will be available here.  We can't insert afterwards since we may
1328   // be replacing a terminator.
1329   Instruction *insertBefore = CS.getInstruction();
1330   IRBuilder<> Builder(insertBefore);
1331   // Copy all of the arguments from the original statepoint - this includes the
1332   // target, call args, and deopt args
1333   SmallVector<llvm::Value *, 64> args;
1334   args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1335   // TODO: Clear the 'needs rewrite' flag
1336
1337   // add all the pointers to be relocated (gc arguments)
1338   // Capture the start of the live variable list for use in the gc_relocates
1339   const int live_start = args.size();
1340   args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1341
1342   // Create the statepoint given all the arguments
1343   Instruction *token = nullptr;
1344   AttributeSet return_attributes;
1345   if (CS.isCall()) {
1346     CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1347     CallInst *call =
1348         Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1349     call->setTailCall(toReplace->isTailCall());
1350     call->setCallingConv(toReplace->getCallingConv());
1351
1352     // Currently we will fail on parameter attributes and on certain
1353     // function attributes.
1354     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1355     // In case if we can handle this set of attributes - set up function attrs
1356     // directly on statepoint and return attrs later for gc_result intrinsic.
1357     call->setAttributes(new_attrs.getFnAttributes());
1358     return_attributes = new_attrs.getRetAttributes();
1359
1360     token = call;
1361
1362     // Put the following gc_result and gc_relocate calls immediately after the
1363     // the old call (which we're about to delete)
1364     BasicBlock::iterator next(toReplace);
1365     assert(BB->end() != next && "not a terminator, must have next");
1366     next++;
1367     Instruction *IP = &*(next);
1368     Builder.SetInsertPoint(IP);
1369     Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1370
1371   } else {
1372     InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1373
1374     // Insert the new invoke into the old block.  We'll remove the old one in a
1375     // moment at which point this will become the new terminator for the
1376     // original block.
1377     InvokeInst *invoke = InvokeInst::Create(
1378         gc_statepoint_decl, toReplace->getNormalDest(),
1379         toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
1380     invoke->setCallingConv(toReplace->getCallingConv());
1381
1382     // Currently we will fail on parameter attributes and on certain
1383     // function attributes.
1384     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1385     // In case if we can handle this set of attributes - set up function attrs
1386     // directly on statepoint and return attrs later for gc_result intrinsic.
1387     invoke->setAttributes(new_attrs.getFnAttributes());
1388     return_attributes = new_attrs.getRetAttributes();
1389
1390     token = invoke;
1391
1392     // Generate gc relocates in exceptional path
1393     BasicBlock *unwindBlock = toReplace->getUnwindDest();
1394     assert(!isa<PHINode>(unwindBlock->begin()) &&
1395            unwindBlock->getUniquePredecessor() &&
1396            "can't safely insert in this block!");
1397
1398     Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1399     Builder.SetInsertPoint(IP);
1400     Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1401
1402     // Extract second element from landingpad return value. We will attach
1403     // exceptional gc relocates to it.
1404     const unsigned idx = 1;
1405     Instruction *exceptional_token =
1406         cast<Instruction>(Builder.CreateExtractValue(
1407             unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1408     result.UnwindToken = exceptional_token;
1409
1410     CreateGCRelocates(liveVariables, live_start, basePtrs,
1411                       exceptional_token, Builder);
1412
1413     // Generate gc relocates and returns for normal block
1414     BasicBlock *normalDest = toReplace->getNormalDest();
1415     assert(!isa<PHINode>(normalDest->begin()) &&
1416            normalDest->getUniquePredecessor() &&
1417            "can't safely insert in this block!");
1418
1419     IP = &*(normalDest->getFirstInsertionPt());
1420     Builder.SetInsertPoint(IP);
1421
1422     // gc relocates will be generated later as if it were regular call
1423     // statepoint
1424   }
1425   assert(token);
1426
1427   // Take the name of the original value call if it had one.
1428   token->takeName(CS.getInstruction());
1429
1430 // The GCResult is already inserted, we just need to find it
1431 #ifndef NDEBUG
1432   Instruction *toReplace = CS.getInstruction();
1433   assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1434          "only valid use before rewrite is gc.result");
1435   assert(!toReplace->hasOneUse() ||
1436          isGCResult(cast<Instruction>(*toReplace->user_begin())));
1437 #endif
1438
1439   // Update the gc.result of the original statepoint (if any) to use the newly
1440   // inserted statepoint.  This is safe to do here since the token can't be
1441   // considered a live reference.
1442   CS.getInstruction()->replaceAllUsesWith(token);
1443
1444   result.StatepointToken = token;
1445
1446   // Second, create a gc.relocate for every live variable
1447   CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1448 }
1449
1450 namespace {
1451 struct name_ordering {
1452   Value *base;
1453   Value *derived;
1454   bool operator()(name_ordering const &a, name_ordering const &b) {
1455     return -1 == a.derived->getName().compare(b.derived->getName());
1456   }
1457 };
1458 }
1459 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1460                            SmallVectorImpl<Value *> &livevec) {
1461   assert(basevec.size() == livevec.size());
1462
1463   SmallVector<name_ordering, 64> temp;
1464   for (size_t i = 0; i < basevec.size(); i++) {
1465     name_ordering v;
1466     v.base = basevec[i];
1467     v.derived = livevec[i];
1468     temp.push_back(v);
1469   }
1470   std::sort(temp.begin(), temp.end(), name_ordering());
1471   for (size_t i = 0; i < basevec.size(); i++) {
1472     basevec[i] = temp[i].base;
1473     livevec[i] = temp[i].derived;
1474   }
1475 }
1476
1477 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1478 // which make the relocations happening at this safepoint explicit.
1479 //
1480 // WARNING: Does not do any fixup to adjust users of the original live
1481 // values.  That's the callers responsibility.
1482 static void
1483 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1484                        PartiallyConstructedSafepointRecord &result) {
1485   auto liveset = result.liveset;
1486   auto PointerToBase = result.PointerToBase;
1487
1488   // Convert to vector for efficient cross referencing.
1489   SmallVector<Value *, 64> basevec, livevec;
1490   livevec.reserve(liveset.size());
1491   basevec.reserve(liveset.size());
1492   for (Value *L : liveset) {
1493     livevec.push_back(L);
1494     assert(PointerToBase.count(L));
1495     Value *base = PointerToBase[L];
1496     basevec.push_back(base);
1497   }
1498   assert(livevec.size() == basevec.size());
1499
1500   // To make the output IR slightly more stable (for use in diffs), ensure a
1501   // fixed order of the values in the safepoint (by sorting the value name).
1502   // The order is otherwise meaningless.
1503   stablize_order(basevec, livevec);
1504
1505   // Do the actual rewriting and delete the old statepoint
1506   makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1507   CS.getInstruction()->eraseFromParent();
1508 }
1509
1510 // Helper function for the relocationViaAlloca.
1511 // It receives iterator to the statepoint gc relocates and emits store to the
1512 // assigned
1513 // location (via allocaMap) for the each one of them.
1514 // Add visited values into the visitedLiveValues set we will later use them
1515 // for sanity check.
1516 static void
1517 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1518                        DenseMap<Value *, Value *> &AllocaMap,
1519                        DenseSet<Value *> &VisitedLiveValues) {
1520
1521   for (User *U : GCRelocs) {
1522     if (!isa<IntrinsicInst>(U))
1523       continue;
1524
1525     IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
1526
1527     // We only care about relocates
1528     if (RelocatedValue->getIntrinsicID() !=
1529         Intrinsic::experimental_gc_relocate) {
1530       continue;
1531     }
1532
1533     GCRelocateOperands RelocateOperands(RelocatedValue);
1534     Value *OriginalValue =
1535         const_cast<Value *>(RelocateOperands.getDerivedPtr());
1536     assert(AllocaMap.count(OriginalValue));
1537     Value *Alloca = AllocaMap[OriginalValue];
1538
1539     // Emit store into the related alloca
1540     // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1541     // the correct type according to alloca.
1542     assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1543     IRBuilder<> Builder(RelocatedValue->getNextNode());
1544     Value *CastedRelocatedValue =
1545         Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1546         RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
1547
1548     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1549     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1550
1551 #ifndef NDEBUG
1552     VisitedLiveValues.insert(OriginalValue);
1553 #endif
1554   }
1555 }
1556
1557 // Helper function for the "relocationViaAlloca". Similar to the
1558 // "insertRelocationStores" but works for rematerialized values.
1559 static void
1560 insertRematerializationStores(
1561   RematerializedValueMapTy RematerializedValues,
1562   DenseMap<Value *, Value *> &AllocaMap,
1563   DenseSet<Value *> &VisitedLiveValues) {
1564
1565   for (auto RematerializedValuePair: RematerializedValues) {
1566     Instruction *RematerializedValue = RematerializedValuePair.first;
1567     Value *OriginalValue = RematerializedValuePair.second;
1568
1569     assert(AllocaMap.count(OriginalValue) &&
1570            "Can not find alloca for rematerialized value");
1571     Value *Alloca = AllocaMap[OriginalValue];
1572
1573     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1574     Store->insertAfter(RematerializedValue);
1575
1576 #ifndef NDEBUG
1577     VisitedLiveValues.insert(OriginalValue);
1578 #endif
1579   }
1580 }
1581
1582 /// do all the relocation update via allocas and mem2reg
1583 static void relocationViaAlloca(
1584     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1585     ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
1586 #ifndef NDEBUG
1587   // record initial number of (static) allocas; we'll check we have the same
1588   // number when we get done.
1589   int InitialAllocaNum = 0;
1590   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1591        I++)
1592     if (isa<AllocaInst>(*I))
1593       InitialAllocaNum++;
1594 #endif
1595
1596   // TODO-PERF: change data structures, reserve
1597   DenseMap<Value *, Value *> AllocaMap;
1598   SmallVector<AllocaInst *, 200> PromotableAllocas;
1599   // Used later to chack that we have enough allocas to store all values
1600   std::size_t NumRematerializedValues = 0;
1601   PromotableAllocas.reserve(Live.size());
1602
1603   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1604   // "PromotableAllocas"
1605   auto emitAllocaFor = [&](Value *LiveValue) {
1606     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1607                                         F.getEntryBlock().getFirstNonPHI());
1608     AllocaMap[LiveValue] = Alloca;
1609     PromotableAllocas.push_back(Alloca);
1610   };
1611
1612   // emit alloca for each live gc pointer
1613   for (unsigned i = 0; i < Live.size(); i++) {
1614     emitAllocaFor(Live[i]);
1615   }
1616
1617   // emit allocas for rematerialized values
1618   for (size_t i = 0; i < Records.size(); i++) {
1619     const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1620
1621     for (auto RematerializedValuePair : Info.RematerializedValues) {
1622       Value *OriginalValue = RematerializedValuePair.second;
1623       if (AllocaMap.count(OriginalValue) != 0)
1624         continue;
1625
1626       emitAllocaFor(OriginalValue);
1627       ++NumRematerializedValues;
1628     }
1629   }
1630
1631   // The next two loops are part of the same conceptual operation.  We need to
1632   // insert a store to the alloca after the original def and at each
1633   // redefinition.  We need to insert a load before each use.  These are split
1634   // into distinct loops for performance reasons.
1635
1636   // update gc pointer after each statepoint
1637   // either store a relocated value or null (if no relocated value found for
1638   // this gc pointer and it is not a gc_result)
1639   // this must happen before we update the statepoint with load of alloca
1640   // otherwise we lose the link between statepoint and old def
1641   for (size_t i = 0; i < Records.size(); i++) {
1642     const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1643     Value *Statepoint = Info.StatepointToken;
1644
1645     // This will be used for consistency check
1646     DenseSet<Value *> VisitedLiveValues;
1647
1648     // Insert stores for normal statepoint gc relocates
1649     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1650
1651     // In case if it was invoke statepoint
1652     // we will insert stores for exceptional path gc relocates.
1653     if (isa<InvokeInst>(Statepoint)) {
1654       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1655                              VisitedLiveValues);
1656     }
1657
1658     // Do similar thing with rematerialized values
1659     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1660                                   VisitedLiveValues);
1661
1662     if (ClobberNonLive) {
1663       // As a debugging aid, pretend that an unrelocated pointer becomes null at
1664       // the gc.statepoint.  This will turn some subtle GC problems into
1665       // slightly easier to debug SEGVs.  Note that on large IR files with
1666       // lots of gc.statepoints this is extremely costly both memory and time
1667       // wise.
1668       SmallVector<AllocaInst *, 64> ToClobber;
1669       for (auto Pair : AllocaMap) {
1670         Value *Def = Pair.first;
1671         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1672
1673         // This value was relocated
1674         if (VisitedLiveValues.count(Def)) {
1675           continue;
1676         }
1677         ToClobber.push_back(Alloca);
1678       }
1679
1680       auto InsertClobbersAt = [&](Instruction *IP) {
1681         for (auto *AI : ToClobber) {
1682           auto AIType = cast<PointerType>(AI->getType());
1683           auto PT = cast<PointerType>(AIType->getElementType());
1684           Constant *CPN = ConstantPointerNull::get(PT);
1685           StoreInst *Store = new StoreInst(CPN, AI);
1686           Store->insertBefore(IP);
1687         }
1688       };
1689
1690       // Insert the clobbering stores.  These may get intermixed with the
1691       // gc.results and gc.relocates, but that's fine.
1692       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1693         InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1694         InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1695       } else {
1696         BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1697         Next++;
1698         InsertClobbersAt(Next);
1699       }
1700     }
1701   }
1702   // update use with load allocas and add store for gc_relocated
1703   for (auto Pair : AllocaMap) {
1704     Value *Def = Pair.first;
1705     Value *Alloca = Pair.second;
1706
1707     // we pre-record the uses of allocas so that we dont have to worry about
1708     // later update
1709     // that change the user information.
1710     SmallVector<Instruction *, 20> Uses;
1711     // PERF: trade a linear scan for repeated reallocation
1712     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1713     for (User *U : Def->users()) {
1714       if (!isa<ConstantExpr>(U)) {
1715         // If the def has a ConstantExpr use, then the def is either a
1716         // ConstantExpr use itself or null.  In either case
1717         // (recursively in the first, directly in the second), the oop
1718         // it is ultimately dependent on is null and this particular
1719         // use does not need to be fixed up.
1720         Uses.push_back(cast<Instruction>(U));
1721       }
1722     }
1723
1724     std::sort(Uses.begin(), Uses.end());
1725     auto Last = std::unique(Uses.begin(), Uses.end());
1726     Uses.erase(Last, Uses.end());
1727
1728     for (Instruction *Use : Uses) {
1729       if (isa<PHINode>(Use)) {
1730         PHINode *Phi = cast<PHINode>(Use);
1731         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1732           if (Def == Phi->getIncomingValue(i)) {
1733             LoadInst *Load = new LoadInst(
1734                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1735             Phi->setIncomingValue(i, Load);
1736           }
1737         }
1738       } else {
1739         LoadInst *Load = new LoadInst(Alloca, "", Use);
1740         Use->replaceUsesOfWith(Def, Load);
1741       }
1742     }
1743
1744     // emit store for the initial gc value
1745     // store must be inserted after load, otherwise store will be in alloca's
1746     // use list and an extra load will be inserted before it
1747     StoreInst *Store = new StoreInst(Def, Alloca);
1748     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1749       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1750         // InvokeInst is a TerminatorInst so the store need to be inserted
1751         // into its normal destination block.
1752         BasicBlock *NormalDest = Invoke->getNormalDest();
1753         Store->insertBefore(NormalDest->getFirstNonPHI());
1754       } else {
1755         assert(!Inst->isTerminator() &&
1756                "The only TerminatorInst that can produce a value is "
1757                "InvokeInst which is handled above.");
1758         Store->insertAfter(Inst);
1759       }
1760     } else {
1761       assert(isa<Argument>(Def));
1762       Store->insertAfter(cast<Instruction>(Alloca));
1763     }
1764   }
1765
1766   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1767          "we must have the same allocas with lives");
1768   if (!PromotableAllocas.empty()) {
1769     // apply mem2reg to promote alloca to SSA
1770     PromoteMemToReg(PromotableAllocas, DT);
1771   }
1772
1773 #ifndef NDEBUG
1774   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1775        I++)
1776     if (isa<AllocaInst>(*I))
1777       InitialAllocaNum--;
1778   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1779 #endif
1780 }
1781
1782 /// Implement a unique function which doesn't require we sort the input
1783 /// vector.  Doing so has the effect of changing the output of a couple of
1784 /// tests in ways which make them less useful in testing fused safepoints.
1785 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1786   SmallSet<T, 8> Seen;
1787   Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1788               return !Seen.insert(V).second;
1789             }), Vec.end());
1790 }
1791
1792 /// Insert holders so that each Value is obviously live through the entire
1793 /// lifetime of the call.
1794 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1795                                  SmallVectorImpl<CallInst *> &Holders) {
1796   if (Values.empty())
1797     // No values to hold live, might as well not insert the empty holder
1798     return;
1799
1800   Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1801   // Use a dummy vararg function to actually hold the values live
1802   Function *Func = cast<Function>(M->getOrInsertFunction(
1803       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1804   if (CS.isCall()) {
1805     // For call safepoints insert dummy calls right after safepoint
1806     BasicBlock::iterator Next(CS.getInstruction());
1807     Next++;
1808     Holders.push_back(CallInst::Create(Func, Values, "", Next));
1809     return;
1810   }
1811   // For invoke safepooints insert dummy calls both in normal and
1812   // exceptional destination blocks
1813   auto *II = cast<InvokeInst>(CS.getInstruction());
1814   Holders.push_back(CallInst::Create(
1815       Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1816   Holders.push_back(CallInst::Create(
1817       Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
1818 }
1819
1820 static void findLiveReferences(
1821     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1822     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1823   GCPtrLivenessData OriginalLivenessData;
1824   computeLiveInValues(DT, F, OriginalLivenessData);
1825   for (size_t i = 0; i < records.size(); i++) {
1826     struct PartiallyConstructedSafepointRecord &info = records[i];
1827     const CallSite &CS = toUpdate[i];
1828     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1829   }
1830 }
1831
1832 /// Remove any vector of pointers from the liveset by scalarizing them over the
1833 /// statepoint instruction.  Adds the scalarized pieces to the liveset.  It
1834 /// would be preferable to include the vector in the statepoint itself, but
1835 /// the lowering code currently does not handle that.  Extending it would be
1836 /// slightly non-trivial since it requires a format change.  Given how rare
1837 /// such cases are (for the moment?) scalarizing is an acceptable compromise.
1838 static void splitVectorValues(Instruction *StatepointInst,
1839                               StatepointLiveSetTy &LiveSet,
1840                               DenseMap<Value *, Value *>& PointerToBase,
1841                               DominatorTree &DT) {
1842   SmallVector<Value *, 16> ToSplit;
1843   for (Value *V : LiveSet)
1844     if (isa<VectorType>(V->getType()))
1845       ToSplit.push_back(V);
1846
1847   if (ToSplit.empty())
1848     return;
1849
1850   DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1851
1852   Function &F = *(StatepointInst->getParent()->getParent());
1853
1854   DenseMap<Value *, AllocaInst *> AllocaMap;
1855   // First is normal return, second is exceptional return (invoke only)
1856   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1857   for (Value *V : ToSplit) {
1858     AllocaInst *Alloca =
1859         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1860     AllocaMap[V] = Alloca;
1861
1862     VectorType *VT = cast<VectorType>(V->getType());
1863     IRBuilder<> Builder(StatepointInst);
1864     SmallVector<Value *, 16> Elements;
1865     for (unsigned i = 0; i < VT->getNumElements(); i++)
1866       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1867     ElementMapping[V] = Elements;
1868
1869     auto InsertVectorReform = [&](Instruction *IP) {
1870       Builder.SetInsertPoint(IP);
1871       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1872       Value *ResultVec = UndefValue::get(VT);
1873       for (unsigned i = 0; i < VT->getNumElements(); i++)
1874         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1875                                                 Builder.getInt32(i));
1876       return ResultVec;
1877     };
1878
1879     if (isa<CallInst>(StatepointInst)) {
1880       BasicBlock::iterator Next(StatepointInst);
1881       Next++;
1882       Instruction *IP = &*(Next);
1883       Replacements[V].first = InsertVectorReform(IP);
1884       Replacements[V].second = nullptr;
1885     } else {
1886       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1887       // We've already normalized - check that we don't have shared destination
1888       // blocks
1889       BasicBlock *NormalDest = Invoke->getNormalDest();
1890       assert(!isa<PHINode>(NormalDest->begin()));
1891       BasicBlock *UnwindDest = Invoke->getUnwindDest();
1892       assert(!isa<PHINode>(UnwindDest->begin()));
1893       // Insert insert element sequences in both successors
1894       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1895       Replacements[V].first = InsertVectorReform(IP);
1896       IP = &*(UnwindDest->getFirstInsertionPt());
1897       Replacements[V].second = InsertVectorReform(IP);
1898     }
1899   }
1900
1901   for (Value *V : ToSplit) {
1902     AllocaInst *Alloca = AllocaMap[V];
1903
1904     // Capture all users before we start mutating use lists
1905     SmallVector<Instruction *, 16> Users;
1906     for (User *U : V->users())
1907       Users.push_back(cast<Instruction>(U));
1908
1909     for (Instruction *I : Users) {
1910       if (auto Phi = dyn_cast<PHINode>(I)) {
1911         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1912           if (V == Phi->getIncomingValue(i)) {
1913             LoadInst *Load = new LoadInst(
1914                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1915             Phi->setIncomingValue(i, Load);
1916           }
1917       } else {
1918         LoadInst *Load = new LoadInst(Alloca, "", I);
1919         I->replaceUsesOfWith(V, Load);
1920       }
1921     }
1922
1923     // Store the original value and the replacement value into the alloca
1924     StoreInst *Store = new StoreInst(V, Alloca);
1925     if (auto I = dyn_cast<Instruction>(V))
1926       Store->insertAfter(I);
1927     else
1928       Store->insertAfter(Alloca);
1929
1930     // Normal return for invoke, or call return
1931     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1932     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1933     // Unwind return for invoke only
1934     Replacement = cast_or_null<Instruction>(Replacements[V].second);
1935     if (Replacement)
1936       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1937   }
1938
1939   // apply mem2reg to promote alloca to SSA
1940   SmallVector<AllocaInst *, 16> Allocas;
1941   for (Value *V : ToSplit)
1942     Allocas.push_back(AllocaMap[V]);
1943   PromoteMemToReg(Allocas, DT);
1944
1945   // Update our tracking of live pointers and base mappings to account for the
1946   // changes we just made.
1947   for (Value *V : ToSplit) {
1948     auto &Elements = ElementMapping[V];
1949
1950     LiveSet.erase(V);
1951     LiveSet.insert(Elements.begin(), Elements.end());
1952     // We need to update the base mapping as well.
1953     assert(PointerToBase.count(V));
1954     Value *OldBase = PointerToBase[V];
1955     auto &BaseElements = ElementMapping[OldBase];
1956     PointerToBase.erase(V);
1957     assert(Elements.size() == BaseElements.size());
1958     for (unsigned i = 0; i < Elements.size(); i++) {
1959       Value *Elem = Elements[i];
1960       PointerToBase[Elem] = BaseElements[i];
1961     }
1962   }
1963 }
1964
1965 // Helper function for the "rematerializeLiveValues". It walks use chain
1966 // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1967 // values are visited (currently it is GEP's and casts). Returns true if it
1968 // successfully reached "BaseValue" and false otherwise.
1969 // Fills "ChainToBase" array with all visited values. "BaseValue" is not
1970 // recorded.
1971 static bool findRematerializableChainToBasePointer(
1972   SmallVectorImpl<Instruction*> &ChainToBase,
1973   Value *CurrentValue, Value *BaseValue) {
1974
1975   // We have found a base value
1976   if (CurrentValue == BaseValue) {
1977     return true;
1978   }
1979
1980   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1981     ChainToBase.push_back(GEP);
1982     return findRematerializableChainToBasePointer(ChainToBase,
1983                                                   GEP->getPointerOperand(),
1984                                                   BaseValue);
1985   }
1986
1987   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1988     Value *Def = CI->stripPointerCasts();
1989
1990     // This two checks are basically similar. First one is here for the
1991     // consistency with findBasePointers logic.
1992     assert(!isa<CastInst>(Def) && "not a pointer cast found");
1993     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1994       return false;
1995
1996     ChainToBase.push_back(CI);
1997     return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1998   }
1999
2000   // Not supported instruction in the chain
2001   return false;
2002 }
2003
2004 // Helper function for the "rematerializeLiveValues". Compute cost of the use
2005 // chain we are going to rematerialize.
2006 static unsigned
2007 chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2008                        TargetTransformInfo &TTI) {
2009   unsigned Cost = 0;
2010
2011   for (Instruction *Instr : Chain) {
2012     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2013       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2014              "non noop cast is found during rematerialization");
2015
2016       Type *SrcTy = CI->getOperand(0)->getType();
2017       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2018
2019     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2020       // Cost of the address calculation
2021       Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2022       Cost += TTI.getAddressComputationCost(ValTy);
2023
2024       // And cost of the GEP itself
2025       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2026       //       allowed for the external usage)
2027       if (!GEP->hasAllConstantIndices())
2028         Cost += 2;
2029
2030     } else {
2031       llvm_unreachable("unsupported instruciton type during rematerialization");
2032     }
2033   }
2034
2035   return Cost;
2036 }
2037
2038 // From the statepoint liveset pick values that are cheaper to recompute then to
2039 // relocate. Remove this values from the liveset, rematerialize them after
2040 // statepoint and record them in "Info" structure. Note that similar to
2041 // relocated values we don't do any user adjustments here.
2042 static void rematerializeLiveValues(CallSite CS,
2043                                     PartiallyConstructedSafepointRecord &Info,
2044                                     TargetTransformInfo &TTI) {
2045   const unsigned int ChainLengthThreshold = 10;
2046
2047   // Record values we are going to delete from this statepoint live set.
2048   // We can not di this in following loop due to iterator invalidation.
2049   SmallVector<Value *, 32> LiveValuesToBeDeleted;
2050
2051   for (Value *LiveValue: Info.liveset) {
2052     // For each live pointer find it's defining chain
2053     SmallVector<Instruction *, 3> ChainToBase;
2054     assert(Info.PointerToBase.count(LiveValue));
2055     bool FoundChain =
2056       findRematerializableChainToBasePointer(ChainToBase,
2057                                              LiveValue,
2058                                              Info.PointerToBase[LiveValue]);
2059     // Nothing to do, or chain is too long
2060     if (!FoundChain ||
2061         ChainToBase.size() == 0 ||
2062         ChainToBase.size() > ChainLengthThreshold)
2063       continue;
2064
2065     // Compute cost of this chain
2066     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2067     // TODO: We can also account for cases when we will be able to remove some
2068     //       of the rematerialized values by later optimization passes. I.e if
2069     //       we rematerialized several intersecting chains. Or if original values
2070     //       don't have any uses besides this statepoint.
2071
2072     // For invokes we need to rematerialize each chain twice - for normal and
2073     // for unwind basic blocks. Model this by multiplying cost by two.
2074     if (CS.isInvoke()) {
2075       Cost *= 2;
2076     }
2077     // If it's too expensive - skip it
2078     if (Cost >= RematerializationThreshold)
2079       continue;
2080
2081     // Remove value from the live set
2082     LiveValuesToBeDeleted.push_back(LiveValue);
2083
2084     // Clone instructions and record them inside "Info" structure
2085
2086     // Walk backwards to visit top-most instructions first
2087     std::reverse(ChainToBase.begin(), ChainToBase.end());
2088
2089     // Utility function which clones all instructions from "ChainToBase"
2090     // and inserts them before "InsertBefore". Returns rematerialized value
2091     // which should be used after statepoint.
2092     auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2093       Instruction *LastClonedValue = nullptr;
2094       Instruction *LastValue = nullptr;
2095       for (Instruction *Instr: ChainToBase) {
2096         // Only GEP's and casts are suported as we need to be careful to not
2097         // introduce any new uses of pointers not in the liveset.
2098         // Note that it's fine to introduce new uses of pointers which were
2099         // otherwise not used after this statepoint.
2100         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2101
2102         Instruction *ClonedValue = Instr->clone();
2103         ClonedValue->insertBefore(InsertBefore);
2104         ClonedValue->setName(Instr->getName() + ".remat");
2105
2106         // If it is not first instruction in the chain then it uses previously
2107         // cloned value. We should update it to use cloned value.
2108         if (LastClonedValue) {
2109           assert(LastValue);
2110           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2111 #ifndef NDEBUG
2112           // Assert that cloned instruction does not use any instructions from
2113           // this chain other than LastClonedValue
2114           for (auto OpValue : ClonedValue->operand_values()) {
2115             assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2116                        ChainToBase.end() &&
2117                    "incorrect use in rematerialization chain");
2118           }
2119 #endif
2120         }
2121
2122         LastClonedValue = ClonedValue;
2123         LastValue = Instr;
2124       }
2125       assert(LastClonedValue);
2126       return LastClonedValue;
2127     };
2128
2129     // Different cases for calls and invokes. For invokes we need to clone
2130     // instructions both on normal and unwind path.
2131     if (CS.isCall()) {
2132       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2133       assert(InsertBefore);
2134       Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2135       Info.RematerializedValues[RematerializedValue] = LiveValue;
2136     } else {
2137       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2138
2139       Instruction *NormalInsertBefore =
2140           Invoke->getNormalDest()->getFirstInsertionPt();
2141       Instruction *UnwindInsertBefore =
2142           Invoke->getUnwindDest()->getFirstInsertionPt();
2143
2144       Instruction *NormalRematerializedValue =
2145           rematerializeChain(NormalInsertBefore);
2146       Instruction *UnwindRematerializedValue =
2147           rematerializeChain(UnwindInsertBefore);
2148
2149       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2150       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2151     }
2152   }
2153
2154   // Remove rematerializaed values from the live set
2155   for (auto LiveValue: LiveValuesToBeDeleted) {
2156     Info.liveset.erase(LiveValue);
2157   }
2158 }
2159
2160 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
2161                               SmallVectorImpl<CallSite> &toUpdate) {
2162 #ifndef NDEBUG
2163   // sanity check the input
2164   std::set<CallSite> uniqued;
2165   uniqued.insert(toUpdate.begin(), toUpdate.end());
2166   assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2167
2168   for (size_t i = 0; i < toUpdate.size(); i++) {
2169     CallSite &CS = toUpdate[i];
2170     assert(CS.getInstruction()->getParent()->getParent() == &F);
2171     assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2172   }
2173 #endif
2174
2175   // When inserting gc.relocates for invokes, we need to be able to insert at
2176   // the top of the successor blocks.  See the comment on
2177   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2178   // may restructure the CFG.
2179   for (CallSite CS : toUpdate) {
2180     if (!CS.isInvoke())
2181       continue;
2182     InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2183     normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
2184                                 DT);
2185     normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
2186                                 DT);
2187   }
2188
2189   // A list of dummy calls added to the IR to keep various values obviously
2190   // live in the IR.  We'll remove all of these when done.
2191   SmallVector<CallInst *, 64> holders;
2192
2193   // Insert a dummy call with all of the arguments to the vm_state we'll need
2194   // for the actual safepoint insertion.  This ensures reference arguments in
2195   // the deopt argument list are considered live through the safepoint (and
2196   // thus makes sure they get relocated.)
2197   for (size_t i = 0; i < toUpdate.size(); i++) {
2198     CallSite &CS = toUpdate[i];
2199     Statepoint StatepointCS(CS);
2200
2201     SmallVector<Value *, 64> DeoptValues;
2202     for (Use &U : StatepointCS.vm_state_args()) {
2203       Value *Arg = cast<Value>(&U);
2204       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2205              "support for FCA unimplemented");
2206       if (isHandledGCPointerType(Arg->getType()))
2207         DeoptValues.push_back(Arg);
2208     }
2209     insertUseHolderAfter(CS, DeoptValues, holders);
2210   }
2211
2212   SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
2213   records.reserve(toUpdate.size());
2214   for (size_t i = 0; i < toUpdate.size(); i++) {
2215     struct PartiallyConstructedSafepointRecord info;
2216     records.push_back(info);
2217   }
2218   assert(records.size() == toUpdate.size());
2219
2220   // A) Identify all gc pointers which are statically live at the given call
2221   // site.
2222   findLiveReferences(F, DT, P, toUpdate, records);
2223
2224   // B) Find the base pointers for each live pointer
2225   /* scope for caching */ {
2226     // Cache the 'defining value' relation used in the computation and
2227     // insertion of base phis and selects.  This ensures that we don't insert
2228     // large numbers of duplicate base_phis.
2229     DefiningValueMapTy DVCache;
2230
2231     for (size_t i = 0; i < records.size(); i++) {
2232       struct PartiallyConstructedSafepointRecord &info = records[i];
2233       CallSite &CS = toUpdate[i];
2234       findBasePointers(DT, DVCache, CS, info);
2235     }
2236   } // end of cache scope
2237
2238   // The base phi insertion logic (for any safepoint) may have inserted new
2239   // instructions which are now live at some safepoint.  The simplest such
2240   // example is:
2241   // loop:
2242   //   phi a  <-- will be a new base_phi here
2243   //   safepoint 1 <-- that needs to be live here
2244   //   gep a + 1
2245   //   safepoint 2
2246   //   br loop
2247   // We insert some dummy calls after each safepoint to definitely hold live
2248   // the base pointers which were identified for that safepoint.  We'll then
2249   // ask liveness for _every_ base inserted to see what is now live.  Then we
2250   // remove the dummy calls.
2251   holders.reserve(holders.size() + records.size());
2252   for (size_t i = 0; i < records.size(); i++) {
2253     struct PartiallyConstructedSafepointRecord &info = records[i];
2254     CallSite &CS = toUpdate[i];
2255
2256     SmallVector<Value *, 128> Bases;
2257     for (auto Pair : info.PointerToBase) {
2258       Bases.push_back(Pair.second);
2259     }
2260     insertUseHolderAfter(CS, Bases, holders);
2261   }
2262
2263   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2264   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2265   // not the key issue.
2266   recomputeLiveInValues(F, DT, P, toUpdate, records);
2267
2268   if (PrintBasePointers) {
2269     for (size_t i = 0; i < records.size(); i++) {
2270       struct PartiallyConstructedSafepointRecord &info = records[i];
2271       errs() << "Base Pairs: (w/Relocation)\n";
2272       for (auto Pair : info.PointerToBase) {
2273         errs() << " derived %" << Pair.first->getName() << " base %"
2274                << Pair.second->getName() << "\n";
2275       }
2276     }
2277   }
2278   for (size_t i = 0; i < holders.size(); i++) {
2279     holders[i]->eraseFromParent();
2280     holders[i] = nullptr;
2281   }
2282   holders.clear();
2283
2284   // Do a limited scalarization of any live at safepoint vector values which
2285   // contain pointers.  This enables this pass to run after vectorization at
2286   // the cost of some possible performance loss.  TODO: it would be nice to
2287   // natively support vectors all the way through the backend so we don't need
2288   // to scalarize here.
2289   for (size_t i = 0; i < records.size(); i++) {
2290     struct PartiallyConstructedSafepointRecord &info = records[i];
2291     Instruction *statepoint = toUpdate[i].getInstruction();
2292     splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2293                       info.PointerToBase, DT);
2294   }
2295
2296   // In order to reduce live set of statepoint we might choose to rematerialize
2297   // some values instead of relocating them. This is purely an optimization and
2298   // does not influence correctness.
2299   TargetTransformInfo &TTI =
2300     P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2301
2302   for (size_t i = 0; i < records.size(); i++) {
2303     struct PartiallyConstructedSafepointRecord &info = records[i];
2304     CallSite &CS = toUpdate[i];
2305
2306     rematerializeLiveValues(CS, info, TTI);
2307   }
2308
2309   // Now run through and replace the existing statepoints with new ones with
2310   // the live variables listed.  We do not yet update uses of the values being
2311   // relocated. We have references to live variables that need to
2312   // survive to the last iteration of this loop.  (By construction, the
2313   // previous statepoint can not be a live variable, thus we can and remove
2314   // the old statepoint calls as we go.)
2315   for (size_t i = 0; i < records.size(); i++) {
2316     struct PartiallyConstructedSafepointRecord &info = records[i];
2317     CallSite &CS = toUpdate[i];
2318     makeStatepointExplicit(DT, CS, P, info);
2319   }
2320   toUpdate.clear(); // prevent accident use of invalid CallSites
2321
2322   // Do all the fixups of the original live variables to their relocated selves
2323   SmallVector<Value *, 128> live;
2324   for (size_t i = 0; i < records.size(); i++) {
2325     struct PartiallyConstructedSafepointRecord &info = records[i];
2326     // We can't simply save the live set from the original insertion.  One of
2327     // the live values might be the result of a call which needs a safepoint.
2328     // That Value* no longer exists and we need to use the new gc_result.
2329     // Thankfully, the liveset is embedded in the statepoint (and updated), so
2330     // we just grab that.
2331     Statepoint statepoint(info.StatepointToken);
2332     live.insert(live.end(), statepoint.gc_args_begin(),
2333                 statepoint.gc_args_end());
2334 #ifndef NDEBUG
2335     // Do some basic sanity checks on our liveness results before performing
2336     // relocation.  Relocation can and will turn mistakes in liveness results
2337     // into non-sensical code which is must harder to debug.
2338     // TODO: It would be nice to test consistency as well
2339     assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2340            "statepoint must be reachable or liveness is meaningless");
2341     for (Value *V : statepoint.gc_args()) {
2342       if (!isa<Instruction>(V))
2343         // Non-instruction values trivial dominate all possible uses
2344         continue;
2345       auto LiveInst = cast<Instruction>(V);
2346       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2347              "unreachable values should never be live");
2348       assert(DT.dominates(LiveInst, info.StatepointToken) &&
2349              "basic SSA liveness expectation violated by liveness analysis");
2350     }
2351 #endif
2352   }
2353   unique_unsorted(live);
2354
2355 #ifndef NDEBUG
2356   // sanity check
2357   for (auto ptr : live) {
2358     assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2359   }
2360 #endif
2361
2362   relocationViaAlloca(F, DT, live, records);
2363   return !records.empty();
2364 }
2365
2366 // Handles both return values and arguments for Functions and CallSites.
2367 template <typename AttrHolder>
2368 static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2369                                    unsigned Index) {
2370   AttrBuilder R;
2371   if (AH.getDereferenceableBytes(Index))
2372     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2373                                   AH.getDereferenceableBytes(Index)));
2374   if (AH.getDereferenceableOrNullBytes(Index))
2375     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2376                                   AH.getDereferenceableOrNullBytes(Index)));
2377
2378   if (!R.empty())
2379     AH.setAttributes(AH.getAttributes().removeAttributes(
2380         Ctx, Index, AttributeSet::get(Ctx, Index, R)));
2381 }
2382
2383 void
2384 RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2385   LLVMContext &Ctx = F.getContext();
2386
2387   for (Argument &A : F.args())
2388     if (isa<PointerType>(A.getType()))
2389       RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2390
2391   if (isa<PointerType>(F.getReturnType()))
2392     RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2393 }
2394
2395 void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2396   if (F.empty())
2397     return;
2398
2399   LLVMContext &Ctx = F.getContext();
2400   MDBuilder Builder(Ctx);
2401
2402   for (Instruction &I : instructions(F)) {
2403     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2404       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2405       bool IsImmutableTBAA =
2406           MD->getNumOperands() == 4 &&
2407           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2408
2409       if (!IsImmutableTBAA)
2410         continue; // no work to do, MD_tbaa is already marked mutable
2411
2412       MDNode *Base = cast<MDNode>(MD->getOperand(0));
2413       MDNode *Access = cast<MDNode>(MD->getOperand(1));
2414       uint64_t Offset =
2415           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2416
2417       MDNode *MutableTBAA =
2418           Builder.createTBAAStructTagNode(Base, Access, Offset);
2419       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2420     }
2421
2422     if (CallSite CS = CallSite(&I)) {
2423       for (int i = 0, e = CS.arg_size(); i != e; i++)
2424         if (isa<PointerType>(CS.getArgument(i)->getType()))
2425           RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2426       if (isa<PointerType>(CS.getType()))
2427         RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2428     }
2429   }
2430 }
2431
2432 /// Returns true if this function should be rewritten by this pass.  The main
2433 /// point of this function is as an extension point for custom logic.
2434 static bool shouldRewriteStatepointsIn(Function &F) {
2435   // TODO: This should check the GCStrategy
2436   if (F.hasGC()) {
2437     const char *FunctionGCName = F.getGC();
2438     const StringRef StatepointExampleName("statepoint-example");
2439     const StringRef CoreCLRName("coreclr");
2440     return (StatepointExampleName == FunctionGCName) ||
2441            (CoreCLRName == FunctionGCName);
2442   } else
2443     return false;
2444 }
2445
2446 void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2447 #ifndef NDEBUG
2448   assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2449          "precondition!");
2450 #endif
2451
2452   for (Function &F : M)
2453     stripDereferenceabilityInfoFromPrototype(F);
2454
2455   for (Function &F : M)
2456     stripDereferenceabilityInfoFromBody(F);
2457 }
2458
2459 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2460   // Nothing to do for declarations.
2461   if (F.isDeclaration() || F.empty())
2462     return false;
2463
2464   // Policy choice says not to rewrite - the most common reason is that we're
2465   // compiling code without a GCStrategy.
2466   if (!shouldRewriteStatepointsIn(F))
2467     return false;
2468
2469   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2470
2471   // Gather all the statepoints which need rewritten.  Be careful to only
2472   // consider those in reachable code since we need to ask dominance queries
2473   // when rewriting.  We'll delete the unreachable ones in a moment.
2474   SmallVector<CallSite, 64> ParsePointNeeded;
2475   bool HasUnreachableStatepoint = false;
2476   for (Instruction &I : instructions(F)) {
2477     // TODO: only the ones with the flag set!
2478     if (isStatepoint(I)) {
2479       if (DT.isReachableFromEntry(I.getParent()))
2480         ParsePointNeeded.push_back(CallSite(&I));
2481       else
2482         HasUnreachableStatepoint = true;
2483     }
2484   }
2485
2486   bool MadeChange = false;
2487
2488   // Delete any unreachable statepoints so that we don't have unrewritten
2489   // statepoints surviving this pass.  This makes testing easier and the
2490   // resulting IR less confusing to human readers.  Rather than be fancy, we
2491   // just reuse a utility function which removes the unreachable blocks.
2492   if (HasUnreachableStatepoint)
2493     MadeChange |= removeUnreachableBlocks(F);
2494
2495   // Return early if no work to do.
2496   if (ParsePointNeeded.empty())
2497     return MadeChange;
2498
2499   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2500   // These are created by LCSSA.  They have the effect of increasing the size
2501   // of liveness sets for no good reason.  It may be harder to do this post
2502   // insertion since relocations and base phis can confuse things.
2503   for (BasicBlock &BB : F)
2504     if (BB.getUniquePredecessor()) {
2505       MadeChange = true;
2506       FoldSingleEntryPHINodes(&BB);
2507     }
2508
2509   // Before we start introducing relocations, we want to tweak the IR a bit to
2510   // avoid unfortunate code generation effects.  The main example is that we 
2511   // want to try to make sure the comparison feeding a branch is after any
2512   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
2513   // values feeding a branch after relocation.  This is semantically correct,
2514   // but results in extra register pressure since both the pre-relocation and
2515   // post-relocation copies must be available in registers.  For code without
2516   // relocations this is handled elsewhere, but teaching the scheduler to
2517   // reverse the transform we're about to do would be slightly complex.
2518   // Note: This may extend the live range of the inputs to the icmp and thus
2519   // increase the liveset of any statepoint we move over.  This is profitable
2520   // as long as all statepoints are in rare blocks.  If we had in-register
2521   // lowering for live values this would be a much safer transform.
2522   auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2523     if (auto *BI = dyn_cast<BranchInst>(TI))
2524       if (BI->isConditional())
2525         return dyn_cast<Instruction>(BI->getCondition());
2526     // TODO: Extend this to handle switches
2527     return nullptr;
2528   };
2529   for (BasicBlock &BB : F) {
2530     TerminatorInst *TI = BB.getTerminator();
2531     if (auto *Cond = getConditionInst(TI))
2532       // TODO: Handle more than just ICmps here.  We should be able to move
2533       // most instructions without side effects or memory access.  
2534       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2535         MadeChange = true;
2536         Cond->moveBefore(TI);
2537       }
2538   }
2539
2540   MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2541   return MadeChange;
2542 }
2543
2544 // liveness computation via standard dataflow
2545 // -------------------------------------------------------------------
2546
2547 // TODO: Consider using bitvectors for liveness, the set of potentially
2548 // interesting values should be small and easy to pre-compute.
2549
2550 /// Compute the live-in set for the location rbegin starting from
2551 /// the live-out set of the basic block
2552 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2553                                 BasicBlock::reverse_iterator rend,
2554                                 DenseSet<Value *> &LiveTmp) {
2555
2556   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2557     Instruction *I = &*ritr;
2558
2559     // KILL/Def - Remove this definition from LiveIn
2560     LiveTmp.erase(I);
2561
2562     // Don't consider *uses* in PHI nodes, we handle their contribution to
2563     // predecessor blocks when we seed the LiveOut sets
2564     if (isa<PHINode>(I))
2565       continue;
2566
2567     // USE - Add to the LiveIn set for this instruction
2568     for (Value *V : I->operands()) {
2569       assert(!isUnhandledGCPointerType(V->getType()) &&
2570              "support for FCA unimplemented");
2571       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2572         // The choice to exclude all things constant here is slightly subtle.
2573         // There are two independent reasons:
2574         // - We assume that things which are constant (from LLVM's definition)
2575         // do not move at runtime.  For example, the address of a global
2576         // variable is fixed, even though it's contents may not be.
2577         // - Second, we can't disallow arbitrary inttoptr constants even
2578         // if the language frontend does.  Optimization passes are free to
2579         // locally exploit facts without respect to global reachability.  This
2580         // can create sections of code which are dynamically unreachable and
2581         // contain just about anything.  (see constants.ll in tests)
2582         LiveTmp.insert(V);
2583       }
2584     }
2585   }
2586 }
2587
2588 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2589
2590   for (BasicBlock *Succ : successors(BB)) {
2591     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2592     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2593       PHINode *Phi = cast<PHINode>(&*I);
2594       Value *V = Phi->getIncomingValueForBlock(BB);
2595       assert(!isUnhandledGCPointerType(V->getType()) &&
2596              "support for FCA unimplemented");
2597       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2598         LiveTmp.insert(V);
2599       }
2600     }
2601   }
2602 }
2603
2604 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2605   DenseSet<Value *> KillSet;
2606   for (Instruction &I : *BB)
2607     if (isHandledGCPointerType(I.getType()))
2608       KillSet.insert(&I);
2609   return KillSet;
2610 }
2611
2612 #ifndef NDEBUG
2613 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2614 /// sanity check for the liveness computation.
2615 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2616                           TerminatorInst *TI, bool TermOkay = false) {
2617   for (Value *V : Live) {
2618     if (auto *I = dyn_cast<Instruction>(V)) {
2619       // The terminator can be a member of the LiveOut set.  LLVM's definition
2620       // of instruction dominance states that V does not dominate itself.  As
2621       // such, we need to special case this to allow it.
2622       if (TermOkay && TI == I)
2623         continue;
2624       assert(DT.dominates(I, TI) &&
2625              "basic SSA liveness expectation violated by liveness analysis");
2626     }
2627   }
2628 }
2629
2630 /// Check that all the liveness sets used during the computation of liveness
2631 /// obey basic SSA properties.  This is useful for finding cases where we miss
2632 /// a def.
2633 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2634                           BasicBlock &BB) {
2635   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2636   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2637   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2638 }
2639 #endif
2640
2641 static void computeLiveInValues(DominatorTree &DT, Function &F,
2642                                 GCPtrLivenessData &Data) {
2643
2644   SmallSetVector<BasicBlock *, 200> Worklist;
2645   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2646     // We use a SetVector so that we don't have duplicates in the worklist.
2647     Worklist.insert(pred_begin(BB), pred_end(BB));
2648   };
2649   auto NextItem = [&]() {
2650     BasicBlock *BB = Worklist.back();
2651     Worklist.pop_back();
2652     return BB;
2653   };
2654
2655   // Seed the liveness for each individual block
2656   for (BasicBlock &BB : F) {
2657     Data.KillSet[&BB] = computeKillSet(&BB);
2658     Data.LiveSet[&BB].clear();
2659     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2660
2661 #ifndef NDEBUG
2662     for (Value *Kill : Data.KillSet[&BB])
2663       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2664 #endif
2665
2666     Data.LiveOut[&BB] = DenseSet<Value *>();
2667     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2668     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2669     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2670     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2671     if (!Data.LiveIn[&BB].empty())
2672       AddPredsToWorklist(&BB);
2673   }
2674
2675   // Propagate that liveness until stable
2676   while (!Worklist.empty()) {
2677     BasicBlock *BB = NextItem();
2678
2679     // Compute our new liveout set, then exit early if it hasn't changed
2680     // despite the contribution of our successor.
2681     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2682     const auto OldLiveOutSize = LiveOut.size();
2683     for (BasicBlock *Succ : successors(BB)) {
2684       assert(Data.LiveIn.count(Succ));
2685       set_union(LiveOut, Data.LiveIn[Succ]);
2686     }
2687     // assert OutLiveOut is a subset of LiveOut
2688     if (OldLiveOutSize == LiveOut.size()) {
2689       // If the sets are the same size, then we didn't actually add anything
2690       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2691       // hasn't changed.
2692       continue;
2693     }
2694     Data.LiveOut[BB] = LiveOut;
2695
2696     // Apply the effects of this basic block
2697     DenseSet<Value *> LiveTmp = LiveOut;
2698     set_union(LiveTmp, Data.LiveSet[BB]);
2699     set_subtract(LiveTmp, Data.KillSet[BB]);
2700
2701     assert(Data.LiveIn.count(BB));
2702     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2703     // assert: OldLiveIn is a subset of LiveTmp
2704     if (OldLiveIn.size() != LiveTmp.size()) {
2705       Data.LiveIn[BB] = LiveTmp;
2706       AddPredsToWorklist(BB);
2707     }
2708   } // while( !worklist.empty() )
2709
2710 #ifndef NDEBUG
2711   // Sanity check our output against SSA properties.  This helps catch any
2712   // missing kills during the above iteration.
2713   for (BasicBlock &BB : F) {
2714     checkBasicSSA(DT, Data, BB);
2715   }
2716 #endif
2717 }
2718
2719 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2720                               StatepointLiveSetTy &Out) {
2721
2722   BasicBlock *BB = Inst->getParent();
2723
2724   // Note: The copy is intentional and required
2725   assert(Data.LiveOut.count(BB));
2726   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2727
2728   // We want to handle the statepoint itself oddly.  It's
2729   // call result is not live (normal), nor are it's arguments
2730   // (unless they're used again later).  This adjustment is
2731   // specifically what we need to relocate
2732   BasicBlock::reverse_iterator rend(Inst);
2733   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2734   LiveOut.erase(Inst);
2735   Out.insert(LiveOut.begin(), LiveOut.end());
2736 }
2737
2738 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2739                                   const CallSite &CS,
2740                                   PartiallyConstructedSafepointRecord &Info) {
2741   Instruction *Inst = CS.getInstruction();
2742   StatepointLiveSetTy Updated;
2743   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2744
2745 #ifndef NDEBUG
2746   DenseSet<Value *> Bases;
2747   for (auto KVPair : Info.PointerToBase) {
2748     Bases.insert(KVPair.second);
2749   }
2750 #endif
2751   // We may have base pointers which are now live that weren't before.  We need
2752   // to update the PointerToBase structure to reflect this.
2753   for (auto V : Updated)
2754     if (!Info.PointerToBase.count(V)) {
2755       assert(Bases.count(V) && "can't find base for unexpected live value");
2756       Info.PointerToBase[V] = V;
2757       continue;
2758     }
2759
2760 #ifndef NDEBUG
2761   for (auto V : Updated) {
2762     assert(Info.PointerToBase.count(V) &&
2763            "must be able to find base for live value");
2764   }
2765 #endif
2766
2767   // Remove any stale base mappings - this can happen since our liveness is
2768   // more precise then the one inherent in the base pointer analysis
2769   DenseSet<Value *> ToErase;
2770   for (auto KVPair : Info.PointerToBase)
2771     if (!Updated.count(KVPair.first))
2772       ToErase.insert(KVPair.first);
2773   for (auto V : ToErase)
2774     Info.PointerToBase.erase(V);
2775
2776 #ifndef NDEBUG
2777   for (auto KVPair : Info.PointerToBase)
2778     assert(Updated.count(KVPair.first) && "record for non-live value");
2779 #endif
2780
2781   Info.liveset = Updated;
2782 }