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