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