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