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