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