b8b739644856b1c2c28692cdf7ec68bffd6077ed
[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 (isa<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>(I) &&
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   // Returns a instruction which produces the base pointer for a given
950   // instruction.  The instruction is assumed to be an input to one of the BDVs
951   // seen in the inference algorithm above.  As such, we must either already
952   // know it's base defining value is a base, or have inserted a new
953   // instruction to propagate the base of it's BDV and have entered that newly
954   // introduced instruction into the state table.  In either case, we are
955   // assured to be able to determine an instruction which produces it's base
956   // pointer. 
957   auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
958     Value *BDV = findBaseOrBDV(Input, cache);
959     Value *Base = nullptr;
960     if (isKnownBaseResult(BDV)) {
961       Base = BDV;
962     } else {
963       // Either conflict or base.
964       assert(states.count(BDV));
965       Base = states[BDV].getBase();
966     }
967     assert(Base && "can't be null");
968     // The cast is needed since base traversal may strip away bitcasts
969     if (Base->getType() != Input->getType() &&
970         InsertPt) {
971       Base = new BitCastInst(Base, Input->getType(), "cast",
972                              InsertPt);
973     }
974     return Base;
975   };
976
977   // Fixup all the inputs of the new PHIs
978   for (auto Pair : states) {
979     Instruction *v = cast<Instruction>(Pair.first);
980     BDVState state = Pair.second;
981
982     assert(!isKnownBaseResult(v) && "why did it get added?");
983     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
984     if (!state.isConflict())
985       continue;
986
987     if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
988       PHINode *phi = cast<PHINode>(v);
989       unsigned NumPHIValues = phi->getNumIncomingValues();
990       for (unsigned i = 0; i < NumPHIValues; i++) {
991         Value *InVal = phi->getIncomingValue(i);
992         BasicBlock *InBB = phi->getIncomingBlock(i);
993
994         // If we've already seen InBB, add the same incoming value
995         // we added for it earlier.  The IR verifier requires phi
996         // nodes with multiple entries from the same basic block
997         // to have the same incoming value for each of those
998         // entries.  If we don't do this check here and basephi
999         // has a different type than base, we'll end up adding two
1000         // bitcasts (and hence two distinct values) as incoming
1001         // values for the same basic block.
1002
1003         int blockIndex = basephi->getBasicBlockIndex(InBB);
1004         if (blockIndex != -1) {
1005           Value *oldBase = basephi->getIncomingValue(blockIndex);
1006           basephi->addIncoming(oldBase, InBB);
1007           
1008 #ifndef NDEBUG
1009           Value *Base = getBaseForInput(InVal, nullptr);
1010           // In essence this assert states: the only way two
1011           // values incoming from the same basic block may be
1012           // different is by being different bitcasts of the same
1013           // value.  A cleanup that remains TODO is changing
1014           // findBaseOrBDV to return an llvm::Value of the correct
1015           // type (and still remain pure).  This will remove the
1016           // need to add bitcasts.
1017           assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
1018                  "sanity -- findBaseOrBDV should be pure!");
1019 #endif
1020           continue;
1021         }
1022
1023         // Find the instruction which produces the base for each input.  We may
1024         // need to insert a bitcast in the incoming block.
1025         // TODO: Need to split critical edges if insertion is needed
1026         Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1027         basephi->addIncoming(Base, InBB);
1028       }
1029       assert(basephi->getNumIncomingValues() == NumPHIValues);
1030     } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(state.getBase())) {
1031       SelectInst *Sel = cast<SelectInst>(v);
1032       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1033       // something more safe and less hacky.
1034       for (int i = 1; i <= 2; i++) {
1035         Value *InVal = Sel->getOperand(i);
1036         // Find the instruction which produces the base for each input.  We may
1037         // need to insert a bitcast.
1038         Value *Base = getBaseForInput(InVal, BaseSel);
1039         BaseSel->setOperand(i, Base);
1040       }
1041     } else {
1042       auto *BaseEE = cast<ExtractElementInst>(state.getBase());
1043       Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
1044       // Find the instruction which produces the base for each input.  We may
1045       // need to insert a bitcast.
1046       Value *Base = getBaseForInput(InVal, BaseEE);
1047       BaseEE->setOperand(0, Base);
1048     }
1049   }
1050
1051   // Now that we're done with the algorithm, see if we can optimize the 
1052   // results slightly by reducing the number of new instructions needed. 
1053   // Arguably, this should be integrated into the algorithm above, but 
1054   // doing as a post process step is easier to reason about for the moment.
1055   DenseMap<Value *, Value *> ReverseMap;
1056   SmallPtrSet<Instruction *, 16> NewInsts;
1057   SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
1058   // Note: We need to visit the states in a deterministic order.  We uses the
1059   // Keys we sorted above for this purpose.  Note that we are papering over a
1060   // bigger problem with the algorithm above - it's visit order is not
1061   // deterministic.  A larger change is needed to fix this.
1062   for (auto Key : Keys) {
1063     Value *V = Key;
1064     auto State = states[Key];
1065     Value *Base = State.getBase();
1066     assert(V && Base);
1067     assert(!isKnownBaseResult(V) && "why did it get added?");
1068     assert(isKnownBaseResult(Base) &&
1069            "must be something we 'know' is a base pointer");
1070     if (!State.isConflict())
1071       continue;
1072
1073     ReverseMap[Base] = V;
1074     if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1075       NewInsts.insert(BaseI);
1076       Worklist.insert(BaseI);
1077     }
1078   }
1079   auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1080                                  Value *Replacement) {
1081     // Add users which are new instructions (excluding self references)
1082     for (User *U : BaseI->users())
1083       if (auto *UI = dyn_cast<Instruction>(U))
1084         if (NewInsts.count(UI) && UI != BaseI)
1085           Worklist.insert(UI);
1086     // Then do the actual replacement
1087     NewInsts.erase(BaseI);
1088     ReverseMap.erase(BaseI);
1089     BaseI->replaceAllUsesWith(Replacement);
1090     BaseI->eraseFromParent();
1091     assert(states.count(BDV));
1092     assert(states[BDV].isConflict() && states[BDV].getBase() == BaseI);
1093     states[BDV] = BDVState(BDVState::Conflict, Replacement);
1094   };
1095   const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1096   while (!Worklist.empty()) {
1097     Instruction *BaseI = Worklist.pop_back_val();
1098     assert(NewInsts.count(BaseI));
1099     Value *Bdv = ReverseMap[BaseI];
1100     if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1101       if (BaseI->isIdenticalTo(BdvI)) {
1102         DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
1103         ReplaceBaseInstWith(Bdv, BaseI, Bdv);
1104         continue;
1105       }
1106     if (Value *V = SimplifyInstruction(BaseI, DL)) {
1107       DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
1108       ReplaceBaseInstWith(Bdv, BaseI, V);
1109       continue;
1110     }
1111   }
1112
1113   // Cache all of our results so we can cheaply reuse them
1114   // NOTE: This is actually two caches: one of the base defining value
1115   // relation and one of the base pointer relation!  FIXME
1116   for (auto item : states) {
1117     Value *v = item.first;
1118     Value *base = item.second.getBase();
1119     assert(v && base);
1120
1121     std::string fromstr =
1122       cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
1123                      : "none";
1124     DEBUG(dbgs() << "Updating base value cache"
1125           << " for: " << (v->hasName() ? v->getName() : "")
1126           << " from: " << fromstr
1127           << " to: " << (base->hasName() ? base->getName() : "") << "\n");
1128
1129     if (cache.count(v)) {
1130       // Once we transition from the BDV relation being store in the cache to
1131       // the base relation being stored, it must be stable
1132       assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
1133              "base relation should be stable");
1134     }
1135     cache[v] = base;
1136   }
1137   assert(cache.find(def) != cache.end());
1138   return cache[def];
1139 }
1140
1141 // For a set of live pointers (base and/or derived), identify the base
1142 // pointer of the object which they are derived from.  This routine will
1143 // mutate the IR graph as needed to make the 'base' pointer live at the
1144 // definition site of 'derived'.  This ensures that any use of 'derived' can
1145 // also use 'base'.  This may involve the insertion of a number of
1146 // additional PHI nodes.
1147 //
1148 // preconditions: live is a set of pointer type Values
1149 //
1150 // side effects: may insert PHI nodes into the existing CFG, will preserve
1151 // CFG, will not remove or mutate any existing nodes
1152 //
1153 // post condition: PointerToBase contains one (derived, base) pair for every
1154 // pointer in live.  Note that derived can be equal to base if the original
1155 // pointer was a base pointer.
1156 static void
1157 findBasePointers(const StatepointLiveSetTy &live,
1158                  DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
1159                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
1160   // For the naming of values inserted to be deterministic - which makes for
1161   // much cleaner and more stable tests - we need to assign an order to the
1162   // live values.  DenseSets do not provide a deterministic order across runs.
1163   SmallVector<Value *, 64> Temp;
1164   Temp.insert(Temp.end(), live.begin(), live.end());
1165   std::sort(Temp.begin(), Temp.end(), order_by_name);
1166   for (Value *ptr : Temp) {
1167     Value *base = findBasePointer(ptr, DVCache);
1168     assert(base && "failed to find base pointer");
1169     PointerToBase[ptr] = base;
1170     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1171             DT->dominates(cast<Instruction>(base)->getParent(),
1172                           cast<Instruction>(ptr)->getParent())) &&
1173            "The base we found better dominate the derived pointer");
1174
1175     // If you see this trip and like to live really dangerously, the code should
1176     // be correct, just with idioms the verifier can't handle.  You can try
1177     // disabling the verifier at your own substantial risk.
1178     assert(!isa<ConstantPointerNull>(base) &&
1179            "the relocation code needs adjustment to handle the relocation of "
1180            "a null pointer constant without causing false positives in the "
1181            "safepoint ir verifier.");
1182   }
1183 }
1184
1185 /// Find the required based pointers (and adjust the live set) for the given
1186 /// parse point.
1187 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1188                              const CallSite &CS,
1189                              PartiallyConstructedSafepointRecord &result) {
1190   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1191   findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
1192
1193   if (PrintBasePointers) {
1194     // Note: Need to print these in a stable order since this is checked in
1195     // some tests.
1196     errs() << "Base Pairs (w/o Relocation):\n";
1197     SmallVector<Value *, 64> Temp;
1198     Temp.reserve(PointerToBase.size());
1199     for (auto Pair : PointerToBase) {
1200       Temp.push_back(Pair.first);
1201     }
1202     std::sort(Temp.begin(), Temp.end(), order_by_name);
1203     for (Value *Ptr : Temp) {
1204       Value *Base = PointerToBase[Ptr];
1205       errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1206              << "\n";
1207     }
1208   }
1209
1210   result.PointerToBase = PointerToBase;
1211 }
1212
1213 /// Given an updated version of the dataflow liveness results, update the
1214 /// liveset and base pointer maps for the call site CS.
1215 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1216                                   const CallSite &CS,
1217                                   PartiallyConstructedSafepointRecord &result);
1218
1219 static void recomputeLiveInValues(
1220     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1221     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1222   // TODO-PERF: reuse the original liveness, then simply run the dataflow
1223   // again.  The old values are still live and will help it stabilize quickly.
1224   GCPtrLivenessData RevisedLivenessData;
1225   computeLiveInValues(DT, F, RevisedLivenessData);
1226   for (size_t i = 0; i < records.size(); i++) {
1227     struct PartiallyConstructedSafepointRecord &info = records[i];
1228     const CallSite &CS = toUpdate[i];
1229     recomputeLiveInValues(RevisedLivenessData, CS, info);
1230   }
1231 }
1232
1233 // When inserting gc.relocate calls, we need to ensure there are no uses
1234 // of the original value between the gc.statepoint and the gc.relocate call.
1235 // One case which can arise is a phi node starting one of the successor blocks.
1236 // We also need to be able to insert the gc.relocates only on the path which
1237 // goes through the statepoint.  We might need to split an edge to make this
1238 // possible.
1239 static BasicBlock *
1240 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1241                             DominatorTree &DT) {
1242   BasicBlock *Ret = BB;
1243   if (!BB->getUniquePredecessor()) {
1244     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1245   }
1246
1247   // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1248   // from it
1249   FoldSingleEntryPHINodes(Ret);
1250   assert(!isa<PHINode>(Ret->begin()));
1251
1252   // At this point, we can safely insert a gc.relocate as the first instruction
1253   // in Ret if needed.
1254   return Ret;
1255 }
1256
1257 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1258   auto itr = std::find(livevec.begin(), livevec.end(), val);
1259   assert(livevec.end() != itr);
1260   size_t index = std::distance(livevec.begin(), itr);
1261   assert(index < livevec.size());
1262   return index;
1263 }
1264
1265 // Create new attribute set containing only attributes which can be transferred
1266 // from original call to the safepoint.
1267 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1268   AttributeSet ret;
1269
1270   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1271     unsigned index = AS.getSlotIndex(Slot);
1272
1273     if (index == AttributeSet::ReturnIndex ||
1274         index == AttributeSet::FunctionIndex) {
1275
1276       for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1277            ++it) {
1278         Attribute attr = *it;
1279
1280         // Do not allow certain attributes - just skip them
1281         // Safepoint can not be read only or read none.
1282         if (attr.hasAttribute(Attribute::ReadNone) ||
1283             attr.hasAttribute(Attribute::ReadOnly))
1284           continue;
1285
1286         ret = ret.addAttributes(
1287             AS.getContext(), index,
1288             AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1289       }
1290     }
1291
1292     // Just skip parameter attributes for now
1293   }
1294
1295   return ret;
1296 }
1297
1298 /// Helper function to place all gc relocates necessary for the given
1299 /// statepoint.
1300 /// Inputs:
1301 ///   liveVariables - list of variables to be relocated.
1302 ///   liveStart - index of the first live variable.
1303 ///   basePtrs - base pointers.
1304 ///   statepointToken - statepoint instruction to which relocates should be
1305 ///   bound.
1306 ///   Builder - Llvm IR builder to be used to construct new calls.
1307 static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1308                               const int LiveStart,
1309                               ArrayRef<llvm::Value *> BasePtrs,
1310                               Instruction *StatepointToken,
1311                               IRBuilder<> Builder) {
1312   if (LiveVariables.empty())
1313     return;
1314   
1315   // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1316   // unique declarations for each pointer type, but this proved problematic
1317   // because the intrinsic mangling code is incomplete and fragile.  Since
1318   // we're moving towards a single unified pointer type anyways, we can just
1319   // cast everything to an i8* of the right address space.  A bitcast is added
1320   // later to convert gc_relocate to the actual value's type. 
1321   Module *M = StatepointToken->getModule();
1322   auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1323   Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1324   Value *GCRelocateDecl =
1325     Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
1326
1327   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1328     // Generate the gc.relocate call and save the result
1329     Value *BaseIdx =
1330       Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1331     Value *LiveIdx =
1332       Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
1333
1334     // only specify a debug name if we can give a useful one
1335     CallInst *Reloc = Builder.CreateCall(
1336         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1337         LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
1338                                     : "");
1339     // Trick CodeGen into thinking there are lots of free registers at this
1340     // fake call.
1341     Reloc->setCallingConv(CallingConv::Cold);
1342   }
1343 }
1344
1345 static void
1346 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1347                            const SmallVectorImpl<llvm::Value *> &basePtrs,
1348                            const SmallVectorImpl<llvm::Value *> &liveVariables,
1349                            Pass *P,
1350                            PartiallyConstructedSafepointRecord &result) {
1351   assert(basePtrs.size() == liveVariables.size());
1352   assert(isStatepoint(CS) &&
1353          "This method expects to be rewriting a statepoint");
1354
1355   BasicBlock *BB = CS.getInstruction()->getParent();
1356   assert(BB);
1357   Function *F = BB->getParent();
1358   assert(F && "must be set");
1359   Module *M = F->getParent();
1360   (void)M;
1361   assert(M && "must be set");
1362
1363   // We're not changing the function signature of the statepoint since the gc
1364   // arguments go into the var args section.
1365   Function *gc_statepoint_decl = CS.getCalledFunction();
1366
1367   // Then go ahead and use the builder do actually do the inserts.  We insert
1368   // immediately before the previous instruction under the assumption that all
1369   // arguments will be available here.  We can't insert afterwards since we may
1370   // be replacing a terminator.
1371   Instruction *insertBefore = CS.getInstruction();
1372   IRBuilder<> Builder(insertBefore);
1373   // Copy all of the arguments from the original statepoint - this includes the
1374   // target, call args, and deopt args
1375   SmallVector<llvm::Value *, 64> args;
1376   args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1377   // TODO: Clear the 'needs rewrite' flag
1378
1379   // add all the pointers to be relocated (gc arguments)
1380   // Capture the start of the live variable list for use in the gc_relocates
1381   const int live_start = args.size();
1382   args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1383
1384   // Create the statepoint given all the arguments
1385   Instruction *token = nullptr;
1386   AttributeSet return_attributes;
1387   if (CS.isCall()) {
1388     CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1389     CallInst *call =
1390         Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1391     call->setTailCall(toReplace->isTailCall());
1392     call->setCallingConv(toReplace->getCallingConv());
1393
1394     // Currently we will fail on parameter attributes and on certain
1395     // function attributes.
1396     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1397     // In case if we can handle this set of attributes - set up function attrs
1398     // directly on statepoint and return attrs later for gc_result intrinsic.
1399     call->setAttributes(new_attrs.getFnAttributes());
1400     return_attributes = new_attrs.getRetAttributes();
1401
1402     token = call;
1403
1404     // Put the following gc_result and gc_relocate calls immediately after the
1405     // the old call (which we're about to delete)
1406     BasicBlock::iterator next(toReplace);
1407     assert(BB->end() != next && "not a terminator, must have next");
1408     next++;
1409     Instruction *IP = &*(next);
1410     Builder.SetInsertPoint(IP);
1411     Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1412
1413   } else {
1414     InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1415
1416     // Insert the new invoke into the old block.  We'll remove the old one in a
1417     // moment at which point this will become the new terminator for the
1418     // original block.
1419     InvokeInst *invoke = InvokeInst::Create(
1420         gc_statepoint_decl, toReplace->getNormalDest(),
1421         toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
1422     invoke->setCallingConv(toReplace->getCallingConv());
1423
1424     // Currently we will fail on parameter attributes and on certain
1425     // function attributes.
1426     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1427     // In case if we can handle this set of attributes - set up function attrs
1428     // directly on statepoint and return attrs later for gc_result intrinsic.
1429     invoke->setAttributes(new_attrs.getFnAttributes());
1430     return_attributes = new_attrs.getRetAttributes();
1431
1432     token = invoke;
1433
1434     // Generate gc relocates in exceptional path
1435     BasicBlock *unwindBlock = toReplace->getUnwindDest();
1436     assert(!isa<PHINode>(unwindBlock->begin()) &&
1437            unwindBlock->getUniquePredecessor() &&
1438            "can't safely insert in this block!");
1439
1440     Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1441     Builder.SetInsertPoint(IP);
1442     Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1443
1444     // Extract second element from landingpad return value. We will attach
1445     // exceptional gc relocates to it.
1446     const unsigned idx = 1;
1447     Instruction *exceptional_token =
1448         cast<Instruction>(Builder.CreateExtractValue(
1449             unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1450     result.UnwindToken = exceptional_token;
1451
1452     CreateGCRelocates(liveVariables, live_start, basePtrs,
1453                       exceptional_token, Builder);
1454
1455     // Generate gc relocates and returns for normal block
1456     BasicBlock *normalDest = toReplace->getNormalDest();
1457     assert(!isa<PHINode>(normalDest->begin()) &&
1458            normalDest->getUniquePredecessor() &&
1459            "can't safely insert in this block!");
1460
1461     IP = &*(normalDest->getFirstInsertionPt());
1462     Builder.SetInsertPoint(IP);
1463
1464     // gc relocates will be generated later as if it were regular call
1465     // statepoint
1466   }
1467   assert(token);
1468
1469   // Take the name of the original value call if it had one.
1470   token->takeName(CS.getInstruction());
1471
1472 // The GCResult is already inserted, we just need to find it
1473 #ifndef NDEBUG
1474   Instruction *toReplace = CS.getInstruction();
1475   assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1476          "only valid use before rewrite is gc.result");
1477   assert(!toReplace->hasOneUse() ||
1478          isGCResult(cast<Instruction>(*toReplace->user_begin())));
1479 #endif
1480
1481   // Update the gc.result of the original statepoint (if any) to use the newly
1482   // inserted statepoint.  This is safe to do here since the token can't be
1483   // considered a live reference.
1484   CS.getInstruction()->replaceAllUsesWith(token);
1485
1486   result.StatepointToken = token;
1487
1488   // Second, create a gc.relocate for every live variable
1489   CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1490 }
1491
1492 namespace {
1493 struct name_ordering {
1494   Value *base;
1495   Value *derived;
1496   bool operator()(name_ordering const &a, name_ordering const &b) {
1497     return -1 == a.derived->getName().compare(b.derived->getName());
1498   }
1499 };
1500 }
1501 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1502                            SmallVectorImpl<Value *> &livevec) {
1503   assert(basevec.size() == livevec.size());
1504
1505   SmallVector<name_ordering, 64> temp;
1506   for (size_t i = 0; i < basevec.size(); i++) {
1507     name_ordering v;
1508     v.base = basevec[i];
1509     v.derived = livevec[i];
1510     temp.push_back(v);
1511   }
1512   std::sort(temp.begin(), temp.end(), name_ordering());
1513   for (size_t i = 0; i < basevec.size(); i++) {
1514     basevec[i] = temp[i].base;
1515     livevec[i] = temp[i].derived;
1516   }
1517 }
1518
1519 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1520 // which make the relocations happening at this safepoint explicit.
1521 //
1522 // WARNING: Does not do any fixup to adjust users of the original live
1523 // values.  That's the callers responsibility.
1524 static void
1525 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1526                        PartiallyConstructedSafepointRecord &result) {
1527   auto liveset = result.liveset;
1528   auto PointerToBase = result.PointerToBase;
1529
1530   // Convert to vector for efficient cross referencing.
1531   SmallVector<Value *, 64> basevec, livevec;
1532   livevec.reserve(liveset.size());
1533   basevec.reserve(liveset.size());
1534   for (Value *L : liveset) {
1535     livevec.push_back(L);
1536     assert(PointerToBase.count(L));
1537     Value *base = PointerToBase[L];
1538     basevec.push_back(base);
1539   }
1540   assert(livevec.size() == basevec.size());
1541
1542   // To make the output IR slightly more stable (for use in diffs), ensure a
1543   // fixed order of the values in the safepoint (by sorting the value name).
1544   // The order is otherwise meaningless.
1545   stablize_order(basevec, livevec);
1546
1547   // Do the actual rewriting and delete the old statepoint
1548   makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1549   CS.getInstruction()->eraseFromParent();
1550 }
1551
1552 // Helper function for the relocationViaAlloca.
1553 // It receives iterator to the statepoint gc relocates and emits store to the
1554 // assigned
1555 // location (via allocaMap) for the each one of them.
1556 // Add visited values into the visitedLiveValues set we will later use them
1557 // for sanity check.
1558 static void
1559 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1560                        DenseMap<Value *, Value *> &AllocaMap,
1561                        DenseSet<Value *> &VisitedLiveValues) {
1562
1563   for (User *U : GCRelocs) {
1564     if (!isa<IntrinsicInst>(U))
1565       continue;
1566
1567     IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
1568
1569     // We only care about relocates
1570     if (RelocatedValue->getIntrinsicID() !=
1571         Intrinsic::experimental_gc_relocate) {
1572       continue;
1573     }
1574
1575     GCRelocateOperands RelocateOperands(RelocatedValue);
1576     Value *OriginalValue =
1577         const_cast<Value *>(RelocateOperands.getDerivedPtr());
1578     assert(AllocaMap.count(OriginalValue));
1579     Value *Alloca = AllocaMap[OriginalValue];
1580
1581     // Emit store into the related alloca
1582     // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1583     // the correct type according to alloca.
1584     assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1585     IRBuilder<> Builder(RelocatedValue->getNextNode());
1586     Value *CastedRelocatedValue =
1587         Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1588         RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
1589
1590     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1591     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1592
1593 #ifndef NDEBUG
1594     VisitedLiveValues.insert(OriginalValue);
1595 #endif
1596   }
1597 }
1598
1599 // Helper function for the "relocationViaAlloca". Similar to the
1600 // "insertRelocationStores" but works for rematerialized values.
1601 static void
1602 insertRematerializationStores(
1603   RematerializedValueMapTy RematerializedValues,
1604   DenseMap<Value *, Value *> &AllocaMap,
1605   DenseSet<Value *> &VisitedLiveValues) {
1606
1607   for (auto RematerializedValuePair: RematerializedValues) {
1608     Instruction *RematerializedValue = RematerializedValuePair.first;
1609     Value *OriginalValue = RematerializedValuePair.second;
1610
1611     assert(AllocaMap.count(OriginalValue) &&
1612            "Can not find alloca for rematerialized value");
1613     Value *Alloca = AllocaMap[OriginalValue];
1614
1615     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1616     Store->insertAfter(RematerializedValue);
1617
1618 #ifndef NDEBUG
1619     VisitedLiveValues.insert(OriginalValue);
1620 #endif
1621   }
1622 }
1623
1624 /// do all the relocation update via allocas and mem2reg
1625 static void relocationViaAlloca(
1626     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1627     ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
1628 #ifndef NDEBUG
1629   // record initial number of (static) allocas; we'll check we have the same
1630   // number when we get done.
1631   int InitialAllocaNum = 0;
1632   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1633        I++)
1634     if (isa<AllocaInst>(*I))
1635       InitialAllocaNum++;
1636 #endif
1637
1638   // TODO-PERF: change data structures, reserve
1639   DenseMap<Value *, Value *> AllocaMap;
1640   SmallVector<AllocaInst *, 200> PromotableAllocas;
1641   // Used later to chack that we have enough allocas to store all values
1642   std::size_t NumRematerializedValues = 0;
1643   PromotableAllocas.reserve(Live.size());
1644
1645   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1646   // "PromotableAllocas"
1647   auto emitAllocaFor = [&](Value *LiveValue) {
1648     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1649                                         F.getEntryBlock().getFirstNonPHI());
1650     AllocaMap[LiveValue] = Alloca;
1651     PromotableAllocas.push_back(Alloca);
1652   };
1653
1654   // emit alloca for each live gc pointer
1655   for (unsigned i = 0; i < Live.size(); i++) {
1656     emitAllocaFor(Live[i]);
1657   }
1658
1659   // emit allocas for rematerialized values
1660   for (size_t i = 0; i < Records.size(); i++) {
1661     const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1662
1663     for (auto RematerializedValuePair : Info.RematerializedValues) {
1664       Value *OriginalValue = RematerializedValuePair.second;
1665       if (AllocaMap.count(OriginalValue) != 0)
1666         continue;
1667
1668       emitAllocaFor(OriginalValue);
1669       ++NumRematerializedValues;
1670     }
1671   }
1672
1673   // The next two loops are part of the same conceptual operation.  We need to
1674   // insert a store to the alloca after the original def and at each
1675   // redefinition.  We need to insert a load before each use.  These are split
1676   // into distinct loops for performance reasons.
1677
1678   // update gc pointer after each statepoint
1679   // either store a relocated value or null (if no relocated value found for
1680   // this gc pointer and it is not a gc_result)
1681   // this must happen before we update the statepoint with load of alloca
1682   // otherwise we lose the link between statepoint and old def
1683   for (size_t i = 0; i < Records.size(); i++) {
1684     const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1685     Value *Statepoint = Info.StatepointToken;
1686
1687     // This will be used for consistency check
1688     DenseSet<Value *> VisitedLiveValues;
1689
1690     // Insert stores for normal statepoint gc relocates
1691     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1692
1693     // In case if it was invoke statepoint
1694     // we will insert stores for exceptional path gc relocates.
1695     if (isa<InvokeInst>(Statepoint)) {
1696       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1697                              VisitedLiveValues);
1698     }
1699
1700     // Do similar thing with rematerialized values
1701     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1702                                   VisitedLiveValues);
1703
1704     if (ClobberNonLive) {
1705       // As a debugging aid, pretend that an unrelocated pointer becomes null at
1706       // the gc.statepoint.  This will turn some subtle GC problems into
1707       // slightly easier to debug SEGVs.  Note that on large IR files with
1708       // lots of gc.statepoints this is extremely costly both memory and time
1709       // wise.
1710       SmallVector<AllocaInst *, 64> ToClobber;
1711       for (auto Pair : AllocaMap) {
1712         Value *Def = Pair.first;
1713         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1714
1715         // This value was relocated
1716         if (VisitedLiveValues.count(Def)) {
1717           continue;
1718         }
1719         ToClobber.push_back(Alloca);
1720       }
1721
1722       auto InsertClobbersAt = [&](Instruction *IP) {
1723         for (auto *AI : ToClobber) {
1724           auto AIType = cast<PointerType>(AI->getType());
1725           auto PT = cast<PointerType>(AIType->getElementType());
1726           Constant *CPN = ConstantPointerNull::get(PT);
1727           StoreInst *Store = new StoreInst(CPN, AI);
1728           Store->insertBefore(IP);
1729         }
1730       };
1731
1732       // Insert the clobbering stores.  These may get intermixed with the
1733       // gc.results and gc.relocates, but that's fine.
1734       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1735         InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1736         InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1737       } else {
1738         BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1739         Next++;
1740         InsertClobbersAt(Next);
1741       }
1742     }
1743   }
1744   // update use with load allocas and add store for gc_relocated
1745   for (auto Pair : AllocaMap) {
1746     Value *Def = Pair.first;
1747     Value *Alloca = Pair.second;
1748
1749     // we pre-record the uses of allocas so that we dont have to worry about
1750     // later update
1751     // that change the user information.
1752     SmallVector<Instruction *, 20> Uses;
1753     // PERF: trade a linear scan for repeated reallocation
1754     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1755     for (User *U : Def->users()) {
1756       if (!isa<ConstantExpr>(U)) {
1757         // If the def has a ConstantExpr use, then the def is either a
1758         // ConstantExpr use itself or null.  In either case
1759         // (recursively in the first, directly in the second), the oop
1760         // it is ultimately dependent on is null and this particular
1761         // use does not need to be fixed up.
1762         Uses.push_back(cast<Instruction>(U));
1763       }
1764     }
1765
1766     std::sort(Uses.begin(), Uses.end());
1767     auto Last = std::unique(Uses.begin(), Uses.end());
1768     Uses.erase(Last, Uses.end());
1769
1770     for (Instruction *Use : Uses) {
1771       if (isa<PHINode>(Use)) {
1772         PHINode *Phi = cast<PHINode>(Use);
1773         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1774           if (Def == Phi->getIncomingValue(i)) {
1775             LoadInst *Load = new LoadInst(
1776                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1777             Phi->setIncomingValue(i, Load);
1778           }
1779         }
1780       } else {
1781         LoadInst *Load = new LoadInst(Alloca, "", Use);
1782         Use->replaceUsesOfWith(Def, Load);
1783       }
1784     }
1785
1786     // emit store for the initial gc value
1787     // store must be inserted after load, otherwise store will be in alloca's
1788     // use list and an extra load will be inserted before it
1789     StoreInst *Store = new StoreInst(Def, Alloca);
1790     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1791       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1792         // InvokeInst is a TerminatorInst so the store need to be inserted
1793         // into its normal destination block.
1794         BasicBlock *NormalDest = Invoke->getNormalDest();
1795         Store->insertBefore(NormalDest->getFirstNonPHI());
1796       } else {
1797         assert(!Inst->isTerminator() &&
1798                "The only TerminatorInst that can produce a value is "
1799                "InvokeInst which is handled above.");
1800         Store->insertAfter(Inst);
1801       }
1802     } else {
1803       assert(isa<Argument>(Def));
1804       Store->insertAfter(cast<Instruction>(Alloca));
1805     }
1806   }
1807
1808   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1809          "we must have the same allocas with lives");
1810   if (!PromotableAllocas.empty()) {
1811     // apply mem2reg to promote alloca to SSA
1812     PromoteMemToReg(PromotableAllocas, DT);
1813   }
1814
1815 #ifndef NDEBUG
1816   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1817        I++)
1818     if (isa<AllocaInst>(*I))
1819       InitialAllocaNum--;
1820   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1821 #endif
1822 }
1823
1824 /// Implement a unique function which doesn't require we sort the input
1825 /// vector.  Doing so has the effect of changing the output of a couple of
1826 /// tests in ways which make them less useful in testing fused safepoints.
1827 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1828   SmallSet<T, 8> Seen;
1829   Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1830               return !Seen.insert(V).second;
1831             }), Vec.end());
1832 }
1833
1834 /// Insert holders so that each Value is obviously live through the entire
1835 /// lifetime of the call.
1836 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1837                                  SmallVectorImpl<CallInst *> &Holders) {
1838   if (Values.empty())
1839     // No values to hold live, might as well not insert the empty holder
1840     return;
1841
1842   Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1843   // Use a dummy vararg function to actually hold the values live
1844   Function *Func = cast<Function>(M->getOrInsertFunction(
1845       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1846   if (CS.isCall()) {
1847     // For call safepoints insert dummy calls right after safepoint
1848     BasicBlock::iterator Next(CS.getInstruction());
1849     Next++;
1850     Holders.push_back(CallInst::Create(Func, Values, "", Next));
1851     return;
1852   }
1853   // For invoke safepooints insert dummy calls both in normal and
1854   // exceptional destination blocks
1855   auto *II = cast<InvokeInst>(CS.getInstruction());
1856   Holders.push_back(CallInst::Create(
1857       Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1858   Holders.push_back(CallInst::Create(
1859       Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
1860 }
1861
1862 static void findLiveReferences(
1863     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1864     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1865   GCPtrLivenessData OriginalLivenessData;
1866   computeLiveInValues(DT, F, OriginalLivenessData);
1867   for (size_t i = 0; i < records.size(); i++) {
1868     struct PartiallyConstructedSafepointRecord &info = records[i];
1869     const CallSite &CS = toUpdate[i];
1870     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1871   }
1872 }
1873
1874 /// Remove any vector of pointers from the liveset by scalarizing them over the
1875 /// statepoint instruction.  Adds the scalarized pieces to the liveset.  It
1876 /// would be preferable to include the vector in the statepoint itself, but
1877 /// the lowering code currently does not handle that.  Extending it would be
1878 /// slightly non-trivial since it requires a format change.  Given how rare
1879 /// such cases are (for the moment?) scalarizing is an acceptable compromise.
1880 static void splitVectorValues(Instruction *StatepointInst,
1881                               StatepointLiveSetTy &LiveSet,
1882                               DenseMap<Value *, Value *>& PointerToBase,
1883                               DominatorTree &DT) {
1884   SmallVector<Value *, 16> ToSplit;
1885   for (Value *V : LiveSet)
1886     if (isa<VectorType>(V->getType()))
1887       ToSplit.push_back(V);
1888
1889   if (ToSplit.empty())
1890     return;
1891
1892   DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1893
1894   Function &F = *(StatepointInst->getParent()->getParent());
1895
1896   DenseMap<Value *, AllocaInst *> AllocaMap;
1897   // First is normal return, second is exceptional return (invoke only)
1898   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1899   for (Value *V : ToSplit) {
1900     AllocaInst *Alloca =
1901         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1902     AllocaMap[V] = Alloca;
1903
1904     VectorType *VT = cast<VectorType>(V->getType());
1905     IRBuilder<> Builder(StatepointInst);
1906     SmallVector<Value *, 16> Elements;
1907     for (unsigned i = 0; i < VT->getNumElements(); i++)
1908       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1909     ElementMapping[V] = Elements;
1910
1911     auto InsertVectorReform = [&](Instruction *IP) {
1912       Builder.SetInsertPoint(IP);
1913       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1914       Value *ResultVec = UndefValue::get(VT);
1915       for (unsigned i = 0; i < VT->getNumElements(); i++)
1916         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1917                                                 Builder.getInt32(i));
1918       return ResultVec;
1919     };
1920
1921     if (isa<CallInst>(StatepointInst)) {
1922       BasicBlock::iterator Next(StatepointInst);
1923       Next++;
1924       Instruction *IP = &*(Next);
1925       Replacements[V].first = InsertVectorReform(IP);
1926       Replacements[V].second = nullptr;
1927     } else {
1928       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1929       // We've already normalized - check that we don't have shared destination
1930       // blocks
1931       BasicBlock *NormalDest = Invoke->getNormalDest();
1932       assert(!isa<PHINode>(NormalDest->begin()));
1933       BasicBlock *UnwindDest = Invoke->getUnwindDest();
1934       assert(!isa<PHINode>(UnwindDest->begin()));
1935       // Insert insert element sequences in both successors
1936       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1937       Replacements[V].first = InsertVectorReform(IP);
1938       IP = &*(UnwindDest->getFirstInsertionPt());
1939       Replacements[V].second = InsertVectorReform(IP);
1940     }
1941   }
1942
1943   for (Value *V : ToSplit) {
1944     AllocaInst *Alloca = AllocaMap[V];
1945
1946     // Capture all users before we start mutating use lists
1947     SmallVector<Instruction *, 16> Users;
1948     for (User *U : V->users())
1949       Users.push_back(cast<Instruction>(U));
1950
1951     for (Instruction *I : Users) {
1952       if (auto Phi = dyn_cast<PHINode>(I)) {
1953         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1954           if (V == Phi->getIncomingValue(i)) {
1955             LoadInst *Load = new LoadInst(
1956                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1957             Phi->setIncomingValue(i, Load);
1958           }
1959       } else {
1960         LoadInst *Load = new LoadInst(Alloca, "", I);
1961         I->replaceUsesOfWith(V, Load);
1962       }
1963     }
1964
1965     // Store the original value and the replacement value into the alloca
1966     StoreInst *Store = new StoreInst(V, Alloca);
1967     if (auto I = dyn_cast<Instruction>(V))
1968       Store->insertAfter(I);
1969     else
1970       Store->insertAfter(Alloca);
1971
1972     // Normal return for invoke, or call return
1973     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1974     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1975     // Unwind return for invoke only
1976     Replacement = cast_or_null<Instruction>(Replacements[V].second);
1977     if (Replacement)
1978       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1979   }
1980
1981   // apply mem2reg to promote alloca to SSA
1982   SmallVector<AllocaInst *, 16> Allocas;
1983   for (Value *V : ToSplit)
1984     Allocas.push_back(AllocaMap[V]);
1985   PromoteMemToReg(Allocas, DT);
1986
1987   // Update our tracking of live pointers and base mappings to account for the
1988   // changes we just made.
1989   for (Value *V : ToSplit) {
1990     auto &Elements = ElementMapping[V];
1991
1992     LiveSet.erase(V);
1993     LiveSet.insert(Elements.begin(), Elements.end());
1994     // We need to update the base mapping as well.
1995     assert(PointerToBase.count(V));
1996     Value *OldBase = PointerToBase[V];
1997     auto &BaseElements = ElementMapping[OldBase];
1998     PointerToBase.erase(V);
1999     assert(Elements.size() == BaseElements.size());
2000     for (unsigned i = 0; i < Elements.size(); i++) {
2001       Value *Elem = Elements[i];
2002       PointerToBase[Elem] = BaseElements[i];
2003     }
2004   }
2005 }
2006
2007 // Helper function for the "rematerializeLiveValues". It walks use chain
2008 // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2009 // values are visited (currently it is GEP's and casts). Returns true if it
2010 // successfully reached "BaseValue" and false otherwise.
2011 // Fills "ChainToBase" array with all visited values. "BaseValue" is not
2012 // recorded.
2013 static bool findRematerializableChainToBasePointer(
2014   SmallVectorImpl<Instruction*> &ChainToBase,
2015   Value *CurrentValue, Value *BaseValue) {
2016
2017   // We have found a base value
2018   if (CurrentValue == BaseValue) {
2019     return true;
2020   }
2021
2022   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2023     ChainToBase.push_back(GEP);
2024     return findRematerializableChainToBasePointer(ChainToBase,
2025                                                   GEP->getPointerOperand(),
2026                                                   BaseValue);
2027   }
2028
2029   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2030     Value *Def = CI->stripPointerCasts();
2031
2032     // This two checks are basically similar. First one is here for the
2033     // consistency with findBasePointers logic.
2034     assert(!isa<CastInst>(Def) && "not a pointer cast found");
2035     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2036       return false;
2037
2038     ChainToBase.push_back(CI);
2039     return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2040   }
2041
2042   // Not supported instruction in the chain
2043   return false;
2044 }
2045
2046 // Helper function for the "rematerializeLiveValues". Compute cost of the use
2047 // chain we are going to rematerialize.
2048 static unsigned
2049 chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2050                        TargetTransformInfo &TTI) {
2051   unsigned Cost = 0;
2052
2053   for (Instruction *Instr : Chain) {
2054     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2055       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2056              "non noop cast is found during rematerialization");
2057
2058       Type *SrcTy = CI->getOperand(0)->getType();
2059       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2060
2061     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2062       // Cost of the address calculation
2063       Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2064       Cost += TTI.getAddressComputationCost(ValTy);
2065
2066       // And cost of the GEP itself
2067       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2068       //       allowed for the external usage)
2069       if (!GEP->hasAllConstantIndices())
2070         Cost += 2;
2071
2072     } else {
2073       llvm_unreachable("unsupported instruciton type during rematerialization");
2074     }
2075   }
2076
2077   return Cost;
2078 }
2079
2080 // From the statepoint liveset pick values that are cheaper to recompute then to
2081 // relocate. Remove this values from the liveset, rematerialize them after
2082 // statepoint and record them in "Info" structure. Note that similar to
2083 // relocated values we don't do any user adjustments here.
2084 static void rematerializeLiveValues(CallSite CS,
2085                                     PartiallyConstructedSafepointRecord &Info,
2086                                     TargetTransformInfo &TTI) {
2087   const unsigned int ChainLengthThreshold = 10;
2088
2089   // Record values we are going to delete from this statepoint live set.
2090   // We can not di this in following loop due to iterator invalidation.
2091   SmallVector<Value *, 32> LiveValuesToBeDeleted;
2092
2093   for (Value *LiveValue: Info.liveset) {
2094     // For each live pointer find it's defining chain
2095     SmallVector<Instruction *, 3> ChainToBase;
2096     assert(Info.PointerToBase.count(LiveValue));
2097     bool FoundChain =
2098       findRematerializableChainToBasePointer(ChainToBase,
2099                                              LiveValue,
2100                                              Info.PointerToBase[LiveValue]);
2101     // Nothing to do, or chain is too long
2102     if (!FoundChain ||
2103         ChainToBase.size() == 0 ||
2104         ChainToBase.size() > ChainLengthThreshold)
2105       continue;
2106
2107     // Compute cost of this chain
2108     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2109     // TODO: We can also account for cases when we will be able to remove some
2110     //       of the rematerialized values by later optimization passes. I.e if
2111     //       we rematerialized several intersecting chains. Or if original values
2112     //       don't have any uses besides this statepoint.
2113
2114     // For invokes we need to rematerialize each chain twice - for normal and
2115     // for unwind basic blocks. Model this by multiplying cost by two.
2116     if (CS.isInvoke()) {
2117       Cost *= 2;
2118     }
2119     // If it's too expensive - skip it
2120     if (Cost >= RematerializationThreshold)
2121       continue;
2122
2123     // Remove value from the live set
2124     LiveValuesToBeDeleted.push_back(LiveValue);
2125
2126     // Clone instructions and record them inside "Info" structure
2127
2128     // Walk backwards to visit top-most instructions first
2129     std::reverse(ChainToBase.begin(), ChainToBase.end());
2130
2131     // Utility function which clones all instructions from "ChainToBase"
2132     // and inserts them before "InsertBefore". Returns rematerialized value
2133     // which should be used after statepoint.
2134     auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2135       Instruction *LastClonedValue = nullptr;
2136       Instruction *LastValue = nullptr;
2137       for (Instruction *Instr: ChainToBase) {
2138         // Only GEP's and casts are suported as we need to be careful to not
2139         // introduce any new uses of pointers not in the liveset.
2140         // Note that it's fine to introduce new uses of pointers which were
2141         // otherwise not used after this statepoint.
2142         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2143
2144         Instruction *ClonedValue = Instr->clone();
2145         ClonedValue->insertBefore(InsertBefore);
2146         ClonedValue->setName(Instr->getName() + ".remat");
2147
2148         // If it is not first instruction in the chain then it uses previously
2149         // cloned value. We should update it to use cloned value.
2150         if (LastClonedValue) {
2151           assert(LastValue);
2152           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2153 #ifndef NDEBUG
2154           // Assert that cloned instruction does not use any instructions from
2155           // this chain other than LastClonedValue
2156           for (auto OpValue : ClonedValue->operand_values()) {
2157             assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2158                        ChainToBase.end() &&
2159                    "incorrect use in rematerialization chain");
2160           }
2161 #endif
2162         }
2163
2164         LastClonedValue = ClonedValue;
2165         LastValue = Instr;
2166       }
2167       assert(LastClonedValue);
2168       return LastClonedValue;
2169     };
2170
2171     // Different cases for calls and invokes. For invokes we need to clone
2172     // instructions both on normal and unwind path.
2173     if (CS.isCall()) {
2174       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2175       assert(InsertBefore);
2176       Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2177       Info.RematerializedValues[RematerializedValue] = LiveValue;
2178     } else {
2179       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2180
2181       Instruction *NormalInsertBefore =
2182           Invoke->getNormalDest()->getFirstInsertionPt();
2183       Instruction *UnwindInsertBefore =
2184           Invoke->getUnwindDest()->getFirstInsertionPt();
2185
2186       Instruction *NormalRematerializedValue =
2187           rematerializeChain(NormalInsertBefore);
2188       Instruction *UnwindRematerializedValue =
2189           rematerializeChain(UnwindInsertBefore);
2190
2191       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2192       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2193     }
2194   }
2195
2196   // Remove rematerializaed values from the live set
2197   for (auto LiveValue: LiveValuesToBeDeleted) {
2198     Info.liveset.erase(LiveValue);
2199   }
2200 }
2201
2202 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
2203                               SmallVectorImpl<CallSite> &toUpdate) {
2204 #ifndef NDEBUG
2205   // sanity check the input
2206   std::set<CallSite> uniqued;
2207   uniqued.insert(toUpdate.begin(), toUpdate.end());
2208   assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2209
2210   for (size_t i = 0; i < toUpdate.size(); i++) {
2211     CallSite &CS = toUpdate[i];
2212     assert(CS.getInstruction()->getParent()->getParent() == &F);
2213     assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2214   }
2215 #endif
2216
2217   // When inserting gc.relocates for invokes, we need to be able to insert at
2218   // the top of the successor blocks.  See the comment on
2219   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2220   // may restructure the CFG.
2221   for (CallSite CS : toUpdate) {
2222     if (!CS.isInvoke())
2223       continue;
2224     InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2225     normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
2226                                 DT);
2227     normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
2228                                 DT);
2229   }
2230
2231   // A list of dummy calls added to the IR to keep various values obviously
2232   // live in the IR.  We'll remove all of these when done.
2233   SmallVector<CallInst *, 64> holders;
2234
2235   // Insert a dummy call with all of the arguments to the vm_state we'll need
2236   // for the actual safepoint insertion.  This ensures reference arguments in
2237   // the deopt argument list are considered live through the safepoint (and
2238   // thus makes sure they get relocated.)
2239   for (size_t i = 0; i < toUpdate.size(); i++) {
2240     CallSite &CS = toUpdate[i];
2241     Statepoint StatepointCS(CS);
2242
2243     SmallVector<Value *, 64> DeoptValues;
2244     for (Use &U : StatepointCS.vm_state_args()) {
2245       Value *Arg = cast<Value>(&U);
2246       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2247              "support for FCA unimplemented");
2248       if (isHandledGCPointerType(Arg->getType()))
2249         DeoptValues.push_back(Arg);
2250     }
2251     insertUseHolderAfter(CS, DeoptValues, holders);
2252   }
2253
2254   SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
2255   records.reserve(toUpdate.size());
2256   for (size_t i = 0; i < toUpdate.size(); i++) {
2257     struct PartiallyConstructedSafepointRecord info;
2258     records.push_back(info);
2259   }
2260   assert(records.size() == toUpdate.size());
2261
2262   // A) Identify all gc pointers which are statically live at the given call
2263   // site.
2264   findLiveReferences(F, DT, P, toUpdate, records);
2265
2266   // B) Find the base pointers for each live pointer
2267   /* scope for caching */ {
2268     // Cache the 'defining value' relation used in the computation and
2269     // insertion of base phis and selects.  This ensures that we don't insert
2270     // large numbers of duplicate base_phis.
2271     DefiningValueMapTy DVCache;
2272
2273     for (size_t i = 0; i < records.size(); i++) {
2274       struct PartiallyConstructedSafepointRecord &info = records[i];
2275       CallSite &CS = toUpdate[i];
2276       findBasePointers(DT, DVCache, CS, info);
2277     }
2278   } // end of cache scope
2279
2280   // The base phi insertion logic (for any safepoint) may have inserted new
2281   // instructions which are now live at some safepoint.  The simplest such
2282   // example is:
2283   // loop:
2284   //   phi a  <-- will be a new base_phi here
2285   //   safepoint 1 <-- that needs to be live here
2286   //   gep a + 1
2287   //   safepoint 2
2288   //   br loop
2289   // We insert some dummy calls after each safepoint to definitely hold live
2290   // the base pointers which were identified for that safepoint.  We'll then
2291   // ask liveness for _every_ base inserted to see what is now live.  Then we
2292   // remove the dummy calls.
2293   holders.reserve(holders.size() + records.size());
2294   for (size_t i = 0; i < records.size(); i++) {
2295     struct PartiallyConstructedSafepointRecord &info = records[i];
2296     CallSite &CS = toUpdate[i];
2297
2298     SmallVector<Value *, 128> Bases;
2299     for (auto Pair : info.PointerToBase) {
2300       Bases.push_back(Pair.second);
2301     }
2302     insertUseHolderAfter(CS, Bases, holders);
2303   }
2304
2305   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2306   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2307   // not the key issue.
2308   recomputeLiveInValues(F, DT, P, toUpdate, records);
2309
2310   if (PrintBasePointers) {
2311     for (size_t i = 0; i < records.size(); i++) {
2312       struct PartiallyConstructedSafepointRecord &info = records[i];
2313       errs() << "Base Pairs: (w/Relocation)\n";
2314       for (auto Pair : info.PointerToBase) {
2315         errs() << " derived %" << Pair.first->getName() << " base %"
2316                << Pair.second->getName() << "\n";
2317       }
2318     }
2319   }
2320   for (size_t i = 0; i < holders.size(); i++) {
2321     holders[i]->eraseFromParent();
2322     holders[i] = nullptr;
2323   }
2324   holders.clear();
2325
2326   // Do a limited scalarization of any live at safepoint vector values which
2327   // contain pointers.  This enables this pass to run after vectorization at
2328   // the cost of some possible performance loss.  TODO: it would be nice to
2329   // natively support vectors all the way through the backend so we don't need
2330   // to scalarize here.
2331   for (size_t i = 0; i < records.size(); i++) {
2332     struct PartiallyConstructedSafepointRecord &info = records[i];
2333     Instruction *statepoint = toUpdate[i].getInstruction();
2334     splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2335                       info.PointerToBase, DT);
2336   }
2337
2338   // In order to reduce live set of statepoint we might choose to rematerialize
2339   // some values instead of relocating them. This is purely an optimization and
2340   // does not influence correctness.
2341   TargetTransformInfo &TTI =
2342     P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2343
2344   for (size_t i = 0; i < records.size(); i++) {
2345     struct PartiallyConstructedSafepointRecord &info = records[i];
2346     CallSite &CS = toUpdate[i];
2347
2348     rematerializeLiveValues(CS, info, TTI);
2349   }
2350
2351   // Now run through and replace the existing statepoints with new ones with
2352   // the live variables listed.  We do not yet update uses of the values being
2353   // relocated. We have references to live variables that need to
2354   // survive to the last iteration of this loop.  (By construction, the
2355   // previous statepoint can not be a live variable, thus we can and remove
2356   // the old statepoint calls as we go.)
2357   for (size_t i = 0; i < records.size(); i++) {
2358     struct PartiallyConstructedSafepointRecord &info = records[i];
2359     CallSite &CS = toUpdate[i];
2360     makeStatepointExplicit(DT, CS, P, info);
2361   }
2362   toUpdate.clear(); // prevent accident use of invalid CallSites
2363
2364   // Do all the fixups of the original live variables to their relocated selves
2365   SmallVector<Value *, 128> live;
2366   for (size_t i = 0; i < records.size(); i++) {
2367     struct PartiallyConstructedSafepointRecord &info = records[i];
2368     // We can't simply save the live set from the original insertion.  One of
2369     // the live values might be the result of a call which needs a safepoint.
2370     // That Value* no longer exists and we need to use the new gc_result.
2371     // Thankfully, the liveset is embedded in the statepoint (and updated), so
2372     // we just grab that.
2373     Statepoint statepoint(info.StatepointToken);
2374     live.insert(live.end(), statepoint.gc_args_begin(),
2375                 statepoint.gc_args_end());
2376 #ifndef NDEBUG
2377     // Do some basic sanity checks on our liveness results before performing
2378     // relocation.  Relocation can and will turn mistakes in liveness results
2379     // into non-sensical code which is must harder to debug.
2380     // TODO: It would be nice to test consistency as well
2381     assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2382            "statepoint must be reachable or liveness is meaningless");
2383     for (Value *V : statepoint.gc_args()) {
2384       if (!isa<Instruction>(V))
2385         // Non-instruction values trivial dominate all possible uses
2386         continue;
2387       auto LiveInst = cast<Instruction>(V);
2388       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2389              "unreachable values should never be live");
2390       assert(DT.dominates(LiveInst, info.StatepointToken) &&
2391              "basic SSA liveness expectation violated by liveness analysis");
2392     }
2393 #endif
2394   }
2395   unique_unsorted(live);
2396
2397 #ifndef NDEBUG
2398   // sanity check
2399   for (auto ptr : live) {
2400     assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2401   }
2402 #endif
2403
2404   relocationViaAlloca(F, DT, live, records);
2405   return !records.empty();
2406 }
2407
2408 // Handles both return values and arguments for Functions and CallSites.
2409 template <typename AttrHolder>
2410 static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2411                                    unsigned Index) {
2412   AttrBuilder R;
2413   if (AH.getDereferenceableBytes(Index))
2414     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2415                                   AH.getDereferenceableBytes(Index)));
2416   if (AH.getDereferenceableOrNullBytes(Index))
2417     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2418                                   AH.getDereferenceableOrNullBytes(Index)));
2419
2420   if (!R.empty())
2421     AH.setAttributes(AH.getAttributes().removeAttributes(
2422         Ctx, Index, AttributeSet::get(Ctx, Index, R)));
2423 }
2424
2425 void
2426 RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2427   LLVMContext &Ctx = F.getContext();
2428
2429   for (Argument &A : F.args())
2430     if (isa<PointerType>(A.getType()))
2431       RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2432
2433   if (isa<PointerType>(F.getReturnType()))
2434     RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2435 }
2436
2437 void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2438   if (F.empty())
2439     return;
2440
2441   LLVMContext &Ctx = F.getContext();
2442   MDBuilder Builder(Ctx);
2443
2444   for (Instruction &I : instructions(F)) {
2445     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2446       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2447       bool IsImmutableTBAA =
2448           MD->getNumOperands() == 4 &&
2449           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2450
2451       if (!IsImmutableTBAA)
2452         continue; // no work to do, MD_tbaa is already marked mutable
2453
2454       MDNode *Base = cast<MDNode>(MD->getOperand(0));
2455       MDNode *Access = cast<MDNode>(MD->getOperand(1));
2456       uint64_t Offset =
2457           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2458
2459       MDNode *MutableTBAA =
2460           Builder.createTBAAStructTagNode(Base, Access, Offset);
2461       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2462     }
2463
2464     if (CallSite CS = CallSite(&I)) {
2465       for (int i = 0, e = CS.arg_size(); i != e; i++)
2466         if (isa<PointerType>(CS.getArgument(i)->getType()))
2467           RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2468       if (isa<PointerType>(CS.getType()))
2469         RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2470     }
2471   }
2472 }
2473
2474 /// Returns true if this function should be rewritten by this pass.  The main
2475 /// point of this function is as an extension point for custom logic.
2476 static bool shouldRewriteStatepointsIn(Function &F) {
2477   // TODO: This should check the GCStrategy
2478   if (F.hasGC()) {
2479     const char *FunctionGCName = F.getGC();
2480     const StringRef StatepointExampleName("statepoint-example");
2481     const StringRef CoreCLRName("coreclr");
2482     return (StatepointExampleName == FunctionGCName) ||
2483            (CoreCLRName == FunctionGCName);
2484   } else
2485     return false;
2486 }
2487
2488 void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2489 #ifndef NDEBUG
2490   assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2491          "precondition!");
2492 #endif
2493
2494   for (Function &F : M)
2495     stripDereferenceabilityInfoFromPrototype(F);
2496
2497   for (Function &F : M)
2498     stripDereferenceabilityInfoFromBody(F);
2499 }
2500
2501 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2502   // Nothing to do for declarations.
2503   if (F.isDeclaration() || F.empty())
2504     return false;
2505
2506   // Policy choice says not to rewrite - the most common reason is that we're
2507   // compiling code without a GCStrategy.
2508   if (!shouldRewriteStatepointsIn(F))
2509     return false;
2510
2511   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2512
2513   // Gather all the statepoints which need rewritten.  Be careful to only
2514   // consider those in reachable code since we need to ask dominance queries
2515   // when rewriting.  We'll delete the unreachable ones in a moment.
2516   SmallVector<CallSite, 64> ParsePointNeeded;
2517   bool HasUnreachableStatepoint = false;
2518   for (Instruction &I : instructions(F)) {
2519     // TODO: only the ones with the flag set!
2520     if (isStatepoint(I)) {
2521       if (DT.isReachableFromEntry(I.getParent()))
2522         ParsePointNeeded.push_back(CallSite(&I));
2523       else
2524         HasUnreachableStatepoint = true;
2525     }
2526   }
2527
2528   bool MadeChange = false;
2529
2530   // Delete any unreachable statepoints so that we don't have unrewritten
2531   // statepoints surviving this pass.  This makes testing easier and the
2532   // resulting IR less confusing to human readers.  Rather than be fancy, we
2533   // just reuse a utility function which removes the unreachable blocks.
2534   if (HasUnreachableStatepoint)
2535     MadeChange |= removeUnreachableBlocks(F);
2536
2537   // Return early if no work to do.
2538   if (ParsePointNeeded.empty())
2539     return MadeChange;
2540
2541   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2542   // These are created by LCSSA.  They have the effect of increasing the size
2543   // of liveness sets for no good reason.  It may be harder to do this post
2544   // insertion since relocations and base phis can confuse things.
2545   for (BasicBlock &BB : F)
2546     if (BB.getUniquePredecessor()) {
2547       MadeChange = true;
2548       FoldSingleEntryPHINodes(&BB);
2549     }
2550
2551   // Before we start introducing relocations, we want to tweak the IR a bit to
2552   // avoid unfortunate code generation effects.  The main example is that we 
2553   // want to try to make sure the comparison feeding a branch is after any
2554   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
2555   // values feeding a branch after relocation.  This is semantically correct,
2556   // but results in extra register pressure since both the pre-relocation and
2557   // post-relocation copies must be available in registers.  For code without
2558   // relocations this is handled elsewhere, but teaching the scheduler to
2559   // reverse the transform we're about to do would be slightly complex.
2560   // Note: This may extend the live range of the inputs to the icmp and thus
2561   // increase the liveset of any statepoint we move over.  This is profitable
2562   // as long as all statepoints are in rare blocks.  If we had in-register
2563   // lowering for live values this would be a much safer transform.
2564   auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2565     if (auto *BI = dyn_cast<BranchInst>(TI))
2566       if (BI->isConditional())
2567         return dyn_cast<Instruction>(BI->getCondition());
2568     // TODO: Extend this to handle switches
2569     return nullptr;
2570   };
2571   for (BasicBlock &BB : F) {
2572     TerminatorInst *TI = BB.getTerminator();
2573     if (auto *Cond = getConditionInst(TI))
2574       // TODO: Handle more than just ICmps here.  We should be able to move
2575       // most instructions without side effects or memory access.  
2576       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2577         MadeChange = true;
2578         Cond->moveBefore(TI);
2579       }
2580   }
2581
2582   MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2583   return MadeChange;
2584 }
2585
2586 // liveness computation via standard dataflow
2587 // -------------------------------------------------------------------
2588
2589 // TODO: Consider using bitvectors for liveness, the set of potentially
2590 // interesting values should be small and easy to pre-compute.
2591
2592 /// Compute the live-in set for the location rbegin starting from
2593 /// the live-out set of the basic block
2594 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2595                                 BasicBlock::reverse_iterator rend,
2596                                 DenseSet<Value *> &LiveTmp) {
2597
2598   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2599     Instruction *I = &*ritr;
2600
2601     // KILL/Def - Remove this definition from LiveIn
2602     LiveTmp.erase(I);
2603
2604     // Don't consider *uses* in PHI nodes, we handle their contribution to
2605     // predecessor blocks when we seed the LiveOut sets
2606     if (isa<PHINode>(I))
2607       continue;
2608
2609     // USE - Add to the LiveIn set for this instruction
2610     for (Value *V : I->operands()) {
2611       assert(!isUnhandledGCPointerType(V->getType()) &&
2612              "support for FCA unimplemented");
2613       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2614         // The choice to exclude all things constant here is slightly subtle.
2615         // There are two independent reasons:
2616         // - We assume that things which are constant (from LLVM's definition)
2617         // do not move at runtime.  For example, the address of a global
2618         // variable is fixed, even though it's contents may not be.
2619         // - Second, we can't disallow arbitrary inttoptr constants even
2620         // if the language frontend does.  Optimization passes are free to
2621         // locally exploit facts without respect to global reachability.  This
2622         // can create sections of code which are dynamically unreachable and
2623         // contain just about anything.  (see constants.ll in tests)
2624         LiveTmp.insert(V);
2625       }
2626     }
2627   }
2628 }
2629
2630 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2631
2632   for (BasicBlock *Succ : successors(BB)) {
2633     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2634     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2635       PHINode *Phi = cast<PHINode>(&*I);
2636       Value *V = Phi->getIncomingValueForBlock(BB);
2637       assert(!isUnhandledGCPointerType(V->getType()) &&
2638              "support for FCA unimplemented");
2639       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2640         LiveTmp.insert(V);
2641       }
2642     }
2643   }
2644 }
2645
2646 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2647   DenseSet<Value *> KillSet;
2648   for (Instruction &I : *BB)
2649     if (isHandledGCPointerType(I.getType()))
2650       KillSet.insert(&I);
2651   return KillSet;
2652 }
2653
2654 #ifndef NDEBUG
2655 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2656 /// sanity check for the liveness computation.
2657 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2658                           TerminatorInst *TI, bool TermOkay = false) {
2659   for (Value *V : Live) {
2660     if (auto *I = dyn_cast<Instruction>(V)) {
2661       // The terminator can be a member of the LiveOut set.  LLVM's definition
2662       // of instruction dominance states that V does not dominate itself.  As
2663       // such, we need to special case this to allow it.
2664       if (TermOkay && TI == I)
2665         continue;
2666       assert(DT.dominates(I, TI) &&
2667              "basic SSA liveness expectation violated by liveness analysis");
2668     }
2669   }
2670 }
2671
2672 /// Check that all the liveness sets used during the computation of liveness
2673 /// obey basic SSA properties.  This is useful for finding cases where we miss
2674 /// a def.
2675 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2676                           BasicBlock &BB) {
2677   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2678   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2679   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2680 }
2681 #endif
2682
2683 static void computeLiveInValues(DominatorTree &DT, Function &F,
2684                                 GCPtrLivenessData &Data) {
2685
2686   SmallSetVector<BasicBlock *, 200> Worklist;
2687   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2688     // We use a SetVector so that we don't have duplicates in the worklist.
2689     Worklist.insert(pred_begin(BB), pred_end(BB));
2690   };
2691   auto NextItem = [&]() {
2692     BasicBlock *BB = Worklist.back();
2693     Worklist.pop_back();
2694     return BB;
2695   };
2696
2697   // Seed the liveness for each individual block
2698   for (BasicBlock &BB : F) {
2699     Data.KillSet[&BB] = computeKillSet(&BB);
2700     Data.LiveSet[&BB].clear();
2701     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2702
2703 #ifndef NDEBUG
2704     for (Value *Kill : Data.KillSet[&BB])
2705       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2706 #endif
2707
2708     Data.LiveOut[&BB] = DenseSet<Value *>();
2709     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2710     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2711     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2712     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2713     if (!Data.LiveIn[&BB].empty())
2714       AddPredsToWorklist(&BB);
2715   }
2716
2717   // Propagate that liveness until stable
2718   while (!Worklist.empty()) {
2719     BasicBlock *BB = NextItem();
2720
2721     // Compute our new liveout set, then exit early if it hasn't changed
2722     // despite the contribution of our successor.
2723     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2724     const auto OldLiveOutSize = LiveOut.size();
2725     for (BasicBlock *Succ : successors(BB)) {
2726       assert(Data.LiveIn.count(Succ));
2727       set_union(LiveOut, Data.LiveIn[Succ]);
2728     }
2729     // assert OutLiveOut is a subset of LiveOut
2730     if (OldLiveOutSize == LiveOut.size()) {
2731       // If the sets are the same size, then we didn't actually add anything
2732       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2733       // hasn't changed.
2734       continue;
2735     }
2736     Data.LiveOut[BB] = LiveOut;
2737
2738     // Apply the effects of this basic block
2739     DenseSet<Value *> LiveTmp = LiveOut;
2740     set_union(LiveTmp, Data.LiveSet[BB]);
2741     set_subtract(LiveTmp, Data.KillSet[BB]);
2742
2743     assert(Data.LiveIn.count(BB));
2744     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2745     // assert: OldLiveIn is a subset of LiveTmp
2746     if (OldLiveIn.size() != LiveTmp.size()) {
2747       Data.LiveIn[BB] = LiveTmp;
2748       AddPredsToWorklist(BB);
2749     }
2750   } // while( !worklist.empty() )
2751
2752 #ifndef NDEBUG
2753   // Sanity check our output against SSA properties.  This helps catch any
2754   // missing kills during the above iteration.
2755   for (BasicBlock &BB : F) {
2756     checkBasicSSA(DT, Data, BB);
2757   }
2758 #endif
2759 }
2760
2761 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2762                               StatepointLiveSetTy &Out) {
2763
2764   BasicBlock *BB = Inst->getParent();
2765
2766   // Note: The copy is intentional and required
2767   assert(Data.LiveOut.count(BB));
2768   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2769
2770   // We want to handle the statepoint itself oddly.  It's
2771   // call result is not live (normal), nor are it's arguments
2772   // (unless they're used again later).  This adjustment is
2773   // specifically what we need to relocate
2774   BasicBlock::reverse_iterator rend(Inst);
2775   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2776   LiveOut.erase(Inst);
2777   Out.insert(LiveOut.begin(), LiveOut.end());
2778 }
2779
2780 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2781                                   const CallSite &CS,
2782                                   PartiallyConstructedSafepointRecord &Info) {
2783   Instruction *Inst = CS.getInstruction();
2784   StatepointLiveSetTy Updated;
2785   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2786
2787 #ifndef NDEBUG
2788   DenseSet<Value *> Bases;
2789   for (auto KVPair : Info.PointerToBase) {
2790     Bases.insert(KVPair.second);
2791   }
2792 #endif
2793   // We may have base pointers which are now live that weren't before.  We need
2794   // to update the PointerToBase structure to reflect this.
2795   for (auto V : Updated)
2796     if (!Info.PointerToBase.count(V)) {
2797       assert(Bases.count(V) && "can't find base for unexpected live value");
2798       Info.PointerToBase[V] = V;
2799       continue;
2800     }
2801
2802 #ifndef NDEBUG
2803   for (auto V : Updated) {
2804     assert(Info.PointerToBase.count(V) &&
2805            "must be able to find base for live value");
2806   }
2807 #endif
2808
2809   // Remove any stale base mappings - this can happen since our liveness is
2810   // more precise then the one inherent in the base pointer analysis
2811   DenseSet<Value *> ToErase;
2812   for (auto KVPair : Info.PointerToBase)
2813     if (!Updated.count(KVPair.first))
2814       ToErase.insert(KVPair.first);
2815   for (auto V : ToErase)
2816     Info.PointerToBase.erase(V);
2817
2818 #ifndef NDEBUG
2819   for (auto KVPair : Info.PointerToBase)
2820     assert(Updated.count(KVPair.first) && "record for non-live value");
2821 #endif
2822
2823   Info.liveset = Updated;
2824 }