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