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