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