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 (Attr.hasAttribute("statepoint-num-patch-bytes") ||
1191             Attr.hasAttribute("statepoint-id"))
1192           continue;
1193 
1194         Ret = Ret.addAttributes(
1195             AS.getContext(), Index,
1196             AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
1197       }
1198     }
1199 
1200     // Just skip parameter attributes for now
1201   }
1202 
1203   return Ret;
1204 }
1205 
1206 /// Helper function to place all gc relocates necessary for the given
1207 /// statepoint.
1208 /// Inputs:
1209 ///   liveVariables - list of variables to be relocated.
1210 ///   liveStart - index of the first live variable.
1211 ///   basePtrs - base pointers.
1212 ///   statepointToken - statepoint instruction to which relocates should be
1213 ///   bound.
1214 ///   Builder - Llvm IR builder to be used to construct new calls.
1215 static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1216                               const int LiveStart,
1217                               ArrayRef<Value *> BasePtrs,
1218                               Instruction *StatepointToken,
1219                               IRBuilder<> Builder) {
1220   if (LiveVariables.empty())
1221     return;
1222 
1223   auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1224     auto ValIt = std::find(LiveVec.begin(), LiveVec.end(), Val);
1225     assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1226     size_t Index = std::distance(LiveVec.begin(), ValIt);
1227     assert(Index < LiveVec.size() && "Bug in std::find?");
1228     return Index;
1229   };
1230   Module *M = StatepointToken->getModule();
1231 
1232   // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1233   // element type is i8 addrspace(1)*). We originally generated unique
1234   // declarations for each pointer type, but this proved problematic because
1235   // the intrinsic mangling code is incomplete and fragile.  Since we're moving
1236   // towards a single unified pointer type anyways, we can just cast everything
1237   // to an i8* of the right address space.  A bitcast is added later to convert
1238   // gc_relocate to the actual value's type.
1239   auto getGCRelocateDecl = [&] (Type *Ty) {
1240     assert(isHandledGCPointerType(Ty));
1241     auto AS = Ty->getScalarType()->getPointerAddressSpace();
1242     Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1243     if (auto *VT = dyn_cast<VectorType>(Ty))
1244       NewTy = VectorType::get(NewTy, VT->getNumElements());
1245     return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1246                                      {NewTy});
1247   };
1248 
1249   // Lazily populated map from input types to the canonicalized form mentioned
1250   // in the comment above.  This should probably be cached somewhere more
1251   // broadly.
1252   DenseMap<Type*, Value*> TypeToDeclMap;
1253 
1254   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1255     // Generate the gc.relocate call and save the result
1256     Value *BaseIdx =
1257       Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
1258     Value *LiveIdx = Builder.getInt32(LiveStart + i);
1259 
1260     Type *Ty = LiveVariables[i]->getType();
1261     if (!TypeToDeclMap.count(Ty))
1262       TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1263     Value *GCRelocateDecl = TypeToDeclMap[Ty];
1264 
1265     // only specify a debug name if we can give a useful one
1266     CallInst *Reloc = Builder.CreateCall(
1267         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1268         suffixed_name_or(LiveVariables[i], ".relocated", ""));
1269     // Trick CodeGen into thinking there are lots of free registers at this
1270     // fake call.
1271     Reloc->setCallingConv(CallingConv::Cold);
1272   }
1273 }
1274 
1275 namespace {
1276 
1277 /// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
1278 /// avoids having to worry about keeping around dangling pointers to Values.
1279 class DeferredReplacement {
1280   AssertingVH<Instruction> Old;
1281   AssertingVH<Instruction> New;
1282 
1283 public:
1284   explicit DeferredReplacement(Instruction *Old, Instruction *New) :
1285     Old(Old), New(New) {
1286     assert(Old != New && "Not allowed!");
1287   }
1288 
1289   /// Does the task represented by this instance.
1290   void doReplacement() {
1291     Instruction *OldI = Old;
1292     Instruction *NewI = New;
1293 
1294     assert(OldI != NewI && "Disallowed at construction?!");
1295 
1296     Old = nullptr;
1297     New = nullptr;
1298 
1299     if (NewI)
1300       OldI->replaceAllUsesWith(NewI);
1301     OldI->eraseFromParent();
1302   }
1303 };
1304 }
1305 
1306 static void
1307 makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1308                            const SmallVectorImpl<Value *> &BasePtrs,
1309                            const SmallVectorImpl<Value *> &LiveVariables,
1310                            PartiallyConstructedSafepointRecord &Result,
1311                            std::vector<DeferredReplacement> &Replacements) {
1312   assert(BasePtrs.size() == LiveVariables.size());
1313 
1314   // Then go ahead and use the builder do actually do the inserts.  We insert
1315   // immediately before the previous instruction under the assumption that all
1316   // arguments will be available here.  We can't insert afterwards since we may
1317   // be replacing a terminator.
1318   Instruction *InsertBefore = CS.getInstruction();
1319   IRBuilder<> Builder(InsertBefore);
1320 
1321   ArrayRef<Value *> GCArgs(LiveVariables);
1322   uint64_t StatepointID = 0xABCDEF00;
1323   uint32_t NumPatchBytes = 0;
1324   uint32_t Flags = uint32_t(StatepointFlags::None);
1325 
1326   ArrayRef<Use> CallArgs(CS.arg_begin(), CS.arg_end());
1327   ArrayRef<Use> DeoptArgs = GetDeoptBundleOperands(CS);
1328   ArrayRef<Use> TransitionArgs;
1329   if (auto TransitionBundle =
1330       CS.getOperandBundle(LLVMContext::OB_gc_transition)) {
1331     Flags |= uint32_t(StatepointFlags::GCTransition);
1332     TransitionArgs = TransitionBundle->Inputs;
1333   }
1334 
1335   Value *CallTarget = CS.getCalledValue();
1336   AttributeSet OriginalAttrs = CS.getAttributes();
1337   Attribute AttrID = OriginalAttrs.getAttribute(AttributeSet::FunctionIndex,
1338                                                 "statepoint-id");
1339   if (AttrID.isStringAttribute())
1340     AttrID.getValueAsString().getAsInteger(10, StatepointID);
1341 
1342   Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
1343     AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
1344   if (AttrNumPatchBytes.isStringAttribute())
1345     AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
1346 
1347   // Create the statepoint given all the arguments
1348   Instruction *Token = nullptr;
1349   AttributeSet ReturnAttrs;
1350   if (CS.isCall()) {
1351     CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
1352     CallInst *Call = Builder.CreateGCStatepointCall(
1353         StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1354         TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1355 
1356     Call->setTailCall(ToReplace->isTailCall());
1357     Call->setCallingConv(ToReplace->getCallingConv());
1358 
1359     // Currently we will fail on parameter attributes and on certain
1360     // function attributes.
1361     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
1362     // In case if we can handle this set of attributes - set up function attrs
1363     // directly on statepoint and return attrs later for gc_result intrinsic.
1364     Call->setAttributes(NewAttrs.getFnAttributes());
1365     ReturnAttrs = NewAttrs.getRetAttributes();
1366 
1367     Token = Call;
1368 
1369     // Put the following gc_result and gc_relocate calls immediately after the
1370     // the old call (which we're about to delete)
1371     assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1372     Builder.SetInsertPoint(ToReplace->getNextNode());
1373     Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
1374   } else {
1375     InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
1376 
1377     // Insert the new invoke into the old block.  We'll remove the old one in a
1378     // moment at which point this will become the new terminator for the
1379     // original block.
1380     InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1381         StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1382         ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1383         GCArgs, "statepoint_token");
1384 
1385     Invoke->setCallingConv(ToReplace->getCallingConv());
1386 
1387     // Currently we will fail on parameter attributes and on certain
1388     // function attributes.
1389     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
1390     // In case if we can handle this set of attributes - set up function attrs
1391     // directly on statepoint and return attrs later for gc_result intrinsic.
1392     Invoke->setAttributes(NewAttrs.getFnAttributes());
1393     ReturnAttrs = NewAttrs.getRetAttributes();
1394 
1395     Token = Invoke;
1396 
1397     // Generate gc relocates in exceptional path
1398     BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1399     assert(!isa<PHINode>(UnwindBlock->begin()) &&
1400            UnwindBlock->getUniquePredecessor() &&
1401            "can't safely insert in this block!");
1402 
1403     Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
1404     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1405 
1406     // Attach exceptional gc relocates to the landingpad.
1407     Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
1408     Result.UnwindToken = ExceptionalToken;
1409 
1410     const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
1411     CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1412                       Builder);
1413 
1414     // Generate gc relocates and returns for normal block
1415     BasicBlock *NormalDest = ToReplace->getNormalDest();
1416     assert(!isa<PHINode>(NormalDest->begin()) &&
1417            NormalDest->getUniquePredecessor() &&
1418            "can't safely insert in this block!");
1419 
1420     Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
1421 
1422     // gc relocates will be generated later as if it were regular call
1423     // statepoint
1424   }
1425   assert(Token && "Should be set in one of the above branches!");
1426 
1427   Token->setName("statepoint_token");
1428   if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1429     StringRef Name =
1430       CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1431     CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
1432     GCResult->setAttributes(CS.getAttributes().getRetAttributes());
1433 
1434     // We cannot RAUW or delete CS.getInstruction() because it could be in the
1435     // live set of some other safepoint, in which case that safepoint's
1436     // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1437     // llvm::Instruction.  Instead, we defer the replacement and deletion to
1438     // after the live sets have been made explicit in the IR, and we no longer
1439     // have raw pointers to worry about.
1440     Replacements.emplace_back(CS.getInstruction(), GCResult);
1441   } else {
1442     Replacements.emplace_back(CS.getInstruction(), nullptr);
1443   }
1444 
1445   Result.StatepointToken = Token;
1446 
1447   // Second, create a gc.relocate for every live variable
1448   const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
1449   CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
1450 }
1451 
1452 static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
1453                            SmallVectorImpl<Value *> &LiveVec) {
1454   assert(BaseVec.size() == LiveVec.size());
1455 
1456   struct BaseDerivedPair {
1457     Value *Base;
1458     Value *Derived;
1459   };
1460 
1461   SmallVector<BaseDerivedPair, 64> NameOrdering;
1462   NameOrdering.reserve(BaseVec.size());
1463 
1464   for (size_t i = 0, e = BaseVec.size(); i < e; i++)
1465     NameOrdering.push_back({BaseVec[i], LiveVec[i]});
1466 
1467   std::sort(NameOrdering.begin(), NameOrdering.end(),
1468             [](const BaseDerivedPair &L, const BaseDerivedPair &R) {
1469               return L.Derived->getName() < R.Derived->getName();
1470             });
1471 
1472   for (size_t i = 0; i < BaseVec.size(); i++) {
1473     BaseVec[i] = NameOrdering[i].Base;
1474     LiveVec[i] = NameOrdering[i].Derived;
1475   }
1476 }
1477 
1478 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1479 // which make the relocations happening at this safepoint explicit.
1480 //
1481 // WARNING: Does not do any fixup to adjust users of the original live
1482 // values.  That's the callers responsibility.
1483 static void
1484 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
1485                        PartiallyConstructedSafepointRecord &Result,
1486                        std::vector<DeferredReplacement> &Replacements) {
1487   const auto &LiveSet = Result.LiveSet;
1488   const auto &PointerToBase = Result.PointerToBase;
1489 
1490   // Convert to vector for efficient cross referencing.
1491   SmallVector<Value *, 64> BaseVec, LiveVec;
1492   LiveVec.reserve(LiveSet.size());
1493   BaseVec.reserve(LiveSet.size());
1494   for (Value *L : LiveSet) {
1495     LiveVec.push_back(L);
1496     assert(PointerToBase.count(L));
1497     Value *Base = PointerToBase.find(L)->second;
1498     BaseVec.push_back(Base);
1499   }
1500   assert(LiveVec.size() == BaseVec.size());
1501 
1502   // To make the output IR slightly more stable (for use in diffs), ensure a
1503   // fixed order of the values in the safepoint (by sorting the value name).
1504   // The order is otherwise meaningless.
1505   StabilizeOrder(BaseVec, LiveVec);
1506 
1507   // Do the actual rewriting and delete the old statepoint
1508   makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
1509 }
1510 
1511 // Helper function for the relocationViaAlloca.
1512 //
1513 // It receives iterator to the statepoint gc relocates and emits a store to the
1514 // assigned location (via allocaMap) for the each one of them.  It adds the
1515 // visited values into the visitedLiveValues set, which we will later use them
1516 // for sanity checking.
1517 static void
1518 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1519                        DenseMap<Value *, Value *> &AllocaMap,
1520                        DenseSet<Value *> &VisitedLiveValues) {
1521 
1522   for (User *U : GCRelocs) {
1523     GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1524     if (!Relocate)
1525       continue;
1526 
1527     Value *OriginalValue = Relocate->getDerivedPtr();
1528     assert(AllocaMap.count(OriginalValue));
1529     Value *Alloca = AllocaMap[OriginalValue];
1530 
1531     // Emit store into the related alloca
1532     // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1533     // the correct type according to alloca.
1534     assert(Relocate->getNextNode() &&
1535            "Should always have one since it's not a terminator");
1536     IRBuilder<> Builder(Relocate->getNextNode());
1537     Value *CastedRelocatedValue =
1538       Builder.CreateBitCast(Relocate,
1539                             cast<AllocaInst>(Alloca)->getAllocatedType(),
1540                             suffixed_name_or(Relocate, ".casted", ""));
1541 
1542     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1543     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1544 
1545 #ifndef NDEBUG
1546     VisitedLiveValues.insert(OriginalValue);
1547 #endif
1548   }
1549 }
1550 
1551 // Helper function for the "relocationViaAlloca". Similar to the
1552 // "insertRelocationStores" but works for rematerialized values.
1553 static void insertRematerializationStores(
1554     const RematerializedValueMapTy &RematerializedValues,
1555     DenseMap<Value *, Value *> &AllocaMap,
1556     DenseSet<Value *> &VisitedLiveValues) {
1557 
1558   for (auto RematerializedValuePair: RematerializedValues) {
1559     Instruction *RematerializedValue = RematerializedValuePair.first;
1560     Value *OriginalValue = RematerializedValuePair.second;
1561 
1562     assert(AllocaMap.count(OriginalValue) &&
1563            "Can not find alloca for rematerialized value");
1564     Value *Alloca = AllocaMap[OriginalValue];
1565 
1566     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1567     Store->insertAfter(RematerializedValue);
1568 
1569 #ifndef NDEBUG
1570     VisitedLiveValues.insert(OriginalValue);
1571 #endif
1572   }
1573 }
1574 
1575 /// Do all the relocation update via allocas and mem2reg
1576 static void relocationViaAlloca(
1577     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1578     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1579 #ifndef NDEBUG
1580   // record initial number of (static) allocas; we'll check we have the same
1581   // number when we get done.
1582   int InitialAllocaNum = 0;
1583   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1584        I++)
1585     if (isa<AllocaInst>(*I))
1586       InitialAllocaNum++;
1587 #endif
1588 
1589   // TODO-PERF: change data structures, reserve
1590   DenseMap<Value *, Value *> AllocaMap;
1591   SmallVector<AllocaInst *, 200> PromotableAllocas;
1592   // Used later to chack that we have enough allocas to store all values
1593   std::size_t NumRematerializedValues = 0;
1594   PromotableAllocas.reserve(Live.size());
1595 
1596   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1597   // "PromotableAllocas"
1598   auto emitAllocaFor = [&](Value *LiveValue) {
1599     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1600                                         F.getEntryBlock().getFirstNonPHI());
1601     AllocaMap[LiveValue] = Alloca;
1602     PromotableAllocas.push_back(Alloca);
1603   };
1604 
1605   // Emit alloca for each live gc pointer
1606   for (Value *V : Live)
1607     emitAllocaFor(V);
1608 
1609   // Emit allocas for rematerialized values
1610   for (const auto &Info : Records)
1611     for (auto RematerializedValuePair : Info.RematerializedValues) {
1612       Value *OriginalValue = RematerializedValuePair.second;
1613       if (AllocaMap.count(OriginalValue) != 0)
1614         continue;
1615 
1616       emitAllocaFor(OriginalValue);
1617       ++NumRematerializedValues;
1618     }
1619 
1620   // The next two loops are part of the same conceptual operation.  We need to
1621   // insert a store to the alloca after the original def and at each
1622   // redefinition.  We need to insert a load before each use.  These are split
1623   // into distinct loops for performance reasons.
1624 
1625   // Update gc pointer after each statepoint: either store a relocated value or
1626   // null (if no relocated value was found for this gc pointer and it is not a
1627   // gc_result).  This must happen before we update the statepoint with load of
1628   // alloca otherwise we lose the link between statepoint and old def.
1629   for (const auto &Info : Records) {
1630     Value *Statepoint = Info.StatepointToken;
1631 
1632     // This will be used for consistency check
1633     DenseSet<Value *> VisitedLiveValues;
1634 
1635     // Insert stores for normal statepoint gc relocates
1636     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1637 
1638     // In case if it was invoke statepoint
1639     // we will insert stores for exceptional path gc relocates.
1640     if (isa<InvokeInst>(Statepoint)) {
1641       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1642                              VisitedLiveValues);
1643     }
1644 
1645     // Do similar thing with rematerialized values
1646     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1647                                   VisitedLiveValues);
1648 
1649     if (ClobberNonLive) {
1650       // As a debugging aid, pretend that an unrelocated pointer becomes null at
1651       // the gc.statepoint.  This will turn some subtle GC problems into
1652       // slightly easier to debug SEGVs.  Note that on large IR files with
1653       // lots of gc.statepoints this is extremely costly both memory and time
1654       // wise.
1655       SmallVector<AllocaInst *, 64> ToClobber;
1656       for (auto Pair : AllocaMap) {
1657         Value *Def = Pair.first;
1658         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1659 
1660         // This value was relocated
1661         if (VisitedLiveValues.count(Def)) {
1662           continue;
1663         }
1664         ToClobber.push_back(Alloca);
1665       }
1666 
1667       auto InsertClobbersAt = [&](Instruction *IP) {
1668         for (auto *AI : ToClobber) {
1669           auto PT = cast<PointerType>(AI->getAllocatedType());
1670           Constant *CPN = ConstantPointerNull::get(PT);
1671           StoreInst *Store = new StoreInst(CPN, AI);
1672           Store->insertBefore(IP);
1673         }
1674       };
1675 
1676       // Insert the clobbering stores.  These may get intermixed with the
1677       // gc.results and gc.relocates, but that's fine.
1678       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1679         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1680         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1681       } else {
1682         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1683       }
1684     }
1685   }
1686 
1687   // Update use with load allocas and add store for gc_relocated.
1688   for (auto Pair : AllocaMap) {
1689     Value *Def = Pair.first;
1690     Value *Alloca = Pair.second;
1691 
1692     // We pre-record the uses of allocas so that we dont have to worry about
1693     // later update that changes the user information..
1694 
1695     SmallVector<Instruction *, 20> Uses;
1696     // PERF: trade a linear scan for repeated reallocation
1697     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1698     for (User *U : Def->users()) {
1699       if (!isa<ConstantExpr>(U)) {
1700         // If the def has a ConstantExpr use, then the def is either a
1701         // ConstantExpr use itself or null.  In either case
1702         // (recursively in the first, directly in the second), the oop
1703         // it is ultimately dependent on is null and this particular
1704         // use does not need to be fixed up.
1705         Uses.push_back(cast<Instruction>(U));
1706       }
1707     }
1708 
1709     std::sort(Uses.begin(), Uses.end());
1710     auto Last = std::unique(Uses.begin(), Uses.end());
1711     Uses.erase(Last, Uses.end());
1712 
1713     for (Instruction *Use : Uses) {
1714       if (isa<PHINode>(Use)) {
1715         PHINode *Phi = cast<PHINode>(Use);
1716         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1717           if (Def == Phi->getIncomingValue(i)) {
1718             LoadInst *Load = new LoadInst(
1719                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1720             Phi->setIncomingValue(i, Load);
1721           }
1722         }
1723       } else {
1724         LoadInst *Load = new LoadInst(Alloca, "", Use);
1725         Use->replaceUsesOfWith(Def, Load);
1726       }
1727     }
1728 
1729     // Emit store for the initial gc value.  Store must be inserted after load,
1730     // otherwise store will be in alloca's use list and an extra load will be
1731     // inserted before it.
1732     StoreInst *Store = new StoreInst(Def, Alloca);
1733     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1734       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1735         // InvokeInst is a TerminatorInst so the store need to be inserted
1736         // into its normal destination block.
1737         BasicBlock *NormalDest = Invoke->getNormalDest();
1738         Store->insertBefore(NormalDest->getFirstNonPHI());
1739       } else {
1740         assert(!Inst->isTerminator() &&
1741                "The only TerminatorInst that can produce a value is "
1742                "InvokeInst which is handled above.");
1743         Store->insertAfter(Inst);
1744       }
1745     } else {
1746       assert(isa<Argument>(Def));
1747       Store->insertAfter(cast<Instruction>(Alloca));
1748     }
1749   }
1750 
1751   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1752          "we must have the same allocas with lives");
1753   if (!PromotableAllocas.empty()) {
1754     // Apply mem2reg to promote alloca to SSA
1755     PromoteMemToReg(PromotableAllocas, DT);
1756   }
1757 
1758 #ifndef NDEBUG
1759   for (auto &I : F.getEntryBlock())
1760     if (isa<AllocaInst>(I))
1761       InitialAllocaNum--;
1762   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1763 #endif
1764 }
1765 
1766 /// Implement a unique function which doesn't require we sort the input
1767 /// vector.  Doing so has the effect of changing the output of a couple of
1768 /// tests in ways which make them less useful in testing fused safepoints.
1769 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1770   SmallSet<T, 8> Seen;
1771   Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1772               return !Seen.insert(V).second;
1773             }), Vec.end());
1774 }
1775 
1776 /// Insert holders so that each Value is obviously live through the entire
1777 /// lifetime of the call.
1778 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1779                                  SmallVectorImpl<CallInst *> &Holders) {
1780   if (Values.empty())
1781     // No values to hold live, might as well not insert the empty holder
1782     return;
1783 
1784   Module *M = CS.getInstruction()->getModule();
1785   // Use a dummy vararg function to actually hold the values live
1786   Function *Func = cast<Function>(M->getOrInsertFunction(
1787       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1788   if (CS.isCall()) {
1789     // For call safepoints insert dummy calls right after safepoint
1790     Holders.push_back(CallInst::Create(Func, Values, "",
1791                                        &*++CS.getInstruction()->getIterator()));
1792     return;
1793   }
1794   // For invoke safepooints insert dummy calls both in normal and
1795   // exceptional destination blocks
1796   auto *II = cast<InvokeInst>(CS.getInstruction());
1797   Holders.push_back(CallInst::Create(
1798       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
1799   Holders.push_back(CallInst::Create(
1800       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
1801 }
1802 
1803 static void findLiveReferences(
1804     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1805     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1806   GCPtrLivenessData OriginalLivenessData;
1807   computeLiveInValues(DT, F, OriginalLivenessData);
1808   for (size_t i = 0; i < records.size(); i++) {
1809     struct PartiallyConstructedSafepointRecord &info = records[i];
1810     const CallSite &CS = toUpdate[i];
1811     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1812   }
1813 }
1814 
1815 // Helper function for the "rematerializeLiveValues". It walks use chain
1816 // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1817 // values are visited (currently it is GEP's and casts). Returns true if it
1818 // successfully reached "BaseValue" and false otherwise.
1819 // Fills "ChainToBase" array with all visited values. "BaseValue" is not
1820 // recorded.
1821 static bool findRematerializableChainToBasePointer(
1822   SmallVectorImpl<Instruction*> &ChainToBase,
1823   Value *CurrentValue, Value *BaseValue) {
1824 
1825   // We have found a base value
1826   if (CurrentValue == BaseValue) {
1827     return true;
1828   }
1829 
1830   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1831     ChainToBase.push_back(GEP);
1832     return findRematerializableChainToBasePointer(ChainToBase,
1833                                                   GEP->getPointerOperand(),
1834                                                   BaseValue);
1835   }
1836 
1837   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1838     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1839       return false;
1840 
1841     ChainToBase.push_back(CI);
1842     return findRematerializableChainToBasePointer(ChainToBase,
1843                                                   CI->getOperand(0), BaseValue);
1844   }
1845 
1846   // Not supported instruction in the chain
1847   return false;
1848 }
1849 
1850 // Helper function for the "rematerializeLiveValues". Compute cost of the use
1851 // chain we are going to rematerialize.
1852 static unsigned
1853 chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1854                        TargetTransformInfo &TTI) {
1855   unsigned Cost = 0;
1856 
1857   for (Instruction *Instr : Chain) {
1858     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1859       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1860              "non noop cast is found during rematerialization");
1861 
1862       Type *SrcTy = CI->getOperand(0)->getType();
1863       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1864 
1865     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1866       // Cost of the address calculation
1867       Type *ValTy = GEP->getSourceElementType();
1868       Cost += TTI.getAddressComputationCost(ValTy);
1869 
1870       // And cost of the GEP itself
1871       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1872       //       allowed for the external usage)
1873       if (!GEP->hasAllConstantIndices())
1874         Cost += 2;
1875 
1876     } else {
1877       llvm_unreachable("unsupported instruciton type during rematerialization");
1878     }
1879   }
1880 
1881   return Cost;
1882 }
1883 
1884 // From the statepoint live set pick values that are cheaper to recompute then
1885 // to relocate. Remove this values from the live set, rematerialize them after
1886 // statepoint and record them in "Info" structure. Note that similar to
1887 // relocated values we don't do any user adjustments here.
1888 static void rematerializeLiveValues(CallSite CS,
1889                                     PartiallyConstructedSafepointRecord &Info,
1890                                     TargetTransformInfo &TTI) {
1891   const unsigned int ChainLengthThreshold = 10;
1892 
1893   // Record values we are going to delete from this statepoint live set.
1894   // We can not di this in following loop due to iterator invalidation.
1895   SmallVector<Value *, 32> LiveValuesToBeDeleted;
1896 
1897   for (Value *LiveValue: Info.LiveSet) {
1898     // For each live pointer find it's defining chain
1899     SmallVector<Instruction *, 3> ChainToBase;
1900     assert(Info.PointerToBase.count(LiveValue));
1901     bool FoundChain =
1902       findRematerializableChainToBasePointer(ChainToBase,
1903                                              LiveValue,
1904                                              Info.PointerToBase[LiveValue]);
1905     // Nothing to do, or chain is too long
1906     if (!FoundChain ||
1907         ChainToBase.size() == 0 ||
1908         ChainToBase.size() > ChainLengthThreshold)
1909       continue;
1910 
1911     // Compute cost of this chain
1912     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1913     // TODO: We can also account for cases when we will be able to remove some
1914     //       of the rematerialized values by later optimization passes. I.e if
1915     //       we rematerialized several intersecting chains. Or if original values
1916     //       don't have any uses besides this statepoint.
1917 
1918     // For invokes we need to rematerialize each chain twice - for normal and
1919     // for unwind basic blocks. Model this by multiplying cost by two.
1920     if (CS.isInvoke()) {
1921       Cost *= 2;
1922     }
1923     // If it's too expensive - skip it
1924     if (Cost >= RematerializationThreshold)
1925       continue;
1926 
1927     // Remove value from the live set
1928     LiveValuesToBeDeleted.push_back(LiveValue);
1929 
1930     // Clone instructions and record them inside "Info" structure
1931 
1932     // Walk backwards to visit top-most instructions first
1933     std::reverse(ChainToBase.begin(), ChainToBase.end());
1934 
1935     // Utility function which clones all instructions from "ChainToBase"
1936     // and inserts them before "InsertBefore". Returns rematerialized value
1937     // which should be used after statepoint.
1938     auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
1939       Instruction *LastClonedValue = nullptr;
1940       Instruction *LastValue = nullptr;
1941       for (Instruction *Instr: ChainToBase) {
1942         // Only GEP's and casts are suported as we need to be careful to not
1943         // introduce any new uses of pointers not in the liveset.
1944         // Note that it's fine to introduce new uses of pointers which were
1945         // otherwise not used after this statepoint.
1946         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
1947 
1948         Instruction *ClonedValue = Instr->clone();
1949         ClonedValue->insertBefore(InsertBefore);
1950         ClonedValue->setName(Instr->getName() + ".remat");
1951 
1952         // If it is not first instruction in the chain then it uses previously
1953         // cloned value. We should update it to use cloned value.
1954         if (LastClonedValue) {
1955           assert(LastValue);
1956           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1957 #ifndef NDEBUG
1958           // Assert that cloned instruction does not use any instructions from
1959           // this chain other than LastClonedValue
1960           for (auto OpValue : ClonedValue->operand_values()) {
1961             assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
1962                        ChainToBase.end() &&
1963                    "incorrect use in rematerialization chain");
1964           }
1965 #endif
1966         }
1967 
1968         LastClonedValue = ClonedValue;
1969         LastValue = Instr;
1970       }
1971       assert(LastClonedValue);
1972       return LastClonedValue;
1973     };
1974 
1975     // Different cases for calls and invokes. For invokes we need to clone
1976     // instructions both on normal and unwind path.
1977     if (CS.isCall()) {
1978       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
1979       assert(InsertBefore);
1980       Instruction *RematerializedValue = rematerializeChain(InsertBefore);
1981       Info.RematerializedValues[RematerializedValue] = LiveValue;
1982     } else {
1983       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
1984 
1985       Instruction *NormalInsertBefore =
1986           &*Invoke->getNormalDest()->getFirstInsertionPt();
1987       Instruction *UnwindInsertBefore =
1988           &*Invoke->getUnwindDest()->getFirstInsertionPt();
1989 
1990       Instruction *NormalRematerializedValue =
1991           rematerializeChain(NormalInsertBefore);
1992       Instruction *UnwindRematerializedValue =
1993           rematerializeChain(UnwindInsertBefore);
1994 
1995       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
1996       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
1997     }
1998   }
1999 
2000   // Remove rematerializaed values from the live set
2001   for (auto LiveValue: LiveValuesToBeDeleted) {
2002     Info.LiveSet.erase(LiveValue);
2003   }
2004 }
2005 
2006 static bool insertParsePoints(Function &F, DominatorTree &DT,
2007                               TargetTransformInfo &TTI,
2008                               SmallVectorImpl<CallSite> &ToUpdate) {
2009 #ifndef NDEBUG
2010   // sanity check the input
2011   std::set<CallSite> Uniqued;
2012   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2013   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2014 
2015   for (CallSite CS : ToUpdate)
2016     assert(CS.getInstruction()->getFunction() == &F);
2017 #endif
2018 
2019   // When inserting gc.relocates for invokes, we need to be able to insert at
2020   // the top of the successor blocks.  See the comment on
2021   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2022   // may restructure the CFG.
2023   for (CallSite CS : ToUpdate) {
2024     if (!CS.isInvoke())
2025       continue;
2026     auto *II = cast<InvokeInst>(CS.getInstruction());
2027     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2028     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2029   }
2030 
2031   // A list of dummy calls added to the IR to keep various values obviously
2032   // live in the IR.  We'll remove all of these when done.
2033   SmallVector<CallInst *, 64> Holders;
2034 
2035   // Insert a dummy call with all of the arguments to the vm_state we'll need
2036   // for the actual safepoint insertion.  This ensures reference arguments in
2037   // the deopt argument list are considered live through the safepoint (and
2038   // thus makes sure they get relocated.)
2039   for (CallSite CS : ToUpdate) {
2040     SmallVector<Value *, 64> DeoptValues;
2041 
2042     for (Value *Arg : GetDeoptBundleOperands(CS)) {
2043       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2044              "support for FCA unimplemented");
2045       if (isHandledGCPointerType(Arg->getType()))
2046         DeoptValues.push_back(Arg);
2047     }
2048 
2049     insertUseHolderAfter(CS, DeoptValues, Holders);
2050   }
2051 
2052   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2053 
2054   // A) Identify all gc pointers which are statically live at the given call
2055   // site.
2056   findLiveReferences(F, DT, ToUpdate, Records);
2057 
2058   // B) Find the base pointers for each live pointer
2059   /* scope for caching */ {
2060     // Cache the 'defining value' relation used in the computation and
2061     // insertion of base phis and selects.  This ensures that we don't insert
2062     // large numbers of duplicate base_phis.
2063     DefiningValueMapTy DVCache;
2064 
2065     for (size_t i = 0; i < Records.size(); i++) {
2066       PartiallyConstructedSafepointRecord &info = Records[i];
2067       findBasePointers(DT, DVCache, ToUpdate[i], info);
2068     }
2069   } // end of cache scope
2070 
2071   // The base phi insertion logic (for any safepoint) may have inserted new
2072   // instructions which are now live at some safepoint.  The simplest such
2073   // example is:
2074   // loop:
2075   //   phi a  <-- will be a new base_phi here
2076   //   safepoint 1 <-- that needs to be live here
2077   //   gep a + 1
2078   //   safepoint 2
2079   //   br loop
2080   // We insert some dummy calls after each safepoint to definitely hold live
2081   // the base pointers which were identified for that safepoint.  We'll then
2082   // ask liveness for _every_ base inserted to see what is now live.  Then we
2083   // remove the dummy calls.
2084   Holders.reserve(Holders.size() + Records.size());
2085   for (size_t i = 0; i < Records.size(); i++) {
2086     PartiallyConstructedSafepointRecord &Info = Records[i];
2087 
2088     SmallVector<Value *, 128> Bases;
2089     for (auto Pair : Info.PointerToBase)
2090       Bases.push_back(Pair.second);
2091 
2092     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2093   }
2094 
2095   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2096   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2097   // not the key issue.
2098   recomputeLiveInValues(F, DT, ToUpdate, Records);
2099 
2100   if (PrintBasePointers) {
2101     for (auto &Info : Records) {
2102       errs() << "Base Pairs: (w/Relocation)\n";
2103       for (auto Pair : Info.PointerToBase) {
2104         errs() << " derived ";
2105         Pair.first->printAsOperand(errs(), false);
2106         errs() << " base ";
2107         Pair.second->printAsOperand(errs(), false);
2108         errs() << "\n";
2109       }
2110     }
2111   }
2112 
2113   // It is possible that non-constant live variables have a constant base.  For
2114   // example, a GEP with a variable offset from a global.  In this case we can
2115   // remove it from the liveset.  We already don't add constants to the liveset
2116   // because we assume they won't move at runtime and the GC doesn't need to be
2117   // informed about them.  The same reasoning applies if the base is constant.
2118   // Note that the relocation placement code relies on this filtering for
2119   // correctness as it expects the base to be in the liveset, which isn't true
2120   // if the base is constant.
2121   for (auto &Info : Records)
2122     for (auto &BasePair : Info.PointerToBase)
2123       if (isa<Constant>(BasePair.second))
2124         Info.LiveSet.erase(BasePair.first);
2125 
2126   for (CallInst *CI : Holders)
2127     CI->eraseFromParent();
2128 
2129   Holders.clear();
2130 
2131   // In order to reduce live set of statepoint we might choose to rematerialize
2132   // some values instead of relocating them. This is purely an optimization and
2133   // does not influence correctness.
2134   for (size_t i = 0; i < Records.size(); i++)
2135     rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
2136 
2137   // We need this to safely RAUW and delete call or invoke return values that
2138   // may themselves be live over a statepoint.  For details, please see usage in
2139   // makeStatepointExplicitImpl.
2140   std::vector<DeferredReplacement> Replacements;
2141 
2142   // Now run through and replace the existing statepoints with new ones with
2143   // the live variables listed.  We do not yet update uses of the values being
2144   // relocated. We have references to live variables that need to
2145   // survive to the last iteration of this loop.  (By construction, the
2146   // previous statepoint can not be a live variable, thus we can and remove
2147   // the old statepoint calls as we go.)
2148   for (size_t i = 0; i < Records.size(); i++)
2149     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
2150 
2151   ToUpdate.clear(); // prevent accident use of invalid CallSites
2152 
2153   for (auto &PR : Replacements)
2154     PR.doReplacement();
2155 
2156   Replacements.clear();
2157 
2158   for (auto &Info : Records) {
2159     // These live sets may contain state Value pointers, since we replaced calls
2160     // with operand bundles with calls wrapped in gc.statepoint, and some of
2161     // those calls may have been def'ing live gc pointers.  Clear these out to
2162     // avoid accidentally using them.
2163     //
2164     // TODO: We should create a separate data structure that does not contain
2165     // these live sets, and migrate to using that data structure from this point
2166     // onward.
2167     Info.LiveSet.clear();
2168     Info.PointerToBase.clear();
2169   }
2170 
2171   // Do all the fixups of the original live variables to their relocated selves
2172   SmallVector<Value *, 128> Live;
2173   for (size_t i = 0; i < Records.size(); i++) {
2174     PartiallyConstructedSafepointRecord &Info = Records[i];
2175 
2176     // We can't simply save the live set from the original insertion.  One of
2177     // the live values might be the result of a call which needs a safepoint.
2178     // That Value* no longer exists and we need to use the new gc_result.
2179     // Thankfully, the live set is embedded in the statepoint (and updated), so
2180     // we just grab that.
2181     Statepoint Statepoint(Info.StatepointToken);
2182     Live.insert(Live.end(), Statepoint.gc_args_begin(),
2183                 Statepoint.gc_args_end());
2184 #ifndef NDEBUG
2185     // Do some basic sanity checks on our liveness results before performing
2186     // relocation.  Relocation can and will turn mistakes in liveness results
2187     // into non-sensical code which is must harder to debug.
2188     // TODO: It would be nice to test consistency as well
2189     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2190            "statepoint must be reachable or liveness is meaningless");
2191     for (Value *V : Statepoint.gc_args()) {
2192       if (!isa<Instruction>(V))
2193         // Non-instruction values trivial dominate all possible uses
2194         continue;
2195       auto *LiveInst = cast<Instruction>(V);
2196       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2197              "unreachable values should never be live");
2198       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2199              "basic SSA liveness expectation violated by liveness analysis");
2200     }
2201 #endif
2202   }
2203   unique_unsorted(Live);
2204 
2205 #ifndef NDEBUG
2206   // sanity check
2207   for (auto *Ptr : Live)
2208     assert(isHandledGCPointerType(Ptr->getType()) &&
2209            "must be a gc pointer type");
2210 #endif
2211 
2212   relocationViaAlloca(F, DT, Live, Records);
2213   return !Records.empty();
2214 }
2215 
2216 // Handles both return values and arguments for Functions and CallSites.
2217 template <typename AttrHolder>
2218 static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2219                                       unsigned Index) {
2220   AttrBuilder R;
2221   if (AH.getDereferenceableBytes(Index))
2222     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2223                                   AH.getDereferenceableBytes(Index)));
2224   if (AH.getDereferenceableOrNullBytes(Index))
2225     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2226                                   AH.getDereferenceableOrNullBytes(Index)));
2227   if (AH.doesNotAlias(Index))
2228     R.addAttribute(Attribute::NoAlias);
2229 
2230   if (!R.empty())
2231     AH.setAttributes(AH.getAttributes().removeAttributes(
2232         Ctx, Index, AttributeSet::get(Ctx, Index, R)));
2233 }
2234 
2235 void
2236 RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
2237   LLVMContext &Ctx = F.getContext();
2238 
2239   for (Argument &A : F.args())
2240     if (isa<PointerType>(A.getType()))
2241       RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2242 
2243   if (isa<PointerType>(F.getReturnType()))
2244     RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2245 }
2246 
2247 void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
2248   if (F.empty())
2249     return;
2250 
2251   LLVMContext &Ctx = F.getContext();
2252   MDBuilder Builder(Ctx);
2253 
2254   for (Instruction &I : instructions(F)) {
2255     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2256       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2257       bool IsImmutableTBAA =
2258           MD->getNumOperands() == 4 &&
2259           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2260 
2261       if (!IsImmutableTBAA)
2262         continue; // no work to do, MD_tbaa is already marked mutable
2263 
2264       MDNode *Base = cast<MDNode>(MD->getOperand(0));
2265       MDNode *Access = cast<MDNode>(MD->getOperand(1));
2266       uint64_t Offset =
2267           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2268 
2269       MDNode *MutableTBAA =
2270           Builder.createTBAAStructTagNode(Base, Access, Offset);
2271       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2272     }
2273 
2274     if (CallSite CS = CallSite(&I)) {
2275       for (int i = 0, e = CS.arg_size(); i != e; i++)
2276         if (isa<PointerType>(CS.getArgument(i)->getType()))
2277           RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
2278       if (isa<PointerType>(CS.getType()))
2279         RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2280     }
2281   }
2282 }
2283 
2284 /// Returns true if this function should be rewritten by this pass.  The main
2285 /// point of this function is as an extension point for custom logic.
2286 static bool shouldRewriteStatepointsIn(Function &F) {
2287   // TODO: This should check the GCStrategy
2288   if (F.hasGC()) {
2289     const auto &FunctionGCName = F.getGC();
2290     const StringRef StatepointExampleName("statepoint-example");
2291     const StringRef CoreCLRName("coreclr");
2292     return (StatepointExampleName == FunctionGCName) ||
2293            (CoreCLRName == FunctionGCName);
2294   } else
2295     return false;
2296 }
2297 
2298 void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
2299 #ifndef NDEBUG
2300   assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2301          "precondition!");
2302 #endif
2303 
2304   for (Function &F : M)
2305     stripNonValidAttributesFromPrototype(F);
2306 
2307   for (Function &F : M)
2308     stripNonValidAttributesFromBody(F);
2309 }
2310 
2311 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2312   // Nothing to do for declarations.
2313   if (F.isDeclaration() || F.empty())
2314     return false;
2315 
2316   // Policy choice says not to rewrite - the most common reason is that we're
2317   // compiling code without a GCStrategy.
2318   if (!shouldRewriteStatepointsIn(F))
2319     return false;
2320 
2321   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2322   TargetTransformInfo &TTI =
2323       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2324 
2325   auto NeedsRewrite = [](Instruction &I) {
2326     if (ImmutableCallSite CS = ImmutableCallSite(&I))
2327       return !callsGCLeafFunction(CS);
2328     return false;
2329   };
2330 
2331   // Gather all the statepoints which need rewritten.  Be careful to only
2332   // consider those in reachable code since we need to ask dominance queries
2333   // when rewriting.  We'll delete the unreachable ones in a moment.
2334   SmallVector<CallSite, 64> ParsePointNeeded;
2335   bool HasUnreachableStatepoint = false;
2336   for (Instruction &I : instructions(F)) {
2337     // TODO: only the ones with the flag set!
2338     if (NeedsRewrite(I)) {
2339       if (DT.isReachableFromEntry(I.getParent()))
2340         ParsePointNeeded.push_back(CallSite(&I));
2341       else
2342         HasUnreachableStatepoint = true;
2343     }
2344   }
2345 
2346   bool MadeChange = false;
2347 
2348   // Delete any unreachable statepoints so that we don't have unrewritten
2349   // statepoints surviving this pass.  This makes testing easier and the
2350   // resulting IR less confusing to human readers.  Rather than be fancy, we
2351   // just reuse a utility function which removes the unreachable blocks.
2352   if (HasUnreachableStatepoint)
2353     MadeChange |= removeUnreachableBlocks(F);
2354 
2355   // Return early if no work to do.
2356   if (ParsePointNeeded.empty())
2357     return MadeChange;
2358 
2359   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2360   // These are created by LCSSA.  They have the effect of increasing the size
2361   // of liveness sets for no good reason.  It may be harder to do this post
2362   // insertion since relocations and base phis can confuse things.
2363   for (BasicBlock &BB : F)
2364     if (BB.getUniquePredecessor()) {
2365       MadeChange = true;
2366       FoldSingleEntryPHINodes(&BB);
2367     }
2368 
2369   // Before we start introducing relocations, we want to tweak the IR a bit to
2370   // avoid unfortunate code generation effects.  The main example is that we
2371   // want to try to make sure the comparison feeding a branch is after any
2372   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
2373   // values feeding a branch after relocation.  This is semantically correct,
2374   // but results in extra register pressure since both the pre-relocation and
2375   // post-relocation copies must be available in registers.  For code without
2376   // relocations this is handled elsewhere, but teaching the scheduler to
2377   // reverse the transform we're about to do would be slightly complex.
2378   // Note: This may extend the live range of the inputs to the icmp and thus
2379   // increase the liveset of any statepoint we move over.  This is profitable
2380   // as long as all statepoints are in rare blocks.  If we had in-register
2381   // lowering for live values this would be a much safer transform.
2382   auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2383     if (auto *BI = dyn_cast<BranchInst>(TI))
2384       if (BI->isConditional())
2385         return dyn_cast<Instruction>(BI->getCondition());
2386     // TODO: Extend this to handle switches
2387     return nullptr;
2388   };
2389   for (BasicBlock &BB : F) {
2390     TerminatorInst *TI = BB.getTerminator();
2391     if (auto *Cond = getConditionInst(TI))
2392       // TODO: Handle more than just ICmps here.  We should be able to move
2393       // most instructions without side effects or memory access.
2394       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2395         MadeChange = true;
2396         Cond->moveBefore(TI);
2397       }
2398   }
2399 
2400   MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
2401   return MadeChange;
2402 }
2403 
2404 // liveness computation via standard dataflow
2405 // -------------------------------------------------------------------
2406 
2407 // TODO: Consider using bitvectors for liveness, the set of potentially
2408 // interesting values should be small and easy to pre-compute.
2409 
2410 /// Compute the live-in set for the location rbegin starting from
2411 /// the live-out set of the basic block
2412 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2413                                 BasicBlock::reverse_iterator rend,
2414                                 DenseSet<Value *> &LiveTmp) {
2415 
2416   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2417     Instruction *I = &*ritr;
2418 
2419     // KILL/Def - Remove this definition from LiveIn
2420     LiveTmp.erase(I);
2421 
2422     // Don't consider *uses* in PHI nodes, we handle their contribution to
2423     // predecessor blocks when we seed the LiveOut sets
2424     if (isa<PHINode>(I))
2425       continue;
2426 
2427     // USE - Add to the LiveIn set for this instruction
2428     for (Value *V : I->operands()) {
2429       assert(!isUnhandledGCPointerType(V->getType()) &&
2430              "support for FCA unimplemented");
2431       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2432         // The choice to exclude all things constant here is slightly subtle.
2433         // There are two independent reasons:
2434         // - We assume that things which are constant (from LLVM's definition)
2435         // do not move at runtime.  For example, the address of a global
2436         // variable is fixed, even though it's contents may not be.
2437         // - Second, we can't disallow arbitrary inttoptr constants even
2438         // if the language frontend does.  Optimization passes are free to
2439         // locally exploit facts without respect to global reachability.  This
2440         // can create sections of code which are dynamically unreachable and
2441         // contain just about anything.  (see constants.ll in tests)
2442         LiveTmp.insert(V);
2443       }
2444     }
2445   }
2446 }
2447 
2448 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2449 
2450   for (BasicBlock *Succ : successors(BB)) {
2451     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2452     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2453       PHINode *Phi = cast<PHINode>(&*I);
2454       Value *V = Phi->getIncomingValueForBlock(BB);
2455       assert(!isUnhandledGCPointerType(V->getType()) &&
2456              "support for FCA unimplemented");
2457       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2458         LiveTmp.insert(V);
2459       }
2460     }
2461   }
2462 }
2463 
2464 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2465   DenseSet<Value *> KillSet;
2466   for (Instruction &I : *BB)
2467     if (isHandledGCPointerType(I.getType()))
2468       KillSet.insert(&I);
2469   return KillSet;
2470 }
2471 
2472 #ifndef NDEBUG
2473 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2474 /// sanity check for the liveness computation.
2475 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2476                           TerminatorInst *TI, bool TermOkay = false) {
2477   for (Value *V : Live) {
2478     if (auto *I = dyn_cast<Instruction>(V)) {
2479       // The terminator can be a member of the LiveOut set.  LLVM's definition
2480       // of instruction dominance states that V does not dominate itself.  As
2481       // such, we need to special case this to allow it.
2482       if (TermOkay && TI == I)
2483         continue;
2484       assert(DT.dominates(I, TI) &&
2485              "basic SSA liveness expectation violated by liveness analysis");
2486     }
2487   }
2488 }
2489 
2490 /// Check that all the liveness sets used during the computation of liveness
2491 /// obey basic SSA properties.  This is useful for finding cases where we miss
2492 /// a def.
2493 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2494                           BasicBlock &BB) {
2495   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2496   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2497   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2498 }
2499 #endif
2500 
2501 static void computeLiveInValues(DominatorTree &DT, Function &F,
2502                                 GCPtrLivenessData &Data) {
2503 
2504   SmallSetVector<BasicBlock *, 32> Worklist;
2505   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2506     // We use a SetVector so that we don't have duplicates in the worklist.
2507     Worklist.insert(pred_begin(BB), pred_end(BB));
2508   };
2509   auto NextItem = [&]() {
2510     BasicBlock *BB = Worklist.back();
2511     Worklist.pop_back();
2512     return BB;
2513   };
2514 
2515   // Seed the liveness for each individual block
2516   for (BasicBlock &BB : F) {
2517     Data.KillSet[&BB] = computeKillSet(&BB);
2518     Data.LiveSet[&BB].clear();
2519     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2520 
2521 #ifndef NDEBUG
2522     for (Value *Kill : Data.KillSet[&BB])
2523       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2524 #endif
2525 
2526     Data.LiveOut[&BB] = DenseSet<Value *>();
2527     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2528     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2529     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2530     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2531     if (!Data.LiveIn[&BB].empty())
2532       AddPredsToWorklist(&BB);
2533   }
2534 
2535   // Propagate that liveness until stable
2536   while (!Worklist.empty()) {
2537     BasicBlock *BB = NextItem();
2538 
2539     // Compute our new liveout set, then exit early if it hasn't changed
2540     // despite the contribution of our successor.
2541     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2542     const auto OldLiveOutSize = LiveOut.size();
2543     for (BasicBlock *Succ : successors(BB)) {
2544       assert(Data.LiveIn.count(Succ));
2545       set_union(LiveOut, Data.LiveIn[Succ]);
2546     }
2547     // assert OutLiveOut is a subset of LiveOut
2548     if (OldLiveOutSize == LiveOut.size()) {
2549       // If the sets are the same size, then we didn't actually add anything
2550       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2551       // hasn't changed.
2552       continue;
2553     }
2554     Data.LiveOut[BB] = LiveOut;
2555 
2556     // Apply the effects of this basic block
2557     DenseSet<Value *> LiveTmp = LiveOut;
2558     set_union(LiveTmp, Data.LiveSet[BB]);
2559     set_subtract(LiveTmp, Data.KillSet[BB]);
2560 
2561     assert(Data.LiveIn.count(BB));
2562     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2563     // assert: OldLiveIn is a subset of LiveTmp
2564     if (OldLiveIn.size() != LiveTmp.size()) {
2565       Data.LiveIn[BB] = LiveTmp;
2566       AddPredsToWorklist(BB);
2567     }
2568   } // while( !worklist.empty() )
2569 
2570 #ifndef NDEBUG
2571   // Sanity check our output against SSA properties.  This helps catch any
2572   // missing kills during the above iteration.
2573   for (BasicBlock &BB : F) {
2574     checkBasicSSA(DT, Data, BB);
2575   }
2576 #endif
2577 }
2578 
2579 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2580                               StatepointLiveSetTy &Out) {
2581 
2582   BasicBlock *BB = Inst->getParent();
2583 
2584   // Note: The copy is intentional and required
2585   assert(Data.LiveOut.count(BB));
2586   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2587 
2588   // We want to handle the statepoint itself oddly.  It's
2589   // call result is not live (normal), nor are it's arguments
2590   // (unless they're used again later).  This adjustment is
2591   // specifically what we need to relocate
2592   BasicBlock::reverse_iterator rend(Inst->getIterator());
2593   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2594   LiveOut.erase(Inst);
2595   Out.insert(LiveOut.begin(), LiveOut.end());
2596 }
2597 
2598 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2599                                   const CallSite &CS,
2600                                   PartiallyConstructedSafepointRecord &Info) {
2601   Instruction *Inst = CS.getInstruction();
2602   StatepointLiveSetTy Updated;
2603   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2604 
2605 #ifndef NDEBUG
2606   DenseSet<Value *> Bases;
2607   for (auto KVPair : Info.PointerToBase) {
2608     Bases.insert(KVPair.second);
2609   }
2610 #endif
2611   // We may have base pointers which are now live that weren't before.  We need
2612   // to update the PointerToBase structure to reflect this.
2613   for (auto V : Updated)
2614     if (!Info.PointerToBase.count(V)) {
2615       assert(Bases.count(V) && "can't find base for unexpected live value");
2616       Info.PointerToBase[V] = V;
2617       continue;
2618     }
2619 
2620 #ifndef NDEBUG
2621   for (auto V : Updated) {
2622     assert(Info.PointerToBase.count(V) &&
2623            "must be able to find base for live value");
2624   }
2625 #endif
2626 
2627   // Remove any stale base mappings - this can happen since our liveness is
2628   // more precise then the one inherent in the base pointer analysis
2629   DenseSet<Value *> ToErase;
2630   for (auto KVPair : Info.PointerToBase)
2631     if (!Updated.count(KVPair.first))
2632       ToErase.insert(KVPair.first);
2633   for (auto V : ToErase)
2634     Info.PointerToBase.erase(V);
2635 
2636 #ifndef NDEBUG
2637   for (auto KVPair : Info.PointerToBase)
2638     assert(Updated.count(KVPair.first) && "record for non-live value");
2639 #endif
2640 
2641   Info.LiveSet = Updated;
2642 }
2643