xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Scalar/RewriteStatepointsForGC.cpp (revision 0ad011ececb978e22a9bff2acf76633b094f1ff6)
1 //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Rewrite call/invoke instructions so as to make potential relocations
10 // performed by the garbage collector explicit in the IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/Analysis/DomTreeUpdater.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/IR/Argument.h"
30 #include "llvm/IR/AttributeMask.h"
31 #include "llvm/IR/Attributes.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constant.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GCStrategy.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/InstIterator.h"
43 #include "llvm/IR/InstrTypes.h"
44 #include "llvm/IR/Instruction.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Intrinsics.h"
48 #include "llvm/IR/LLVMContext.h"
49 #include "llvm/IR/MDBuilder.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/Statepoint.h"
53 #include "llvm/IR/Type.h"
54 #include "llvm/IR/User.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/IR/ValueHandle.h"
57 #include "llvm/InitializePasses.h"
58 #include "llvm/Pass.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Transforms/Scalar.h"
66 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
67 #include "llvm/Transforms/Utils/Local.h"
68 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
69 #include <algorithm>
70 #include <cassert>
71 #include <cstddef>
72 #include <cstdint>
73 #include <iterator>
74 #include <optional>
75 #include <set>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
81 
82 using namespace llvm;
83 
84 // Print the liveset found at the insert location
85 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
86                                   cl::init(false));
87 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
88                                       cl::init(false));
89 
90 // Print out the base pointers for debugging
91 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
92                                        cl::init(false));
93 
94 // Cost threshold measuring when it is profitable to rematerialize value instead
95 // of relocating it
96 static cl::opt<unsigned>
97 RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
98                            cl::init(6));
99 
100 #ifdef EXPENSIVE_CHECKS
101 static bool ClobberNonLive = true;
102 #else
103 static bool ClobberNonLive = false;
104 #endif
105 
106 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
107                                                   cl::location(ClobberNonLive),
108                                                   cl::Hidden);
109 
110 static cl::opt<bool>
111     AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
112                                    cl::Hidden, cl::init(true));
113 
114 static cl::opt<bool> RematDerivedAtUses("rs4gc-remat-derived-at-uses",
115                                         cl::Hidden, cl::init(true));
116 
117 /// The IR fed into RewriteStatepointsForGC may have had attributes and
118 /// metadata implying dereferenceability that are no longer valid/correct after
119 /// RewriteStatepointsForGC has run. This is because semantically, after
120 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
121 /// heap. stripNonValidData (conservatively) restores
122 /// correctness by erasing all attributes in the module that externally imply
123 /// dereferenceability. Similar reasoning also applies to the noalias
124 /// attributes and metadata. gc.statepoint can touch the entire heap including
125 /// noalias objects.
126 /// Apart from attributes and metadata, we also remove instructions that imply
127 /// constant physical memory: llvm.invariant.start.
128 static void stripNonValidData(Module &M);
129 
130 // Find the GC strategy for a function, or null if it doesn't have one.
131 static std::unique_ptr<GCStrategy> findGCStrategy(Function &F);
132 
133 static bool shouldRewriteStatepointsIn(Function &F);
134 
135 PreservedAnalyses RewriteStatepointsForGC::run(Module &M,
136                                                ModuleAnalysisManager &AM) {
137   bool Changed = false;
138   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
139   for (Function &F : M) {
140     // Nothing to do for declarations.
141     if (F.isDeclaration() || F.empty())
142       continue;
143 
144     // Policy choice says not to rewrite - the most common reason is that we're
145     // compiling code without a GCStrategy.
146     if (!shouldRewriteStatepointsIn(F))
147       continue;
148 
149     auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
150     auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
151     auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
152     Changed |= runOnFunction(F, DT, TTI, TLI);
153   }
154   if (!Changed)
155     return PreservedAnalyses::all();
156 
157   // stripNonValidData asserts that shouldRewriteStatepointsIn
158   // returns true for at least one function in the module.  Since at least
159   // one function changed, we know that the precondition is satisfied.
160   stripNonValidData(M);
161 
162   PreservedAnalyses PA;
163   PA.preserve<TargetIRAnalysis>();
164   PA.preserve<TargetLibraryAnalysis>();
165   return PA;
166 }
167 
168 namespace {
169 
170 struct GCPtrLivenessData {
171   /// Values defined in this block.
172   MapVector<BasicBlock *, SetVector<Value *>> KillSet;
173 
174   /// Values used in this block (and thus live); does not included values
175   /// killed within this block.
176   MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
177 
178   /// Values live into this basic block (i.e. used by any
179   /// instruction in this basic block or ones reachable from here)
180   MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
181 
182   /// Values live out of this basic block (i.e. live into
183   /// any successor block)
184   MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
185 };
186 
187 // The type of the internal cache used inside the findBasePointers family
188 // of functions.  From the callers perspective, this is an opaque type and
189 // should not be inspected.
190 //
191 // In the actual implementation this caches two relations:
192 // - The base relation itself (i.e. this pointer is based on that one)
193 // - The base defining value relation (i.e. before base_phi insertion)
194 // Generally, after the execution of a full findBasePointer call, only the
195 // base relation will remain.  Internally, we add a mixture of the two
196 // types, then update all the second type to the first type
197 using DefiningValueMapTy = MapVector<Value *, Value *>;
198 using IsKnownBaseMapTy = MapVector<Value *, bool>;
199 using PointerToBaseTy = MapVector<Value *, Value *>;
200 using StatepointLiveSetTy = SetVector<Value *>;
201 using RematerializedValueMapTy =
202     MapVector<AssertingVH<Instruction>, AssertingVH<Value>>;
203 
204 struct PartiallyConstructedSafepointRecord {
205   /// The set of values known to be live across this safepoint
206   StatepointLiveSetTy LiveSet;
207 
208   /// The *new* gc.statepoint instruction itself.  This produces the token
209   /// that normal path gc.relocates and the gc.result are tied to.
210   GCStatepointInst *StatepointToken;
211 
212   /// Instruction to which exceptional gc relocates are attached
213   /// Makes it easier to iterate through them during relocationViaAlloca.
214   Instruction *UnwindToken;
215 
216   /// Record live values we are rematerialized instead of relocating.
217   /// They are not included into 'LiveSet' field.
218   /// Maps rematerialized copy to it's original value.
219   RematerializedValueMapTy RematerializedValues;
220 };
221 
222 struct RematerizlizationCandidateRecord {
223   // Chain from derived pointer to base.
224   SmallVector<Instruction *, 3> ChainToBase;
225   // Original base.
226   Value *RootOfChain;
227   // Cost of chain.
228   InstructionCost Cost;
229 };
230 using RematCandTy = MapVector<Value *, RematerizlizationCandidateRecord>;
231 
232 } // end anonymous namespace
233 
234 static ArrayRef<Use> GetDeoptBundleOperands(const CallBase *Call) {
235   std::optional<OperandBundleUse> DeoptBundle =
236       Call->getOperandBundle(LLVMContext::OB_deopt);
237 
238   if (!DeoptBundle) {
239     assert(AllowStatepointWithNoDeoptInfo &&
240            "Found non-leaf call without deopt info!");
241     return std::nullopt;
242   }
243 
244   return DeoptBundle->Inputs;
245 }
246 
247 /// Compute the live-in set for every basic block in the function
248 static void computeLiveInValues(DominatorTree &DT, Function &F,
249                                 GCPtrLivenessData &Data, GCStrategy *GC);
250 
251 /// Given results from the dataflow liveness computation, find the set of live
252 /// Values at a particular instruction.
253 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
254                               StatepointLiveSetTy &out, GCStrategy *GC);
255 
256 static bool isGCPointerType(Type *T, GCStrategy *GC) {
257   assert(GC && "GC Strategy for isGCPointerType cannot be null");
258 
259   if (!isa<PointerType>(T))
260     return false;
261 
262   // conservative - same as StatepointLowering
263   return GC->isGCManagedPointer(T).value_or(true);
264 }
265 
266 // Return true if this type is one which a) is a gc pointer or contains a GC
267 // pointer and b) is of a type this code expects to encounter as a live value.
268 // (The insertion code will assert that a type which matches (a) and not (b)
269 // is not encountered.)
270 static bool isHandledGCPointerType(Type *T, GCStrategy *GC) {
271   // We fully support gc pointers
272   if (isGCPointerType(T, GC))
273     return true;
274   // We partially support vectors of gc pointers. The code will assert if it
275   // can't handle something.
276   if (auto VT = dyn_cast<VectorType>(T))
277     if (isGCPointerType(VT->getElementType(), GC))
278       return true;
279   return false;
280 }
281 
282 #ifndef NDEBUG
283 /// Returns true if this type contains a gc pointer whether we know how to
284 /// handle that type or not.
285 static bool containsGCPtrType(Type *Ty, GCStrategy *GC) {
286   if (isGCPointerType(Ty, GC))
287     return true;
288   if (VectorType *VT = dyn_cast<VectorType>(Ty))
289     return isGCPointerType(VT->getScalarType(), GC);
290   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
291     return containsGCPtrType(AT->getElementType(), GC);
292   if (StructType *ST = dyn_cast<StructType>(Ty))
293     return llvm::any_of(ST->elements(),
294                         [GC](Type *Ty) { return containsGCPtrType(Ty, GC); });
295   return false;
296 }
297 
298 // Returns true if this is a type which a) is a gc pointer or contains a GC
299 // pointer and b) is of a type which the code doesn't expect (i.e. first class
300 // aggregates).  Used to trip assertions.
301 static bool isUnhandledGCPointerType(Type *Ty, GCStrategy *GC) {
302   return containsGCPtrType(Ty, GC) && !isHandledGCPointerType(Ty, GC);
303 }
304 #endif
305 
306 // Return the name of the value suffixed with the provided value, or if the
307 // value didn't have a name, the default value specified.
308 static std::string suffixed_name_or(Value *V, StringRef Suffix,
309                                     StringRef DefaultName) {
310   return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
311 }
312 
313 // Conservatively identifies any definitions which might be live at the
314 // given instruction. The  analysis is performed immediately before the
315 // given instruction. Values defined by that instruction are not considered
316 // live.  Values used by that instruction are considered live.
317 static void analyzeParsePointLiveness(
318     DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, CallBase *Call,
319     PartiallyConstructedSafepointRecord &Result, GCStrategy *GC) {
320   StatepointLiveSetTy LiveSet;
321   findLiveSetAtInst(Call, OriginalLivenessData, LiveSet, GC);
322 
323   if (PrintLiveSet) {
324     dbgs() << "Live Variables:\n";
325     for (Value *V : LiveSet)
326       dbgs() << " " << V->getName() << " " << *V << "\n";
327   }
328   if (PrintLiveSetSize) {
329     dbgs() << "Safepoint For: " << Call->getCalledOperand()->getName() << "\n";
330     dbgs() << "Number live values: " << LiveSet.size() << "\n";
331   }
332   Result.LiveSet = LiveSet;
333 }
334 
335 /// Returns true if V is a known base.
336 static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases);
337 
338 /// Caches the IsKnownBase flag for a value and asserts that it wasn't present
339 /// in the cache before.
340 static void setKnownBase(Value *V, bool IsKnownBase,
341                          IsKnownBaseMapTy &KnownBases);
342 
343 static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
344                                     IsKnownBaseMapTy &KnownBases);
345 
346 /// Return a base defining value for the 'Index' element of the given vector
347 /// instruction 'I'.  If Index is null, returns a BDV for the entire vector
348 /// 'I'.  As an optimization, this method will try to determine when the
349 /// element is known to already be a base pointer.  If this can be established,
350 /// the second value in the returned pair will be true.  Note that either a
351 /// vector or a pointer typed value can be returned.  For the former, the
352 /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
353 /// If the later, the return pointer is a BDV (or possibly a base) for the
354 /// particular element in 'I'.
355 static Value *findBaseDefiningValueOfVector(Value *I, DefiningValueMapTy &Cache,
356                                             IsKnownBaseMapTy &KnownBases) {
357   // Each case parallels findBaseDefiningValue below, see that code for
358   // detailed motivation.
359 
360   auto Cached = Cache.find(I);
361   if (Cached != Cache.end())
362     return Cached->second;
363 
364   if (isa<Argument>(I)) {
365     // An incoming argument to the function is a base pointer
366     Cache[I] = I;
367     setKnownBase(I, /* IsKnownBase */true, KnownBases);
368     return I;
369   }
370 
371   if (isa<Constant>(I)) {
372     // Base of constant vector consists only of constant null pointers.
373     // For reasoning see similar case inside 'findBaseDefiningValue' function.
374     auto *CAZ = ConstantAggregateZero::get(I->getType());
375     Cache[I] = CAZ;
376     setKnownBase(CAZ, /* IsKnownBase */true, KnownBases);
377     return CAZ;
378   }
379 
380   if (isa<LoadInst>(I)) {
381     Cache[I] = I;
382     setKnownBase(I, /* IsKnownBase */true, KnownBases);
383     return I;
384   }
385 
386   if (isa<InsertElementInst>(I)) {
387     // We don't know whether this vector contains entirely base pointers or
388     // not.  To be conservatively correct, we treat it as a BDV and will
389     // duplicate code as needed to construct a parallel vector of bases.
390     Cache[I] = I;
391     setKnownBase(I, /* IsKnownBase */false, KnownBases);
392     return I;
393   }
394 
395   if (isa<ShuffleVectorInst>(I)) {
396     // We don't know whether this vector contains entirely base pointers or
397     // not.  To be conservatively correct, we treat it as a BDV and will
398     // duplicate code as needed to construct a parallel vector of bases.
399     // TODO: There a number of local optimizations which could be applied here
400     // for particular sufflevector patterns.
401     Cache[I] = I;
402     setKnownBase(I, /* IsKnownBase */false, KnownBases);
403     return I;
404   }
405 
406   // The behavior of getelementptr instructions is the same for vector and
407   // non-vector data types.
408   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
409     auto *BDV =
410         findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
411     Cache[GEP] = BDV;
412     return BDV;
413   }
414 
415   // The behavior of freeze instructions is the same for vector and
416   // non-vector data types.
417   if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
418     auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
419     Cache[Freeze] = BDV;
420     return BDV;
421   }
422 
423   // If the pointer comes through a bitcast of a vector of pointers to
424   // a vector of another type of pointer, then look through the bitcast
425   if (auto *BC = dyn_cast<BitCastInst>(I)) {
426     auto *BDV = findBaseDefiningValue(BC->getOperand(0), Cache, KnownBases);
427     Cache[BC] = BDV;
428     return BDV;
429   }
430 
431   // We assume that functions in the source language only return base
432   // pointers.  This should probably be generalized via attributes to support
433   // both source language and internal functions.
434   if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
435     Cache[I] = I;
436     setKnownBase(I, /* IsKnownBase */true, KnownBases);
437     return I;
438   }
439 
440   // A PHI or Select is a base defining value.  The outer findBasePointer
441   // algorithm is responsible for constructing a base value for this BDV.
442   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
443          "unknown vector instruction - no base found for vector element");
444   Cache[I] = I;
445   setKnownBase(I, /* IsKnownBase */false, KnownBases);
446   return I;
447 }
448 
449 /// Helper function for findBasePointer - Will return a value which either a)
450 /// defines the base pointer for the input, b) blocks the simple search
451 /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
452 /// from pointer to vector type or back.
453 static Value *findBaseDefiningValue(Value *I, DefiningValueMapTy &Cache,
454                                     IsKnownBaseMapTy &KnownBases) {
455   assert(I->getType()->isPtrOrPtrVectorTy() &&
456          "Illegal to ask for the base pointer of a non-pointer type");
457   auto Cached = Cache.find(I);
458   if (Cached != Cache.end())
459     return Cached->second;
460 
461   if (I->getType()->isVectorTy())
462     return findBaseDefiningValueOfVector(I, Cache, KnownBases);
463 
464   if (isa<Argument>(I)) {
465     // An incoming argument to the function is a base pointer
466     // We should have never reached here if this argument isn't an gc value
467     Cache[I] = I;
468     setKnownBase(I, /* IsKnownBase */true, KnownBases);
469     return I;
470   }
471 
472   if (isa<Constant>(I)) {
473     // We assume that objects with a constant base (e.g. a global) can't move
474     // and don't need to be reported to the collector because they are always
475     // live. Besides global references, all kinds of constants (e.g. undef,
476     // constant expressions, null pointers) can be introduced by the inliner or
477     // the optimizer, especially on dynamically dead paths.
478     // Here we treat all of them as having single null base. By doing this we
479     // trying to avoid problems reporting various conflicts in a form of
480     // "phi (const1, const2)" or "phi (const, regular gc ptr)".
481     // See constant.ll file for relevant test cases.
482 
483     auto *CPN = ConstantPointerNull::get(cast<PointerType>(I->getType()));
484     Cache[I] = CPN;
485     setKnownBase(CPN, /* IsKnownBase */true, KnownBases);
486     return CPN;
487   }
488 
489   // inttoptrs in an integral address space are currently ill-defined.  We
490   // treat them as defining base pointers here for consistency with the
491   // constant rule above and because we don't really have a better semantic
492   // to give them.  Note that the optimizer is always free to insert undefined
493   // behavior on dynamically dead paths as well.
494   if (isa<IntToPtrInst>(I)) {
495     Cache[I] = I;
496     setKnownBase(I, /* IsKnownBase */true, KnownBases);
497     return I;
498   }
499 
500   if (CastInst *CI = dyn_cast<CastInst>(I)) {
501     Value *Def = CI->stripPointerCasts();
502     // If stripping pointer casts changes the address space there is an
503     // addrspacecast in between.
504     assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
505                cast<PointerType>(CI->getType())->getAddressSpace() &&
506            "unsupported addrspacecast");
507     // If we find a cast instruction here, it means we've found a cast which is
508     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
509     // handle int->ptr conversion.
510     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
511     auto *BDV = findBaseDefiningValue(Def, Cache, KnownBases);
512     Cache[CI] = BDV;
513     return BDV;
514   }
515 
516   if (isa<LoadInst>(I)) {
517     // The value loaded is an gc base itself
518     Cache[I] = I;
519     setKnownBase(I, /* IsKnownBase */true, KnownBases);
520     return I;
521   }
522 
523   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
524     // The base of this GEP is the base
525     auto *BDV =
526         findBaseDefiningValue(GEP->getPointerOperand(), Cache, KnownBases);
527     Cache[GEP] = BDV;
528     return BDV;
529   }
530 
531   if (auto *Freeze = dyn_cast<FreezeInst>(I)) {
532     auto *BDV = findBaseDefiningValue(Freeze->getOperand(0), Cache, KnownBases);
533     Cache[Freeze] = BDV;
534     return BDV;
535   }
536 
537   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
538     switch (II->getIntrinsicID()) {
539     default:
540       // fall through to general call handling
541       break;
542     case Intrinsic::experimental_gc_statepoint:
543       llvm_unreachable("statepoints don't produce pointers");
544     case Intrinsic::experimental_gc_relocate:
545       // Rerunning safepoint insertion after safepoints are already
546       // inserted is not supported.  It could probably be made to work,
547       // but why are you doing this?  There's no good reason.
548       llvm_unreachable("repeat safepoint insertion is not supported");
549     case Intrinsic::gcroot:
550       // Currently, this mechanism hasn't been extended to work with gcroot.
551       // There's no reason it couldn't be, but I haven't thought about the
552       // implications much.
553       llvm_unreachable(
554           "interaction with the gcroot mechanism is not supported");
555     case Intrinsic::experimental_gc_get_pointer_base:
556       auto *BDV = findBaseDefiningValue(II->getOperand(0), Cache, KnownBases);
557       Cache[II] = BDV;
558       return BDV;
559     }
560   }
561   // We assume that functions in the source language only return base
562   // pointers.  This should probably be generalized via attributes to support
563   // both source language and internal functions.
564   if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
565     Cache[I] = I;
566     setKnownBase(I, /* IsKnownBase */true, KnownBases);
567     return I;
568   }
569 
570   // TODO: I have absolutely no idea how to implement this part yet.  It's not
571   // necessarily hard, I just haven't really looked at it yet.
572   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
573 
574   if (isa<AtomicCmpXchgInst>(I)) {
575     // A CAS is effectively a atomic store and load combined under a
576     // predicate.  From the perspective of base pointers, we just treat it
577     // like a load.
578     Cache[I] = I;
579     setKnownBase(I, /* IsKnownBase */true, KnownBases);
580     return I;
581   }
582 
583   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
584                                    "binary ops which don't apply to pointers");
585 
586   // The aggregate ops.  Aggregates can either be in the heap or on the
587   // stack, but in either case, this is simply a field load.  As a result,
588   // this is a defining definition of the base just like a load is.
589   if (isa<ExtractValueInst>(I)) {
590     Cache[I] = I;
591     setKnownBase(I, /* IsKnownBase */true, KnownBases);
592     return I;
593   }
594 
595   // We should never see an insert vector since that would require we be
596   // tracing back a struct value not a pointer value.
597   assert(!isa<InsertValueInst>(I) &&
598          "Base pointer for a struct is meaningless");
599 
600   // This value might have been generated by findBasePointer() called when
601   // substituting gc.get.pointer.base() intrinsic.
602   bool IsKnownBase =
603       isa<Instruction>(I) && cast<Instruction>(I)->getMetadata("is_base_value");
604   setKnownBase(I, /* IsKnownBase */IsKnownBase, KnownBases);
605   Cache[I] = I;
606 
607   // An extractelement produces a base result exactly when it's input does.
608   // We may need to insert a parallel instruction to extract the appropriate
609   // element out of the base vector corresponding to the input. Given this,
610   // it's analogous to the phi and select case even though it's not a merge.
611   if (isa<ExtractElementInst>(I))
612     // Note: There a lot of obvious peephole cases here.  This are deliberately
613     // handled after the main base pointer inference algorithm to make writing
614     // test cases to exercise that code easier.
615     return I;
616 
617   // The last two cases here don't return a base pointer.  Instead, they
618   // return a value which dynamically selects from among several base
619   // derived pointers (each with it's own base potentially).  It's the job of
620   // the caller to resolve these.
621   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
622          "missing instruction case in findBaseDefiningValue");
623   return I;
624 }
625 
626 /// Returns the base defining value for this value.
627 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache,
628                                           IsKnownBaseMapTy &KnownBases) {
629   if (!Cache.contains(I)) {
630     auto *BDV = findBaseDefiningValue(I, Cache, KnownBases);
631     Cache[I] = BDV;
632     LLVM_DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
633                       << Cache[I]->getName() << ", is known base = "
634                       << KnownBases[I] << "\n");
635   }
636   assert(Cache[I] != nullptr);
637   assert(KnownBases.contains(Cache[I]) &&
638          "Cached value must be present in known bases map");
639   return Cache[I];
640 }
641 
642 /// Return a base pointer for this value if known.  Otherwise, return it's
643 /// base defining value.
644 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache,
645                             IsKnownBaseMapTy &KnownBases) {
646   Value *Def = findBaseDefiningValueCached(I, Cache, KnownBases);
647   auto Found = Cache.find(Def);
648   if (Found != Cache.end()) {
649     // Either a base-of relation, or a self reference.  Caller must check.
650     return Found->second;
651   }
652   // Only a BDV available
653   return Def;
654 }
655 
656 #ifndef NDEBUG
657 /// This value is a base pointer that is not generated by RS4GC, i.e. it already
658 /// exists in the code.
659 static bool isOriginalBaseResult(Value *V) {
660   // no recursion possible
661   return !isa<PHINode>(V) && !isa<SelectInst>(V) &&
662          !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
663          !isa<ShuffleVectorInst>(V);
664 }
665 #endif
666 
667 static bool isKnownBase(Value *V, const IsKnownBaseMapTy &KnownBases) {
668   auto It = KnownBases.find(V);
669   assert(It != KnownBases.end() && "Value not present in the map");
670   return It->second;
671 }
672 
673 static void setKnownBase(Value *V, bool IsKnownBase,
674                          IsKnownBaseMapTy &KnownBases) {
675 #ifndef NDEBUG
676   auto It = KnownBases.find(V);
677   if (It != KnownBases.end())
678     assert(It->second == IsKnownBase && "Changing already present value");
679 #endif
680   KnownBases[V] = IsKnownBase;
681 }
682 
683 // Returns true if First and Second values are both scalar or both vector.
684 static bool areBothVectorOrScalar(Value *First, Value *Second) {
685   return isa<VectorType>(First->getType()) ==
686          isa<VectorType>(Second->getType());
687 }
688 
689 namespace {
690 
691 /// Models the state of a single base defining value in the findBasePointer
692 /// algorithm for determining where a new instruction is needed to propagate
693 /// the base of this BDV.
694 class BDVState {
695 public:
696   enum StatusTy {
697      // Starting state of lattice
698      Unknown,
699      // Some specific base value -- does *not* mean that instruction
700      // propagates the base of the object
701      // ex: gep %arg, 16 -> %arg is the base value
702      Base,
703      // Need to insert a node to represent a merge.
704      Conflict
705   };
706 
707   BDVState() {
708     llvm_unreachable("missing state in map");
709   }
710 
711   explicit BDVState(Value *OriginalValue)
712     : OriginalValue(OriginalValue) {}
713   explicit BDVState(Value *OriginalValue, StatusTy Status, Value *BaseValue = nullptr)
714     : OriginalValue(OriginalValue), Status(Status), BaseValue(BaseValue) {
715     assert(Status != Base || BaseValue);
716   }
717 
718   StatusTy getStatus() const { return Status; }
719   Value *getOriginalValue() const { return OriginalValue; }
720   Value *getBaseValue() const { return BaseValue; }
721 
722   bool isBase() const { return getStatus() == Base; }
723   bool isUnknown() const { return getStatus() == Unknown; }
724   bool isConflict() const { return getStatus() == Conflict; }
725 
726   // Values of type BDVState form a lattice, and this function implements the
727   // meet
728   // operation.
729   void meet(const BDVState &Other) {
730     auto markConflict = [&]() {
731       Status = BDVState::Conflict;
732       BaseValue = nullptr;
733     };
734     // Conflict is a final state.
735     if (isConflict())
736       return;
737     // if we are not known - just take other state.
738     if (isUnknown()) {
739       Status = Other.getStatus();
740       BaseValue = Other.getBaseValue();
741       return;
742     }
743     // We are base.
744     assert(isBase() && "Unknown state");
745     // If other is unknown - just keep our state.
746     if (Other.isUnknown())
747       return;
748     // If other is conflict - it is a final state.
749     if (Other.isConflict())
750       return markConflict();
751     // Other is base as well.
752     assert(Other.isBase() && "Unknown state");
753     // If bases are different - Conflict.
754     if (getBaseValue() != Other.getBaseValue())
755       return markConflict();
756     // We are identical, do nothing.
757   }
758 
759   bool operator==(const BDVState &Other) const {
760     return OriginalValue == Other.OriginalValue && BaseValue == Other.BaseValue &&
761       Status == Other.Status;
762   }
763 
764   bool operator!=(const BDVState &other) const { return !(*this == other); }
765 
766   LLVM_DUMP_METHOD
767   void dump() const {
768     print(dbgs());
769     dbgs() << '\n';
770   }
771 
772   void print(raw_ostream &OS) const {
773     switch (getStatus()) {
774     case Unknown:
775       OS << "U";
776       break;
777     case Base:
778       OS << "B";
779       break;
780     case Conflict:
781       OS << "C";
782       break;
783     }
784     OS << " (base " << getBaseValue() << " - "
785        << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << ")"
786        << " for  "  << OriginalValue->getName() << ":";
787   }
788 
789 private:
790   AssertingVH<Value> OriginalValue; // instruction this state corresponds to
791   StatusTy Status = Unknown;
792   AssertingVH<Value> BaseValue = nullptr; // Non-null only if Status == Base.
793 };
794 
795 } // end anonymous namespace
796 
797 #ifndef NDEBUG
798 static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
799   State.print(OS);
800   return OS;
801 }
802 #endif
803 
804 /// For a given value or instruction, figure out what base ptr its derived from.
805 /// For gc objects, this is simply itself.  On success, returns a value which is
806 /// the base pointer.  (This is reliable and can be used for relocation.)  On
807 /// failure, returns nullptr.
808 static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache,
809                               IsKnownBaseMapTy &KnownBases) {
810   Value *Def = findBaseOrBDV(I, Cache, KnownBases);
811 
812   if (isKnownBase(Def, KnownBases) && areBothVectorOrScalar(Def, I))
813     return Def;
814 
815   // Here's the rough algorithm:
816   // - For every SSA value, construct a mapping to either an actual base
817   //   pointer or a PHI which obscures the base pointer.
818   // - Construct a mapping from PHI to unknown TOP state.  Use an
819   //   optimistic algorithm to propagate base pointer information.  Lattice
820   //   looks like:
821   //   UNKNOWN
822   //   b1 b2 b3 b4
823   //   CONFLICT
824   //   When algorithm terminates, all PHIs will either have a single concrete
825   //   base or be in a conflict state.
826   // - For every conflict, insert a dummy PHI node without arguments.  Add
827   //   these to the base[Instruction] = BasePtr mapping.  For every
828   //   non-conflict, add the actual base.
829   //  - For every conflict, add arguments for the base[a] of each input
830   //   arguments.
831   //
832   // Note: A simpler form of this would be to add the conflict form of all
833   // PHIs without running the optimistic algorithm.  This would be
834   // analogous to pessimistic data flow and would likely lead to an
835   // overall worse solution.
836 
837 #ifndef NDEBUG
838   auto isExpectedBDVType = [](Value *BDV) {
839     return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
840            isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
841            isa<ShuffleVectorInst>(BDV);
842   };
843 #endif
844 
845   // Once populated, will contain a mapping from each potentially non-base BDV
846   // to a lattice value (described above) which corresponds to that BDV.
847   // We use the order of insertion (DFS over the def/use graph) to provide a
848   // stable deterministic ordering for visiting DenseMaps (which are unordered)
849   // below.  This is important for deterministic compilation.
850   MapVector<Value *, BDVState> States;
851 
852 #ifndef NDEBUG
853   auto VerifyStates = [&]() {
854     for (auto &Entry : States) {
855       assert(Entry.first == Entry.second.getOriginalValue());
856     }
857   };
858 #endif
859 
860   auto visitBDVOperands = [](Value *BDV, std::function<void (Value*)> F) {
861     if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
862       for (Value *InVal : PN->incoming_values())
863         F(InVal);
864     } else if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
865       F(SI->getTrueValue());
866       F(SI->getFalseValue());
867     } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
868       F(EE->getVectorOperand());
869     } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)) {
870       F(IE->getOperand(0));
871       F(IE->getOperand(1));
872     } else if (auto *SV = dyn_cast<ShuffleVectorInst>(BDV)) {
873       // For a canonical broadcast, ignore the undef argument
874       // (without this, we insert a parallel base shuffle for every broadcast)
875       F(SV->getOperand(0));
876       if (!SV->isZeroEltSplat())
877         F(SV->getOperand(1));
878     } else {
879       llvm_unreachable("unexpected BDV type");
880     }
881   };
882 
883 
884   // Recursively fill in all base defining values reachable from the initial
885   // one for which we don't already know a definite base value for
886   /* scope */ {
887     SmallVector<Value*, 16> Worklist;
888     Worklist.push_back(Def);
889     States.insert({Def, BDVState(Def)});
890     while (!Worklist.empty()) {
891       Value *Current = Worklist.pop_back_val();
892       assert(!isOriginalBaseResult(Current) && "why did it get added?");
893 
894       auto visitIncomingValue = [&](Value *InVal) {
895         Value *Base = findBaseOrBDV(InVal, Cache, KnownBases);
896         if (isKnownBase(Base, KnownBases) && areBothVectorOrScalar(Base, InVal))
897           // Known bases won't need new instructions introduced and can be
898           // ignored safely. However, this can only be done when InVal and Base
899           // are both scalar or both vector. Otherwise, we need to find a
900           // correct BDV for InVal, by creating an entry in the lattice
901           // (States).
902           return;
903         assert(isExpectedBDVType(Base) && "the only non-base values "
904                "we see should be base defining values");
905         if (States.insert(std::make_pair(Base, BDVState(Base))).second)
906           Worklist.push_back(Base);
907       };
908 
909       visitBDVOperands(Current, visitIncomingValue);
910     }
911   }
912 
913 #ifndef NDEBUG
914   VerifyStates();
915   LLVM_DEBUG(dbgs() << "States after initialization:\n");
916   for (const auto &Pair : States) {
917     LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
918   }
919 #endif
920 
921   // Iterate forward through the value graph pruning any node from the state
922   // list where all of the inputs are base pointers.  The purpose of this is to
923   // reuse existing values when the derived pointer we were asked to materialize
924   // a base pointer for happens to be a base pointer itself.  (Or a sub-graph
925   // feeding it does.)
926   SmallVector<Value *> ToRemove;
927   do {
928     ToRemove.clear();
929     for (auto Pair : States) {
930       Value *BDV = Pair.first;
931       auto canPruneInput = [&](Value *V) {
932         // If the input of the BDV is the BDV itself we can prune it. This is
933         // only possible if the BDV is a PHI node.
934         if (V->stripPointerCasts() == BDV)
935           return true;
936         Value *VBDV = findBaseOrBDV(V, Cache, KnownBases);
937         if (V->stripPointerCasts() != VBDV)
938           return false;
939         // The assumption is that anything not in the state list is
940         // propagates a base pointer.
941         return States.count(VBDV) == 0;
942       };
943 
944       bool CanPrune = true;
945       visitBDVOperands(BDV, [&](Value *Op) {
946         CanPrune = CanPrune && canPruneInput(Op);
947       });
948       if (CanPrune)
949         ToRemove.push_back(BDV);
950     }
951     for (Value *V : ToRemove) {
952       States.erase(V);
953       // Cache the fact V is it's own base for later usage.
954       Cache[V] = V;
955     }
956   } while (!ToRemove.empty());
957 
958   // Did we manage to prove that Def itself must be a base pointer?
959   if (!States.count(Def))
960     return Def;
961 
962   // Return a phi state for a base defining value.  We'll generate a new
963   // base state for known bases and expect to find a cached state otherwise.
964   auto GetStateForBDV = [&](Value *BaseValue, Value *Input) {
965     auto I = States.find(BaseValue);
966     if (I != States.end())
967       return I->second;
968     assert(areBothVectorOrScalar(BaseValue, Input));
969     return BDVState(BaseValue, BDVState::Base, BaseValue);
970   };
971 
972   bool Progress = true;
973   while (Progress) {
974 #ifndef NDEBUG
975     const size_t OldSize = States.size();
976 #endif
977     Progress = false;
978     // We're only changing values in this loop, thus safe to keep iterators.
979     // Since this is computing a fixed point, the order of visit does not
980     // effect the result.  TODO: We could use a worklist here and make this run
981     // much faster.
982     for (auto Pair : States) {
983       Value *BDV = Pair.first;
984       // Only values that do not have known bases or those that have differing
985       // type (scalar versus vector) from a possible known base should be in the
986       // lattice.
987       assert((!isKnownBase(BDV, KnownBases) ||
988              !areBothVectorOrScalar(BDV, Pair.second.getBaseValue())) &&
989                  "why did it get added?");
990 
991       BDVState NewState(BDV);
992       visitBDVOperands(BDV, [&](Value *Op) {
993         Value *BDV = findBaseOrBDV(Op, Cache, KnownBases);
994         auto OpState = GetStateForBDV(BDV, Op);
995         NewState.meet(OpState);
996       });
997 
998       BDVState OldState = States[BDV];
999       if (OldState != NewState) {
1000         Progress = true;
1001         States[BDV] = NewState;
1002       }
1003     }
1004 
1005     assert(OldSize == States.size() &&
1006            "fixed point shouldn't be adding any new nodes to state");
1007   }
1008 
1009 #ifndef NDEBUG
1010   VerifyStates();
1011   LLVM_DEBUG(dbgs() << "States after meet iteration:\n");
1012   for (const auto &Pair : States) {
1013     LLVM_DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
1014   }
1015 #endif
1016 
1017   // Handle all instructions that have a vector BDV, but the instruction itself
1018   // is of scalar type.
1019   for (auto Pair : States) {
1020     Instruction *I = cast<Instruction>(Pair.first);
1021     BDVState State = Pair.second;
1022     auto *BaseValue = State.getBaseValue();
1023     // Only values that do not have known bases or those that have differing
1024     // type (scalar versus vector) from a possible known base should be in the
1025     // lattice.
1026     assert(
1027         (!isKnownBase(I, KnownBases) || !areBothVectorOrScalar(I, BaseValue)) &&
1028         "why did it get added?");
1029     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1030 
1031     if (!State.isBase() || !isa<VectorType>(BaseValue->getType()))
1032       continue;
1033     // extractelement instructions are a bit special in that we may need to
1034     // insert an extract even when we know an exact base for the instruction.
1035     // The problem is that we need to convert from a vector base to a scalar
1036     // base for the particular indice we're interested in.
1037     if (isa<ExtractElementInst>(I)) {
1038       auto *EE = cast<ExtractElementInst>(I);
1039       // TODO: In many cases, the new instruction is just EE itself.  We should
1040       // exploit this, but can't do it here since it would break the invariant
1041       // about the BDV not being known to be a base.
1042       auto *BaseInst = ExtractElementInst::Create(
1043           State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
1044       BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
1045       States[I] = BDVState(I, BDVState::Base, BaseInst);
1046       setKnownBase(BaseInst, /* IsKnownBase */true, KnownBases);
1047     } else if (!isa<VectorType>(I->getType())) {
1048       // We need to handle cases that have a vector base but the instruction is
1049       // a scalar type (these could be phis or selects or any instruction that
1050       // are of scalar type, but the base can be a vector type).  We
1051       // conservatively set this as conflict.  Setting the base value for these
1052       // conflicts is handled in the next loop which traverses States.
1053       States[I] = BDVState(I, BDVState::Conflict);
1054     }
1055   }
1056 
1057 #ifndef NDEBUG
1058   VerifyStates();
1059 #endif
1060 
1061   // Insert Phis for all conflicts
1062   // TODO: adjust naming patterns to avoid this order of iteration dependency
1063   for (auto Pair : States) {
1064     Instruction *I = cast<Instruction>(Pair.first);
1065     BDVState State = Pair.second;
1066     // Only values that do not have known bases or those that have differing
1067     // type (scalar versus vector) from a possible known base should be in the
1068     // lattice.
1069     assert((!isKnownBase(I, KnownBases) ||
1070             !areBothVectorOrScalar(I, State.getBaseValue())) &&
1071            "why did it get added?");
1072     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1073 
1074     // Since we're joining a vector and scalar base, they can never be the
1075     // same.  As a result, we should always see insert element having reached
1076     // the conflict state.
1077     assert(!isa<InsertElementInst>(I) || State.isConflict());
1078 
1079     if (!State.isConflict())
1080       continue;
1081 
1082     auto getMangledName = [](Instruction *I) -> std::string {
1083       if (isa<PHINode>(I)) {
1084         return suffixed_name_or(I, ".base", "base_phi");
1085       } else if (isa<SelectInst>(I)) {
1086         return suffixed_name_or(I, ".base", "base_select");
1087       } else if (isa<ExtractElementInst>(I)) {
1088         return suffixed_name_or(I, ".base", "base_ee");
1089       } else if (isa<InsertElementInst>(I)) {
1090         return suffixed_name_or(I, ".base", "base_ie");
1091       } else {
1092         return suffixed_name_or(I, ".base", "base_sv");
1093       }
1094     };
1095 
1096     Instruction *BaseInst = I->clone();
1097     BaseInst->insertBefore(I);
1098     BaseInst->setName(getMangledName(I));
1099     // Add metadata marking this as a base value
1100     BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
1101     States[I] = BDVState(I, BDVState::Conflict, BaseInst);
1102     setKnownBase(BaseInst, /* IsKnownBase */true, KnownBases);
1103   }
1104 
1105 #ifndef NDEBUG
1106   VerifyStates();
1107 #endif
1108 
1109   // Returns a instruction which produces the base pointer for a given
1110   // instruction.  The instruction is assumed to be an input to one of the BDVs
1111   // seen in the inference algorithm above.  As such, we must either already
1112   // know it's base defining value is a base, or have inserted a new
1113   // instruction to propagate the base of it's BDV and have entered that newly
1114   // introduced instruction into the state table.  In either case, we are
1115   // assured to be able to determine an instruction which produces it's base
1116   // pointer.
1117   auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
1118     Value *BDV = findBaseOrBDV(Input, Cache, KnownBases);
1119     Value *Base = nullptr;
1120     if (!States.count(BDV)) {
1121       assert(areBothVectorOrScalar(BDV, Input));
1122       Base = BDV;
1123     } else {
1124       // Either conflict or base.
1125       assert(States.count(BDV));
1126       Base = States[BDV].getBaseValue();
1127     }
1128     assert(Base && "Can't be null");
1129     // The cast is needed since base traversal may strip away bitcasts
1130     if (Base->getType() != Input->getType() && InsertPt)
1131       Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
1132     return Base;
1133   };
1134 
1135   // Fixup all the inputs of the new PHIs.  Visit order needs to be
1136   // deterministic and predictable because we're naming newly created
1137   // instructions.
1138   for (auto Pair : States) {
1139     Instruction *BDV = cast<Instruction>(Pair.first);
1140     BDVState State = Pair.second;
1141 
1142     // Only values that do not have known bases or those that have differing
1143     // type (scalar versus vector) from a possible known base should be in the
1144     // lattice.
1145     assert((!isKnownBase(BDV, KnownBases) ||
1146             !areBothVectorOrScalar(BDV, State.getBaseValue())) &&
1147            "why did it get added?");
1148     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
1149     if (!State.isConflict())
1150       continue;
1151 
1152     if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
1153       PHINode *PN = cast<PHINode>(BDV);
1154       const unsigned NumPHIValues = PN->getNumIncomingValues();
1155 
1156       // The IR verifier requires phi nodes with multiple entries from the
1157       // same basic block to have the same incoming value for each of those
1158       // entries.  Since we're inserting bitcasts in the loop, make sure we
1159       // do so at least once per incoming block.
1160       DenseMap<BasicBlock *, Value*> BlockToValue;
1161       for (unsigned i = 0; i < NumPHIValues; i++) {
1162         Value *InVal = PN->getIncomingValue(i);
1163         BasicBlock *InBB = PN->getIncomingBlock(i);
1164         if (!BlockToValue.count(InBB))
1165           BlockToValue[InBB] = getBaseForInput(InVal, InBB->getTerminator());
1166         else {
1167 #ifndef NDEBUG
1168           Value *OldBase = BlockToValue[InBB];
1169           Value *Base = getBaseForInput(InVal, nullptr);
1170 
1171           // We can't use `stripPointerCasts` instead of this function because
1172           // `stripPointerCasts` doesn't handle vectors of pointers.
1173           auto StripBitCasts = [](Value *V) -> Value * {
1174             while (auto *BC = dyn_cast<BitCastInst>(V))
1175               V = BC->getOperand(0);
1176             return V;
1177           };
1178           // In essence this assert states: the only way two values
1179           // incoming from the same basic block may be different is by
1180           // being different bitcasts of the same value.  A cleanup
1181           // that remains TODO is changing findBaseOrBDV to return an
1182           // llvm::Value of the correct type (and still remain pure).
1183           // This will remove the need to add bitcasts.
1184           assert(StripBitCasts(Base) == StripBitCasts(OldBase) &&
1185                  "findBaseOrBDV should be pure!");
1186 #endif
1187         }
1188         Value *Base = BlockToValue[InBB];
1189         BasePHI->setIncomingValue(i, Base);
1190       }
1191     } else if (SelectInst *BaseSI =
1192                    dyn_cast<SelectInst>(State.getBaseValue())) {
1193       SelectInst *SI = cast<SelectInst>(BDV);
1194 
1195       // Find the instruction which produces the base for each input.
1196       // We may need to insert a bitcast.
1197       BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
1198       BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
1199     } else if (auto *BaseEE =
1200                    dyn_cast<ExtractElementInst>(State.getBaseValue())) {
1201       Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
1202       // Find the instruction which produces the base for each input.  We may
1203       // need to insert a bitcast.
1204       BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
1205     } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
1206       auto *BdvIE = cast<InsertElementInst>(BDV);
1207       auto UpdateOperand = [&](int OperandIdx) {
1208         Value *InVal = BdvIE->getOperand(OperandIdx);
1209         Value *Base = getBaseForInput(InVal, BaseIE);
1210         BaseIE->setOperand(OperandIdx, Base);
1211       };
1212       UpdateOperand(0); // vector operand
1213       UpdateOperand(1); // scalar operand
1214     } else {
1215       auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1216       auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1217       auto UpdateOperand = [&](int OperandIdx) {
1218         Value *InVal = BdvSV->getOperand(OperandIdx);
1219         Value *Base = getBaseForInput(InVal, BaseSV);
1220         BaseSV->setOperand(OperandIdx, Base);
1221       };
1222       UpdateOperand(0); // vector operand
1223       if (!BdvSV->isZeroEltSplat())
1224         UpdateOperand(1); // vector operand
1225       else {
1226         // Never read, so just use poison
1227         Value *InVal = BdvSV->getOperand(1);
1228         BaseSV->setOperand(1, PoisonValue::get(InVal->getType()));
1229       }
1230     }
1231   }
1232 
1233 #ifndef NDEBUG
1234   VerifyStates();
1235 #endif
1236 
1237   // Cache all of our results so we can cheaply reuse them
1238   // NOTE: This is actually two caches: one of the base defining value
1239   // relation and one of the base pointer relation!  FIXME
1240   for (auto Pair : States) {
1241     auto *BDV = Pair.first;
1242     Value *Base = Pair.second.getBaseValue();
1243     assert(BDV && Base);
1244     // Only values that do not have known bases or those that have differing
1245     // type (scalar versus vector) from a possible known base should be in the
1246     // lattice.
1247     assert(
1248         (!isKnownBase(BDV, KnownBases) || !areBothVectorOrScalar(BDV, Base)) &&
1249         "why did it get added?");
1250 
1251     LLVM_DEBUG(
1252         dbgs() << "Updating base value cache"
1253                << " for: " << BDV->getName() << " from: "
1254                << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
1255                << " to: " << Base->getName() << "\n");
1256 
1257     Cache[BDV] = Base;
1258   }
1259   assert(Cache.count(Def));
1260   return Cache[Def];
1261 }
1262 
1263 // For a set of live pointers (base and/or derived), identify the base
1264 // pointer of the object which they are derived from.  This routine will
1265 // mutate the IR graph as needed to make the 'base' pointer live at the
1266 // definition site of 'derived'.  This ensures that any use of 'derived' can
1267 // also use 'base'.  This may involve the insertion of a number of
1268 // additional PHI nodes.
1269 //
1270 // preconditions: live is a set of pointer type Values
1271 //
1272 // side effects: may insert PHI nodes into the existing CFG, will preserve
1273 // CFG, will not remove or mutate any existing nodes
1274 //
1275 // post condition: PointerToBase contains one (derived, base) pair for every
1276 // pointer in live.  Note that derived can be equal to base if the original
1277 // pointer was a base pointer.
1278 static void findBasePointers(const StatepointLiveSetTy &live,
1279                              PointerToBaseTy &PointerToBase, DominatorTree *DT,
1280                              DefiningValueMapTy &DVCache,
1281                              IsKnownBaseMapTy &KnownBases) {
1282   for (Value *ptr : live) {
1283     Value *base = findBasePointer(ptr, DVCache, KnownBases);
1284     assert(base && "failed to find base pointer");
1285     PointerToBase[ptr] = base;
1286     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1287             DT->dominates(cast<Instruction>(base)->getParent(),
1288                           cast<Instruction>(ptr)->getParent())) &&
1289            "The base we found better dominate the derived pointer");
1290   }
1291 }
1292 
1293 /// Find the required based pointers (and adjust the live set) for the given
1294 /// parse point.
1295 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1296                              CallBase *Call,
1297                              PartiallyConstructedSafepointRecord &result,
1298                              PointerToBaseTy &PointerToBase,
1299                              IsKnownBaseMapTy &KnownBases) {
1300   StatepointLiveSetTy PotentiallyDerivedPointers = result.LiveSet;
1301   // We assume that all pointers passed to deopt are base pointers; as an
1302   // optimization, we can use this to avoid seperately materializing the base
1303   // pointer graph.  This is only relevant since we're very conservative about
1304   // generating new conflict nodes during base pointer insertion.  If we were
1305   // smarter there, this would be irrelevant.
1306   if (auto Opt = Call->getOperandBundle(LLVMContext::OB_deopt))
1307     for (Value *V : Opt->Inputs) {
1308       if (!PotentiallyDerivedPointers.count(V))
1309         continue;
1310       PotentiallyDerivedPointers.remove(V);
1311       PointerToBase[V] = V;
1312     }
1313   findBasePointers(PotentiallyDerivedPointers, PointerToBase, &DT, DVCache,
1314                    KnownBases);
1315 }
1316 
1317 /// Given an updated version of the dataflow liveness results, update the
1318 /// liveset and base pointer maps for the call site CS.
1319 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1320                                   CallBase *Call,
1321                                   PartiallyConstructedSafepointRecord &result,
1322                                   PointerToBaseTy &PointerToBase,
1323                                   GCStrategy *GC);
1324 
1325 static void recomputeLiveInValues(
1326     Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
1327     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,
1328     PointerToBaseTy &PointerToBase, GCStrategy *GC) {
1329   // TODO-PERF: reuse the original liveness, then simply run the dataflow
1330   // again.  The old values are still live and will help it stabilize quickly.
1331   GCPtrLivenessData RevisedLivenessData;
1332   computeLiveInValues(DT, F, RevisedLivenessData, GC);
1333   for (size_t i = 0; i < records.size(); i++) {
1334     struct PartiallyConstructedSafepointRecord &info = records[i];
1335     recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info, PointerToBase,
1336                           GC);
1337   }
1338 }
1339 
1340 // Utility function which clones all instructions from "ChainToBase"
1341 // and inserts them before "InsertBefore". Returns rematerialized value
1342 // which should be used after statepoint.
1343 static Instruction *rematerializeChain(ArrayRef<Instruction *> ChainToBase,
1344                                        Instruction *InsertBefore,
1345                                        Value *RootOfChain,
1346                                        Value *AlternateLiveBase) {
1347   Instruction *LastClonedValue = nullptr;
1348   Instruction *LastValue = nullptr;
1349   // Walk backwards to visit top-most instructions first.
1350   for (Instruction *Instr :
1351        make_range(ChainToBase.rbegin(), ChainToBase.rend())) {
1352     // Only GEP's and casts are supported as we need to be careful to not
1353     // introduce any new uses of pointers not in the liveset.
1354     // Note that it's fine to introduce new uses of pointers which were
1355     // otherwise not used after this statepoint.
1356     assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
1357 
1358     Instruction *ClonedValue = Instr->clone();
1359     ClonedValue->insertBefore(InsertBefore);
1360     ClonedValue->setName(Instr->getName() + ".remat");
1361 
1362     // If it is not first instruction in the chain then it uses previously
1363     // cloned value. We should update it to use cloned value.
1364     if (LastClonedValue) {
1365       assert(LastValue);
1366       ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1367 #ifndef NDEBUG
1368       for (auto *OpValue : ClonedValue->operand_values()) {
1369         // Assert that cloned instruction does not use any instructions from
1370         // this chain other than LastClonedValue
1371         assert(!is_contained(ChainToBase, OpValue) &&
1372                "incorrect use in rematerialization chain");
1373         // Assert that the cloned instruction does not use the RootOfChain
1374         // or the AlternateLiveBase.
1375         assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
1376       }
1377 #endif
1378     } else {
1379       // For the first instruction, replace the use of unrelocated base i.e.
1380       // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
1381       // live set. They have been proved to be the same PHI nodes.  Note
1382       // that the *only* use of the RootOfChain in the ChainToBase list is
1383       // the first Value in the list.
1384       if (RootOfChain != AlternateLiveBase)
1385         ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
1386     }
1387 
1388     LastClonedValue = ClonedValue;
1389     LastValue = Instr;
1390   }
1391   assert(LastClonedValue);
1392   return LastClonedValue;
1393 }
1394 
1395 // When inserting gc.relocate and gc.result calls, we need to ensure there are
1396 // no uses of the original value / return value between the gc.statepoint and
1397 // the gc.relocate / gc.result call.  One case which can arise is a phi node
1398 // starting one of the successor blocks.  We also need to be able to insert the
1399 // gc.relocates only on the path which goes through the statepoint.  We might
1400 // need to split an edge to make this possible.
1401 static BasicBlock *
1402 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1403                             DominatorTree &DT) {
1404   BasicBlock *Ret = BB;
1405   if (!BB->getUniquePredecessor())
1406     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1407 
1408   // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1409   // from it
1410   FoldSingleEntryPHINodes(Ret);
1411   assert(!isa<PHINode>(Ret->begin()) &&
1412          "All PHI nodes should have been removed!");
1413 
1414   // At this point, we can safely insert a gc.relocate or gc.result as the first
1415   // instruction in Ret if needed.
1416   return Ret;
1417 }
1418 
1419 // List of all function attributes which must be stripped when lowering from
1420 // abstract machine model to physical machine model.  Essentially, these are
1421 // all the effects a safepoint might have which we ignored in the abstract
1422 // machine model for purposes of optimization.  We have to strip these on
1423 // both function declarations and call sites.
1424 static constexpr Attribute::AttrKind FnAttrsToStrip[] =
1425   {Attribute::Memory, Attribute::NoSync, Attribute::NoFree};
1426 
1427 // Create new attribute set containing only attributes which can be transferred
1428 // from original call to the safepoint.
1429 static AttributeList legalizeCallAttributes(LLVMContext &Ctx,
1430                                             AttributeList OrigAL,
1431                                             AttributeList StatepointAL) {
1432   if (OrigAL.isEmpty())
1433     return StatepointAL;
1434 
1435   // Remove the readonly, readnone, and statepoint function attributes.
1436   AttrBuilder FnAttrs(Ctx, OrigAL.getFnAttrs());
1437   for (auto Attr : FnAttrsToStrip)
1438     FnAttrs.removeAttribute(Attr);
1439 
1440   for (Attribute A : OrigAL.getFnAttrs()) {
1441     if (isStatepointDirectiveAttr(A))
1442       FnAttrs.removeAttribute(A);
1443   }
1444 
1445   // Just skip parameter and return attributes for now
1446   return StatepointAL.addFnAttributes(Ctx, FnAttrs);
1447 }
1448 
1449 /// Helper function to place all gc relocates necessary for the given
1450 /// statepoint.
1451 /// Inputs:
1452 ///   liveVariables - list of variables to be relocated.
1453 ///   basePtrs - base pointers.
1454 ///   statepointToken - statepoint instruction to which relocates should be
1455 ///   bound.
1456 ///   Builder - Llvm IR builder to be used to construct new calls.
1457 static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1458                               ArrayRef<Value *> BasePtrs,
1459                               Instruction *StatepointToken,
1460                               IRBuilder<> &Builder, GCStrategy *GC) {
1461   if (LiveVariables.empty())
1462     return;
1463 
1464   auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1465     auto ValIt = llvm::find(LiveVec, Val);
1466     assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1467     size_t Index = std::distance(LiveVec.begin(), ValIt);
1468     assert(Index < LiveVec.size() && "Bug in std::find?");
1469     return Index;
1470   };
1471   Module *M = StatepointToken->getModule();
1472 
1473   // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1474   // element type is i8 addrspace(1)*). We originally generated unique
1475   // declarations for each pointer type, but this proved problematic because
1476   // the intrinsic mangling code is incomplete and fragile.  Since we're moving
1477   // towards a single unified pointer type anyways, we can just cast everything
1478   // to an i8* of the right address space.  A bitcast is added later to convert
1479   // gc_relocate to the actual value's type.
1480   auto getGCRelocateDecl = [&](Type *Ty) {
1481     assert(isHandledGCPointerType(Ty, GC));
1482     auto AS = Ty->getScalarType()->getPointerAddressSpace();
1483     Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1484     if (auto *VT = dyn_cast<VectorType>(Ty))
1485       NewTy = FixedVectorType::get(NewTy,
1486                                    cast<FixedVectorType>(VT)->getNumElements());
1487     return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1488                                      {NewTy});
1489   };
1490 
1491   // Lazily populated map from input types to the canonicalized form mentioned
1492   // in the comment above.  This should probably be cached somewhere more
1493   // broadly.
1494   DenseMap<Type *, Function *> TypeToDeclMap;
1495 
1496   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1497     // Generate the gc.relocate call and save the result
1498     Value *BaseIdx = Builder.getInt32(FindIndex(LiveVariables, BasePtrs[i]));
1499     Value *LiveIdx = Builder.getInt32(i);
1500 
1501     Type *Ty = LiveVariables[i]->getType();
1502     if (!TypeToDeclMap.count(Ty))
1503       TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1504     Function *GCRelocateDecl = TypeToDeclMap[Ty];
1505 
1506     // only specify a debug name if we can give a useful one
1507     CallInst *Reloc = Builder.CreateCall(
1508         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1509         suffixed_name_or(LiveVariables[i], ".relocated", ""));
1510     // Trick CodeGen into thinking there are lots of free registers at this
1511     // fake call.
1512     Reloc->setCallingConv(CallingConv::Cold);
1513   }
1514 }
1515 
1516 namespace {
1517 
1518 /// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
1519 /// avoids having to worry about keeping around dangling pointers to Values.
1520 class DeferredReplacement {
1521   AssertingVH<Instruction> Old;
1522   AssertingVH<Instruction> New;
1523   bool IsDeoptimize = false;
1524 
1525   DeferredReplacement() = default;
1526 
1527 public:
1528   static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
1529     assert(Old != New && Old && New &&
1530            "Cannot RAUW equal values or to / from null!");
1531 
1532     DeferredReplacement D;
1533     D.Old = Old;
1534     D.New = New;
1535     return D;
1536   }
1537 
1538   static DeferredReplacement createDelete(Instruction *ToErase) {
1539     DeferredReplacement D;
1540     D.Old = ToErase;
1541     return D;
1542   }
1543 
1544   static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
1545 #ifndef NDEBUG
1546     auto *F = cast<CallInst>(Old)->getCalledFunction();
1547     assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1548            "Only way to construct a deoptimize deferred replacement");
1549 #endif
1550     DeferredReplacement D;
1551     D.Old = Old;
1552     D.IsDeoptimize = true;
1553     return D;
1554   }
1555 
1556   /// Does the task represented by this instance.
1557   void doReplacement() {
1558     Instruction *OldI = Old;
1559     Instruction *NewI = New;
1560 
1561     assert(OldI != NewI && "Disallowed at construction?!");
1562     assert((!IsDeoptimize || !New) &&
1563            "Deoptimize intrinsics are not replaced!");
1564 
1565     Old = nullptr;
1566     New = nullptr;
1567 
1568     if (NewI)
1569       OldI->replaceAllUsesWith(NewI);
1570 
1571     if (IsDeoptimize) {
1572       // Note: we've inserted instructions, so the call to llvm.deoptimize may
1573       // not necessarily be followed by the matching return.
1574       auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
1575       new UnreachableInst(RI->getContext(), RI);
1576       RI->eraseFromParent();
1577     }
1578 
1579     OldI->eraseFromParent();
1580   }
1581 };
1582 
1583 } // end anonymous namespace
1584 
1585 static StringRef getDeoptLowering(CallBase *Call) {
1586   const char *DeoptLowering = "deopt-lowering";
1587   if (Call->hasFnAttr(DeoptLowering)) {
1588     // FIXME: Calls have a *really* confusing interface around attributes
1589     // with values.
1590     const AttributeList &CSAS = Call->getAttributes();
1591     if (CSAS.hasFnAttr(DeoptLowering))
1592       return CSAS.getFnAttr(DeoptLowering).getValueAsString();
1593     Function *F = Call->getCalledFunction();
1594     assert(F && F->hasFnAttribute(DeoptLowering));
1595     return F->getFnAttribute(DeoptLowering).getValueAsString();
1596   }
1597   return "live-through";
1598 }
1599 
1600 static void
1601 makeStatepointExplicitImpl(CallBase *Call, /* to replace */
1602                            const SmallVectorImpl<Value *> &BasePtrs,
1603                            const SmallVectorImpl<Value *> &LiveVariables,
1604                            PartiallyConstructedSafepointRecord &Result,
1605                            std::vector<DeferredReplacement> &Replacements,
1606                            const PointerToBaseTy &PointerToBase,
1607                            GCStrategy *GC) {
1608   assert(BasePtrs.size() == LiveVariables.size());
1609 
1610   // Then go ahead and use the builder do actually do the inserts.  We insert
1611   // immediately before the previous instruction under the assumption that all
1612   // arguments will be available here.  We can't insert afterwards since we may
1613   // be replacing a terminator.
1614   IRBuilder<> Builder(Call);
1615 
1616   ArrayRef<Value *> GCArgs(LiveVariables);
1617   uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
1618   uint32_t NumPatchBytes = 0;
1619   uint32_t Flags = uint32_t(StatepointFlags::None);
1620 
1621   SmallVector<Value *, 8> CallArgs(Call->args());
1622   std::optional<ArrayRef<Use>> DeoptArgs;
1623   if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_deopt))
1624     DeoptArgs = Bundle->Inputs;
1625   std::optional<ArrayRef<Use>> TransitionArgs;
1626   if (auto Bundle = Call->getOperandBundle(LLVMContext::OB_gc_transition)) {
1627     TransitionArgs = Bundle->Inputs;
1628     // TODO: This flag no longer serves a purpose and can be removed later
1629     Flags |= uint32_t(StatepointFlags::GCTransition);
1630   }
1631 
1632   // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
1633   // with a return value, we lower then as never returning calls to
1634   // __llvm_deoptimize that are followed by unreachable to get better codegen.
1635   bool IsDeoptimize = false;
1636 
1637   StatepointDirectives SD =
1638       parseStatepointDirectivesFromAttrs(Call->getAttributes());
1639   if (SD.NumPatchBytes)
1640     NumPatchBytes = *SD.NumPatchBytes;
1641   if (SD.StatepointID)
1642     StatepointID = *SD.StatepointID;
1643 
1644   // Pass through the requested lowering if any.  The default is live-through.
1645   StringRef DeoptLowering = getDeoptLowering(Call);
1646   if (DeoptLowering.equals("live-in"))
1647     Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
1648   else {
1649     assert(DeoptLowering.equals("live-through") && "Unsupported value!");
1650   }
1651 
1652   FunctionCallee CallTarget(Call->getFunctionType(), Call->getCalledOperand());
1653   if (Function *F = dyn_cast<Function>(CallTarget.getCallee())) {
1654     auto IID = F->getIntrinsicID();
1655     if (IID == Intrinsic::experimental_deoptimize) {
1656       // Calls to llvm.experimental.deoptimize are lowered to calls to the
1657       // __llvm_deoptimize symbol.  We want to resolve this now, since the
1658       // verifier does not allow taking the address of an intrinsic function.
1659 
1660       SmallVector<Type *, 8> DomainTy;
1661       for (Value *Arg : CallArgs)
1662         DomainTy.push_back(Arg->getType());
1663       auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1664                                     /* isVarArg = */ false);
1665 
1666       // Note: CallTarget can be a bitcast instruction of a symbol if there are
1667       // calls to @llvm.experimental.deoptimize with different argument types in
1668       // the same module.  This is fine -- we assume the frontend knew what it
1669       // was doing when generating this kind of IR.
1670       CallTarget = F->getParent()
1671                        ->getOrInsertFunction("__llvm_deoptimize", FTy);
1672 
1673       IsDeoptimize = true;
1674     } else if (IID == Intrinsic::memcpy_element_unordered_atomic ||
1675                IID == Intrinsic::memmove_element_unordered_atomic) {
1676       // Unordered atomic memcpy and memmove intrinsics which are not explicitly
1677       // marked as "gc-leaf-function" should be lowered in a GC parseable way.
1678       // Specifically, these calls should be lowered to the
1679       // __llvm_{memcpy|memmove}_element_unordered_atomic_safepoint symbols.
1680       // Similarly to __llvm_deoptimize we want to resolve this now, since the
1681       // verifier does not allow taking the address of an intrinsic function.
1682       //
1683       // Moreover we need to shuffle the arguments for the call in order to
1684       // accommodate GC. The underlying source and destination objects might be
1685       // relocated during copy operation should the GC occur. To relocate the
1686       // derived source and destination pointers the implementation of the
1687       // intrinsic should know the corresponding base pointers.
1688       //
1689       // To make the base pointers available pass them explicitly as arguments:
1690       //   memcpy(dest_derived, source_derived, ...) =>
1691       //   memcpy(dest_base, dest_offset, source_base, source_offset, ...)
1692       auto &Context = Call->getContext();
1693       auto &DL = Call->getModule()->getDataLayout();
1694       auto GetBaseAndOffset = [&](Value *Derived) {
1695         Value *Base = nullptr;
1696         // Optimizations in unreachable code might substitute the real pointer
1697         // with undef, poison or null-derived constant. Return null base for
1698         // them to be consistent with the handling in the main algorithm in
1699         // findBaseDefiningValue.
1700         if (isa<Constant>(Derived))
1701           Base =
1702               ConstantPointerNull::get(cast<PointerType>(Derived->getType()));
1703         else {
1704           assert(PointerToBase.count(Derived));
1705           Base = PointerToBase.find(Derived)->second;
1706         }
1707         unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
1708         unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
1709         Value *Base_int = Builder.CreatePtrToInt(
1710             Base, Type::getIntNTy(Context, IntPtrSize));
1711         Value *Derived_int = Builder.CreatePtrToInt(
1712             Derived, Type::getIntNTy(Context, IntPtrSize));
1713         return std::make_pair(Base, Builder.CreateSub(Derived_int, Base_int));
1714       };
1715 
1716       auto *Dest = CallArgs[0];
1717       Value *DestBase, *DestOffset;
1718       std::tie(DestBase, DestOffset) = GetBaseAndOffset(Dest);
1719 
1720       auto *Source = CallArgs[1];
1721       Value *SourceBase, *SourceOffset;
1722       std::tie(SourceBase, SourceOffset) = GetBaseAndOffset(Source);
1723 
1724       auto *LengthInBytes = CallArgs[2];
1725       auto *ElementSizeCI = cast<ConstantInt>(CallArgs[3]);
1726 
1727       CallArgs.clear();
1728       CallArgs.push_back(DestBase);
1729       CallArgs.push_back(DestOffset);
1730       CallArgs.push_back(SourceBase);
1731       CallArgs.push_back(SourceOffset);
1732       CallArgs.push_back(LengthInBytes);
1733 
1734       SmallVector<Type *, 8> DomainTy;
1735       for (Value *Arg : CallArgs)
1736         DomainTy.push_back(Arg->getType());
1737       auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
1738                                     /* isVarArg = */ false);
1739 
1740       auto GetFunctionName = [](Intrinsic::ID IID, ConstantInt *ElementSizeCI) {
1741         uint64_t ElementSize = ElementSizeCI->getZExtValue();
1742         if (IID == Intrinsic::memcpy_element_unordered_atomic) {
1743           switch (ElementSize) {
1744           case 1:
1745             return "__llvm_memcpy_element_unordered_atomic_safepoint_1";
1746           case 2:
1747             return "__llvm_memcpy_element_unordered_atomic_safepoint_2";
1748           case 4:
1749             return "__llvm_memcpy_element_unordered_atomic_safepoint_4";
1750           case 8:
1751             return "__llvm_memcpy_element_unordered_atomic_safepoint_8";
1752           case 16:
1753             return "__llvm_memcpy_element_unordered_atomic_safepoint_16";
1754           default:
1755             llvm_unreachable("unexpected element size!");
1756           }
1757         }
1758         assert(IID == Intrinsic::memmove_element_unordered_atomic);
1759         switch (ElementSize) {
1760         case 1:
1761           return "__llvm_memmove_element_unordered_atomic_safepoint_1";
1762         case 2:
1763           return "__llvm_memmove_element_unordered_atomic_safepoint_2";
1764         case 4:
1765           return "__llvm_memmove_element_unordered_atomic_safepoint_4";
1766         case 8:
1767           return "__llvm_memmove_element_unordered_atomic_safepoint_8";
1768         case 16:
1769           return "__llvm_memmove_element_unordered_atomic_safepoint_16";
1770         default:
1771           llvm_unreachable("unexpected element size!");
1772         }
1773       };
1774 
1775       CallTarget =
1776           F->getParent()
1777               ->getOrInsertFunction(GetFunctionName(IID, ElementSizeCI), FTy);
1778     }
1779   }
1780 
1781   // Create the statepoint given all the arguments
1782   GCStatepointInst *Token = nullptr;
1783   if (auto *CI = dyn_cast<CallInst>(Call)) {
1784     CallInst *SPCall = Builder.CreateGCStatepointCall(
1785         StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1786         TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1787 
1788     SPCall->setTailCallKind(CI->getTailCallKind());
1789     SPCall->setCallingConv(CI->getCallingConv());
1790 
1791     // Currently we will fail on parameter attributes and on certain
1792     // function attributes.  In case if we can handle this set of attributes -
1793     // set up function attrs directly on statepoint and return attrs later for
1794     // gc_result intrinsic.
1795     SPCall->setAttributes(legalizeCallAttributes(
1796         CI->getContext(), CI->getAttributes(), SPCall->getAttributes()));
1797 
1798     Token = cast<GCStatepointInst>(SPCall);
1799 
1800     // Put the following gc_result and gc_relocate calls immediately after the
1801     // the old call (which we're about to delete)
1802     assert(CI->getNextNode() && "Not a terminator, must have next!");
1803     Builder.SetInsertPoint(CI->getNextNode());
1804     Builder.SetCurrentDebugLocation(CI->getNextNode()->getDebugLoc());
1805   } else {
1806     auto *II = cast<InvokeInst>(Call);
1807 
1808     // Insert the new invoke into the old block.  We'll remove the old one in a
1809     // moment at which point this will become the new terminator for the
1810     // original block.
1811     InvokeInst *SPInvoke = Builder.CreateGCStatepointInvoke(
1812         StatepointID, NumPatchBytes, CallTarget, II->getNormalDest(),
1813         II->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs, GCArgs,
1814         "statepoint_token");
1815 
1816     SPInvoke->setCallingConv(II->getCallingConv());
1817 
1818     // Currently we will fail on parameter attributes and on certain
1819     // function attributes.  In case if we can handle this set of attributes -
1820     // set up function attrs directly on statepoint and return attrs later for
1821     // gc_result intrinsic.
1822     SPInvoke->setAttributes(legalizeCallAttributes(
1823         II->getContext(), II->getAttributes(), SPInvoke->getAttributes()));
1824 
1825     Token = cast<GCStatepointInst>(SPInvoke);
1826 
1827     // Generate gc relocates in exceptional path
1828     BasicBlock *UnwindBlock = II->getUnwindDest();
1829     assert(!isa<PHINode>(UnwindBlock->begin()) &&
1830            UnwindBlock->getUniquePredecessor() &&
1831            "can't safely insert in this block!");
1832 
1833     Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
1834     Builder.SetCurrentDebugLocation(II->getDebugLoc());
1835 
1836     // Attach exceptional gc relocates to the landingpad.
1837     Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
1838     Result.UnwindToken = ExceptionalToken;
1839 
1840     CreateGCRelocates(LiveVariables, BasePtrs, ExceptionalToken, Builder, GC);
1841 
1842     // Generate gc relocates and returns for normal block
1843     BasicBlock *NormalDest = II->getNormalDest();
1844     assert(!isa<PHINode>(NormalDest->begin()) &&
1845            NormalDest->getUniquePredecessor() &&
1846            "can't safely insert in this block!");
1847 
1848     Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
1849 
1850     // gc relocates will be generated later as if it were regular call
1851     // statepoint
1852   }
1853   assert(Token && "Should be set in one of the above branches!");
1854 
1855   if (IsDeoptimize) {
1856     // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
1857     // transform the tail-call like structure to a call to a void function
1858     // followed by unreachable to get better codegen.
1859     Replacements.push_back(
1860         DeferredReplacement::createDeoptimizeReplacement(Call));
1861   } else {
1862     Token->setName("statepoint_token");
1863     if (!Call->getType()->isVoidTy() && !Call->use_empty()) {
1864       StringRef Name = Call->hasName() ? Call->getName() : "";
1865       CallInst *GCResult = Builder.CreateGCResult(Token, Call->getType(), Name);
1866       GCResult->setAttributes(
1867           AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
1868                              Call->getAttributes().getRetAttrs()));
1869 
1870       // We cannot RAUW or delete CS.getInstruction() because it could be in the
1871       // live set of some other safepoint, in which case that safepoint's
1872       // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1873       // llvm::Instruction.  Instead, we defer the replacement and deletion to
1874       // after the live sets have been made explicit in the IR, and we no longer
1875       // have raw pointers to worry about.
1876       Replacements.emplace_back(
1877           DeferredReplacement::createRAUW(Call, GCResult));
1878     } else {
1879       Replacements.emplace_back(DeferredReplacement::createDelete(Call));
1880     }
1881   }
1882 
1883   Result.StatepointToken = Token;
1884 
1885   // Second, create a gc.relocate for every live variable
1886   CreateGCRelocates(LiveVariables, BasePtrs, Token, Builder, GC);
1887 }
1888 
1889 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1890 // which make the relocations happening at this safepoint explicit.
1891 //
1892 // WARNING: Does not do any fixup to adjust users of the original live
1893 // values.  That's the callers responsibility.
1894 static void
1895 makeStatepointExplicit(DominatorTree &DT, CallBase *Call,
1896                        PartiallyConstructedSafepointRecord &Result,
1897                        std::vector<DeferredReplacement> &Replacements,
1898                        const PointerToBaseTy &PointerToBase, GCStrategy *GC) {
1899   const auto &LiveSet = Result.LiveSet;
1900 
1901   // Convert to vector for efficient cross referencing.
1902   SmallVector<Value *, 64> BaseVec, LiveVec;
1903   LiveVec.reserve(LiveSet.size());
1904   BaseVec.reserve(LiveSet.size());
1905   for (Value *L : LiveSet) {
1906     LiveVec.push_back(L);
1907     assert(PointerToBase.count(L));
1908     Value *Base = PointerToBase.find(L)->second;
1909     BaseVec.push_back(Base);
1910   }
1911   assert(LiveVec.size() == BaseVec.size());
1912 
1913   // Do the actual rewriting and delete the old statepoint
1914   makeStatepointExplicitImpl(Call, BaseVec, LiveVec, Result, Replacements,
1915                              PointerToBase, GC);
1916 }
1917 
1918 // Helper function for the relocationViaAlloca.
1919 //
1920 // It receives iterator to the statepoint gc relocates and emits a store to the
1921 // assigned location (via allocaMap) for the each one of them.  It adds the
1922 // visited values into the visitedLiveValues set, which we will later use them
1923 // for validation checking.
1924 static void
1925 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1926                        DenseMap<Value *, AllocaInst *> &AllocaMap,
1927                        DenseSet<Value *> &VisitedLiveValues) {
1928   for (User *U : GCRelocs) {
1929     GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1930     if (!Relocate)
1931       continue;
1932 
1933     Value *OriginalValue = Relocate->getDerivedPtr();
1934     assert(AllocaMap.count(OriginalValue));
1935     Value *Alloca = AllocaMap[OriginalValue];
1936 
1937     // Emit store into the related alloca
1938     // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1939     // the correct type according to alloca.
1940     assert(Relocate->getNextNode() &&
1941            "Should always have one since it's not a terminator");
1942     IRBuilder<> Builder(Relocate->getNextNode());
1943     Value *CastedRelocatedValue =
1944       Builder.CreateBitCast(Relocate,
1945                             cast<AllocaInst>(Alloca)->getAllocatedType(),
1946                             suffixed_name_or(Relocate, ".casted", ""));
1947 
1948     new StoreInst(CastedRelocatedValue, Alloca,
1949                   cast<Instruction>(CastedRelocatedValue)->getNextNode());
1950 
1951 #ifndef NDEBUG
1952     VisitedLiveValues.insert(OriginalValue);
1953 #endif
1954   }
1955 }
1956 
1957 // Helper function for the "relocationViaAlloca". Similar to the
1958 // "insertRelocationStores" but works for rematerialized values.
1959 static void insertRematerializationStores(
1960     const RematerializedValueMapTy &RematerializedValues,
1961     DenseMap<Value *, AllocaInst *> &AllocaMap,
1962     DenseSet<Value *> &VisitedLiveValues) {
1963   for (auto RematerializedValuePair: RematerializedValues) {
1964     Instruction *RematerializedValue = RematerializedValuePair.first;
1965     Value *OriginalValue = RematerializedValuePair.second;
1966 
1967     assert(AllocaMap.count(OriginalValue) &&
1968            "Can not find alloca for rematerialized value");
1969     Value *Alloca = AllocaMap[OriginalValue];
1970 
1971     new StoreInst(RematerializedValue, Alloca,
1972                   RematerializedValue->getNextNode());
1973 
1974 #ifndef NDEBUG
1975     VisitedLiveValues.insert(OriginalValue);
1976 #endif
1977   }
1978 }
1979 
1980 /// Do all the relocation update via allocas and mem2reg
1981 static void relocationViaAlloca(
1982     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1983     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1984 #ifndef NDEBUG
1985   // record initial number of (static) allocas; we'll check we have the same
1986   // number when we get done.
1987   int InitialAllocaNum = 0;
1988   for (Instruction &I : F.getEntryBlock())
1989     if (isa<AllocaInst>(I))
1990       InitialAllocaNum++;
1991 #endif
1992 
1993   // TODO-PERF: change data structures, reserve
1994   DenseMap<Value *, AllocaInst *> AllocaMap;
1995   SmallVector<AllocaInst *, 200> PromotableAllocas;
1996   // Used later to chack that we have enough allocas to store all values
1997   std::size_t NumRematerializedValues = 0;
1998   PromotableAllocas.reserve(Live.size());
1999 
2000   // Emit alloca for "LiveValue" and record it in "allocaMap" and
2001   // "PromotableAllocas"
2002   const DataLayout &DL = F.getParent()->getDataLayout();
2003   auto emitAllocaFor = [&](Value *LiveValue) {
2004     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
2005                                         DL.getAllocaAddrSpace(), "",
2006                                         F.getEntryBlock().getFirstNonPHI());
2007     AllocaMap[LiveValue] = Alloca;
2008     PromotableAllocas.push_back(Alloca);
2009   };
2010 
2011   // Emit alloca for each live gc pointer
2012   for (Value *V : Live)
2013     emitAllocaFor(V);
2014 
2015   // Emit allocas for rematerialized values
2016   for (const auto &Info : Records)
2017     for (auto RematerializedValuePair : Info.RematerializedValues) {
2018       Value *OriginalValue = RematerializedValuePair.second;
2019       if (AllocaMap.count(OriginalValue) != 0)
2020         continue;
2021 
2022       emitAllocaFor(OriginalValue);
2023       ++NumRematerializedValues;
2024     }
2025 
2026   // The next two loops are part of the same conceptual operation.  We need to
2027   // insert a store to the alloca after the original def and at each
2028   // redefinition.  We need to insert a load before each use.  These are split
2029   // into distinct loops for performance reasons.
2030 
2031   // Update gc pointer after each statepoint: either store a relocated value or
2032   // null (if no relocated value was found for this gc pointer and it is not a
2033   // gc_result).  This must happen before we update the statepoint with load of
2034   // alloca otherwise we lose the link between statepoint and old def.
2035   for (const auto &Info : Records) {
2036     Value *Statepoint = Info.StatepointToken;
2037 
2038     // This will be used for consistency check
2039     DenseSet<Value *> VisitedLiveValues;
2040 
2041     // Insert stores for normal statepoint gc relocates
2042     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
2043 
2044     // In case if it was invoke statepoint
2045     // we will insert stores for exceptional path gc relocates.
2046     if (isa<InvokeInst>(Statepoint)) {
2047       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
2048                              VisitedLiveValues);
2049     }
2050 
2051     // Do similar thing with rematerialized values
2052     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
2053                                   VisitedLiveValues);
2054 
2055     if (ClobberNonLive) {
2056       // As a debugging aid, pretend that an unrelocated pointer becomes null at
2057       // the gc.statepoint.  This will turn some subtle GC problems into
2058       // slightly easier to debug SEGVs.  Note that on large IR files with
2059       // lots of gc.statepoints this is extremely costly both memory and time
2060       // wise.
2061       SmallVector<AllocaInst *, 64> ToClobber;
2062       for (auto Pair : AllocaMap) {
2063         Value *Def = Pair.first;
2064         AllocaInst *Alloca = Pair.second;
2065 
2066         // This value was relocated
2067         if (VisitedLiveValues.count(Def)) {
2068           continue;
2069         }
2070         ToClobber.push_back(Alloca);
2071       }
2072 
2073       auto InsertClobbersAt = [&](Instruction *IP) {
2074         for (auto *AI : ToClobber) {
2075           auto AT = AI->getAllocatedType();
2076           Constant *CPN;
2077           if (AT->isVectorTy())
2078             CPN = ConstantAggregateZero::get(AT);
2079           else
2080             CPN = ConstantPointerNull::get(cast<PointerType>(AT));
2081           new StoreInst(CPN, AI, IP);
2082         }
2083       };
2084 
2085       // Insert the clobbering stores.  These may get intermixed with the
2086       // gc.results and gc.relocates, but that's fine.
2087       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
2088         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
2089         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
2090       } else {
2091         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
2092       }
2093     }
2094   }
2095 
2096   // Update use with load allocas and add store for gc_relocated.
2097   for (auto Pair : AllocaMap) {
2098     Value *Def = Pair.first;
2099     AllocaInst *Alloca = Pair.second;
2100 
2101     // We pre-record the uses of allocas so that we dont have to worry about
2102     // later update that changes the user information..
2103 
2104     SmallVector<Instruction *, 20> Uses;
2105     // PERF: trade a linear scan for repeated reallocation
2106     Uses.reserve(Def->getNumUses());
2107     for (User *U : Def->users()) {
2108       if (!isa<ConstantExpr>(U)) {
2109         // If the def has a ConstantExpr use, then the def is either a
2110         // ConstantExpr use itself or null.  In either case
2111         // (recursively in the first, directly in the second), the oop
2112         // it is ultimately dependent on is null and this particular
2113         // use does not need to be fixed up.
2114         Uses.push_back(cast<Instruction>(U));
2115       }
2116     }
2117 
2118     llvm::sort(Uses);
2119     auto Last = std::unique(Uses.begin(), Uses.end());
2120     Uses.erase(Last, Uses.end());
2121 
2122     for (Instruction *Use : Uses) {
2123       if (isa<PHINode>(Use)) {
2124         PHINode *Phi = cast<PHINode>(Use);
2125         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
2126           if (Def == Phi->getIncomingValue(i)) {
2127             LoadInst *Load =
2128                 new LoadInst(Alloca->getAllocatedType(), Alloca, "",
2129                              Phi->getIncomingBlock(i)->getTerminator());
2130             Phi->setIncomingValue(i, Load);
2131           }
2132         }
2133       } else {
2134         LoadInst *Load =
2135             new LoadInst(Alloca->getAllocatedType(), Alloca, "", Use);
2136         Use->replaceUsesOfWith(Def, Load);
2137       }
2138     }
2139 
2140     // Emit store for the initial gc value.  Store must be inserted after load,
2141     // otherwise store will be in alloca's use list and an extra load will be
2142     // inserted before it.
2143     StoreInst *Store = new StoreInst(Def, Alloca, /*volatile*/ false,
2144                                      DL.getABITypeAlign(Def->getType()));
2145     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
2146       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
2147         // InvokeInst is a terminator so the store need to be inserted into its
2148         // normal destination block.
2149         BasicBlock *NormalDest = Invoke->getNormalDest();
2150         Store->insertBefore(NormalDest->getFirstNonPHI());
2151       } else {
2152         assert(!Inst->isTerminator() &&
2153                "The only terminator that can produce a value is "
2154                "InvokeInst which is handled above.");
2155         Store->insertAfter(Inst);
2156       }
2157     } else {
2158       assert(isa<Argument>(Def));
2159       Store->insertAfter(cast<Instruction>(Alloca));
2160     }
2161   }
2162 
2163   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
2164          "we must have the same allocas with lives");
2165   (void) NumRematerializedValues;
2166   if (!PromotableAllocas.empty()) {
2167     // Apply mem2reg to promote alloca to SSA
2168     PromoteMemToReg(PromotableAllocas, DT);
2169   }
2170 
2171 #ifndef NDEBUG
2172   for (auto &I : F.getEntryBlock())
2173     if (isa<AllocaInst>(I))
2174       InitialAllocaNum--;
2175   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
2176 #endif
2177 }
2178 
2179 /// Implement a unique function which doesn't require we sort the input
2180 /// vector.  Doing so has the effect of changing the output of a couple of
2181 /// tests in ways which make them less useful in testing fused safepoints.
2182 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
2183   SmallSet<T, 8> Seen;
2184   erase_if(Vec, [&](const T &V) { return !Seen.insert(V).second; });
2185 }
2186 
2187 /// Insert holders so that each Value is obviously live through the entire
2188 /// lifetime of the call.
2189 static void insertUseHolderAfter(CallBase *Call, const ArrayRef<Value *> Values,
2190                                  SmallVectorImpl<CallInst *> &Holders) {
2191   if (Values.empty())
2192     // No values to hold live, might as well not insert the empty holder
2193     return;
2194 
2195   Module *M = Call->getModule();
2196   // Use a dummy vararg function to actually hold the values live
2197   FunctionCallee Func = M->getOrInsertFunction(
2198       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true));
2199   if (isa<CallInst>(Call)) {
2200     // For call safepoints insert dummy calls right after safepoint
2201     Holders.push_back(
2202         CallInst::Create(Func, Values, "", &*++Call->getIterator()));
2203     return;
2204   }
2205   // For invoke safepooints insert dummy calls both in normal and
2206   // exceptional destination blocks
2207   auto *II = cast<InvokeInst>(Call);
2208   Holders.push_back(CallInst::Create(
2209       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
2210   Holders.push_back(CallInst::Create(
2211       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
2212 }
2213 
2214 static void findLiveReferences(
2215     Function &F, DominatorTree &DT, ArrayRef<CallBase *> toUpdate,
2216     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records,
2217     GCStrategy *GC) {
2218   GCPtrLivenessData OriginalLivenessData;
2219   computeLiveInValues(DT, F, OriginalLivenessData, GC);
2220   for (size_t i = 0; i < records.size(); i++) {
2221     struct PartiallyConstructedSafepointRecord &info = records[i];
2222     analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info, GC);
2223   }
2224 }
2225 
2226 // Helper function for the "rematerializeLiveValues". It walks use chain
2227 // starting from the "CurrentValue" until it reaches the root of the chain, i.e.
2228 // the base or a value it cannot process. Only "simple" values are processed
2229 // (currently it is GEP's and casts). The returned root is  examined by the
2230 // callers of findRematerializableChainToBasePointer.  Fills "ChainToBase" array
2231 // with all visited values.
2232 static Value* findRematerializableChainToBasePointer(
2233   SmallVectorImpl<Instruction*> &ChainToBase,
2234   Value *CurrentValue) {
2235   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2236     ChainToBase.push_back(GEP);
2237     return findRematerializableChainToBasePointer(ChainToBase,
2238                                                   GEP->getPointerOperand());
2239   }
2240 
2241   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2242     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2243       return CI;
2244 
2245     ChainToBase.push_back(CI);
2246     return findRematerializableChainToBasePointer(ChainToBase,
2247                                                   CI->getOperand(0));
2248   }
2249 
2250   // We have reached the root of the chain, which is either equal to the base or
2251   // is the first unsupported value along the use chain.
2252   return CurrentValue;
2253 }
2254 
2255 // Helper function for the "rematerializeLiveValues". Compute cost of the use
2256 // chain we are going to rematerialize.
2257 static InstructionCost
2258 chainToBasePointerCost(SmallVectorImpl<Instruction *> &Chain,
2259                        TargetTransformInfo &TTI) {
2260   InstructionCost Cost = 0;
2261 
2262   for (Instruction *Instr : Chain) {
2263     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2264       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2265              "non noop cast is found during rematerialization");
2266 
2267       Type *SrcTy = CI->getOperand(0)->getType();
2268       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy,
2269                                    TTI::getCastContextHint(CI),
2270                                    TargetTransformInfo::TCK_SizeAndLatency, CI);
2271 
2272     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2273       // Cost of the address calculation
2274       Type *ValTy = GEP->getSourceElementType();
2275       Cost += TTI.getAddressComputationCost(ValTy);
2276 
2277       // And cost of the GEP itself
2278       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2279       //       allowed for the external usage)
2280       if (!GEP->hasAllConstantIndices())
2281         Cost += 2;
2282 
2283     } else {
2284       llvm_unreachable("unsupported instruction type during rematerialization");
2285     }
2286   }
2287 
2288   return Cost;
2289 }
2290 
2291 static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
2292   unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
2293   if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
2294       OrigRootPhi.getParent() != AlternateRootPhi.getParent())
2295     return false;
2296   // Map of incoming values and their corresponding basic blocks of
2297   // OrigRootPhi.
2298   SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
2299   for (unsigned i = 0; i < PhiNum; i++)
2300     CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
2301         OrigRootPhi.getIncomingBlock(i);
2302 
2303   // Both current and base PHIs should have same incoming values and
2304   // the same basic blocks corresponding to the incoming values.
2305   for (unsigned i = 0; i < PhiNum; i++) {
2306     auto CIVI =
2307         CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
2308     if (CIVI == CurrentIncomingValues.end())
2309       return false;
2310     BasicBlock *CurrentIncomingBB = CIVI->second;
2311     if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
2312       return false;
2313   }
2314   return true;
2315 }
2316 
2317 // Find derived pointers that can be recomputed cheap enough and fill
2318 // RematerizationCandidates with such candidates.
2319 static void
2320 findRematerializationCandidates(PointerToBaseTy PointerToBase,
2321                                 RematCandTy &RematerizationCandidates,
2322                                 TargetTransformInfo &TTI) {
2323   const unsigned int ChainLengthThreshold = 10;
2324 
2325   for (auto P2B : PointerToBase) {
2326     auto *Derived = P2B.first;
2327     auto *Base = P2B.second;
2328     // Consider only derived pointers.
2329     if (Derived == Base)
2330       continue;
2331 
2332     // For each live pointer find its defining chain.
2333     SmallVector<Instruction *, 3> ChainToBase;
2334     Value *RootOfChain =
2335         findRematerializableChainToBasePointer(ChainToBase, Derived);
2336 
2337     // Nothing to do, or chain is too long
2338     if ( ChainToBase.size() == 0 ||
2339         ChainToBase.size() > ChainLengthThreshold)
2340       continue;
2341 
2342     // Handle the scenario where the RootOfChain is not equal to the
2343     // Base Value, but they are essentially the same phi values.
2344     if (RootOfChain != PointerToBase[Derived]) {
2345       PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
2346       PHINode *AlternateRootPhi = dyn_cast<PHINode>(PointerToBase[Derived]);
2347       if (!OrigRootPhi || !AlternateRootPhi)
2348         continue;
2349       // PHI nodes that have the same incoming values, and belonging to the same
2350       // basic blocks are essentially the same SSA value.  When the original phi
2351       // has incoming values with different base pointers, the original phi is
2352       // marked as conflict, and an additional `AlternateRootPhi` with the same
2353       // incoming values get generated by the findBasePointer function. We need
2354       // to identify the newly generated AlternateRootPhi (.base version of phi)
2355       // and RootOfChain (the original phi node itself) are the same, so that we
2356       // can rematerialize the gep and casts. This is a workaround for the
2357       // deficiency in the findBasePointer algorithm.
2358       if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
2359         continue;
2360     }
2361     // Compute cost of this chain.
2362     InstructionCost Cost = chainToBasePointerCost(ChainToBase, TTI);
2363     // TODO: We can also account for cases when we will be able to remove some
2364     //       of the rematerialized values by later optimization passes. I.e if
2365     //       we rematerialized several intersecting chains. Or if original values
2366     //       don't have any uses besides this statepoint.
2367 
2368     // Ok, there is a candidate.
2369     RematerizlizationCandidateRecord Record;
2370     Record.ChainToBase = ChainToBase;
2371     Record.RootOfChain = RootOfChain;
2372     Record.Cost = Cost;
2373     RematerizationCandidates.insert({ Derived, Record });
2374   }
2375 }
2376 
2377 // Try to rematerialize derived pointers immediately before their uses
2378 // (instead of rematerializing after every statepoint it is live through).
2379 // This can be beneficial when derived pointer is live across many
2380 // statepoints, but uses are rare.
2381 static void rematerializeLiveValuesAtUses(
2382     RematCandTy &RematerizationCandidates,
2383     MutableArrayRef<PartiallyConstructedSafepointRecord> Records,
2384     PointerToBaseTy &PointerToBase) {
2385   if (!RematDerivedAtUses)
2386     return;
2387 
2388   SmallVector<Instruction *, 32> LiveValuesToBeDeleted;
2389 
2390   LLVM_DEBUG(dbgs() << "Rematerialize derived pointers at uses, "
2391                     << "Num statepoints: " << Records.size() << '\n');
2392 
2393   for (auto &It : RematerizationCandidates) {
2394     Instruction *Cand = cast<Instruction>(It.first);
2395     auto &Record = It.second;
2396 
2397     if (Record.Cost >= RematerializationThreshold)
2398       continue;
2399 
2400     if (Cand->user_empty())
2401       continue;
2402 
2403     if (Cand->hasOneUse())
2404       if (auto *U = dyn_cast<Instruction>(Cand->getUniqueUndroppableUser()))
2405         if (U->getParent() == Cand->getParent())
2406           continue;
2407 
2408     // Rematerialization before PHI nodes is not implemented.
2409     if (llvm::any_of(Cand->users(),
2410                      [](const auto *U) { return isa<PHINode>(U); }))
2411       continue;
2412 
2413     LLVM_DEBUG(dbgs() << "Trying cand " << *Cand << " ... ");
2414 
2415     // Count of rematerialization instructions we introduce is equal to number
2416     // of candidate uses.
2417     // Count of rematerialization instructions we eliminate is equal to number
2418     // of statepoints it is live through.
2419     // Consider transformation profitable if latter is greater than former
2420     // (in other words, we create less than eliminate).
2421     unsigned NumLiveStatepoints = llvm::count_if(
2422         Records, [Cand](const auto &R) { return R.LiveSet.contains(Cand); });
2423     unsigned NumUses = Cand->getNumUses();
2424 
2425     LLVM_DEBUG(dbgs() << "Num uses: " << NumUses << " Num live statepoints: "
2426                       << NumLiveStatepoints << " ");
2427 
2428     if (NumLiveStatepoints < NumUses) {
2429       LLVM_DEBUG(dbgs() << "not profitable\n");
2430       continue;
2431     }
2432 
2433     // If rematerialization is 'free', then favor rematerialization at
2434     // uses as it generally shortens live ranges.
2435     // TODO: Short (size ==1) chains only?
2436     if (NumLiveStatepoints == NumUses && Record.Cost > 0) {
2437       LLVM_DEBUG(dbgs() << "not profitable\n");
2438       continue;
2439     }
2440 
2441     LLVM_DEBUG(dbgs() << "looks profitable\n");
2442 
2443     // ChainToBase may contain another remat candidate (as a sub chain) which
2444     // has been rewritten by now. Need to recollect chain to have up to date
2445     // value.
2446     // TODO: sort records in findRematerializationCandidates() in
2447     // decreasing chain size order?
2448     if (Record.ChainToBase.size() > 1) {
2449       Record.ChainToBase.clear();
2450       findRematerializableChainToBasePointer(Record.ChainToBase, Cand);
2451     }
2452 
2453     // Current rematerialization algorithm is very simple: we rematerialize
2454     // immediately before EVERY use, even if there are several uses in same
2455     // block or if use is local to Cand Def. The reason is that this allows
2456     // us to avoid recomputing liveness without complicated analysis:
2457     // - If we did not eliminate all uses of original Candidate, we do not
2458     //   know exaclty in what BBs it is still live.
2459     // - If we rematerialize once per BB, we need to find proper insertion
2460     //   place (first use in block, but after Def) and analyze if there is
2461     //   statepoint between uses in the block.
2462     while (!Cand->user_empty()) {
2463       Instruction *UserI = cast<Instruction>(*Cand->user_begin());
2464       Instruction *RematChain = rematerializeChain(
2465           Record.ChainToBase, UserI, Record.RootOfChain, PointerToBase[Cand]);
2466       UserI->replaceUsesOfWith(Cand, RematChain);
2467       PointerToBase[RematChain] = PointerToBase[Cand];
2468     }
2469     LiveValuesToBeDeleted.push_back(Cand);
2470   }
2471 
2472   LLVM_DEBUG(dbgs() << "Rematerialized " << LiveValuesToBeDeleted.size()
2473                     << " derived pointers\n");
2474   for (auto *Cand : LiveValuesToBeDeleted) {
2475     assert(Cand->use_empty() && "Unexpected user remain");
2476     RematerizationCandidates.erase(Cand);
2477     for (auto &R : Records) {
2478       assert(!R.LiveSet.contains(Cand) ||
2479              R.LiveSet.contains(PointerToBase[Cand]));
2480       R.LiveSet.remove(Cand);
2481     }
2482   }
2483 
2484   // Recollect not rematerialized chains - we might have rewritten
2485   // their sub-chains.
2486   if (!LiveValuesToBeDeleted.empty()) {
2487     for (auto &P : RematerizationCandidates) {
2488       auto &R = P.second;
2489       if (R.ChainToBase.size() > 1) {
2490         R.ChainToBase.clear();
2491         findRematerializableChainToBasePointer(R.ChainToBase, P.first);
2492       }
2493     }
2494   }
2495 }
2496 
2497 // From the statepoint live set pick values that are cheaper to recompute then
2498 // to relocate. Remove this values from the live set, rematerialize them after
2499 // statepoint and record them in "Info" structure. Note that similar to
2500 // relocated values we don't do any user adjustments here.
2501 static void rematerializeLiveValues(CallBase *Call,
2502                                     PartiallyConstructedSafepointRecord &Info,
2503                                     PointerToBaseTy &PointerToBase,
2504                                     RematCandTy &RematerizationCandidates,
2505                                     TargetTransformInfo &TTI) {
2506   // Record values we are going to delete from this statepoint live set.
2507   // We can not di this in following loop due to iterator invalidation.
2508   SmallVector<Value *, 32> LiveValuesToBeDeleted;
2509 
2510   for (Value *LiveValue : Info.LiveSet) {
2511     auto It = RematerizationCandidates.find(LiveValue);
2512     if (It == RematerizationCandidates.end())
2513       continue;
2514 
2515     RematerizlizationCandidateRecord &Record = It->second;
2516 
2517     InstructionCost Cost = Record.Cost;
2518     // For invokes we need to rematerialize each chain twice - for normal and
2519     // for unwind basic blocks. Model this by multiplying cost by two.
2520     if (isa<InvokeInst>(Call))
2521       Cost *= 2;
2522 
2523     // If it's too expensive - skip it.
2524     if (Cost >= RematerializationThreshold)
2525       continue;
2526 
2527     // Remove value from the live set
2528     LiveValuesToBeDeleted.push_back(LiveValue);
2529 
2530     // Clone instructions and record them inside "Info" structure.
2531 
2532     // Different cases for calls and invokes. For invokes we need to clone
2533     // instructions both on normal and unwind path.
2534     if (isa<CallInst>(Call)) {
2535       Instruction *InsertBefore = Call->getNextNode();
2536       assert(InsertBefore);
2537       Instruction *RematerializedValue =
2538           rematerializeChain(Record.ChainToBase, InsertBefore,
2539                              Record.RootOfChain, PointerToBase[LiveValue]);
2540       Info.RematerializedValues[RematerializedValue] = LiveValue;
2541     } else {
2542       auto *Invoke = cast<InvokeInst>(Call);
2543 
2544       Instruction *NormalInsertBefore =
2545           &*Invoke->getNormalDest()->getFirstInsertionPt();
2546       Instruction *UnwindInsertBefore =
2547           &*Invoke->getUnwindDest()->getFirstInsertionPt();
2548 
2549       Instruction *NormalRematerializedValue =
2550           rematerializeChain(Record.ChainToBase, NormalInsertBefore,
2551                              Record.RootOfChain, PointerToBase[LiveValue]);
2552       Instruction *UnwindRematerializedValue =
2553           rematerializeChain(Record.ChainToBase, UnwindInsertBefore,
2554                              Record.RootOfChain, PointerToBase[LiveValue]);
2555 
2556       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2557       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2558     }
2559   }
2560 
2561   // Remove rematerialized values from the live set.
2562   for (auto *LiveValue: LiveValuesToBeDeleted) {
2563     Info.LiveSet.remove(LiveValue);
2564   }
2565 }
2566 
2567 static bool inlineGetBaseAndOffset(Function &F,
2568                                    SmallVectorImpl<CallInst *> &Intrinsics,
2569                                    DefiningValueMapTy &DVCache,
2570                                    IsKnownBaseMapTy &KnownBases) {
2571   auto &Context = F.getContext();
2572   auto &DL = F.getParent()->getDataLayout();
2573   bool Changed = false;
2574 
2575   for (auto *Callsite : Intrinsics)
2576     switch (Callsite->getIntrinsicID()) {
2577     case Intrinsic::experimental_gc_get_pointer_base: {
2578       Changed = true;
2579       Value *Base =
2580           findBasePointer(Callsite->getOperand(0), DVCache, KnownBases);
2581       assert(!DVCache.count(Callsite));
2582       auto *BaseBC = IRBuilder<>(Callsite).CreateBitCast(
2583           Base, Callsite->getType(), suffixed_name_or(Base, ".cast", ""));
2584       if (BaseBC != Base)
2585         DVCache[BaseBC] = Base;
2586       Callsite->replaceAllUsesWith(BaseBC);
2587       if (!BaseBC->hasName())
2588         BaseBC->takeName(Callsite);
2589       Callsite->eraseFromParent();
2590       break;
2591     }
2592     case Intrinsic::experimental_gc_get_pointer_offset: {
2593       Changed = true;
2594       Value *Derived = Callsite->getOperand(0);
2595       Value *Base = findBasePointer(Derived, DVCache, KnownBases);
2596       assert(!DVCache.count(Callsite));
2597       unsigned AddressSpace = Derived->getType()->getPointerAddressSpace();
2598       unsigned IntPtrSize = DL.getPointerSizeInBits(AddressSpace);
2599       IRBuilder<> Builder(Callsite);
2600       Value *BaseInt =
2601           Builder.CreatePtrToInt(Base, Type::getIntNTy(Context, IntPtrSize),
2602                                  suffixed_name_or(Base, ".int", ""));
2603       Value *DerivedInt =
2604           Builder.CreatePtrToInt(Derived, Type::getIntNTy(Context, IntPtrSize),
2605                                  suffixed_name_or(Derived, ".int", ""));
2606       Value *Offset = Builder.CreateSub(DerivedInt, BaseInt);
2607       Callsite->replaceAllUsesWith(Offset);
2608       Offset->takeName(Callsite);
2609       Callsite->eraseFromParent();
2610       break;
2611     }
2612     default:
2613       llvm_unreachable("Unknown intrinsic");
2614     }
2615 
2616   return Changed;
2617 }
2618 
2619 static bool insertParsePoints(Function &F, DominatorTree &DT,
2620                               TargetTransformInfo &TTI,
2621                               SmallVectorImpl<CallBase *> &ToUpdate,
2622                               DefiningValueMapTy &DVCache,
2623                               IsKnownBaseMapTy &KnownBases) {
2624   std::unique_ptr<GCStrategy> GC = findGCStrategy(F);
2625 
2626 #ifndef NDEBUG
2627   // Validate the input
2628   std::set<CallBase *> Uniqued;
2629   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2630   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2631 
2632   for (CallBase *Call : ToUpdate)
2633     assert(Call->getFunction() == &F);
2634 #endif
2635 
2636   // When inserting gc.relocates for invokes, we need to be able to insert at
2637   // the top of the successor blocks.  See the comment on
2638   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2639   // may restructure the CFG.
2640   for (CallBase *Call : ToUpdate) {
2641     auto *II = dyn_cast<InvokeInst>(Call);
2642     if (!II)
2643       continue;
2644     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2645     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2646   }
2647 
2648   // A list of dummy calls added to the IR to keep various values obviously
2649   // live in the IR.  We'll remove all of these when done.
2650   SmallVector<CallInst *, 64> Holders;
2651 
2652   // Insert a dummy call with all of the deopt operands we'll need for the
2653   // actual safepoint insertion as arguments.  This ensures reference operands
2654   // in the deopt argument list are considered live through the safepoint (and
2655   // thus makes sure they get relocated.)
2656   for (CallBase *Call : ToUpdate) {
2657     SmallVector<Value *, 64> DeoptValues;
2658 
2659     for (Value *Arg : GetDeoptBundleOperands(Call)) {
2660       assert(!isUnhandledGCPointerType(Arg->getType(), GC.get()) &&
2661              "support for FCA unimplemented");
2662       if (isHandledGCPointerType(Arg->getType(), GC.get()))
2663         DeoptValues.push_back(Arg);
2664     }
2665 
2666     insertUseHolderAfter(Call, DeoptValues, Holders);
2667   }
2668 
2669   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2670 
2671   // A) Identify all gc pointers which are statically live at the given call
2672   // site.
2673   findLiveReferences(F, DT, ToUpdate, Records, GC.get());
2674 
2675   /// Global mapping from live pointers to a base-defining-value.
2676   PointerToBaseTy PointerToBase;
2677 
2678   // B) Find the base pointers for each live pointer
2679   for (size_t i = 0; i < Records.size(); i++) {
2680     PartiallyConstructedSafepointRecord &info = Records[i];
2681     findBasePointers(DT, DVCache, ToUpdate[i], info, PointerToBase, KnownBases);
2682   }
2683   if (PrintBasePointers) {
2684     errs() << "Base Pairs (w/o Relocation):\n";
2685     for (auto &Pair : PointerToBase) {
2686       errs() << " derived ";
2687       Pair.first->printAsOperand(errs(), false);
2688       errs() << " base ";
2689       Pair.second->printAsOperand(errs(), false);
2690       errs() << "\n";
2691       ;
2692     }
2693   }
2694 
2695   // The base phi insertion logic (for any safepoint) may have inserted new
2696   // instructions which are now live at some safepoint.  The simplest such
2697   // example is:
2698   // loop:
2699   //   phi a  <-- will be a new base_phi here
2700   //   safepoint 1 <-- that needs to be live here
2701   //   gep a + 1
2702   //   safepoint 2
2703   //   br loop
2704   // We insert some dummy calls after each safepoint to definitely hold live
2705   // the base pointers which were identified for that safepoint.  We'll then
2706   // ask liveness for _every_ base inserted to see what is now live.  Then we
2707   // remove the dummy calls.
2708   Holders.reserve(Holders.size() + Records.size());
2709   for (size_t i = 0; i < Records.size(); i++) {
2710     PartiallyConstructedSafepointRecord &Info = Records[i];
2711 
2712     SmallVector<Value *, 128> Bases;
2713     for (auto *Derived : Info.LiveSet) {
2714       assert(PointerToBase.count(Derived) && "Missed base for derived pointer");
2715       Bases.push_back(PointerToBase[Derived]);
2716     }
2717 
2718     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2719   }
2720 
2721   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2722   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2723   // not the key issue.
2724   recomputeLiveInValues(F, DT, ToUpdate, Records, PointerToBase, GC.get());
2725 
2726   if (PrintBasePointers) {
2727     errs() << "Base Pairs: (w/Relocation)\n";
2728     for (auto Pair : PointerToBase) {
2729       errs() << " derived ";
2730       Pair.first->printAsOperand(errs(), false);
2731       errs() << " base ";
2732       Pair.second->printAsOperand(errs(), false);
2733       errs() << "\n";
2734     }
2735   }
2736 
2737   // It is possible that non-constant live variables have a constant base.  For
2738   // example, a GEP with a variable offset from a global.  In this case we can
2739   // remove it from the liveset.  We already don't add constants to the liveset
2740   // because we assume they won't move at runtime and the GC doesn't need to be
2741   // informed about them.  The same reasoning applies if the base is constant.
2742   // Note that the relocation placement code relies on this filtering for
2743   // correctness as it expects the base to be in the liveset, which isn't true
2744   // if the base is constant.
2745   for (auto &Info : Records) {
2746     Info.LiveSet.remove_if([&](Value *LiveV) {
2747       assert(PointerToBase.count(LiveV) && "Missed base for derived pointer");
2748       return isa<Constant>(PointerToBase[LiveV]);
2749     });
2750   }
2751 
2752   for (CallInst *CI : Holders)
2753     CI->eraseFromParent();
2754 
2755   Holders.clear();
2756 
2757   // Compute the cost of possible re-materialization of derived pointers.
2758   RematCandTy RematerizationCandidates;
2759   findRematerializationCandidates(PointerToBase, RematerizationCandidates, TTI);
2760 
2761   // In order to reduce live set of statepoint we might choose to rematerialize
2762   // some values instead of relocating them. This is purely an optimization and
2763   // does not influence correctness.
2764   // First try rematerialization at uses, then after statepoints.
2765   rematerializeLiveValuesAtUses(RematerizationCandidates, Records,
2766                                 PointerToBase);
2767   for (size_t i = 0; i < Records.size(); i++)
2768     rematerializeLiveValues(ToUpdate[i], Records[i], PointerToBase,
2769                             RematerizationCandidates, TTI);
2770 
2771   // We need this to safely RAUW and delete call or invoke return values that
2772   // may themselves be live over a statepoint.  For details, please see usage in
2773   // makeStatepointExplicitImpl.
2774   std::vector<DeferredReplacement> Replacements;
2775 
2776   // Now run through and replace the existing statepoints with new ones with
2777   // the live variables listed.  We do not yet update uses of the values being
2778   // relocated. We have references to live variables that need to
2779   // survive to the last iteration of this loop.  (By construction, the
2780   // previous statepoint can not be a live variable, thus we can and remove
2781   // the old statepoint calls as we go.)
2782   for (size_t i = 0; i < Records.size(); i++)
2783     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements,
2784                            PointerToBase, GC.get());
2785 
2786   ToUpdate.clear(); // prevent accident use of invalid calls.
2787 
2788   for (auto &PR : Replacements)
2789     PR.doReplacement();
2790 
2791   Replacements.clear();
2792 
2793   for (auto &Info : Records) {
2794     // These live sets may contain state Value pointers, since we replaced calls
2795     // with operand bundles with calls wrapped in gc.statepoint, and some of
2796     // those calls may have been def'ing live gc pointers.  Clear these out to
2797     // avoid accidentally using them.
2798     //
2799     // TODO: We should create a separate data structure that does not contain
2800     // these live sets, and migrate to using that data structure from this point
2801     // onward.
2802     Info.LiveSet.clear();
2803   }
2804   PointerToBase.clear();
2805 
2806   // Do all the fixups of the original live variables to their relocated selves
2807   SmallVector<Value *, 128> Live;
2808   for (const PartiallyConstructedSafepointRecord &Info : Records) {
2809     // We can't simply save the live set from the original insertion.  One of
2810     // the live values might be the result of a call which needs a safepoint.
2811     // That Value* no longer exists and we need to use the new gc_result.
2812     // Thankfully, the live set is embedded in the statepoint (and updated), so
2813     // we just grab that.
2814     llvm::append_range(Live, Info.StatepointToken->gc_args());
2815 #ifndef NDEBUG
2816     // Do some basic validation checking on our liveness results before
2817     // performing relocation.  Relocation can and will turn mistakes in liveness
2818     // results into non-sensical code which is must harder to debug.
2819     // TODO: It would be nice to test consistency as well
2820     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2821            "statepoint must be reachable or liveness is meaningless");
2822     for (Value *V : Info.StatepointToken->gc_args()) {
2823       if (!isa<Instruction>(V))
2824         // Non-instruction values trivial dominate all possible uses
2825         continue;
2826       auto *LiveInst = cast<Instruction>(V);
2827       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2828              "unreachable values should never be live");
2829       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2830              "basic SSA liveness expectation violated by liveness analysis");
2831     }
2832 #endif
2833   }
2834   unique_unsorted(Live);
2835 
2836 #ifndef NDEBUG
2837   // Validation check
2838   for (auto *Ptr : Live)
2839     assert(isHandledGCPointerType(Ptr->getType(), GC.get()) &&
2840            "must be a gc pointer type");
2841 #endif
2842 
2843   relocationViaAlloca(F, DT, Live, Records);
2844   return !Records.empty();
2845 }
2846 
2847 // List of all parameter and return attributes which must be stripped when
2848 // lowering from the abstract machine model.  Note that we list attributes
2849 // here which aren't valid as return attributes, that is okay.
2850 static AttributeMask getParamAndReturnAttributesToRemove() {
2851   AttributeMask R;
2852   R.addAttribute(Attribute::Dereferenceable);
2853   R.addAttribute(Attribute::DereferenceableOrNull);
2854   R.addAttribute(Attribute::ReadNone);
2855   R.addAttribute(Attribute::ReadOnly);
2856   R.addAttribute(Attribute::WriteOnly);
2857   R.addAttribute(Attribute::NoAlias);
2858   R.addAttribute(Attribute::NoFree);
2859   return R;
2860 }
2861 
2862 static void stripNonValidAttributesFromPrototype(Function &F) {
2863   LLVMContext &Ctx = F.getContext();
2864 
2865   // Intrinsics are very delicate.  Lowering sometimes depends the presence
2866   // of certain attributes for correctness, but we may have also inferred
2867   // additional ones in the abstract machine model which need stripped.  This
2868   // assumes that the attributes defined in Intrinsic.td are conservatively
2869   // correct for both physical and abstract model.
2870   if (Intrinsic::ID id = F.getIntrinsicID()) {
2871     F.setAttributes(Intrinsic::getAttributes(Ctx, id));
2872     return;
2873   }
2874 
2875   AttributeMask R = getParamAndReturnAttributesToRemove();
2876   for (Argument &A : F.args())
2877     if (isa<PointerType>(A.getType()))
2878       F.removeParamAttrs(A.getArgNo(), R);
2879 
2880   if (isa<PointerType>(F.getReturnType()))
2881     F.removeRetAttrs(R);
2882 
2883   for (auto Attr : FnAttrsToStrip)
2884     F.removeFnAttr(Attr);
2885 }
2886 
2887 /// Certain metadata on instructions are invalid after running RS4GC.
2888 /// Optimizations that run after RS4GC can incorrectly use this metadata to
2889 /// optimize functions. We drop such metadata on the instruction.
2890 static void stripInvalidMetadataFromInstruction(Instruction &I) {
2891   if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2892     return;
2893   // These are the attributes that are still valid on loads and stores after
2894   // RS4GC.
2895   // The metadata implying dereferenceability and noalias are (conservatively)
2896   // dropped.  This is because semantically, after RewriteStatepointsForGC runs,
2897   // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
2898   // touch the entire heap including noalias objects. Note: The reasoning is
2899   // same as stripping the dereferenceability and noalias attributes that are
2900   // analogous to the metadata counterparts.
2901   // We also drop the invariant.load metadata on the load because that metadata
2902   // implies the address operand to the load points to memory that is never
2903   // changed once it became dereferenceable. This is no longer true after RS4GC.
2904   // Similar reasoning applies to invariant.group metadata, which applies to
2905   // loads within a group.
2906   unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
2907                          LLVMContext::MD_range,
2908                          LLVMContext::MD_alias_scope,
2909                          LLVMContext::MD_nontemporal,
2910                          LLVMContext::MD_nonnull,
2911                          LLVMContext::MD_align,
2912                          LLVMContext::MD_type};
2913 
2914   // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
2915   I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
2916 }
2917 
2918 static void stripNonValidDataFromBody(Function &F) {
2919   if (F.empty())
2920     return;
2921 
2922   LLVMContext &Ctx = F.getContext();
2923   MDBuilder Builder(Ctx);
2924 
2925   // Set of invariantstart instructions that we need to remove.
2926   // Use this to avoid invalidating the instruction iterator.
2927   SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
2928 
2929   for (Instruction &I : instructions(F)) {
2930     // invariant.start on memory location implies that the referenced memory
2931     // location is constant and unchanging. This is no longer true after
2932     // RewriteStatepointsForGC runs because there can be calls to gc.statepoint
2933     // which frees the entire heap and the presence of invariant.start allows
2934     // the optimizer to sink the load of a memory location past a statepoint,
2935     // which is incorrect.
2936     if (auto *II = dyn_cast<IntrinsicInst>(&I))
2937       if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2938         InvariantStartInstructions.push_back(II);
2939         continue;
2940       }
2941 
2942     if (MDNode *Tag = I.getMetadata(LLVMContext::MD_tbaa)) {
2943       MDNode *MutableTBAA = Builder.createMutableTBAAAccessTag(Tag);
2944       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2945     }
2946 
2947     stripInvalidMetadataFromInstruction(I);
2948 
2949     AttributeMask R = getParamAndReturnAttributesToRemove();
2950     if (auto *Call = dyn_cast<CallBase>(&I)) {
2951       for (int i = 0, e = Call->arg_size(); i != e; i++)
2952         if (isa<PointerType>(Call->getArgOperand(i)->getType()))
2953           Call->removeParamAttrs(i, R);
2954       if (isa<PointerType>(Call->getType()))
2955         Call->removeRetAttrs(R);
2956     }
2957   }
2958 
2959   // Delete the invariant.start instructions and RAUW poison.
2960   for (auto *II : InvariantStartInstructions) {
2961     II->replaceAllUsesWith(PoisonValue::get(II->getType()));
2962     II->eraseFromParent();
2963   }
2964 }
2965 
2966 /// Looks up the GC strategy for a given function, returning null if the
2967 /// function doesn't have a GC tag. The strategy is stored in the cache.
2968 static std::unique_ptr<GCStrategy> findGCStrategy(Function &F) {
2969   if (!F.hasGC())
2970     return nullptr;
2971 
2972   return getGCStrategy(F.getGC());
2973 }
2974 
2975 /// Returns true if this function should be rewritten by this pass.  The main
2976 /// point of this function is as an extension point for custom logic.
2977 static bool shouldRewriteStatepointsIn(Function &F) {
2978   if (!F.hasGC())
2979     return false;
2980 
2981   std::unique_ptr<GCStrategy> Strategy = findGCStrategy(F);
2982 
2983   assert(Strategy && "GC strategy is required by function, but was not found");
2984 
2985   return Strategy->useRS4GC();
2986 }
2987 
2988 static void stripNonValidData(Module &M) {
2989 #ifndef NDEBUG
2990   assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
2991 #endif
2992 
2993   for (Function &F : M)
2994     stripNonValidAttributesFromPrototype(F);
2995 
2996   for (Function &F : M)
2997     stripNonValidDataFromBody(F);
2998 }
2999 
3000 bool RewriteStatepointsForGC::runOnFunction(Function &F, DominatorTree &DT,
3001                                             TargetTransformInfo &TTI,
3002                                             const TargetLibraryInfo &TLI) {
3003   assert(!F.isDeclaration() && !F.empty() &&
3004          "need function body to rewrite statepoints in");
3005   assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
3006 
3007   auto NeedsRewrite = [&TLI](Instruction &I) {
3008     if (const auto *Call = dyn_cast<CallBase>(&I)) {
3009       if (isa<GCStatepointInst>(Call))
3010         return false;
3011       if (callsGCLeafFunction(Call, TLI))
3012         return false;
3013 
3014       // Normally it's up to the frontend to make sure that non-leaf calls also
3015       // have proper deopt state if it is required. We make an exception for
3016       // element atomic memcpy/memmove intrinsics here. Unlike other intrinsics
3017       // these are non-leaf by default. They might be generated by the optimizer
3018       // which doesn't know how to produce a proper deopt state. So if we see a
3019       // non-leaf memcpy/memmove without deopt state just treat it as a leaf
3020       // copy and don't produce a statepoint.
3021       if (!AllowStatepointWithNoDeoptInfo &&
3022           !Call->getOperandBundle(LLVMContext::OB_deopt)) {
3023         assert((isa<AtomicMemCpyInst>(Call) || isa<AtomicMemMoveInst>(Call)) &&
3024                "Don't expect any other calls here!");
3025         return false;
3026       }
3027       return true;
3028     }
3029     return false;
3030   };
3031 
3032   // Delete any unreachable statepoints so that we don't have unrewritten
3033   // statepoints surviving this pass.  This makes testing easier and the
3034   // resulting IR less confusing to human readers.
3035   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
3036   bool MadeChange = removeUnreachableBlocks(F, &DTU);
3037   // Flush the Dominator Tree.
3038   DTU.getDomTree();
3039 
3040   // Gather all the statepoints which need rewritten.  Be careful to only
3041   // consider those in reachable code since we need to ask dominance queries
3042   // when rewriting.  We'll delete the unreachable ones in a moment.
3043   SmallVector<CallBase *, 64> ParsePointNeeded;
3044   SmallVector<CallInst *, 64> Intrinsics;
3045   for (Instruction &I : instructions(F)) {
3046     // TODO: only the ones with the flag set!
3047     if (NeedsRewrite(I)) {
3048       // NOTE removeUnreachableBlocks() is stronger than
3049       // DominatorTree::isReachableFromEntry(). In other words
3050       // removeUnreachableBlocks can remove some blocks for which
3051       // isReachableFromEntry() returns true.
3052       assert(DT.isReachableFromEntry(I.getParent()) &&
3053             "no unreachable blocks expected");
3054       ParsePointNeeded.push_back(cast<CallBase>(&I));
3055     }
3056     if (auto *CI = dyn_cast<CallInst>(&I))
3057       if (CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_base ||
3058           CI->getIntrinsicID() == Intrinsic::experimental_gc_get_pointer_offset)
3059         Intrinsics.emplace_back(CI);
3060   }
3061 
3062   // Return early if no work to do.
3063   if (ParsePointNeeded.empty() && Intrinsics.empty())
3064     return MadeChange;
3065 
3066   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
3067   // These are created by LCSSA.  They have the effect of increasing the size
3068   // of liveness sets for no good reason.  It may be harder to do this post
3069   // insertion since relocations and base phis can confuse things.
3070   for (BasicBlock &BB : F)
3071     if (BB.getUniquePredecessor())
3072       MadeChange |= FoldSingleEntryPHINodes(&BB);
3073 
3074   // Before we start introducing relocations, we want to tweak the IR a bit to
3075   // avoid unfortunate code generation effects.  The main example is that we
3076   // want to try to make sure the comparison feeding a branch is after any
3077   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
3078   // values feeding a branch after relocation.  This is semantically correct,
3079   // but results in extra register pressure since both the pre-relocation and
3080   // post-relocation copies must be available in registers.  For code without
3081   // relocations this is handled elsewhere, but teaching the scheduler to
3082   // reverse the transform we're about to do would be slightly complex.
3083   // Note: This may extend the live range of the inputs to the icmp and thus
3084   // increase the liveset of any statepoint we move over.  This is profitable
3085   // as long as all statepoints are in rare blocks.  If we had in-register
3086   // lowering for live values this would be a much safer transform.
3087   auto getConditionInst = [](Instruction *TI) -> Instruction * {
3088     if (auto *BI = dyn_cast<BranchInst>(TI))
3089       if (BI->isConditional())
3090         return dyn_cast<Instruction>(BI->getCondition());
3091     // TODO: Extend this to handle switches
3092     return nullptr;
3093   };
3094   for (BasicBlock &BB : F) {
3095     Instruction *TI = BB.getTerminator();
3096     if (auto *Cond = getConditionInst(TI))
3097       // TODO: Handle more than just ICmps here.  We should be able to move
3098       // most instructions without side effects or memory access.
3099       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
3100         MadeChange = true;
3101         Cond->moveBefore(TI);
3102       }
3103   }
3104 
3105   // Nasty workaround - The base computation code in the main algorithm doesn't
3106   // consider the fact that a GEP can be used to convert a scalar to a vector.
3107   // The right fix for this is to integrate GEPs into the base rewriting
3108   // algorithm properly, this is just a short term workaround to prevent
3109   // crashes by canonicalizing such GEPs into fully vector GEPs.
3110   for (Instruction &I : instructions(F)) {
3111     if (!isa<GetElementPtrInst>(I))
3112       continue;
3113 
3114     unsigned VF = 0;
3115     for (unsigned i = 0; i < I.getNumOperands(); i++)
3116       if (auto *OpndVTy = dyn_cast<VectorType>(I.getOperand(i)->getType())) {
3117         assert(VF == 0 ||
3118                VF == cast<FixedVectorType>(OpndVTy)->getNumElements());
3119         VF = cast<FixedVectorType>(OpndVTy)->getNumElements();
3120       }
3121 
3122     // It's the vector to scalar traversal through the pointer operand which
3123     // confuses base pointer rewriting, so limit ourselves to that case.
3124     if (!I.getOperand(0)->getType()->isVectorTy() && VF != 0) {
3125       IRBuilder<> B(&I);
3126       auto *Splat = B.CreateVectorSplat(VF, I.getOperand(0));
3127       I.setOperand(0, Splat);
3128       MadeChange = true;
3129     }
3130   }
3131 
3132   // Cache the 'defining value' relation used in the computation and
3133   // insertion of base phis and selects.  This ensures that we don't insert
3134   // large numbers of duplicate base_phis. Use one cache for both
3135   // inlineGetBaseAndOffset() and insertParsePoints().
3136   DefiningValueMapTy DVCache;
3137 
3138   // Mapping between a base values and a flag indicating whether it's a known
3139   // base or not.
3140   IsKnownBaseMapTy KnownBases;
3141 
3142   if (!Intrinsics.empty())
3143     // Inline @gc.get.pointer.base() and @gc.get.pointer.offset() before finding
3144     // live references.
3145     MadeChange |= inlineGetBaseAndOffset(F, Intrinsics, DVCache, KnownBases);
3146 
3147   if (!ParsePointNeeded.empty())
3148     MadeChange |=
3149         insertParsePoints(F, DT, TTI, ParsePointNeeded, DVCache, KnownBases);
3150 
3151   return MadeChange;
3152 }
3153 
3154 // liveness computation via standard dataflow
3155 // -------------------------------------------------------------------
3156 
3157 // TODO: Consider using bitvectors for liveness, the set of potentially
3158 // interesting values should be small and easy to pre-compute.
3159 
3160 /// Compute the live-in set for the location rbegin starting from
3161 /// the live-out set of the basic block
3162 static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
3163                                 BasicBlock::reverse_iterator End,
3164                                 SetVector<Value *> &LiveTmp, GCStrategy *GC) {
3165   for (auto &I : make_range(Begin, End)) {
3166     // KILL/Def - Remove this definition from LiveIn
3167     LiveTmp.remove(&I);
3168 
3169     // Don't consider *uses* in PHI nodes, we handle their contribution to
3170     // predecessor blocks when we seed the LiveOut sets
3171     if (isa<PHINode>(I))
3172       continue;
3173 
3174     // USE - Add to the LiveIn set for this instruction
3175     for (Value *V : I.operands()) {
3176       assert(!isUnhandledGCPointerType(V->getType(), GC) &&
3177              "support for FCA unimplemented");
3178       if (isHandledGCPointerType(V->getType(), GC) && !isa<Constant>(V)) {
3179         // The choice to exclude all things constant here is slightly subtle.
3180         // There are two independent reasons:
3181         // - We assume that things which are constant (from LLVM's definition)
3182         // do not move at runtime.  For example, the address of a global
3183         // variable is fixed, even though it's contents may not be.
3184         // - Second, we can't disallow arbitrary inttoptr constants even
3185         // if the language frontend does.  Optimization passes are free to
3186         // locally exploit facts without respect to global reachability.  This
3187         // can create sections of code which are dynamically unreachable and
3188         // contain just about anything.  (see constants.ll in tests)
3189         LiveTmp.insert(V);
3190       }
3191     }
3192   }
3193 }
3194 
3195 static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp,
3196                                GCStrategy *GC) {
3197   for (BasicBlock *Succ : successors(BB)) {
3198     for (auto &I : *Succ) {
3199       PHINode *PN = dyn_cast<PHINode>(&I);
3200       if (!PN)
3201         break;
3202 
3203       Value *V = PN->getIncomingValueForBlock(BB);
3204       assert(!isUnhandledGCPointerType(V->getType(), GC) &&
3205              "support for FCA unimplemented");
3206       if (isHandledGCPointerType(V->getType(), GC) && !isa<Constant>(V))
3207         LiveTmp.insert(V);
3208     }
3209   }
3210 }
3211 
3212 static SetVector<Value *> computeKillSet(BasicBlock *BB, GCStrategy *GC) {
3213   SetVector<Value *> KillSet;
3214   for (Instruction &I : *BB)
3215     if (isHandledGCPointerType(I.getType(), GC))
3216       KillSet.insert(&I);
3217   return KillSet;
3218 }
3219 
3220 #ifndef NDEBUG
3221 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
3222 /// validation check for the liveness computation.
3223 static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
3224                           Instruction *TI, bool TermOkay = false) {
3225   for (Value *V : Live) {
3226     if (auto *I = dyn_cast<Instruction>(V)) {
3227       // The terminator can be a member of the LiveOut set.  LLVM's definition
3228       // of instruction dominance states that V does not dominate itself.  As
3229       // such, we need to special case this to allow it.
3230       if (TermOkay && TI == I)
3231         continue;
3232       assert(DT.dominates(I, TI) &&
3233              "basic SSA liveness expectation violated by liveness analysis");
3234     }
3235   }
3236 }
3237 
3238 /// Check that all the liveness sets used during the computation of liveness
3239 /// obey basic SSA properties.  This is useful for finding cases where we miss
3240 /// a def.
3241 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
3242                           BasicBlock &BB) {
3243   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
3244   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
3245   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
3246 }
3247 #endif
3248 
3249 static void computeLiveInValues(DominatorTree &DT, Function &F,
3250                                 GCPtrLivenessData &Data, GCStrategy *GC) {
3251   SmallSetVector<BasicBlock *, 32> Worklist;
3252 
3253   // Seed the liveness for each individual block
3254   for (BasicBlock &BB : F) {
3255     Data.KillSet[&BB] = computeKillSet(&BB, GC);
3256     Data.LiveSet[&BB].clear();
3257     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB], GC);
3258 
3259 #ifndef NDEBUG
3260     for (Value *Kill : Data.KillSet[&BB])
3261       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
3262 #endif
3263 
3264     Data.LiveOut[&BB] = SetVector<Value *>();
3265     computeLiveOutSeed(&BB, Data.LiveOut[&BB], GC);
3266     Data.LiveIn[&BB] = Data.LiveSet[&BB];
3267     Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
3268     Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
3269     if (!Data.LiveIn[&BB].empty())
3270       Worklist.insert(pred_begin(&BB), pred_end(&BB));
3271   }
3272 
3273   // Propagate that liveness until stable
3274   while (!Worklist.empty()) {
3275     BasicBlock *BB = Worklist.pop_back_val();
3276 
3277     // Compute our new liveout set, then exit early if it hasn't changed despite
3278     // the contribution of our successor.
3279     SetVector<Value *> LiveOut = Data.LiveOut[BB];
3280     const auto OldLiveOutSize = LiveOut.size();
3281     for (BasicBlock *Succ : successors(BB)) {
3282       assert(Data.LiveIn.count(Succ));
3283       LiveOut.set_union(Data.LiveIn[Succ]);
3284     }
3285     // assert OutLiveOut is a subset of LiveOut
3286     if (OldLiveOutSize == LiveOut.size()) {
3287       // If the sets are the same size, then we didn't actually add anything
3288       // when unioning our successors LiveIn.  Thus, the LiveIn of this block
3289       // hasn't changed.
3290       continue;
3291     }
3292     Data.LiveOut[BB] = LiveOut;
3293 
3294     // Apply the effects of this basic block
3295     SetVector<Value *> LiveTmp = LiveOut;
3296     LiveTmp.set_union(Data.LiveSet[BB]);
3297     LiveTmp.set_subtract(Data.KillSet[BB]);
3298 
3299     assert(Data.LiveIn.count(BB));
3300     const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
3301     // assert: OldLiveIn is a subset of LiveTmp
3302     if (OldLiveIn.size() != LiveTmp.size()) {
3303       Data.LiveIn[BB] = LiveTmp;
3304       Worklist.insert(pred_begin(BB), pred_end(BB));
3305     }
3306   } // while (!Worklist.empty())
3307 
3308 #ifndef NDEBUG
3309   // Verify our output against SSA properties.  This helps catch any
3310   // missing kills during the above iteration.
3311   for (BasicBlock &BB : F)
3312     checkBasicSSA(DT, Data, BB);
3313 #endif
3314 }
3315 
3316 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
3317                               StatepointLiveSetTy &Out, GCStrategy *GC) {
3318   BasicBlock *BB = Inst->getParent();
3319 
3320   // Note: The copy is intentional and required
3321   assert(Data.LiveOut.count(BB));
3322   SetVector<Value *> LiveOut = Data.LiveOut[BB];
3323 
3324   // We want to handle the statepoint itself oddly.  It's
3325   // call result is not live (normal), nor are it's arguments
3326   // (unless they're used again later).  This adjustment is
3327   // specifically what we need to relocate
3328   computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(), LiveOut,
3329                       GC);
3330   LiveOut.remove(Inst);
3331   Out.insert(LiveOut.begin(), LiveOut.end());
3332 }
3333 
3334 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
3335                                   CallBase *Call,
3336                                   PartiallyConstructedSafepointRecord &Info,
3337                                   PointerToBaseTy &PointerToBase,
3338                                   GCStrategy *GC) {
3339   StatepointLiveSetTy Updated;
3340   findLiveSetAtInst(Call, RevisedLivenessData, Updated, GC);
3341 
3342   // We may have base pointers which are now live that weren't before.  We need
3343   // to update the PointerToBase structure to reflect this.
3344   for (auto *V : Updated)
3345     PointerToBase.insert({ V, V });
3346 
3347   Info.LiveSet = Updated;
3348 }
3349