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