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