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