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