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