1ff0cc061SDimitry Andric //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2ff0cc061SDimitry Andric //
3ff0cc061SDimitry Andric //                     The LLVM Compiler Infrastructure
4ff0cc061SDimitry Andric //
5ff0cc061SDimitry Andric // This file is distributed under the University of Illinois Open Source
6ff0cc061SDimitry Andric // License. See LICENSE.TXT for details.
7ff0cc061SDimitry Andric //
8ff0cc061SDimitry Andric //===----------------------------------------------------------------------===//
9ff0cc061SDimitry Andric //
106d97bb29SDimitry Andric // Rewrite call/invoke instructions so as to make potential relocations
116d97bb29SDimitry Andric // performed by the garbage collector explicit in the IR.
12ff0cc061SDimitry Andric //
13ff0cc061SDimitry Andric //===----------------------------------------------------------------------===//
14ff0cc061SDimitry Andric 
152cab237bSDimitry Andric #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
162cab237bSDimitry Andric 
172cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
182cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
19db17bf38SDimitry Andric #include "llvm/ADT/DenseSet.h"
20db17bf38SDimitry Andric #include "llvm/ADT/MapVector.h"
212cab237bSDimitry Andric #include "llvm/ADT/None.h"
222cab237bSDimitry Andric #include "llvm/ADT/Optional.h"
232cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
24db17bf38SDimitry Andric #include "llvm/ADT/SetVector.h"
252cab237bSDimitry Andric #include "llvm/ADT/SmallSet.h"
262cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
27db17bf38SDimitry Andric #include "llvm/ADT/StringRef.h"
282cab237bSDimitry Andric #include "llvm/ADT/iterator_range.h"
292cab237bSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
30ff0cc061SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
312cab237bSDimitry Andric #include "llvm/IR/Argument.h"
322cab237bSDimitry Andric #include "llvm/IR/Attributes.h"
33ff0cc061SDimitry Andric #include "llvm/IR/BasicBlock.h"
34ff0cc061SDimitry Andric #include "llvm/IR/CallSite.h"
352cab237bSDimitry Andric #include "llvm/IR/CallingConv.h"
362cab237bSDimitry Andric #include "llvm/IR/Constant.h"
372cab237bSDimitry Andric #include "llvm/IR/Constants.h"
382cab237bSDimitry Andric #include "llvm/IR/DataLayout.h"
392cab237bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
40ff0cc061SDimitry Andric #include "llvm/IR/Dominators.h"
41ff0cc061SDimitry Andric #include "llvm/IR/Function.h"
42ff0cc061SDimitry Andric #include "llvm/IR/IRBuilder.h"
43ff0cc061SDimitry Andric #include "llvm/IR/InstIterator.h"
442cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
452cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
46ff0cc061SDimitry Andric #include "llvm/IR/Instructions.h"
47ff0cc061SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
48db17bf38SDimitry Andric #include "llvm/IR/Intrinsics.h"
492cab237bSDimitry Andric #include "llvm/IR/LLVMContext.h"
5097bc6c73SDimitry Andric #include "llvm/IR/MDBuilder.h"
512cab237bSDimitry Andric #include "llvm/IR/Metadata.h"
52db17bf38SDimitry Andric #include "llvm/IR/Module.h"
53ff0cc061SDimitry Andric #include "llvm/IR/Statepoint.h"
542cab237bSDimitry Andric #include "llvm/IR/Type.h"
552cab237bSDimitry Andric #include "llvm/IR/User.h"
56ff0cc061SDimitry Andric #include "llvm/IR/Value.h"
572cab237bSDimitry Andric #include "llvm/IR/ValueHandle.h"
58db17bf38SDimitry Andric #include "llvm/Pass.h"
592cab237bSDimitry Andric #include "llvm/Support/Casting.h"
60ff0cc061SDimitry Andric #include "llvm/Support/CommandLine.h"
612cab237bSDimitry Andric #include "llvm/Support/Compiler.h"
62db17bf38SDimitry Andric #include "llvm/Support/Debug.h"
632cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
642cab237bSDimitry Andric #include "llvm/Support/raw_ostream.h"
65ff0cc061SDimitry Andric #include "llvm/Transforms/Scalar.h"
66ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
67ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
68ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
692cab237bSDimitry Andric #include <algorithm>
702cab237bSDimitry Andric #include <cassert>
712cab237bSDimitry Andric #include <cstddef>
722cab237bSDimitry Andric #include <cstdint>
732cab237bSDimitry Andric #include <iterator>
742cab237bSDimitry Andric #include <set>
752cab237bSDimitry Andric #include <string>
762cab237bSDimitry Andric #include <utility>
772cab237bSDimitry Andric #include <vector>
78ff0cc061SDimitry Andric 
79ff0cc061SDimitry Andric #define DEBUG_TYPE "rewrite-statepoints-for-gc"
80ff0cc061SDimitry Andric 
81ff0cc061SDimitry Andric using namespace llvm;
82ff0cc061SDimitry Andric 
83ff0cc061SDimitry Andric // Print the liveset found at the insert location
84ff0cc061SDimitry Andric static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
85ff0cc061SDimitry Andric                                   cl::init(false));
86ff0cc061SDimitry Andric static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
87ff0cc061SDimitry Andric                                       cl::init(false));
882cab237bSDimitry Andric 
89ff0cc061SDimitry Andric // Print out the base pointers for debugging
90ff0cc061SDimitry Andric static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
91ff0cc061SDimitry Andric                                        cl::init(false));
92ff0cc061SDimitry Andric 
93ff0cc061SDimitry Andric // Cost threshold measuring when it is profitable to rematerialize value instead
94ff0cc061SDimitry Andric // of relocating it
95ff0cc061SDimitry Andric static cl::opt<unsigned>
96ff0cc061SDimitry Andric RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
97ff0cc061SDimitry Andric                            cl::init(6));
98ff0cc061SDimitry Andric 
993ca95b02SDimitry Andric #ifdef EXPENSIVE_CHECKS
100ff0cc061SDimitry Andric static bool ClobberNonLive = true;
101ff0cc061SDimitry Andric #else
102ff0cc061SDimitry Andric static bool ClobberNonLive = false;
103ff0cc061SDimitry Andric #endif
1042cab237bSDimitry Andric 
105ff0cc061SDimitry Andric static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
106ff0cc061SDimitry Andric                                                   cl::location(ClobberNonLive),
107ff0cc061SDimitry Andric                                                   cl::Hidden);
108ff0cc061SDimitry Andric 
1097d523365SDimitry Andric static cl::opt<bool>
1107d523365SDimitry Andric     AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
1117d523365SDimitry Andric                                    cl::Hidden, cl::init(true));
1127d523365SDimitry Andric 
1132cab237bSDimitry Andric /// The IR fed into RewriteStatepointsForGC may have had attributes and
1142cab237bSDimitry Andric /// metadata implying dereferenceability that are no longer valid/correct after
1152cab237bSDimitry Andric /// RewriteStatepointsForGC has run. This is because semantically, after
1162cab237bSDimitry Andric /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
1172cab237bSDimitry Andric /// heap. stripNonValidData (conservatively) restores
1182cab237bSDimitry Andric /// correctness by erasing all attributes in the module that externally imply
1192cab237bSDimitry Andric /// dereferenceability. Similar reasoning also applies to the noalias
1202cab237bSDimitry Andric /// attributes and metadata. gc.statepoint can touch the entire heap including
1212cab237bSDimitry Andric /// noalias objects.
1222cab237bSDimitry Andric /// Apart from attributes and metadata, we also remove instructions that imply
1232cab237bSDimitry Andric /// constant physical memory: llvm.invariant.start.
1242cab237bSDimitry Andric static void stripNonValidData(Module &M);
125ff0cc061SDimitry Andric 
1262cab237bSDimitry Andric static bool shouldRewriteStatepointsIn(Function &F);
1272cab237bSDimitry Andric 
1282cab237bSDimitry Andric PreservedAnalyses RewriteStatepointsForGC::run(Module &M,
1292cab237bSDimitry Andric                                                ModuleAnalysisManager &AM) {
13097bc6c73SDimitry Andric   bool Changed = false;
1312cab237bSDimitry Andric   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1322cab237bSDimitry Andric   for (Function &F : M) {
1332cab237bSDimitry Andric     // Nothing to do for declarations.
1342cab237bSDimitry Andric     if (F.isDeclaration() || F.empty())
1352cab237bSDimitry Andric       continue;
13697bc6c73SDimitry Andric 
1372cab237bSDimitry Andric     // Policy choice says not to rewrite - the most common reason is that we're
1382cab237bSDimitry Andric     // compiling code without a GCStrategy.
1392cab237bSDimitry Andric     if (!shouldRewriteStatepointsIn(F))
1402cab237bSDimitry Andric       continue;
1412cab237bSDimitry Andric 
1422cab237bSDimitry Andric     auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1432cab237bSDimitry Andric     auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
1442cab237bSDimitry Andric     auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1452cab237bSDimitry Andric     Changed |= runOnFunction(F, DT, TTI, TLI);
1462cab237bSDimitry Andric   }
1472cab237bSDimitry Andric   if (!Changed)
1482cab237bSDimitry Andric     return PreservedAnalyses::all();
1492cab237bSDimitry Andric 
1502cab237bSDimitry Andric   // stripNonValidData asserts that shouldRewriteStatepointsIn
15197bc6c73SDimitry Andric   // returns true for at least one function in the module.  Since at least
15297bc6c73SDimitry Andric   // one function changed, we know that the precondition is satisfied.
1532cab237bSDimitry Andric   stripNonValidData(M);
1542cab237bSDimitry Andric 
1552cab237bSDimitry Andric   PreservedAnalyses PA;
1562cab237bSDimitry Andric   PA.preserve<TargetIRAnalysis>();
1572cab237bSDimitry Andric   PA.preserve<TargetLibraryAnalysis>();
1582cab237bSDimitry Andric   return PA;
15997bc6c73SDimitry Andric }
16097bc6c73SDimitry Andric 
1612cab237bSDimitry Andric namespace {
1622cab237bSDimitry Andric 
1632cab237bSDimitry Andric class RewriteStatepointsForGCLegacyPass : public ModulePass {
1642cab237bSDimitry Andric   RewriteStatepointsForGC Impl;
1652cab237bSDimitry Andric 
1662cab237bSDimitry Andric public:
1672cab237bSDimitry Andric   static char ID; // Pass identification, replacement for typeid
1682cab237bSDimitry Andric 
1692cab237bSDimitry Andric   RewriteStatepointsForGCLegacyPass() : ModulePass(ID), Impl() {
1702cab237bSDimitry Andric     initializeRewriteStatepointsForGCLegacyPassPass(
1712cab237bSDimitry Andric         *PassRegistry::getPassRegistry());
1722cab237bSDimitry Andric   }
1732cab237bSDimitry Andric 
1742cab237bSDimitry Andric   bool runOnModule(Module &M) override {
1752cab237bSDimitry Andric     bool Changed = false;
1762cab237bSDimitry Andric     const TargetLibraryInfo &TLI =
1772cab237bSDimitry Andric         getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1782cab237bSDimitry Andric     for (Function &F : M) {
1792cab237bSDimitry Andric       // Nothing to do for declarations.
1802cab237bSDimitry Andric       if (F.isDeclaration() || F.empty())
1812cab237bSDimitry Andric         continue;
1822cab237bSDimitry Andric 
1832cab237bSDimitry Andric       // Policy choice says not to rewrite - the most common reason is that
1842cab237bSDimitry Andric       // we're compiling code without a GCStrategy.
1852cab237bSDimitry Andric       if (!shouldRewriteStatepointsIn(F))
1862cab237bSDimitry Andric         continue;
1872cab237bSDimitry Andric 
1882cab237bSDimitry Andric       TargetTransformInfo &TTI =
1892cab237bSDimitry Andric           getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1902cab237bSDimitry Andric       auto &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
1912cab237bSDimitry Andric 
1922cab237bSDimitry Andric       Changed |= Impl.runOnFunction(F, DT, TTI, TLI);
1932cab237bSDimitry Andric     }
1942cab237bSDimitry Andric 
1952cab237bSDimitry Andric     if (!Changed)
1962cab237bSDimitry Andric       return false;
1972cab237bSDimitry Andric 
1982cab237bSDimitry Andric     // stripNonValidData asserts that shouldRewriteStatepointsIn
1992cab237bSDimitry Andric     // returns true for at least one function in the module.  Since at least
2002cab237bSDimitry Andric     // one function changed, we know that the precondition is satisfied.
2012cab237bSDimitry Andric     stripNonValidData(M);
2022cab237bSDimitry Andric     return true;
20397bc6c73SDimitry Andric   }
204ff0cc061SDimitry Andric 
205ff0cc061SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
206ff0cc061SDimitry Andric     // We add and rewrite a bunch of instructions, but don't really do much
207ff0cc061SDimitry Andric     // else.  We could in theory preserve a lot more analyses here.
208ff0cc061SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
209ff0cc061SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
2102cab237bSDimitry Andric     AU.addRequired<TargetLibraryInfoWrapperPass>();
211ff0cc061SDimitry Andric   }
212ff0cc061SDimitry Andric };
213ff0cc061SDimitry Andric 
2142cab237bSDimitry Andric } // end anonymous namespace
215ff0cc061SDimitry Andric 
2162cab237bSDimitry Andric char RewriteStatepointsForGCLegacyPass::ID = 0;
2172cab237bSDimitry Andric 
2182cab237bSDimitry Andric ModulePass *llvm::createRewriteStatepointsForGCLegacyPass() {
2192cab237bSDimitry Andric   return new RewriteStatepointsForGCLegacyPass();
220ff0cc061SDimitry Andric }
221ff0cc061SDimitry Andric 
2222cab237bSDimitry Andric INITIALIZE_PASS_BEGIN(RewriteStatepointsForGCLegacyPass,
2232cab237bSDimitry Andric                       "rewrite-statepoints-for-gc",
224ff0cc061SDimitry Andric                       "Make relocations explicit at statepoints", false, false)
225ff0cc061SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2263ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2272cab237bSDimitry Andric INITIALIZE_PASS_END(RewriteStatepointsForGCLegacyPass,
2282cab237bSDimitry Andric                     "rewrite-statepoints-for-gc",
229ff0cc061SDimitry Andric                     "Make relocations explicit at statepoints", false, false)
230ff0cc061SDimitry Andric 
231ff0cc061SDimitry Andric namespace {
2322cab237bSDimitry Andric 
233ff0cc061SDimitry Andric struct GCPtrLivenessData {
234ff0cc061SDimitry Andric   /// Values defined in this block.
2353ca95b02SDimitry Andric   MapVector<BasicBlock *, SetVector<Value *>> KillSet;
2362cab237bSDimitry Andric 
237ff0cc061SDimitry Andric   /// Values used in this block (and thus live); does not included values
238ff0cc061SDimitry Andric   /// killed within this block.
2393ca95b02SDimitry Andric   MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
240ff0cc061SDimitry Andric 
241ff0cc061SDimitry Andric   /// Values live into this basic block (i.e. used by any
242ff0cc061SDimitry Andric   /// instruction in this basic block or ones reachable from here)
2433ca95b02SDimitry Andric   MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
244ff0cc061SDimitry Andric 
245ff0cc061SDimitry Andric   /// Values live out of this basic block (i.e. live into
246ff0cc061SDimitry Andric   /// any successor block)
2473ca95b02SDimitry Andric   MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
248ff0cc061SDimitry Andric };
249ff0cc061SDimitry Andric 
250ff0cc061SDimitry Andric // The type of the internal cache used inside the findBasePointers family
251ff0cc061SDimitry Andric // of functions.  From the callers perspective, this is an opaque type and
252ff0cc061SDimitry Andric // should not be inspected.
253ff0cc061SDimitry Andric //
254ff0cc061SDimitry Andric // In the actual implementation this caches two relations:
255ff0cc061SDimitry Andric // - The base relation itself (i.e. this pointer is based on that one)
256ff0cc061SDimitry Andric // - The base defining value relation (i.e. before base_phi insertion)
257ff0cc061SDimitry Andric // Generally, after the execution of a full findBasePointer call, only the
258ff0cc061SDimitry Andric // base relation will remain.  Internally, we add a mixture of the two
259ff0cc061SDimitry Andric // types, then update all the second type to the first type
2602cab237bSDimitry Andric using DefiningValueMapTy = MapVector<Value *, Value *>;
2612cab237bSDimitry Andric using StatepointLiveSetTy = SetVector<Value *>;
2622cab237bSDimitry Andric using RematerializedValueMapTy =
2632cab237bSDimitry Andric     MapVector<AssertingVH<Instruction>, AssertingVH<Value>>;
264ff0cc061SDimitry Andric 
265ff0cc061SDimitry Andric struct PartiallyConstructedSafepointRecord {
2667d523365SDimitry Andric   /// The set of values known to be live across this safepoint
2677d523365SDimitry Andric   StatepointLiveSetTy LiveSet;
268ff0cc061SDimitry Andric 
269ff0cc061SDimitry Andric   /// Mapping from live pointers to a base-defining-value
2703ca95b02SDimitry Andric   MapVector<Value *, Value *> PointerToBase;
271ff0cc061SDimitry Andric 
272ff0cc061SDimitry Andric   /// The *new* gc.statepoint instruction itself.  This produces the token
273ff0cc061SDimitry Andric   /// that normal path gc.relocates and the gc.result are tied to.
274ff0cc061SDimitry Andric   Instruction *StatepointToken;
275ff0cc061SDimitry Andric 
276ff0cc061SDimitry Andric   /// Instruction to which exceptional gc relocates are attached
277ff0cc061SDimitry Andric   /// Makes it easier to iterate through them during relocationViaAlloca.
278ff0cc061SDimitry Andric   Instruction *UnwindToken;
279ff0cc061SDimitry Andric 
280ff0cc061SDimitry Andric   /// Record live values we are rematerialized instead of relocating.
2817d523365SDimitry Andric   /// They are not included into 'LiveSet' field.
282ff0cc061SDimitry Andric   /// Maps rematerialized copy to it's original value.
283ff0cc061SDimitry Andric   RematerializedValueMapTy RematerializedValues;
284ff0cc061SDimitry Andric };
2852cab237bSDimitry Andric 
2862cab237bSDimitry Andric } // end anonymous namespace
287ff0cc061SDimitry Andric 
2887d523365SDimitry Andric static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
2893ca95b02SDimitry Andric   Optional<OperandBundleUse> DeoptBundle =
2903ca95b02SDimitry Andric       CS.getOperandBundle(LLVMContext::OB_deopt);
2917d523365SDimitry Andric 
2927d523365SDimitry Andric   if (!DeoptBundle.hasValue()) {
2937d523365SDimitry Andric     assert(AllowStatepointWithNoDeoptInfo &&
2947d523365SDimitry Andric            "Found non-leaf call without deopt info!");
2957d523365SDimitry Andric     return None;
2967d523365SDimitry Andric   }
2977d523365SDimitry Andric 
2987d523365SDimitry Andric   return DeoptBundle.getValue().Inputs;
2997d523365SDimitry Andric }
3007d523365SDimitry Andric 
301ff0cc061SDimitry Andric /// Compute the live-in set for every basic block in the function
302ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
303ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data);
304ff0cc061SDimitry Andric 
305ff0cc061SDimitry Andric /// Given results from the dataflow liveness computation, find the set of live
306ff0cc061SDimitry Andric /// Values at a particular instruction.
307ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
308ff0cc061SDimitry Andric                               StatepointLiveSetTy &out);
309ff0cc061SDimitry Andric 
310ff0cc061SDimitry Andric // TODO: Once we can get to the GCStrategy, this becomes
3117d523365SDimitry Andric // Optional<bool> isGCManagedPointer(const Type *Ty) const override {
312ff0cc061SDimitry Andric 
3137d523365SDimitry Andric static bool isGCPointerType(Type *T) {
3147d523365SDimitry Andric   if (auto *PT = dyn_cast<PointerType>(T))
315ff0cc061SDimitry Andric     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
316ff0cc061SDimitry Andric     // GC managed heap.  We know that a pointer into this heap needs to be
317ff0cc061SDimitry Andric     // updated and that no other pointer does.
3183ca95b02SDimitry Andric     return PT->getAddressSpace() == 1;
319ff0cc061SDimitry Andric   return false;
320ff0cc061SDimitry Andric }
321ff0cc061SDimitry Andric 
322ff0cc061SDimitry Andric // Return true if this type is one which a) is a gc pointer or contains a GC
323ff0cc061SDimitry Andric // pointer and b) is of a type this code expects to encounter as a live value.
324ff0cc061SDimitry Andric // (The insertion code will assert that a type which matches (a) and not (b)
325ff0cc061SDimitry Andric // is not encountered.)
326ff0cc061SDimitry Andric static bool isHandledGCPointerType(Type *T) {
327ff0cc061SDimitry Andric   // We fully support gc pointers
328ff0cc061SDimitry Andric   if (isGCPointerType(T))
329ff0cc061SDimitry Andric     return true;
330ff0cc061SDimitry Andric   // We partially support vectors of gc pointers. The code will assert if it
331ff0cc061SDimitry Andric   // can't handle something.
332ff0cc061SDimitry Andric   if (auto VT = dyn_cast<VectorType>(T))
333ff0cc061SDimitry Andric     if (isGCPointerType(VT->getElementType()))
334ff0cc061SDimitry Andric       return true;
335ff0cc061SDimitry Andric   return false;
336ff0cc061SDimitry Andric }
337ff0cc061SDimitry Andric 
338ff0cc061SDimitry Andric #ifndef NDEBUG
339ff0cc061SDimitry Andric /// Returns true if this type contains a gc pointer whether we know how to
340ff0cc061SDimitry Andric /// handle that type or not.
341ff0cc061SDimitry Andric static bool containsGCPtrType(Type *Ty) {
342ff0cc061SDimitry Andric   if (isGCPointerType(Ty))
343ff0cc061SDimitry Andric     return true;
344ff0cc061SDimitry Andric   if (VectorType *VT = dyn_cast<VectorType>(Ty))
345ff0cc061SDimitry Andric     return isGCPointerType(VT->getScalarType());
346ff0cc061SDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
347ff0cc061SDimitry Andric     return containsGCPtrType(AT->getElementType());
348ff0cc061SDimitry Andric   if (StructType *ST = dyn_cast<StructType>(Ty))
3492cab237bSDimitry Andric     return llvm::any_of(ST->subtypes(), containsGCPtrType);
350ff0cc061SDimitry Andric   return false;
351ff0cc061SDimitry Andric }
352ff0cc061SDimitry Andric 
353ff0cc061SDimitry Andric // Returns true if this is a type which a) is a gc pointer or contains a GC
354ff0cc061SDimitry Andric // pointer and b) is of a type which the code doesn't expect (i.e. first class
355ff0cc061SDimitry Andric // aggregates).  Used to trip assertions.
356ff0cc061SDimitry Andric static bool isUnhandledGCPointerType(Type *Ty) {
357ff0cc061SDimitry Andric   return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
358ff0cc061SDimitry Andric }
359ff0cc061SDimitry Andric #endif
360ff0cc061SDimitry Andric 
3617d523365SDimitry Andric // Return the name of the value suffixed with the provided value, or if the
3627d523365SDimitry Andric // value didn't have a name, the default value specified.
3637d523365SDimitry Andric static std::string suffixed_name_or(Value *V, StringRef Suffix,
3647d523365SDimitry Andric                                     StringRef DefaultName) {
3657d523365SDimitry Andric   return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
3667d523365SDimitry Andric }
3677d523365SDimitry Andric 
368ff0cc061SDimitry Andric // Conservatively identifies any definitions which might be live at the
369ff0cc061SDimitry Andric // given instruction. The  analysis is performed immediately before the
370ff0cc061SDimitry Andric // given instruction. Values defined by that instruction are not considered
371ff0cc061SDimitry Andric // live.  Values used by that instruction are considered live.
3723ca95b02SDimitry Andric static void
3733ca95b02SDimitry Andric analyzeParsePointLiveness(DominatorTree &DT,
3743ca95b02SDimitry Andric                           GCPtrLivenessData &OriginalLivenessData, CallSite CS,
3753ca95b02SDimitry Andric                           PartiallyConstructedSafepointRecord &Result) {
3763ca95b02SDimitry Andric   Instruction *Inst = CS.getInstruction();
377ff0cc061SDimitry Andric 
3787d523365SDimitry Andric   StatepointLiveSetTy LiveSet;
3793ca95b02SDimitry Andric   findLiveSetAtInst(Inst, OriginalLivenessData, LiveSet);
380ff0cc061SDimitry Andric 
381ff0cc061SDimitry Andric   if (PrintLiveSet) {
3823ca95b02SDimitry Andric     dbgs() << "Live Variables:\n";
3833ca95b02SDimitry Andric     for (Value *V : LiveSet)
3847d523365SDimitry Andric       dbgs() << " " << V->getName() << " " << *V << "\n";
385ff0cc061SDimitry Andric   }
386ff0cc061SDimitry Andric   if (PrintLiveSetSize) {
3873ca95b02SDimitry Andric     dbgs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
3883ca95b02SDimitry Andric     dbgs() << "Number live values: " << LiveSet.size() << "\n";
389ff0cc061SDimitry Andric   }
3903ca95b02SDimitry Andric   Result.LiveSet = LiveSet;
391ff0cc061SDimitry Andric }
392ff0cc061SDimitry Andric 
3937d523365SDimitry Andric static bool isKnownBaseResult(Value *V);
3942cab237bSDimitry Andric 
3957d523365SDimitry Andric namespace {
3962cab237bSDimitry Andric 
3977d523365SDimitry Andric /// A single base defining value - An immediate base defining value for an
3987d523365SDimitry Andric /// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
3997d523365SDimitry Andric /// For instructions which have multiple pointer [vector] inputs or that
4007d523365SDimitry Andric /// transition between vector and scalar types, there is no immediate base
4017d523365SDimitry Andric /// defining value.  The 'base defining value' for 'Def' is the transitive
4027d523365SDimitry Andric /// closure of this relation stopping at the first instruction which has no
4037d523365SDimitry Andric /// immediate base defining value.  The b.d.v. might itself be a base pointer,
4047d523365SDimitry Andric /// but it can also be an arbitrary derived pointer.
4057d523365SDimitry Andric struct BaseDefiningValueResult {
4067d523365SDimitry Andric   /// Contains the value which is the base defining value.
4077d523365SDimitry Andric   Value * const BDV;
4082cab237bSDimitry Andric 
4097d523365SDimitry Andric   /// True if the base defining value is also known to be an actual base
4107d523365SDimitry Andric   /// pointer.
4117d523365SDimitry Andric   const bool IsKnownBase;
4122cab237bSDimitry Andric 
4137d523365SDimitry Andric   BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
4147d523365SDimitry Andric     : BDV(BDV), IsKnownBase(IsKnownBase) {
4157d523365SDimitry Andric #ifndef NDEBUG
4167d523365SDimitry Andric     // Check consistency between new and old means of checking whether a BDV is
4177d523365SDimitry Andric     // a base.
4187d523365SDimitry Andric     bool MustBeBase = isKnownBaseResult(BDV);
4197d523365SDimitry Andric     assert(!MustBeBase || MustBeBase == IsKnownBase);
4207d523365SDimitry Andric #endif
4217d523365SDimitry Andric   }
4227d523365SDimitry Andric };
4232cab237bSDimitry Andric 
4242cab237bSDimitry Andric } // end anonymous namespace
4257d523365SDimitry Andric 
4267d523365SDimitry Andric static BaseDefiningValueResult findBaseDefiningValue(Value *I);
427ff0cc061SDimitry Andric 
4283dac3a9bSDimitry Andric /// Return a base defining value for the 'Index' element of the given vector
4293dac3a9bSDimitry Andric /// instruction 'I'.  If Index is null, returns a BDV for the entire vector
4303dac3a9bSDimitry Andric /// 'I'.  As an optimization, this method will try to determine when the
4313dac3a9bSDimitry Andric /// element is known to already be a base pointer.  If this can be established,
4323dac3a9bSDimitry Andric /// the second value in the returned pair will be true.  Note that either a
4333dac3a9bSDimitry Andric /// vector or a pointer typed value can be returned.  For the former, the
4343dac3a9bSDimitry Andric /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
4353dac3a9bSDimitry Andric /// If the later, the return pointer is a BDV (or possibly a base) for the
4363dac3a9bSDimitry Andric /// particular element in 'I'.
4377d523365SDimitry Andric static BaseDefiningValueResult
4387d523365SDimitry Andric findBaseDefiningValueOfVector(Value *I) {
439ff0cc061SDimitry Andric   // Each case parallels findBaseDefiningValue below, see that code for
440ff0cc061SDimitry Andric   // detailed motivation.
441ff0cc061SDimitry Andric 
442ff0cc061SDimitry Andric   if (isa<Argument>(I))
443ff0cc061SDimitry Andric     // An incoming argument to the function is a base pointer
4447d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
445ff0cc061SDimitry Andric 
446444ed5c5SDimitry Andric   if (isa<Constant>(I))
4473ca95b02SDimitry Andric     // Base of constant vector consists only of constant null pointers.
4483ca95b02SDimitry Andric     // For reasoning see similar case inside 'findBaseDefiningValue' function.
4493ca95b02SDimitry Andric     return BaseDefiningValueResult(ConstantAggregateZero::get(I->getType()),
4503ca95b02SDimitry Andric                                    true);
451ff0cc061SDimitry Andric 
452ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
4537d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
454ff0cc061SDimitry Andric 
4557d523365SDimitry Andric   if (isa<InsertElementInst>(I))
4563dac3a9bSDimitry Andric     // We don't know whether this vector contains entirely base pointers or
4573dac3a9bSDimitry Andric     // not.  To be conservatively correct, we treat it as a BDV and will
4583dac3a9bSDimitry Andric     // duplicate code as needed to construct a parallel vector of bases.
4597d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
460ff0cc061SDimitry Andric 
4613dac3a9bSDimitry Andric   if (isa<ShuffleVectorInst>(I))
4623dac3a9bSDimitry Andric     // We don't know whether this vector contains entirely base pointers or
4633dac3a9bSDimitry Andric     // not.  To be conservatively correct, we treat it as a BDV and will
4643dac3a9bSDimitry Andric     // duplicate code as needed to construct a parallel vector of bases.
4653dac3a9bSDimitry Andric     // TODO: There a number of local optimizations which could be applied here
4663dac3a9bSDimitry Andric     // for particular sufflevector patterns.
4677d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
4683dac3a9bSDimitry Andric 
4697a7e6055SDimitry Andric   // The behavior of getelementptr instructions is the same for vector and
4707a7e6055SDimitry Andric   // non-vector data types.
4717a7e6055SDimitry Andric   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
4727a7e6055SDimitry Andric     return findBaseDefiningValue(GEP->getPointerOperand());
4737a7e6055SDimitry Andric 
4742cab237bSDimitry Andric   // If the pointer comes through a bitcast of a vector of pointers to
4752cab237bSDimitry Andric   // a vector of another type of pointer, then look through the bitcast
4762cab237bSDimitry Andric   if (auto *BC = dyn_cast<BitCastInst>(I))
4772cab237bSDimitry Andric     return findBaseDefiningValue(BC->getOperand(0));
4782cab237bSDimitry Andric 
4793dac3a9bSDimitry Andric   // A PHI or Select is a base defining value.  The outer findBasePointer
4803dac3a9bSDimitry Andric   // algorithm is responsible for constructing a base value for this BDV.
4813dac3a9bSDimitry Andric   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
4823dac3a9bSDimitry Andric          "unknown vector instruction - no base found for vector element");
4837d523365SDimitry Andric   return BaseDefiningValueResult(I, false);
4843dac3a9bSDimitry Andric }
4853dac3a9bSDimitry Andric 
486ff0cc061SDimitry Andric /// Helper function for findBasePointer - Will return a value which either a)
4877d523365SDimitry Andric /// defines the base pointer for the input, b) blocks the simple search
4887d523365SDimitry Andric /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
4897d523365SDimitry Andric /// from pointer to vector type or back.
4907d523365SDimitry Andric static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
491444ed5c5SDimitry Andric   assert(I->getType()->isPtrOrPtrVectorTy() &&
492444ed5c5SDimitry Andric          "Illegal to ask for the base pointer of a non-pointer type");
493444ed5c5SDimitry Andric 
4943dac3a9bSDimitry Andric   if (I->getType()->isVectorTy())
4957d523365SDimitry Andric     return findBaseDefiningValueOfVector(I);
4963dac3a9bSDimitry Andric 
497ff0cc061SDimitry Andric   if (isa<Argument>(I))
498ff0cc061SDimitry Andric     // An incoming argument to the function is a base pointer
499ff0cc061SDimitry Andric     // We should have never reached here if this argument isn't an gc value
5007d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
501ff0cc061SDimitry Andric 
5023ca95b02SDimitry Andric   if (isa<Constant>(I)) {
5034d0b32cdSDimitry Andric     // We assume that objects with a constant base (e.g. a global) can't move
5044d0b32cdSDimitry Andric     // and don't need to be reported to the collector because they are always
5053ca95b02SDimitry Andric     // live. Besides global references, all kinds of constants (e.g. undef,
5063ca95b02SDimitry Andric     // constant expressions, null pointers) can be introduced by the inliner or
5073ca95b02SDimitry Andric     // the optimizer, especially on dynamically dead paths.
5083ca95b02SDimitry Andric     // Here we treat all of them as having single null base. By doing this we
5093ca95b02SDimitry Andric     // trying to avoid problems reporting various conflicts in a form of
5103ca95b02SDimitry Andric     // "phi (const1, const2)" or "phi (const, regular gc ptr)".
5113ca95b02SDimitry Andric     // See constant.ll file for relevant test cases.
5123ca95b02SDimitry Andric 
5133ca95b02SDimitry Andric     return BaseDefiningValueResult(
5143ca95b02SDimitry Andric         ConstantPointerNull::get(cast<PointerType>(I->getType())), true);
5153ca95b02SDimitry Andric   }
516ff0cc061SDimitry Andric 
517ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(I)) {
518ff0cc061SDimitry Andric     Value *Def = CI->stripPointerCasts();
5197d523365SDimitry Andric     // If stripping pointer casts changes the address space there is an
5207d523365SDimitry Andric     // addrspacecast in between.
5217d523365SDimitry Andric     assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
5227d523365SDimitry Andric                cast<PointerType>(CI->getType())->getAddressSpace() &&
5237d523365SDimitry Andric            "unsupported addrspacecast");
524ff0cc061SDimitry Andric     // If we find a cast instruction here, it means we've found a cast which is
525ff0cc061SDimitry Andric     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
526ff0cc061SDimitry Andric     // handle int->ptr conversion.
527ff0cc061SDimitry Andric     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
528ff0cc061SDimitry Andric     return findBaseDefiningValue(Def);
529ff0cc061SDimitry Andric   }
530ff0cc061SDimitry Andric 
531ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
5327d523365SDimitry Andric     // The value loaded is an gc base itself
5337d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
5347d523365SDimitry Andric 
535ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
536ff0cc061SDimitry Andric     // The base of this GEP is the base
537ff0cc061SDimitry Andric     return findBaseDefiningValue(GEP->getPointerOperand());
538ff0cc061SDimitry Andric 
539ff0cc061SDimitry Andric   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
540ff0cc061SDimitry Andric     switch (II->getIntrinsicID()) {
541ff0cc061SDimitry Andric     default:
542ff0cc061SDimitry Andric       // fall through to general call handling
543ff0cc061SDimitry Andric       break;
544ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_statepoint:
5457d523365SDimitry Andric       llvm_unreachable("statepoints don't produce pointers");
5462cab237bSDimitry Andric     case Intrinsic::experimental_gc_relocate:
547ff0cc061SDimitry Andric       // Rerunning safepoint insertion after safepoints are already
548ff0cc061SDimitry Andric       // inserted is not supported.  It could probably be made to work,
549ff0cc061SDimitry Andric       // but why are you doing this?  There's no good reason.
550ff0cc061SDimitry Andric       llvm_unreachable("repeat safepoint insertion is not supported");
551ff0cc061SDimitry Andric     case Intrinsic::gcroot:
552ff0cc061SDimitry Andric       // Currently, this mechanism hasn't been extended to work with gcroot.
553ff0cc061SDimitry Andric       // There's no reason it couldn't be, but I haven't thought about the
554ff0cc061SDimitry Andric       // implications much.
555ff0cc061SDimitry Andric       llvm_unreachable(
556ff0cc061SDimitry Andric           "interaction with the gcroot mechanism is not supported");
557ff0cc061SDimitry Andric     }
558ff0cc061SDimitry Andric   }
559ff0cc061SDimitry Andric   // We assume that functions in the source language only return base
560ff0cc061SDimitry Andric   // pointers.  This should probably be generalized via attributes to support
561ff0cc061SDimitry Andric   // both source language and internal functions.
562ff0cc061SDimitry Andric   if (isa<CallInst>(I) || isa<InvokeInst>(I))
5637d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
564ff0cc061SDimitry Andric 
565d88c1a5aSDimitry Andric   // TODO: I have absolutely no idea how to implement this part yet.  It's not
5667d523365SDimitry Andric   // necessarily hard, I just haven't really looked at it yet.
567ff0cc061SDimitry Andric   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
568ff0cc061SDimitry Andric 
569ff0cc061SDimitry Andric   if (isa<AtomicCmpXchgInst>(I))
570ff0cc061SDimitry Andric     // A CAS is effectively a atomic store and load combined under a
571ff0cc061SDimitry Andric     // predicate.  From the perspective of base pointers, we just treat it
572ff0cc061SDimitry Andric     // like a load.
5737d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
574ff0cc061SDimitry Andric 
575ff0cc061SDimitry Andric   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
576ff0cc061SDimitry Andric                                    "binary ops which don't apply to pointers");
577ff0cc061SDimitry Andric 
578ff0cc061SDimitry Andric   // The aggregate ops.  Aggregates can either be in the heap or on the
579ff0cc061SDimitry Andric   // stack, but in either case, this is simply a field load.  As a result,
580ff0cc061SDimitry Andric   // this is a defining definition of the base just like a load is.
581ff0cc061SDimitry Andric   if (isa<ExtractValueInst>(I))
5827d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
583ff0cc061SDimitry Andric 
584ff0cc061SDimitry Andric   // We should never see an insert vector since that would require we be
585ff0cc061SDimitry Andric   // tracing back a struct value not a pointer value.
586ff0cc061SDimitry Andric   assert(!isa<InsertValueInst>(I) &&
587ff0cc061SDimitry Andric          "Base pointer for a struct is meaningless");
588ff0cc061SDimitry Andric 
5897d523365SDimitry Andric   // An extractelement produces a base result exactly when it's input does.
5907d523365SDimitry Andric   // We may need to insert a parallel instruction to extract the appropriate
5917d523365SDimitry Andric   // element out of the base vector corresponding to the input. Given this,
5927d523365SDimitry Andric   // it's analogous to the phi and select case even though it's not a merge.
5937d523365SDimitry Andric   if (isa<ExtractElementInst>(I))
5947d523365SDimitry Andric     // Note: There a lot of obvious peephole cases here.  This are deliberately
5957d523365SDimitry Andric     // handled after the main base pointer inference algorithm to make writing
5967d523365SDimitry Andric     // test cases to exercise that code easier.
5977d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
5987d523365SDimitry Andric 
599ff0cc061SDimitry Andric   // The last two cases here don't return a base pointer.  Instead, they
6007d523365SDimitry Andric   // return a value which dynamically selects from among several base
601ff0cc061SDimitry Andric   // derived pointers (each with it's own base potentially).  It's the job of
602ff0cc061SDimitry Andric   // the caller to resolve these.
603ff0cc061SDimitry Andric   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
604ff0cc061SDimitry Andric          "missing instruction case in findBaseDefiningValing");
6057d523365SDimitry Andric   return BaseDefiningValueResult(I, false);
606ff0cc061SDimitry Andric }
607ff0cc061SDimitry Andric 
608ff0cc061SDimitry Andric /// Returns the base defining value for this value.
609ff0cc061SDimitry Andric static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
610ff0cc061SDimitry Andric   Value *&Cached = Cache[I];
611ff0cc061SDimitry Andric   if (!Cached) {
6127d523365SDimitry Andric     Cached = findBaseDefiningValue(I).BDV;
6137d523365SDimitry Andric     DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
6147d523365SDimitry Andric                  << Cached->getName() << "\n");
615ff0cc061SDimitry Andric   }
616ff0cc061SDimitry Andric   assert(Cache[I] != nullptr);
617ff0cc061SDimitry Andric   return Cached;
618ff0cc061SDimitry Andric }
619ff0cc061SDimitry Andric 
620ff0cc061SDimitry Andric /// Return a base pointer for this value if known.  Otherwise, return it's
621ff0cc061SDimitry Andric /// base defining value.
622ff0cc061SDimitry Andric static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
623ff0cc061SDimitry Andric   Value *Def = findBaseDefiningValueCached(I, Cache);
624ff0cc061SDimitry Andric   auto Found = Cache.find(Def);
625ff0cc061SDimitry Andric   if (Found != Cache.end()) {
626ff0cc061SDimitry Andric     // Either a base-of relation, or a self reference.  Caller must check.
627ff0cc061SDimitry Andric     return Found->second;
628ff0cc061SDimitry Andric   }
629ff0cc061SDimitry Andric   // Only a BDV available
630ff0cc061SDimitry Andric   return Def;
631ff0cc061SDimitry Andric }
632ff0cc061SDimitry Andric 
633ff0cc061SDimitry Andric /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
634ff0cc061SDimitry Andric /// is it known to be a base pointer?  Or do we need to continue searching.
635ff0cc061SDimitry Andric static bool isKnownBaseResult(Value *V) {
6367d523365SDimitry Andric   if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
6377d523365SDimitry Andric       !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
6387d523365SDimitry Andric       !isa<ShuffleVectorInst>(V)) {
639ff0cc061SDimitry Andric     // no recursion possible
640ff0cc061SDimitry Andric     return true;
641ff0cc061SDimitry Andric   }
642ff0cc061SDimitry Andric   if (isa<Instruction>(V) &&
643ff0cc061SDimitry Andric       cast<Instruction>(V)->getMetadata("is_base_value")) {
644ff0cc061SDimitry Andric     // This is a previously inserted base phi or select.  We know
645ff0cc061SDimitry Andric     // that this is a base value.
646ff0cc061SDimitry Andric     return true;
647ff0cc061SDimitry Andric   }
648ff0cc061SDimitry Andric 
649ff0cc061SDimitry Andric   // We need to keep searching
650ff0cc061SDimitry Andric   return false;
651ff0cc061SDimitry Andric }
652ff0cc061SDimitry Andric 
653ff0cc061SDimitry Andric namespace {
6542cab237bSDimitry Andric 
6557d523365SDimitry Andric /// Models the state of a single base defining value in the findBasePointer
6567d523365SDimitry Andric /// algorithm for determining where a new instruction is needed to propagate
6577d523365SDimitry Andric /// the base of this BDV.
6587d523365SDimitry Andric class BDVState {
659ff0cc061SDimitry Andric public:
660ff0cc061SDimitry Andric   enum Status { Unknown, Base, Conflict };
661ff0cc061SDimitry Andric 
6622cab237bSDimitry Andric   BDVState() : BaseValue(nullptr) {}
663ff0cc061SDimitry Andric 
6643ca95b02SDimitry Andric   explicit BDVState(Status Status, Value *BaseValue = nullptr)
6653ca95b02SDimitry Andric       : Status(Status), BaseValue(BaseValue) {
6663ca95b02SDimitry Andric     assert(Status != Base || BaseValue);
6673ca95b02SDimitry Andric   }
6683ca95b02SDimitry Andric 
6693ca95b02SDimitry Andric   explicit BDVState(Value *BaseValue) : Status(Base), BaseValue(BaseValue) {}
6703ca95b02SDimitry Andric 
6713ca95b02SDimitry Andric   Status getStatus() const { return Status; }
6723ca95b02SDimitry Andric   Value *getBaseValue() const { return BaseValue; }
673ff0cc061SDimitry Andric 
674ff0cc061SDimitry Andric   bool isBase() const { return getStatus() == Base; }
675ff0cc061SDimitry Andric   bool isUnknown() const { return getStatus() == Unknown; }
676ff0cc061SDimitry Andric   bool isConflict() const { return getStatus() == Conflict; }
677ff0cc061SDimitry Andric 
6783ca95b02SDimitry Andric   bool operator==(const BDVState &Other) const {
6793ca95b02SDimitry Andric     return BaseValue == Other.BaseValue && Status == Other.Status;
680ff0cc061SDimitry Andric   }
681ff0cc061SDimitry Andric 
6827d523365SDimitry Andric   bool operator!=(const BDVState &other) const { return !(*this == other); }
683ff0cc061SDimitry Andric 
6847d523365SDimitry Andric   LLVM_DUMP_METHOD
6853ca95b02SDimitry Andric   void dump() const {
6863ca95b02SDimitry Andric     print(dbgs());
6873ca95b02SDimitry Andric     dbgs() << '\n';
6883ca95b02SDimitry Andric   }
6897d523365SDimitry Andric 
6907d523365SDimitry Andric   void print(raw_ostream &OS) const {
6913ca95b02SDimitry Andric     switch (getStatus()) {
6927d523365SDimitry Andric     case Unknown:
6937d523365SDimitry Andric       OS << "U";
6947d523365SDimitry Andric       break;
6957d523365SDimitry Andric     case Base:
6967d523365SDimitry Andric       OS << "B";
6977d523365SDimitry Andric       break;
6987d523365SDimitry Andric     case Conflict:
6997d523365SDimitry Andric       OS << "C";
7007d523365SDimitry Andric       break;
7012cab237bSDimitry Andric     }
7023ca95b02SDimitry Andric     OS << " (" << getBaseValue() << " - "
7033ca95b02SDimitry Andric        << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << "): ";
704ff0cc061SDimitry Andric   }
705ff0cc061SDimitry Andric 
706ff0cc061SDimitry Andric private:
7072cab237bSDimitry Andric   Status Status = Unknown;
7083ca95b02SDimitry Andric   AssertingVH<Value> BaseValue; // Non-null only if Status == Base.
709ff0cc061SDimitry Andric };
7102cab237bSDimitry Andric 
7112cab237bSDimitry Andric } // end anonymous namespace
712ff0cc061SDimitry Andric 
7137d523365SDimitry Andric #ifndef NDEBUG
7147d523365SDimitry Andric static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
7157d523365SDimitry Andric   State.print(OS);
7167d523365SDimitry Andric   return OS;
7177d523365SDimitry Andric }
7187d523365SDimitry Andric #endif
7197d523365SDimitry Andric 
7203ca95b02SDimitry Andric static BDVState meetBDVStateImpl(const BDVState &LHS, const BDVState &RHS) {
7213ca95b02SDimitry Andric   switch (LHS.getStatus()) {
7227d523365SDimitry Andric   case BDVState::Unknown:
7233ca95b02SDimitry Andric     return RHS;
724ff0cc061SDimitry Andric 
7257d523365SDimitry Andric   case BDVState::Base:
7263ca95b02SDimitry Andric     assert(LHS.getBaseValue() && "can't be null");
7273ca95b02SDimitry Andric     if (RHS.isUnknown())
7283ca95b02SDimitry Andric       return LHS;
729ff0cc061SDimitry Andric 
7303ca95b02SDimitry Andric     if (RHS.isBase()) {
7313ca95b02SDimitry Andric       if (LHS.getBaseValue() == RHS.getBaseValue()) {
7323ca95b02SDimitry Andric         assert(LHS == RHS && "equality broken!");
7333ca95b02SDimitry Andric         return LHS;
734ff0cc061SDimitry Andric       }
7357d523365SDimitry Andric       return BDVState(BDVState::Conflict);
736ff0cc061SDimitry Andric     }
7373ca95b02SDimitry Andric     assert(RHS.isConflict() && "only three states!");
7387d523365SDimitry Andric     return BDVState(BDVState::Conflict);
739ff0cc061SDimitry Andric 
7407d523365SDimitry Andric   case BDVState::Conflict:
7413ca95b02SDimitry Andric     return LHS;
742ff0cc061SDimitry Andric   }
743ff0cc061SDimitry Andric   llvm_unreachable("only three states!");
744ff0cc061SDimitry Andric }
7453ca95b02SDimitry Andric 
7463ca95b02SDimitry Andric // Values of type BDVState form a lattice, and this function implements the meet
7473ca95b02SDimitry Andric // operation.
7487a7e6055SDimitry Andric static BDVState meetBDVState(const BDVState &LHS, const BDVState &RHS) {
7493ca95b02SDimitry Andric   BDVState Result = meetBDVStateImpl(LHS, RHS);
7503ca95b02SDimitry Andric   assert(Result == meetBDVStateImpl(RHS, LHS) &&
7513ca95b02SDimitry Andric          "Math is wrong: meet does not commute!");
7523ca95b02SDimitry Andric   return Result;
7533dac3a9bSDimitry Andric }
7547d523365SDimitry Andric 
7553ca95b02SDimitry Andric /// For a given value or instruction, figure out what base ptr its derived from.
7563ca95b02SDimitry Andric /// For gc objects, this is simply itself.  On success, returns a value which is
7573ca95b02SDimitry Andric /// the base pointer.  (This is reliable and can be used for relocation.)  On
7583ca95b02SDimitry Andric /// failure, returns nullptr.
7593ca95b02SDimitry Andric static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache) {
7603ca95b02SDimitry Andric   Value *Def = findBaseOrBDV(I, Cache);
7617d523365SDimitry Andric 
7623ca95b02SDimitry Andric   if (isKnownBaseResult(Def))
7633ca95b02SDimitry Andric     return Def;
764ff0cc061SDimitry Andric 
765ff0cc061SDimitry Andric   // Here's the rough algorithm:
766ff0cc061SDimitry Andric   // - For every SSA value, construct a mapping to either an actual base
767ff0cc061SDimitry Andric   //   pointer or a PHI which obscures the base pointer.
768ff0cc061SDimitry Andric   // - Construct a mapping from PHI to unknown TOP state.  Use an
769ff0cc061SDimitry Andric   //   optimistic algorithm to propagate base pointer information.  Lattice
770ff0cc061SDimitry Andric   //   looks like:
771ff0cc061SDimitry Andric   //   UNKNOWN
772ff0cc061SDimitry Andric   //   b1 b2 b3 b4
773ff0cc061SDimitry Andric   //   CONFLICT
774ff0cc061SDimitry Andric   //   When algorithm terminates, all PHIs will either have a single concrete
775ff0cc061SDimitry Andric   //   base or be in a conflict state.
776ff0cc061SDimitry Andric   // - For every conflict, insert a dummy PHI node without arguments.  Add
777ff0cc061SDimitry Andric   //   these to the base[Instruction] = BasePtr mapping.  For every
778ff0cc061SDimitry Andric   //   non-conflict, add the actual base.
779ff0cc061SDimitry Andric   //  - For every conflict, add arguments for the base[a] of each input
780ff0cc061SDimitry Andric   //   arguments.
781ff0cc061SDimitry Andric   //
782ff0cc061SDimitry Andric   // Note: A simpler form of this would be to add the conflict form of all
783ff0cc061SDimitry Andric   // PHIs without running the optimistic algorithm.  This would be
7847d523365SDimitry Andric   // analogous to pessimistic data flow and would likely lead to an
785ff0cc061SDimitry Andric   // overall worse solution.
786ff0cc061SDimitry Andric 
7877d523365SDimitry Andric #ifndef NDEBUG
7887d523365SDimitry Andric   auto isExpectedBDVType = [](Value *BDV) {
7897d523365SDimitry Andric     return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
790d88c1a5aSDimitry Andric            isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
791d88c1a5aSDimitry Andric            isa<ShuffleVectorInst>(BDV);
7927d523365SDimitry Andric   };
7937d523365SDimitry Andric #endif
7947d523365SDimitry Andric 
7957d523365SDimitry Andric   // Once populated, will contain a mapping from each potentially non-base BDV
7967d523365SDimitry Andric   // to a lattice value (described above) which corresponds to that BDV.
7977d523365SDimitry Andric   // We use the order of insertion (DFS over the def/use graph) to provide a
7987d523365SDimitry Andric   // stable deterministic ordering for visiting DenseMaps (which are unordered)
7997d523365SDimitry Andric   // below.  This is important for deterministic compilation.
8007d523365SDimitry Andric   MapVector<Value *, BDVState> States;
8017d523365SDimitry Andric 
8027d523365SDimitry Andric   // Recursively fill in all base defining values reachable from the initial
8037d523365SDimitry Andric   // one for which we don't already know a definite base value for
8047d523365SDimitry Andric   /* scope */ {
8057d523365SDimitry Andric     SmallVector<Value*, 16> Worklist;
8063ca95b02SDimitry Andric     Worklist.push_back(Def);
8073ca95b02SDimitry Andric     States.insert({Def, BDVState()});
8087d523365SDimitry Andric     while (!Worklist.empty()) {
8097d523365SDimitry Andric       Value *Current = Worklist.pop_back_val();
8107d523365SDimitry Andric       assert(!isKnownBaseResult(Current) && "why did it get added?");
8117d523365SDimitry Andric 
8127d523365SDimitry Andric       auto visitIncomingValue = [&](Value *InVal) {
8133ca95b02SDimitry Andric         Value *Base = findBaseOrBDV(InVal, Cache);
8147d523365SDimitry Andric         if (isKnownBaseResult(Base))
8157d523365SDimitry Andric           // Known bases won't need new instructions introduced and can be
8167d523365SDimitry Andric           // ignored safely
8177d523365SDimitry Andric           return;
8187d523365SDimitry Andric         assert(isExpectedBDVType(Base) && "the only non-base values "
8197d523365SDimitry Andric                "we see should be base defining values");
8207d523365SDimitry Andric         if (States.insert(std::make_pair(Base, BDVState())).second)
8217d523365SDimitry Andric           Worklist.push_back(Base);
8227d523365SDimitry Andric       };
8233ca95b02SDimitry Andric       if (PHINode *PN = dyn_cast<PHINode>(Current)) {
8243ca95b02SDimitry Andric         for (Value *InVal : PN->incoming_values())
8257d523365SDimitry Andric           visitIncomingValue(InVal);
8263ca95b02SDimitry Andric       } else if (SelectInst *SI = dyn_cast<SelectInst>(Current)) {
8273ca95b02SDimitry Andric         visitIncomingValue(SI->getTrueValue());
8283ca95b02SDimitry Andric         visitIncomingValue(SI->getFalseValue());
8297d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
8307d523365SDimitry Andric         visitIncomingValue(EE->getVectorOperand());
8317d523365SDimitry Andric       } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
8327d523365SDimitry Andric         visitIncomingValue(IE->getOperand(0)); // vector operand
8337d523365SDimitry Andric         visitIncomingValue(IE->getOperand(1)); // scalar operand
834d88c1a5aSDimitry Andric       } else if (auto *SV = dyn_cast<ShuffleVectorInst>(Current)) {
835d88c1a5aSDimitry Andric         visitIncomingValue(SV->getOperand(0));
836d88c1a5aSDimitry Andric         visitIncomingValue(SV->getOperand(1));
837d88c1a5aSDimitry Andric       }
838d88c1a5aSDimitry Andric       else {
8393ca95b02SDimitry Andric         llvm_unreachable("Unimplemented instruction case");
840ff0cc061SDimitry Andric       }
841ff0cc061SDimitry Andric     }
842ff0cc061SDimitry Andric   }
843ff0cc061SDimitry Andric 
8447d523365SDimitry Andric #ifndef NDEBUG
8457d523365SDimitry Andric   DEBUG(dbgs() << "States after initialization:\n");
8467d523365SDimitry Andric   for (auto Pair : States) {
8477d523365SDimitry Andric     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
848ff0cc061SDimitry Andric   }
8497d523365SDimitry Andric #endif
850ff0cc061SDimitry Andric 
8517d523365SDimitry Andric   // Return a phi state for a base defining value.  We'll generate a new
8527d523365SDimitry Andric   // base state for known bases and expect to find a cached state otherwise.
8537d523365SDimitry Andric   auto getStateForBDV = [&](Value *baseValue) {
8547d523365SDimitry Andric     if (isKnownBaseResult(baseValue))
8557d523365SDimitry Andric       return BDVState(baseValue);
8567d523365SDimitry Andric     auto I = States.find(baseValue);
8577d523365SDimitry Andric     assert(I != States.end() && "lookup failed!");
8587d523365SDimitry Andric     return I->second;
8597d523365SDimitry Andric   };
860ff0cc061SDimitry Andric 
8613ca95b02SDimitry Andric   bool Progress = true;
8623ca95b02SDimitry Andric   while (Progress) {
863ff0cc061SDimitry Andric #ifndef NDEBUG
8643ca95b02SDimitry Andric     const size_t OldSize = States.size();
865ff0cc061SDimitry Andric #endif
8663ca95b02SDimitry Andric     Progress = false;
8677d523365SDimitry Andric     // We're only changing values in this loop, thus safe to keep iterators.
8687d523365SDimitry Andric     // Since this is computing a fixed point, the order of visit does not
8697d523365SDimitry Andric     // effect the result.  TODO: We could use a worklist here and make this run
8707d523365SDimitry Andric     // much faster.
8717d523365SDimitry Andric     for (auto Pair : States) {
8727d523365SDimitry Andric       Value *BDV = Pair.first;
8737d523365SDimitry Andric       assert(!isKnownBaseResult(BDV) && "why did it get added?");
874ff0cc061SDimitry Andric 
8757d523365SDimitry Andric       // Given an input value for the current instruction, return a BDVState
8767d523365SDimitry Andric       // instance which represents the BDV of that value.
8777d523365SDimitry Andric       auto getStateForInput = [&](Value *V) mutable {
8783ca95b02SDimitry Andric         Value *BDV = findBaseOrBDV(V, Cache);
8797d523365SDimitry Andric         return getStateForBDV(BDV);
8807d523365SDimitry Andric       };
8817d523365SDimitry Andric 
8823ca95b02SDimitry Andric       BDVState NewState;
8833ca95b02SDimitry Andric       if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
8843ca95b02SDimitry Andric         NewState = meetBDVState(NewState, getStateForInput(SI->getTrueValue()));
8853ca95b02SDimitry Andric         NewState =
8863ca95b02SDimitry Andric             meetBDVState(NewState, getStateForInput(SI->getFalseValue()));
8873ca95b02SDimitry Andric       } else if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
8883ca95b02SDimitry Andric         for (Value *Val : PN->incoming_values())
8893ca95b02SDimitry Andric           NewState = meetBDVState(NewState, getStateForInput(Val));
8907d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
8917d523365SDimitry Andric         // The 'meet' for an extractelement is slightly trivial, but it's still
8927d523365SDimitry Andric         // useful in that it drives us to conflict if our input is.
8933ca95b02SDimitry Andric         NewState =
8943ca95b02SDimitry Andric             meetBDVState(NewState, getStateForInput(EE->getVectorOperand()));
895d88c1a5aSDimitry Andric       } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)){
8967d523365SDimitry Andric         // Given there's a inherent type mismatch between the operands, will
8977d523365SDimitry Andric         // *always* produce Conflict.
8983ca95b02SDimitry Andric         NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(0)));
8993ca95b02SDimitry Andric         NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(1)));
900d88c1a5aSDimitry Andric       } else {
901d88c1a5aSDimitry Andric         // The only instance this does not return a Conflict is when both the
902d88c1a5aSDimitry Andric         // vector operands are the same vector.
903d88c1a5aSDimitry Andric         auto *SV = cast<ShuffleVectorInst>(BDV);
904d88c1a5aSDimitry Andric         NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(0)));
905d88c1a5aSDimitry Andric         NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(1)));
9067d523365SDimitry Andric       }
9077d523365SDimitry Andric 
9083ca95b02SDimitry Andric       BDVState OldState = States[BDV];
9093ca95b02SDimitry Andric       if (OldState != NewState) {
9103ca95b02SDimitry Andric         Progress = true;
9113ca95b02SDimitry Andric         States[BDV] = NewState;
912ff0cc061SDimitry Andric       }
913ff0cc061SDimitry Andric     }
914ff0cc061SDimitry Andric 
9153ca95b02SDimitry Andric     assert(OldSize == States.size() &&
9167d523365SDimitry Andric            "fixed point shouldn't be adding any new nodes to state");
917ff0cc061SDimitry Andric   }
918ff0cc061SDimitry Andric 
9197d523365SDimitry Andric #ifndef NDEBUG
9207d523365SDimitry Andric   DEBUG(dbgs() << "States after meet iteration:\n");
9217d523365SDimitry Andric   for (auto Pair : States) {
9227d523365SDimitry Andric     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
923ff0cc061SDimitry Andric   }
9247d523365SDimitry Andric #endif
925ff0cc061SDimitry Andric 
926ff0cc061SDimitry Andric   // Insert Phis for all conflicts
927ff0cc061SDimitry Andric   // TODO: adjust naming patterns to avoid this order of iteration dependency
9287d523365SDimitry Andric   for (auto Pair : States) {
9297d523365SDimitry Andric     Instruction *I = cast<Instruction>(Pair.first);
9307d523365SDimitry Andric     BDVState State = Pair.second;
9317d523365SDimitry Andric     assert(!isKnownBaseResult(I) && "why did it get added?");
9327d523365SDimitry Andric     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
9337d523365SDimitry Andric 
9347d523365SDimitry Andric     // extractelement instructions are a bit special in that we may need to
9357d523365SDimitry Andric     // insert an extract even when we know an exact base for the instruction.
9367d523365SDimitry Andric     // The problem is that we need to convert from a vector base to a scalar
9377d523365SDimitry Andric     // base for the particular indice we're interested in.
9387d523365SDimitry Andric     if (State.isBase() && isa<ExtractElementInst>(I) &&
9393ca95b02SDimitry Andric         isa<VectorType>(State.getBaseValue()->getType())) {
9407d523365SDimitry Andric       auto *EE = cast<ExtractElementInst>(I);
9417d523365SDimitry Andric       // TODO: In many cases, the new instruction is just EE itself.  We should
9427d523365SDimitry Andric       // exploit this, but can't do it here since it would break the invariant
9437d523365SDimitry Andric       // about the BDV not being known to be a base.
9443ca95b02SDimitry Andric       auto *BaseInst = ExtractElementInst::Create(
9453ca95b02SDimitry Andric           State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
9467d523365SDimitry Andric       BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
9477d523365SDimitry Andric       States[I] = BDVState(BDVState::Base, BaseInst);
9487d523365SDimitry Andric     }
9497d523365SDimitry Andric 
9507d523365SDimitry Andric     // Since we're joining a vector and scalar base, they can never be the
9517d523365SDimitry Andric     // same.  As a result, we should always see insert element having reached
9527d523365SDimitry Andric     // the conflict state.
9533ca95b02SDimitry Andric     assert(!isa<InsertElementInst>(I) || State.isConflict());
9547d523365SDimitry Andric 
9557d523365SDimitry Andric     if (!State.isConflict())
956ff0cc061SDimitry Andric       continue;
957ff0cc061SDimitry Andric 
9587d523365SDimitry Andric     /// Create and insert a new instruction which will represent the base of
9597d523365SDimitry Andric     /// the given instruction 'I'.
9607d523365SDimitry Andric     auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
9617d523365SDimitry Andric       if (isa<PHINode>(I)) {
9627d523365SDimitry Andric         BasicBlock *BB = I->getParent();
9637d523365SDimitry Andric         int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
9647d523365SDimitry Andric         assert(NumPreds > 0 && "how did we reach here");
9657d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_phi");
9667d523365SDimitry Andric         return PHINode::Create(I->getType(), NumPreds, Name, I);
9673ca95b02SDimitry Andric       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
968ff0cc061SDimitry Andric         // The undef will be replaced later
9693ca95b02SDimitry Andric         UndefValue *Undef = UndefValue::get(SI->getType());
9707d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_select");
9713ca95b02SDimitry Andric         return SelectInst::Create(SI->getCondition(), Undef, Undef, Name, SI);
9727d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
9737d523365SDimitry Andric         UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
9747d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_ee");
9757d523365SDimitry Andric         return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
9767d523365SDimitry Andric                                           EE);
977d88c1a5aSDimitry Andric       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
9787d523365SDimitry Andric         UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
9797d523365SDimitry Andric         UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
9807d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_ie");
9817d523365SDimitry Andric         return InsertElementInst::Create(VecUndef, ScalarUndef,
9827d523365SDimitry Andric                                          IE->getOperand(2), Name, IE);
983d88c1a5aSDimitry Andric       } else {
984d88c1a5aSDimitry Andric         auto *SV = cast<ShuffleVectorInst>(I);
985d88c1a5aSDimitry Andric         UndefValue *VecUndef = UndefValue::get(SV->getOperand(0)->getType());
986d88c1a5aSDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_sv");
987d88c1a5aSDimitry Andric         return new ShuffleVectorInst(VecUndef, VecUndef, SV->getOperand(2),
988d88c1a5aSDimitry Andric                                      Name, SV);
9897d523365SDimitry Andric       }
9907d523365SDimitry Andric     };
9917d523365SDimitry Andric     Instruction *BaseInst = MakeBaseInstPlaceholder(I);
992ff0cc061SDimitry Andric     // Add metadata marking this as a base value
9937d523365SDimitry Andric     BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
9947d523365SDimitry Andric     States[I] = BDVState(BDVState::Conflict, BaseInst);
995ff0cc061SDimitry Andric   }
996ff0cc061SDimitry Andric 
9977d523365SDimitry Andric   // Returns a instruction which produces the base pointer for a given
9987d523365SDimitry Andric   // instruction.  The instruction is assumed to be an input to one of the BDVs
9997d523365SDimitry Andric   // seen in the inference algorithm above.  As such, we must either already
10007d523365SDimitry Andric   // know it's base defining value is a base, or have inserted a new
10017d523365SDimitry Andric   // instruction to propagate the base of it's BDV and have entered that newly
10027d523365SDimitry Andric   // introduced instruction into the state table.  In either case, we are
10037d523365SDimitry Andric   // assured to be able to determine an instruction which produces it's base
10047d523365SDimitry Andric   // pointer.
10057d523365SDimitry Andric   auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
10063ca95b02SDimitry Andric     Value *BDV = findBaseOrBDV(Input, Cache);
10077d523365SDimitry Andric     Value *Base = nullptr;
10087d523365SDimitry Andric     if (isKnownBaseResult(BDV)) {
10097d523365SDimitry Andric       Base = BDV;
10107d523365SDimitry Andric     } else {
10117d523365SDimitry Andric       // Either conflict or base.
10127d523365SDimitry Andric       assert(States.count(BDV));
10133ca95b02SDimitry Andric       Base = States[BDV].getBaseValue();
10147d523365SDimitry Andric     }
10153ca95b02SDimitry Andric     assert(Base && "Can't be null");
10167d523365SDimitry Andric     // The cast is needed since base traversal may strip away bitcasts
10173ca95b02SDimitry Andric     if (Base->getType() != Input->getType() && InsertPt)
10183ca95b02SDimitry Andric       Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
10197d523365SDimitry Andric     return Base;
10207d523365SDimitry Andric   };
1021ff0cc061SDimitry Andric 
10227d523365SDimitry Andric   // Fixup all the inputs of the new PHIs.  Visit order needs to be
10237d523365SDimitry Andric   // deterministic and predictable because we're naming newly created
10247d523365SDimitry Andric   // instructions.
10257d523365SDimitry Andric   for (auto Pair : States) {
10267d523365SDimitry Andric     Instruction *BDV = cast<Instruction>(Pair.first);
10277d523365SDimitry Andric     BDVState State = Pair.second;
10287d523365SDimitry Andric 
10297d523365SDimitry Andric     assert(!isKnownBaseResult(BDV) && "why did it get added?");
10307d523365SDimitry Andric     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
10317d523365SDimitry Andric     if (!State.isConflict())
1032ff0cc061SDimitry Andric       continue;
1033ff0cc061SDimitry Andric 
10343ca95b02SDimitry Andric     if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
10353ca95b02SDimitry Andric       PHINode *PN = cast<PHINode>(BDV);
10363ca95b02SDimitry Andric       unsigned NumPHIValues = PN->getNumIncomingValues();
1037ff0cc061SDimitry Andric       for (unsigned i = 0; i < NumPHIValues; i++) {
10383ca95b02SDimitry Andric         Value *InVal = PN->getIncomingValue(i);
10393ca95b02SDimitry Andric         BasicBlock *InBB = PN->getIncomingBlock(i);
1040ff0cc061SDimitry Andric 
1041ff0cc061SDimitry Andric         // If we've already seen InBB, add the same incoming value
1042ff0cc061SDimitry Andric         // we added for it earlier.  The IR verifier requires phi
1043ff0cc061SDimitry Andric         // nodes with multiple entries from the same basic block
1044ff0cc061SDimitry Andric         // to have the same incoming value for each of those
1045ff0cc061SDimitry Andric         // entries.  If we don't do this check here and basephi
1046ff0cc061SDimitry Andric         // has a different type than base, we'll end up adding two
1047ff0cc061SDimitry Andric         // bitcasts (and hence two distinct values) as incoming
1048ff0cc061SDimitry Andric         // values for the same basic block.
1049ff0cc061SDimitry Andric 
10503ca95b02SDimitry Andric         int BlockIndex = BasePHI->getBasicBlockIndex(InBB);
10513ca95b02SDimitry Andric         if (BlockIndex != -1) {
10523ca95b02SDimitry Andric           Value *OldBase = BasePHI->getIncomingValue(BlockIndex);
10533ca95b02SDimitry Andric           BasePHI->addIncoming(OldBase, InBB);
1054ff0cc061SDimitry Andric 
10557d523365SDimitry Andric #ifndef NDEBUG
10567d523365SDimitry Andric           Value *Base = getBaseForInput(InVal, nullptr);
10573ca95b02SDimitry Andric           // In essence this assert states: the only way two values
10583ca95b02SDimitry Andric           // incoming from the same basic block may be different is by
10593ca95b02SDimitry Andric           // being different bitcasts of the same value.  A cleanup
10603ca95b02SDimitry Andric           // that remains TODO is changing findBaseOrBDV to return an
10613ca95b02SDimitry Andric           // llvm::Value of the correct type (and still remain pure).
10623ca95b02SDimitry Andric           // This will remove the need to add bitcasts.
10633ca95b02SDimitry Andric           assert(Base->stripPointerCasts() == OldBase->stripPointerCasts() &&
10643ca95b02SDimitry Andric                  "Sanity -- findBaseOrBDV should be pure!");
1065ff0cc061SDimitry Andric #endif
1066ff0cc061SDimitry Andric           continue;
1067ff0cc061SDimitry Andric         }
1068ff0cc061SDimitry Andric 
10697d523365SDimitry Andric         // Find the instruction which produces the base for each input.  We may
10707d523365SDimitry Andric         // need to insert a bitcast in the incoming block.
10717d523365SDimitry Andric         // TODO: Need to split critical edges if insertion is needed
10727d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, InBB->getTerminator());
10733ca95b02SDimitry Andric         BasePHI->addIncoming(Base, InBB);
1074ff0cc061SDimitry Andric       }
10753ca95b02SDimitry Andric       assert(BasePHI->getNumIncomingValues() == NumPHIValues);
10763ca95b02SDimitry Andric     } else if (SelectInst *BaseSI =
10773ca95b02SDimitry Andric                    dyn_cast<SelectInst>(State.getBaseValue())) {
10783ca95b02SDimitry Andric       SelectInst *SI = cast<SelectInst>(BDV);
10793ca95b02SDimitry Andric 
10803ca95b02SDimitry Andric       // Find the instruction which produces the base for each input.
10813ca95b02SDimitry Andric       // We may need to insert a bitcast.
10823ca95b02SDimitry Andric       BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
10833ca95b02SDimitry Andric       BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
10843ca95b02SDimitry Andric     } else if (auto *BaseEE =
10853ca95b02SDimitry Andric                    dyn_cast<ExtractElementInst>(State.getBaseValue())) {
10867d523365SDimitry Andric       Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
10877d523365SDimitry Andric       // Find the instruction which produces the base for each input.  We may
10887d523365SDimitry Andric       // need to insert a bitcast.
10893ca95b02SDimitry Andric       BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
1090d88c1a5aSDimitry Andric     } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
10917d523365SDimitry Andric       auto *BdvIE = cast<InsertElementInst>(BDV);
10927d523365SDimitry Andric       auto UpdateOperand = [&](int OperandIdx) {
10937d523365SDimitry Andric         Value *InVal = BdvIE->getOperand(OperandIdx);
10947d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, BaseIE);
10957d523365SDimitry Andric         BaseIE->setOperand(OperandIdx, Base);
10967d523365SDimitry Andric       };
10977d523365SDimitry Andric       UpdateOperand(0); // vector operand
10987d523365SDimitry Andric       UpdateOperand(1); // scalar operand
1099d88c1a5aSDimitry Andric     } else {
1100d88c1a5aSDimitry Andric       auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1101d88c1a5aSDimitry Andric       auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1102d88c1a5aSDimitry Andric       auto UpdateOperand = [&](int OperandIdx) {
1103d88c1a5aSDimitry Andric         Value *InVal = BdvSV->getOperand(OperandIdx);
1104d88c1a5aSDimitry Andric         Value *Base = getBaseForInput(InVal, BaseSV);
1105d88c1a5aSDimitry Andric         BaseSV->setOperand(OperandIdx, Base);
1106d88c1a5aSDimitry Andric       };
1107d88c1a5aSDimitry Andric       UpdateOperand(0); // vector operand
1108d88c1a5aSDimitry Andric       UpdateOperand(1); // vector operand
1109ff0cc061SDimitry Andric     }
1110ff0cc061SDimitry Andric   }
1111ff0cc061SDimitry Andric 
1112ff0cc061SDimitry Andric   // Cache all of our results so we can cheaply reuse them
1113ff0cc061SDimitry Andric   // NOTE: This is actually two caches: one of the base defining value
1114ff0cc061SDimitry Andric   // relation and one of the base pointer relation!  FIXME
11157d523365SDimitry Andric   for (auto Pair : States) {
11167d523365SDimitry Andric     auto *BDV = Pair.first;
11173ca95b02SDimitry Andric     Value *Base = Pair.second.getBaseValue();
11183ca95b02SDimitry Andric     assert(BDV && Base);
11193ca95b02SDimitry Andric     assert(!isKnownBaseResult(BDV) && "why did it get added?");
1120ff0cc061SDimitry Andric 
11217d523365SDimitry Andric     DEBUG(dbgs() << "Updating base value cache"
11223ca95b02SDimitry Andric                  << " for: " << BDV->getName() << " from: "
11233ca95b02SDimitry Andric                  << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
11243ca95b02SDimitry Andric                  << " to: " << Base->getName() << "\n");
1125ff0cc061SDimitry Andric 
11263ca95b02SDimitry Andric     if (Cache.count(BDV)) {
11273ca95b02SDimitry Andric       assert(isKnownBaseResult(Base) &&
11283ca95b02SDimitry Andric              "must be something we 'know' is a base pointer");
11293ca95b02SDimitry Andric       // Once we transition from the BDV relation being store in the Cache to
1130ff0cc061SDimitry Andric       // the base relation being stored, it must be stable
11313ca95b02SDimitry Andric       assert((!isKnownBaseResult(Cache[BDV]) || Cache[BDV] == Base) &&
1132ff0cc061SDimitry Andric              "base relation should be stable");
1133ff0cc061SDimitry Andric     }
11343ca95b02SDimitry Andric     Cache[BDV] = Base;
1135ff0cc061SDimitry Andric   }
11363ca95b02SDimitry Andric   assert(Cache.count(Def));
11373ca95b02SDimitry Andric   return Cache[Def];
1138ff0cc061SDimitry Andric }
1139ff0cc061SDimitry Andric 
1140ff0cc061SDimitry Andric // For a set of live pointers (base and/or derived), identify the base
1141ff0cc061SDimitry Andric // pointer of the object which they are derived from.  This routine will
1142ff0cc061SDimitry Andric // mutate the IR graph as needed to make the 'base' pointer live at the
1143ff0cc061SDimitry Andric // definition site of 'derived'.  This ensures that any use of 'derived' can
1144ff0cc061SDimitry Andric // also use 'base'.  This may involve the insertion of a number of
1145ff0cc061SDimitry Andric // additional PHI nodes.
1146ff0cc061SDimitry Andric //
1147ff0cc061SDimitry Andric // preconditions: live is a set of pointer type Values
1148ff0cc061SDimitry Andric //
1149ff0cc061SDimitry Andric // side effects: may insert PHI nodes into the existing CFG, will preserve
1150ff0cc061SDimitry Andric // CFG, will not remove or mutate any existing nodes
1151ff0cc061SDimitry Andric //
1152ff0cc061SDimitry Andric // post condition: PointerToBase contains one (derived, base) pair for every
1153ff0cc061SDimitry Andric // pointer in live.  Note that derived can be equal to base if the original
1154ff0cc061SDimitry Andric // pointer was a base pointer.
1155ff0cc061SDimitry Andric static void
1156ff0cc061SDimitry Andric findBasePointers(const StatepointLiveSetTy &live,
11573ca95b02SDimitry Andric                  MapVector<Value *, Value *> &PointerToBase,
1158ff0cc061SDimitry Andric                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
11593ca95b02SDimitry Andric   for (Value *ptr : live) {
1160ff0cc061SDimitry Andric     Value *base = findBasePointer(ptr, DVCache);
1161ff0cc061SDimitry Andric     assert(base && "failed to find base pointer");
1162ff0cc061SDimitry Andric     PointerToBase[ptr] = base;
1163ff0cc061SDimitry Andric     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1164ff0cc061SDimitry Andric             DT->dominates(cast<Instruction>(base)->getParent(),
1165ff0cc061SDimitry Andric                           cast<Instruction>(ptr)->getParent())) &&
1166ff0cc061SDimitry Andric            "The base we found better dominate the derived pointer");
1167ff0cc061SDimitry Andric   }
1168ff0cc061SDimitry Andric }
1169ff0cc061SDimitry Andric 
1170ff0cc061SDimitry Andric /// Find the required based pointers (and adjust the live set) for the given
1171ff0cc061SDimitry Andric /// parse point.
1172ff0cc061SDimitry Andric static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
11733ca95b02SDimitry Andric                              CallSite CS,
1174ff0cc061SDimitry Andric                              PartiallyConstructedSafepointRecord &result) {
11753ca95b02SDimitry Andric   MapVector<Value *, Value *> PointerToBase;
11767d523365SDimitry Andric   findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
1177ff0cc061SDimitry Andric 
1178ff0cc061SDimitry Andric   if (PrintBasePointers) {
1179ff0cc061SDimitry Andric     errs() << "Base Pairs (w/o Relocation):\n";
11803ca95b02SDimitry Andric     for (auto &Pair : PointerToBase) {
11817d523365SDimitry Andric       errs() << " derived ";
11823ca95b02SDimitry Andric       Pair.first->printAsOperand(errs(), false);
11837d523365SDimitry Andric       errs() << " base ";
11843ca95b02SDimitry Andric       Pair.second->printAsOperand(errs(), false);
11857d523365SDimitry Andric       errs() << "\n";;
1186ff0cc061SDimitry Andric     }
1187ff0cc061SDimitry Andric   }
1188ff0cc061SDimitry Andric 
1189ff0cc061SDimitry Andric   result.PointerToBase = PointerToBase;
1190ff0cc061SDimitry Andric }
1191ff0cc061SDimitry Andric 
1192ff0cc061SDimitry Andric /// Given an updated version of the dataflow liveness results, update the
1193ff0cc061SDimitry Andric /// liveset and base pointer maps for the call site CS.
1194ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
11953ca95b02SDimitry Andric                                   CallSite CS,
1196ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &result);
1197ff0cc061SDimitry Andric 
1198ff0cc061SDimitry Andric static void recomputeLiveInValues(
11997d523365SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1200ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1201ff0cc061SDimitry Andric   // TODO-PERF: reuse the original liveness, then simply run the dataflow
12027d523365SDimitry Andric   // again.  The old values are still live and will help it stabilize quickly.
1203ff0cc061SDimitry Andric   GCPtrLivenessData RevisedLivenessData;
1204ff0cc061SDimitry Andric   computeLiveInValues(DT, F, RevisedLivenessData);
1205ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1206ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
12073ca95b02SDimitry Andric     recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info);
1208ff0cc061SDimitry Andric   }
1209ff0cc061SDimitry Andric }
1210ff0cc061SDimitry Andric 
12117d523365SDimitry Andric // When inserting gc.relocate and gc.result calls, we need to ensure there are
12127d523365SDimitry Andric // no uses of the original value / return value between the gc.statepoint and
12137d523365SDimitry Andric // the gc.relocate / gc.result call.  One case which can arise is a phi node
12147d523365SDimitry Andric // starting one of the successor blocks.  We also need to be able to insert the
12157d523365SDimitry Andric // gc.relocates only on the path which goes through the statepoint.  We might
12167d523365SDimitry Andric // need to split an edge to make this possible.
1217ff0cc061SDimitry Andric static BasicBlock *
121897bc6c73SDimitry Andric normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
121997bc6c73SDimitry Andric                             DominatorTree &DT) {
1220ff0cc061SDimitry Andric   BasicBlock *Ret = BB;
12217d523365SDimitry Andric   if (!BB->getUniquePredecessor())
12227d523365SDimitry Andric     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1223ff0cc061SDimitry Andric 
12247d523365SDimitry Andric   // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1225ff0cc061SDimitry Andric   // from it
1226ff0cc061SDimitry Andric   FoldSingleEntryPHINodes(Ret);
12277d523365SDimitry Andric   assert(!isa<PHINode>(Ret->begin()) &&
12287d523365SDimitry Andric          "All PHI nodes should have been removed!");
1229ff0cc061SDimitry Andric 
12307d523365SDimitry Andric   // At this point, we can safely insert a gc.relocate or gc.result as the first
12317d523365SDimitry Andric   // instruction in Ret if needed.
1232ff0cc061SDimitry Andric   return Ret;
1233ff0cc061SDimitry Andric }
1234ff0cc061SDimitry Andric 
12357d523365SDimitry Andric // Create new attribute set containing only attributes which can be transferred
1236ff0cc061SDimitry Andric // from original call to the safepoint.
1237f37b6182SDimitry Andric static AttributeList legalizeCallAttributes(AttributeList AL) {
1238f37b6182SDimitry Andric   if (AL.isEmpty())
1239f37b6182SDimitry Andric     return AL;
1240ff0cc061SDimitry Andric 
1241f37b6182SDimitry Andric   // Remove the readonly, readnone, and statepoint function attributes.
1242f37b6182SDimitry Andric   AttrBuilder FnAttrs = AL.getFnAttributes();
1243f37b6182SDimitry Andric   FnAttrs.removeAttribute(Attribute::ReadNone);
1244f37b6182SDimitry Andric   FnAttrs.removeAttribute(Attribute::ReadOnly);
1245f37b6182SDimitry Andric   for (Attribute A : AL.getFnAttributes()) {
1246f37b6182SDimitry Andric     if (isStatepointDirectiveAttr(A))
1247f37b6182SDimitry Andric       FnAttrs.remove(A);
1248ff0cc061SDimitry Andric   }
1249ff0cc061SDimitry Andric 
1250f37b6182SDimitry Andric   // Just skip parameter and return attributes for now
1251f37b6182SDimitry Andric   LLVMContext &Ctx = AL.getContext();
1252f37b6182SDimitry Andric   return AttributeList::get(Ctx, AttributeList::FunctionIndex,
1253f37b6182SDimitry Andric                             AttributeSet::get(Ctx, FnAttrs));
1254ff0cc061SDimitry Andric }
1255ff0cc061SDimitry Andric 
1256ff0cc061SDimitry Andric /// Helper function to place all gc relocates necessary for the given
1257ff0cc061SDimitry Andric /// statepoint.
1258ff0cc061SDimitry Andric /// Inputs:
1259ff0cc061SDimitry Andric ///   liveVariables - list of variables to be relocated.
1260ff0cc061SDimitry Andric ///   liveStart - index of the first live variable.
1261ff0cc061SDimitry Andric ///   basePtrs - base pointers.
1262ff0cc061SDimitry Andric ///   statepointToken - statepoint instruction to which relocates should be
1263ff0cc061SDimitry Andric ///   bound.
1264ff0cc061SDimitry Andric ///   Builder - Llvm IR builder to be used to construct new calls.
12657d523365SDimitry Andric static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1266ff0cc061SDimitry Andric                               const int LiveStart,
12677d523365SDimitry Andric                               ArrayRef<Value *> BasePtrs,
1268ff0cc061SDimitry Andric                               Instruction *StatepointToken,
1269ff0cc061SDimitry Andric                               IRBuilder<> Builder) {
12707d523365SDimitry Andric   if (LiveVariables.empty())
12717d523365SDimitry Andric     return;
1272ff0cc061SDimitry Andric 
12737d523365SDimitry Andric   auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
12742cab237bSDimitry Andric     auto ValIt = llvm::find(LiveVec, Val);
12757d523365SDimitry Andric     assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
12767d523365SDimitry Andric     size_t Index = std::distance(LiveVec.begin(), ValIt);
12777d523365SDimitry Andric     assert(Index < LiveVec.size() && "Bug in std::find?");
12787d523365SDimitry Andric     return Index;
12797d523365SDimitry Andric   };
12807d523365SDimitry Andric   Module *M = StatepointToken->getModule();
1281444ed5c5SDimitry Andric 
1282444ed5c5SDimitry Andric   // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1283444ed5c5SDimitry Andric   // element type is i8 addrspace(1)*). We originally generated unique
1284444ed5c5SDimitry Andric   // declarations for each pointer type, but this proved problematic because
1285444ed5c5SDimitry Andric   // the intrinsic mangling code is incomplete and fragile.  Since we're moving
1286444ed5c5SDimitry Andric   // towards a single unified pointer type anyways, we can just cast everything
1287444ed5c5SDimitry Andric   // to an i8* of the right address space.  A bitcast is added later to convert
1288444ed5c5SDimitry Andric   // gc_relocate to the actual value's type.
1289444ed5c5SDimitry Andric   auto getGCRelocateDecl = [&] (Type *Ty) {
1290444ed5c5SDimitry Andric     assert(isHandledGCPointerType(Ty));
1291444ed5c5SDimitry Andric     auto AS = Ty->getScalarType()->getPointerAddressSpace();
1292444ed5c5SDimitry Andric     Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1293444ed5c5SDimitry Andric     if (auto *VT = dyn_cast<VectorType>(Ty))
1294444ed5c5SDimitry Andric       NewTy = VectorType::get(NewTy, VT->getNumElements());
1295444ed5c5SDimitry Andric     return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1296444ed5c5SDimitry Andric                                      {NewTy});
1297444ed5c5SDimitry Andric   };
1298444ed5c5SDimitry Andric 
1299444ed5c5SDimitry Andric   // Lazily populated map from input types to the canonicalized form mentioned
1300444ed5c5SDimitry Andric   // in the comment above.  This should probably be cached somewhere more
1301444ed5c5SDimitry Andric   // broadly.
1302444ed5c5SDimitry Andric   DenseMap<Type*, Value*> TypeToDeclMap;
1303ff0cc061SDimitry Andric 
1304ff0cc061SDimitry Andric   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1305ff0cc061SDimitry Andric     // Generate the gc.relocate call and save the result
1306ff0cc061SDimitry Andric     Value *BaseIdx =
13077d523365SDimitry Andric       Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
13087d523365SDimitry Andric     Value *LiveIdx = Builder.getInt32(LiveStart + i);
1309ff0cc061SDimitry Andric 
1310444ed5c5SDimitry Andric     Type *Ty = LiveVariables[i]->getType();
1311444ed5c5SDimitry Andric     if (!TypeToDeclMap.count(Ty))
1312444ed5c5SDimitry Andric       TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1313444ed5c5SDimitry Andric     Value *GCRelocateDecl = TypeToDeclMap[Ty];
1314444ed5c5SDimitry Andric 
1315ff0cc061SDimitry Andric     // only specify a debug name if we can give a useful one
13167d523365SDimitry Andric     CallInst *Reloc = Builder.CreateCall(
1317ff0cc061SDimitry Andric         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
13187d523365SDimitry Andric         suffixed_name_or(LiveVariables[i], ".relocated", ""));
1319ff0cc061SDimitry Andric     // Trick CodeGen into thinking there are lots of free registers at this
1320ff0cc061SDimitry Andric     // fake call.
13217d523365SDimitry Andric     Reloc->setCallingConv(CallingConv::Cold);
1322ff0cc061SDimitry Andric   }
13237d523365SDimitry Andric }
13247d523365SDimitry Andric 
13257d523365SDimitry Andric namespace {
13267d523365SDimitry Andric 
13277d523365SDimitry Andric /// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
13287d523365SDimitry Andric /// avoids having to worry about keeping around dangling pointers to Values.
13297d523365SDimitry Andric class DeferredReplacement {
13307d523365SDimitry Andric   AssertingVH<Instruction> Old;
13317d523365SDimitry Andric   AssertingVH<Instruction> New;
13323ca95b02SDimitry Andric   bool IsDeoptimize = false;
13333ca95b02SDimitry Andric 
13342cab237bSDimitry Andric   DeferredReplacement() = default;
13357d523365SDimitry Andric 
13367d523365SDimitry Andric public:
13373ca95b02SDimitry Andric   static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
13383ca95b02SDimitry Andric     assert(Old != New && Old && New &&
13393ca95b02SDimitry Andric            "Cannot RAUW equal values or to / from null!");
13403ca95b02SDimitry Andric 
13413ca95b02SDimitry Andric     DeferredReplacement D;
13423ca95b02SDimitry Andric     D.Old = Old;
13433ca95b02SDimitry Andric     D.New = New;
13443ca95b02SDimitry Andric     return D;
13453ca95b02SDimitry Andric   }
13463ca95b02SDimitry Andric 
13473ca95b02SDimitry Andric   static DeferredReplacement createDelete(Instruction *ToErase) {
13483ca95b02SDimitry Andric     DeferredReplacement D;
13493ca95b02SDimitry Andric     D.Old = ToErase;
13503ca95b02SDimitry Andric     return D;
13513ca95b02SDimitry Andric   }
13523ca95b02SDimitry Andric 
13533ca95b02SDimitry Andric   static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
13543ca95b02SDimitry Andric #ifndef NDEBUG
13553ca95b02SDimitry Andric     auto *F = cast<CallInst>(Old)->getCalledFunction();
13563ca95b02SDimitry Andric     assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
13573ca95b02SDimitry Andric            "Only way to construct a deoptimize deferred replacement");
13583ca95b02SDimitry Andric #endif
13593ca95b02SDimitry Andric     DeferredReplacement D;
13603ca95b02SDimitry Andric     D.Old = Old;
13613ca95b02SDimitry Andric     D.IsDeoptimize = true;
13623ca95b02SDimitry Andric     return D;
13637d523365SDimitry Andric   }
13647d523365SDimitry Andric 
13657d523365SDimitry Andric   /// Does the task represented by this instance.
13667d523365SDimitry Andric   void doReplacement() {
13677d523365SDimitry Andric     Instruction *OldI = Old;
13687d523365SDimitry Andric     Instruction *NewI = New;
13697d523365SDimitry Andric 
13707d523365SDimitry Andric     assert(OldI != NewI && "Disallowed at construction?!");
13713ca95b02SDimitry Andric     assert((!IsDeoptimize || !New) &&
13723ca95b02SDimitry Andric            "Deoptimize instrinsics are not replaced!");
13737d523365SDimitry Andric 
13747d523365SDimitry Andric     Old = nullptr;
13757d523365SDimitry Andric     New = nullptr;
13767d523365SDimitry Andric 
13777d523365SDimitry Andric     if (NewI)
13787d523365SDimitry Andric       OldI->replaceAllUsesWith(NewI);
13793ca95b02SDimitry Andric 
13803ca95b02SDimitry Andric     if (IsDeoptimize) {
13813ca95b02SDimitry Andric       // Note: we've inserted instructions, so the call to llvm.deoptimize may
13823ca95b02SDimitry Andric       // not necessarilly be followed by the matching return.
13833ca95b02SDimitry Andric       auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
13843ca95b02SDimitry Andric       new UnreachableInst(RI->getContext(), RI);
13853ca95b02SDimitry Andric       RI->eraseFromParent();
13863ca95b02SDimitry Andric     }
13873ca95b02SDimitry Andric 
13887d523365SDimitry Andric     OldI->eraseFromParent();
13897d523365SDimitry Andric   }
13907d523365SDimitry Andric };
13912cab237bSDimitry Andric 
13922cab237bSDimitry Andric } // end anonymous namespace
1393ff0cc061SDimitry Andric 
1394d88c1a5aSDimitry Andric static StringRef getDeoptLowering(CallSite CS) {
1395d88c1a5aSDimitry Andric   const char *DeoptLowering = "deopt-lowering";
1396d88c1a5aSDimitry Andric   if (CS.hasFnAttr(DeoptLowering)) {
1397d88c1a5aSDimitry Andric     // FIXME: CallSite has a *really* confusing interface around attributes
1398d88c1a5aSDimitry Andric     // with values.
13997a7e6055SDimitry Andric     const AttributeList &CSAS = CS.getAttributes();
14007a7e6055SDimitry Andric     if (CSAS.hasAttribute(AttributeList::FunctionIndex, DeoptLowering))
14017a7e6055SDimitry Andric       return CSAS.getAttribute(AttributeList::FunctionIndex, DeoptLowering)
14027a7e6055SDimitry Andric           .getValueAsString();
1403d88c1a5aSDimitry Andric     Function *F = CS.getCalledFunction();
1404d88c1a5aSDimitry Andric     assert(F && F->hasFnAttribute(DeoptLowering));
1405d88c1a5aSDimitry Andric     return F->getFnAttribute(DeoptLowering).getValueAsString();
1406d88c1a5aSDimitry Andric   }
1407d88c1a5aSDimitry Andric   return "live-through";
1408d88c1a5aSDimitry Andric }
1409d88c1a5aSDimitry Andric 
1410ff0cc061SDimitry Andric static void
14117d523365SDimitry Andric makeStatepointExplicitImpl(const CallSite CS, /* to replace */
14127d523365SDimitry Andric                            const SmallVectorImpl<Value *> &BasePtrs,
14137d523365SDimitry Andric                            const SmallVectorImpl<Value *> &LiveVariables,
14147d523365SDimitry Andric                            PartiallyConstructedSafepointRecord &Result,
14157d523365SDimitry Andric                            std::vector<DeferredReplacement> &Replacements) {
14167d523365SDimitry Andric   assert(BasePtrs.size() == LiveVariables.size());
1417ff0cc061SDimitry Andric 
1418ff0cc061SDimitry Andric   // Then go ahead and use the builder do actually do the inserts.  We insert
1419ff0cc061SDimitry Andric   // immediately before the previous instruction under the assumption that all
1420ff0cc061SDimitry Andric   // arguments will be available here.  We can't insert afterwards since we may
1421ff0cc061SDimitry Andric   // be replacing a terminator.
14227d523365SDimitry Andric   Instruction *InsertBefore = CS.getInstruction();
14237d523365SDimitry Andric   IRBuilder<> Builder(InsertBefore);
1424ff0cc061SDimitry Andric 
14257d523365SDimitry Andric   ArrayRef<Value *> GCArgs(LiveVariables);
14263ca95b02SDimitry Andric   uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
14277d523365SDimitry Andric   uint32_t NumPatchBytes = 0;
14287d523365SDimitry Andric   uint32_t Flags = uint32_t(StatepointFlags::None);
14297d523365SDimitry Andric 
14303ca95b02SDimitry Andric   ArrayRef<Use> CallArgs(CS.arg_begin(), CS.arg_end());
14313ca95b02SDimitry Andric   ArrayRef<Use> DeoptArgs = GetDeoptBundleOperands(CS);
14327d523365SDimitry Andric   ArrayRef<Use> TransitionArgs;
14333ca95b02SDimitry Andric   if (auto TransitionBundle =
14343ca95b02SDimitry Andric       CS.getOperandBundle(LLVMContext::OB_gc_transition)) {
14353ca95b02SDimitry Andric     Flags |= uint32_t(StatepointFlags::GCTransition);
14363ca95b02SDimitry Andric     TransitionArgs = TransitionBundle->Inputs;
14373ca95b02SDimitry Andric   }
14387d523365SDimitry Andric 
14393ca95b02SDimitry Andric   // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
14403ca95b02SDimitry Andric   // with a return value, we lower then as never returning calls to
14413ca95b02SDimitry Andric   // __llvm_deoptimize that are followed by unreachable to get better codegen.
14423ca95b02SDimitry Andric   bool IsDeoptimize = false;
14437d523365SDimitry Andric 
14443ca95b02SDimitry Andric   StatepointDirectives SD =
14453ca95b02SDimitry Andric       parseStatepointDirectivesFromAttrs(CS.getAttributes());
14463ca95b02SDimitry Andric   if (SD.NumPatchBytes)
14473ca95b02SDimitry Andric     NumPatchBytes = *SD.NumPatchBytes;
14483ca95b02SDimitry Andric   if (SD.StatepointID)
14493ca95b02SDimitry Andric     StatepointID = *SD.StatepointID;
14507d523365SDimitry Andric 
1451d88c1a5aSDimitry Andric   // Pass through the requested lowering if any.  The default is live-through.
1452d88c1a5aSDimitry Andric   StringRef DeoptLowering = getDeoptLowering(CS);
1453d88c1a5aSDimitry Andric   if (DeoptLowering.equals("live-in"))
1454d88c1a5aSDimitry Andric     Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
1455d88c1a5aSDimitry Andric   else {
1456d88c1a5aSDimitry Andric     assert(DeoptLowering.equals("live-through") && "Unsupported value!");
1457d88c1a5aSDimitry Andric   }
1458d88c1a5aSDimitry Andric 
14593ca95b02SDimitry Andric   Value *CallTarget = CS.getCalledValue();
14603ca95b02SDimitry Andric   if (Function *F = dyn_cast<Function>(CallTarget)) {
14613ca95b02SDimitry Andric     if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize) {
14623ca95b02SDimitry Andric       // Calls to llvm.experimental.deoptimize are lowered to calls to the
14633ca95b02SDimitry Andric       // __llvm_deoptimize symbol.  We want to resolve this now, since the
14643ca95b02SDimitry Andric       // verifier does not allow taking the address of an intrinsic function.
14657d523365SDimitry Andric 
14663ca95b02SDimitry Andric       SmallVector<Type *, 8> DomainTy;
14673ca95b02SDimitry Andric       for (Value *Arg : CallArgs)
14683ca95b02SDimitry Andric         DomainTy.push_back(Arg->getType());
14693ca95b02SDimitry Andric       auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
14703ca95b02SDimitry Andric                                     /* isVarArg = */ false);
14717d523365SDimitry Andric 
14723ca95b02SDimitry Andric       // Note: CallTarget can be a bitcast instruction of a symbol if there are
14733ca95b02SDimitry Andric       // calls to @llvm.experimental.deoptimize with different argument types in
14743ca95b02SDimitry Andric       // the same module.  This is fine -- we assume the frontend knew what it
14753ca95b02SDimitry Andric       // was doing when generating this kind of IR.
14763ca95b02SDimitry Andric       CallTarget =
14773ca95b02SDimitry Andric           F->getParent()->getOrInsertFunction("__llvm_deoptimize", FTy);
14787d523365SDimitry Andric 
14793ca95b02SDimitry Andric       IsDeoptimize = true;
14803ca95b02SDimitry Andric     }
14817d523365SDimitry Andric   }
1482ff0cc061SDimitry Andric 
1483ff0cc061SDimitry Andric   // Create the statepoint given all the arguments
14847d523365SDimitry Andric   Instruction *Token = nullptr;
1485ff0cc061SDimitry Andric   if (CS.isCall()) {
14867d523365SDimitry Andric     CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
14877d523365SDimitry Andric     CallInst *Call = Builder.CreateGCStatepointCall(
14887d523365SDimitry Andric         StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
14897d523365SDimitry Andric         TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
14907d523365SDimitry Andric 
1491d88c1a5aSDimitry Andric     Call->setTailCallKind(ToReplace->getTailCallKind());
14927d523365SDimitry Andric     Call->setCallingConv(ToReplace->getCallingConv());
1493ff0cc061SDimitry Andric 
1494ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1495f37b6182SDimitry Andric     // function attributes.  In case if we can handle this set of attributes -
1496f37b6182SDimitry Andric     // set up function attrs directly on statepoint and return attrs later for
1497f37b6182SDimitry Andric     // gc_result intrinsic.
1498f37b6182SDimitry Andric     Call->setAttributes(legalizeCallAttributes(ToReplace->getAttributes()));
1499ff0cc061SDimitry Andric 
15007d523365SDimitry Andric     Token = Call;
1501ff0cc061SDimitry Andric 
1502ff0cc061SDimitry Andric     // Put the following gc_result and gc_relocate calls immediately after the
1503ff0cc061SDimitry Andric     // the old call (which we're about to delete)
15047d523365SDimitry Andric     assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
15057d523365SDimitry Andric     Builder.SetInsertPoint(ToReplace->getNextNode());
15067d523365SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
1507ff0cc061SDimitry Andric   } else {
15087d523365SDimitry Andric     InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
1509ff0cc061SDimitry Andric 
1510ff0cc061SDimitry Andric     // Insert the new invoke into the old block.  We'll remove the old one in a
1511ff0cc061SDimitry Andric     // moment at which point this will become the new terminator for the
1512ff0cc061SDimitry Andric     // original block.
15137d523365SDimitry Andric     InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
15147d523365SDimitry Andric         StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
15157d523365SDimitry Andric         ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
15167d523365SDimitry Andric         GCArgs, "statepoint_token");
15177d523365SDimitry Andric 
15187d523365SDimitry Andric     Invoke->setCallingConv(ToReplace->getCallingConv());
1519ff0cc061SDimitry Andric 
1520ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1521f37b6182SDimitry Andric     // function attributes.  In case if we can handle this set of attributes -
1522f37b6182SDimitry Andric     // set up function attrs directly on statepoint and return attrs later for
1523f37b6182SDimitry Andric     // gc_result intrinsic.
1524f37b6182SDimitry Andric     Invoke->setAttributes(legalizeCallAttributes(ToReplace->getAttributes()));
1525ff0cc061SDimitry Andric 
15267d523365SDimitry Andric     Token = Invoke;
1527ff0cc061SDimitry Andric 
1528ff0cc061SDimitry Andric     // Generate gc relocates in exceptional path
15297d523365SDimitry Andric     BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
15307d523365SDimitry Andric     assert(!isa<PHINode>(UnwindBlock->begin()) &&
15317d523365SDimitry Andric            UnwindBlock->getUniquePredecessor() &&
1532ff0cc061SDimitry Andric            "can't safely insert in this block!");
1533ff0cc061SDimitry Andric 
15347d523365SDimitry Andric     Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
15357d523365SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1536ff0cc061SDimitry Andric 
15377d523365SDimitry Andric     // Attach exceptional gc relocates to the landingpad.
15387d523365SDimitry Andric     Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
15397d523365SDimitry Andric     Result.UnwindToken = ExceptionalToken;
1540ff0cc061SDimitry Andric 
15417d523365SDimitry Andric     const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
15427d523365SDimitry Andric     CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
15437d523365SDimitry Andric                       Builder);
1544ff0cc061SDimitry Andric 
1545ff0cc061SDimitry Andric     // Generate gc relocates and returns for normal block
15467d523365SDimitry Andric     BasicBlock *NormalDest = ToReplace->getNormalDest();
15477d523365SDimitry Andric     assert(!isa<PHINode>(NormalDest->begin()) &&
15487d523365SDimitry Andric            NormalDest->getUniquePredecessor() &&
1549ff0cc061SDimitry Andric            "can't safely insert in this block!");
1550ff0cc061SDimitry Andric 
15517d523365SDimitry Andric     Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
1552ff0cc061SDimitry Andric 
1553ff0cc061SDimitry Andric     // gc relocates will be generated later as if it were regular call
1554ff0cc061SDimitry Andric     // statepoint
1555ff0cc061SDimitry Andric   }
15567d523365SDimitry Andric   assert(Token && "Should be set in one of the above branches!");
1557ff0cc061SDimitry Andric 
15583ca95b02SDimitry Andric   if (IsDeoptimize) {
15593ca95b02SDimitry Andric     // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
15603ca95b02SDimitry Andric     // transform the tail-call like structure to a call to a void function
15613ca95b02SDimitry Andric     // followed by unreachable to get better codegen.
15623ca95b02SDimitry Andric     Replacements.push_back(
15633ca95b02SDimitry Andric         DeferredReplacement::createDeoptimizeReplacement(CS.getInstruction()));
15643ca95b02SDimitry Andric   } else {
15657d523365SDimitry Andric     Token->setName("statepoint_token");
15667d523365SDimitry Andric     if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
15677d523365SDimitry Andric       StringRef Name =
15687d523365SDimitry Andric           CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
15697d523365SDimitry Andric       CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
15707a7e6055SDimitry Andric       GCResult->setAttributes(
15717a7e6055SDimitry Andric           AttributeList::get(GCResult->getContext(), AttributeList::ReturnIndex,
15727a7e6055SDimitry Andric                              CS.getAttributes().getRetAttributes()));
1573ff0cc061SDimitry Andric 
15747d523365SDimitry Andric       // We cannot RAUW or delete CS.getInstruction() because it could be in the
15757d523365SDimitry Andric       // live set of some other safepoint, in which case that safepoint's
15767d523365SDimitry Andric       // PartiallyConstructedSafepointRecord will hold a raw pointer to this
15777d523365SDimitry Andric       // llvm::Instruction.  Instead, we defer the replacement and deletion to
15787d523365SDimitry Andric       // after the live sets have been made explicit in the IR, and we no longer
15797d523365SDimitry Andric       // have raw pointers to worry about.
15803ca95b02SDimitry Andric       Replacements.emplace_back(
15813ca95b02SDimitry Andric           DeferredReplacement::createRAUW(CS.getInstruction(), GCResult));
15827d523365SDimitry Andric     } else {
15833ca95b02SDimitry Andric       Replacements.emplace_back(
15843ca95b02SDimitry Andric           DeferredReplacement::createDelete(CS.getInstruction()));
15857d523365SDimitry Andric     }
15867d523365SDimitry Andric   }
1587ff0cc061SDimitry Andric 
15887d523365SDimitry Andric   Result.StatepointToken = Token;
1589ff0cc061SDimitry Andric 
1590ff0cc061SDimitry Andric   // Second, create a gc.relocate for every live variable
15917d523365SDimitry Andric   const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
15927d523365SDimitry Andric   CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
1593ff0cc061SDimitry Andric }
1594ff0cc061SDimitry Andric 
1595ff0cc061SDimitry Andric // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1596ff0cc061SDimitry Andric // which make the relocations happening at this safepoint explicit.
1597ff0cc061SDimitry Andric //
1598ff0cc061SDimitry Andric // WARNING: Does not do any fixup to adjust users of the original live
1599ff0cc061SDimitry Andric // values.  That's the callers responsibility.
1600ff0cc061SDimitry Andric static void
16013ca95b02SDimitry Andric makeStatepointExplicit(DominatorTree &DT, CallSite CS,
16027d523365SDimitry Andric                        PartiallyConstructedSafepointRecord &Result,
16037d523365SDimitry Andric                        std::vector<DeferredReplacement> &Replacements) {
16047d523365SDimitry Andric   const auto &LiveSet = Result.LiveSet;
16057d523365SDimitry Andric   const auto &PointerToBase = Result.PointerToBase;
1606ff0cc061SDimitry Andric 
1607ff0cc061SDimitry Andric   // Convert to vector for efficient cross referencing.
16087d523365SDimitry Andric   SmallVector<Value *, 64> BaseVec, LiveVec;
16097d523365SDimitry Andric   LiveVec.reserve(LiveSet.size());
16107d523365SDimitry Andric   BaseVec.reserve(LiveSet.size());
16117d523365SDimitry Andric   for (Value *L : LiveSet) {
16127d523365SDimitry Andric     LiveVec.push_back(L);
16137d523365SDimitry Andric     assert(PointerToBase.count(L));
16147d523365SDimitry Andric     Value *Base = PointerToBase.find(L)->second;
16157d523365SDimitry Andric     BaseVec.push_back(Base);
1616ff0cc061SDimitry Andric   }
16177d523365SDimitry Andric   assert(LiveVec.size() == BaseVec.size());
1618ff0cc061SDimitry Andric 
1619ff0cc061SDimitry Andric   // Do the actual rewriting and delete the old statepoint
16207d523365SDimitry Andric   makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
1621ff0cc061SDimitry Andric }
1622ff0cc061SDimitry Andric 
1623ff0cc061SDimitry Andric // Helper function for the relocationViaAlloca.
16247d523365SDimitry Andric //
16257d523365SDimitry Andric // It receives iterator to the statepoint gc relocates and emits a store to the
16267d523365SDimitry Andric // assigned location (via allocaMap) for the each one of them.  It adds the
16277d523365SDimitry Andric // visited values into the visitedLiveValues set, which we will later use them
16287d523365SDimitry Andric // for sanity checking.
1629ff0cc061SDimitry Andric static void
1630ff0cc061SDimitry Andric insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1631ff0cc061SDimitry Andric                        DenseMap<Value *, Value *> &AllocaMap,
1632ff0cc061SDimitry Andric                        DenseSet<Value *> &VisitedLiveValues) {
1633ff0cc061SDimitry Andric   for (User *U : GCRelocs) {
16344d0b32cdSDimitry Andric     GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
16354d0b32cdSDimitry Andric     if (!Relocate)
1636ff0cc061SDimitry Andric       continue;
1637ff0cc061SDimitry Andric 
16383ca95b02SDimitry Andric     Value *OriginalValue = Relocate->getDerivedPtr();
1639ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue));
1640ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1641ff0cc061SDimitry Andric 
1642ff0cc061SDimitry Andric     // Emit store into the related alloca
16437d523365SDimitry Andric     // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1644ff0cc061SDimitry Andric     // the correct type according to alloca.
16454d0b32cdSDimitry Andric     assert(Relocate->getNextNode() &&
16467d523365SDimitry Andric            "Should always have one since it's not a terminator");
16474d0b32cdSDimitry Andric     IRBuilder<> Builder(Relocate->getNextNode());
1648ff0cc061SDimitry Andric     Value *CastedRelocatedValue =
16494d0b32cdSDimitry Andric       Builder.CreateBitCast(Relocate,
16507d523365SDimitry Andric                             cast<AllocaInst>(Alloca)->getAllocatedType(),
16514d0b32cdSDimitry Andric                             suffixed_name_or(Relocate, ".casted", ""));
1652ff0cc061SDimitry Andric 
1653ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1654ff0cc061SDimitry Andric     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1655ff0cc061SDimitry Andric 
1656ff0cc061SDimitry Andric #ifndef NDEBUG
1657ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1658ff0cc061SDimitry Andric #endif
1659ff0cc061SDimitry Andric   }
1660ff0cc061SDimitry Andric }
1661ff0cc061SDimitry Andric 
1662ff0cc061SDimitry Andric // Helper function for the "relocationViaAlloca". Similar to the
1663ff0cc061SDimitry Andric // "insertRelocationStores" but works for rematerialized values.
16643ca95b02SDimitry Andric static void insertRematerializationStores(
16653ca95b02SDimitry Andric     const RematerializedValueMapTy &RematerializedValues,
1666ff0cc061SDimitry Andric     DenseMap<Value *, Value *> &AllocaMap,
1667ff0cc061SDimitry Andric     DenseSet<Value *> &VisitedLiveValues) {
1668ff0cc061SDimitry Andric   for (auto RematerializedValuePair: RematerializedValues) {
1669ff0cc061SDimitry Andric     Instruction *RematerializedValue = RematerializedValuePair.first;
1670ff0cc061SDimitry Andric     Value *OriginalValue = RematerializedValuePair.second;
1671ff0cc061SDimitry Andric 
1672ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue) &&
1673ff0cc061SDimitry Andric            "Can not find alloca for rematerialized value");
1674ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1675ff0cc061SDimitry Andric 
1676ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1677ff0cc061SDimitry Andric     Store->insertAfter(RematerializedValue);
1678ff0cc061SDimitry Andric 
1679ff0cc061SDimitry Andric #ifndef NDEBUG
1680ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1681ff0cc061SDimitry Andric #endif
1682ff0cc061SDimitry Andric   }
1683ff0cc061SDimitry Andric }
1684ff0cc061SDimitry Andric 
16857d523365SDimitry Andric /// Do all the relocation update via allocas and mem2reg
1686ff0cc061SDimitry Andric static void relocationViaAlloca(
1687ff0cc061SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
16887d523365SDimitry Andric     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1689ff0cc061SDimitry Andric #ifndef NDEBUG
1690ff0cc061SDimitry Andric   // record initial number of (static) allocas; we'll check we have the same
1691ff0cc061SDimitry Andric   // number when we get done.
1692ff0cc061SDimitry Andric   int InitialAllocaNum = 0;
16933ca95b02SDimitry Andric   for (Instruction &I : F.getEntryBlock())
16943ca95b02SDimitry Andric     if (isa<AllocaInst>(I))
1695ff0cc061SDimitry Andric       InitialAllocaNum++;
1696ff0cc061SDimitry Andric #endif
1697ff0cc061SDimitry Andric 
1698ff0cc061SDimitry Andric   // TODO-PERF: change data structures, reserve
1699ff0cc061SDimitry Andric   DenseMap<Value *, Value *> AllocaMap;
1700ff0cc061SDimitry Andric   SmallVector<AllocaInst *, 200> PromotableAllocas;
1701ff0cc061SDimitry Andric   // Used later to chack that we have enough allocas to store all values
1702ff0cc061SDimitry Andric   std::size_t NumRematerializedValues = 0;
1703ff0cc061SDimitry Andric   PromotableAllocas.reserve(Live.size());
1704ff0cc061SDimitry Andric 
1705ff0cc061SDimitry Andric   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1706ff0cc061SDimitry Andric   // "PromotableAllocas"
17077a7e6055SDimitry Andric   const DataLayout &DL = F.getParent()->getDataLayout();
1708ff0cc061SDimitry Andric   auto emitAllocaFor = [&](Value *LiveValue) {
17097a7e6055SDimitry Andric     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(),
17107a7e6055SDimitry Andric                                         DL.getAllocaAddrSpace(), "",
1711ff0cc061SDimitry Andric                                         F.getEntryBlock().getFirstNonPHI());
1712ff0cc061SDimitry Andric     AllocaMap[LiveValue] = Alloca;
1713ff0cc061SDimitry Andric     PromotableAllocas.push_back(Alloca);
1714ff0cc061SDimitry Andric   };
1715ff0cc061SDimitry Andric 
17167d523365SDimitry Andric   // Emit alloca for each live gc pointer
17177d523365SDimitry Andric   for (Value *V : Live)
17187d523365SDimitry Andric     emitAllocaFor(V);
1719ff0cc061SDimitry Andric 
17207d523365SDimitry Andric   // Emit allocas for rematerialized values
17217d523365SDimitry Andric   for (const auto &Info : Records)
1722ff0cc061SDimitry Andric     for (auto RematerializedValuePair : Info.RematerializedValues) {
1723ff0cc061SDimitry Andric       Value *OriginalValue = RematerializedValuePair.second;
1724ff0cc061SDimitry Andric       if (AllocaMap.count(OriginalValue) != 0)
1725ff0cc061SDimitry Andric         continue;
1726ff0cc061SDimitry Andric 
1727ff0cc061SDimitry Andric       emitAllocaFor(OriginalValue);
1728ff0cc061SDimitry Andric       ++NumRematerializedValues;
1729ff0cc061SDimitry Andric     }
1730ff0cc061SDimitry Andric 
1731ff0cc061SDimitry Andric   // The next two loops are part of the same conceptual operation.  We need to
1732ff0cc061SDimitry Andric   // insert a store to the alloca after the original def and at each
1733ff0cc061SDimitry Andric   // redefinition.  We need to insert a load before each use.  These are split
1734ff0cc061SDimitry Andric   // into distinct loops for performance reasons.
1735ff0cc061SDimitry Andric 
17367d523365SDimitry Andric   // Update gc pointer after each statepoint: either store a relocated value or
17377d523365SDimitry Andric   // null (if no relocated value was found for this gc pointer and it is not a
17387d523365SDimitry Andric   // gc_result).  This must happen before we update the statepoint with load of
17397d523365SDimitry Andric   // alloca otherwise we lose the link between statepoint and old def.
17407d523365SDimitry Andric   for (const auto &Info : Records) {
1741ff0cc061SDimitry Andric     Value *Statepoint = Info.StatepointToken;
1742ff0cc061SDimitry Andric 
1743ff0cc061SDimitry Andric     // This will be used for consistency check
1744ff0cc061SDimitry Andric     DenseSet<Value *> VisitedLiveValues;
1745ff0cc061SDimitry Andric 
1746ff0cc061SDimitry Andric     // Insert stores for normal statepoint gc relocates
1747ff0cc061SDimitry Andric     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1748ff0cc061SDimitry Andric 
1749ff0cc061SDimitry Andric     // In case if it was invoke statepoint
1750ff0cc061SDimitry Andric     // we will insert stores for exceptional path gc relocates.
1751ff0cc061SDimitry Andric     if (isa<InvokeInst>(Statepoint)) {
1752ff0cc061SDimitry Andric       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1753ff0cc061SDimitry Andric                              VisitedLiveValues);
1754ff0cc061SDimitry Andric     }
1755ff0cc061SDimitry Andric 
1756ff0cc061SDimitry Andric     // Do similar thing with rematerialized values
1757ff0cc061SDimitry Andric     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1758ff0cc061SDimitry Andric                                   VisitedLiveValues);
1759ff0cc061SDimitry Andric 
1760ff0cc061SDimitry Andric     if (ClobberNonLive) {
17617d523365SDimitry Andric       // As a debugging aid, pretend that an unrelocated pointer becomes null at
1762ff0cc061SDimitry Andric       // the gc.statepoint.  This will turn some subtle GC problems into
1763ff0cc061SDimitry Andric       // slightly easier to debug SEGVs.  Note that on large IR files with
1764ff0cc061SDimitry Andric       // lots of gc.statepoints this is extremely costly both memory and time
1765ff0cc061SDimitry Andric       // wise.
1766ff0cc061SDimitry Andric       SmallVector<AllocaInst *, 64> ToClobber;
1767ff0cc061SDimitry Andric       for (auto Pair : AllocaMap) {
1768ff0cc061SDimitry Andric         Value *Def = Pair.first;
1769ff0cc061SDimitry Andric         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1770ff0cc061SDimitry Andric 
1771ff0cc061SDimitry Andric         // This value was relocated
1772ff0cc061SDimitry Andric         if (VisitedLiveValues.count(Def)) {
1773ff0cc061SDimitry Andric           continue;
1774ff0cc061SDimitry Andric         }
1775ff0cc061SDimitry Andric         ToClobber.push_back(Alloca);
1776ff0cc061SDimitry Andric       }
1777ff0cc061SDimitry Andric 
1778ff0cc061SDimitry Andric       auto InsertClobbersAt = [&](Instruction *IP) {
1779ff0cc061SDimitry Andric         for (auto *AI : ToClobber) {
17803ca95b02SDimitry Andric           auto PT = cast<PointerType>(AI->getAllocatedType());
1781ff0cc061SDimitry Andric           Constant *CPN = ConstantPointerNull::get(PT);
1782ff0cc061SDimitry Andric           StoreInst *Store = new StoreInst(CPN, AI);
1783ff0cc061SDimitry Andric           Store->insertBefore(IP);
1784ff0cc061SDimitry Andric         }
1785ff0cc061SDimitry Andric       };
1786ff0cc061SDimitry Andric 
1787ff0cc061SDimitry Andric       // Insert the clobbering stores.  These may get intermixed with the
1788ff0cc061SDimitry Andric       // gc.results and gc.relocates, but that's fine.
1789ff0cc061SDimitry Andric       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
17907d523365SDimitry Andric         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
17917d523365SDimitry Andric         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1792ff0cc061SDimitry Andric       } else {
17937d523365SDimitry Andric         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1794ff0cc061SDimitry Andric       }
1795ff0cc061SDimitry Andric     }
1796ff0cc061SDimitry Andric   }
17977d523365SDimitry Andric 
17987d523365SDimitry Andric   // Update use with load allocas and add store for gc_relocated.
1799ff0cc061SDimitry Andric   for (auto Pair : AllocaMap) {
1800ff0cc061SDimitry Andric     Value *Def = Pair.first;
1801ff0cc061SDimitry Andric     Value *Alloca = Pair.second;
1802ff0cc061SDimitry Andric 
18037d523365SDimitry Andric     // We pre-record the uses of allocas so that we dont have to worry about
18047d523365SDimitry Andric     // later update that changes the user information..
18057d523365SDimitry Andric 
1806ff0cc061SDimitry Andric     SmallVector<Instruction *, 20> Uses;
1807ff0cc061SDimitry Andric     // PERF: trade a linear scan for repeated reallocation
1808ff0cc061SDimitry Andric     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1809ff0cc061SDimitry Andric     for (User *U : Def->users()) {
1810ff0cc061SDimitry Andric       if (!isa<ConstantExpr>(U)) {
1811ff0cc061SDimitry Andric         // If the def has a ConstantExpr use, then the def is either a
1812ff0cc061SDimitry Andric         // ConstantExpr use itself or null.  In either case
1813ff0cc061SDimitry Andric         // (recursively in the first, directly in the second), the oop
1814ff0cc061SDimitry Andric         // it is ultimately dependent on is null and this particular
1815ff0cc061SDimitry Andric         // use does not need to be fixed up.
1816ff0cc061SDimitry Andric         Uses.push_back(cast<Instruction>(U));
1817ff0cc061SDimitry Andric       }
1818ff0cc061SDimitry Andric     }
1819ff0cc061SDimitry Andric 
1820ff0cc061SDimitry Andric     std::sort(Uses.begin(), Uses.end());
1821ff0cc061SDimitry Andric     auto Last = std::unique(Uses.begin(), Uses.end());
1822ff0cc061SDimitry Andric     Uses.erase(Last, Uses.end());
1823ff0cc061SDimitry Andric 
1824ff0cc061SDimitry Andric     for (Instruction *Use : Uses) {
1825ff0cc061SDimitry Andric       if (isa<PHINode>(Use)) {
1826ff0cc061SDimitry Andric         PHINode *Phi = cast<PHINode>(Use);
1827ff0cc061SDimitry Andric         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1828ff0cc061SDimitry Andric           if (Def == Phi->getIncomingValue(i)) {
1829ff0cc061SDimitry Andric             LoadInst *Load = new LoadInst(
1830ff0cc061SDimitry Andric                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1831ff0cc061SDimitry Andric             Phi->setIncomingValue(i, Load);
1832ff0cc061SDimitry Andric           }
1833ff0cc061SDimitry Andric         }
1834ff0cc061SDimitry Andric       } else {
1835ff0cc061SDimitry Andric         LoadInst *Load = new LoadInst(Alloca, "", Use);
1836ff0cc061SDimitry Andric         Use->replaceUsesOfWith(Def, Load);
1837ff0cc061SDimitry Andric       }
1838ff0cc061SDimitry Andric     }
1839ff0cc061SDimitry Andric 
18407d523365SDimitry Andric     // Emit store for the initial gc value.  Store must be inserted after load,
18417d523365SDimitry Andric     // otherwise store will be in alloca's use list and an extra load will be
18427d523365SDimitry Andric     // inserted before it.
1843ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(Def, Alloca);
1844ff0cc061SDimitry Andric     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1845ff0cc061SDimitry Andric       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1846ff0cc061SDimitry Andric         // InvokeInst is a TerminatorInst so the store need to be inserted
1847ff0cc061SDimitry Andric         // into its normal destination block.
1848ff0cc061SDimitry Andric         BasicBlock *NormalDest = Invoke->getNormalDest();
1849ff0cc061SDimitry Andric         Store->insertBefore(NormalDest->getFirstNonPHI());
1850ff0cc061SDimitry Andric       } else {
1851ff0cc061SDimitry Andric         assert(!Inst->isTerminator() &&
1852ff0cc061SDimitry Andric                "The only TerminatorInst that can produce a value is "
1853ff0cc061SDimitry Andric                "InvokeInst which is handled above.");
1854ff0cc061SDimitry Andric         Store->insertAfter(Inst);
1855ff0cc061SDimitry Andric       }
1856ff0cc061SDimitry Andric     } else {
1857ff0cc061SDimitry Andric       assert(isa<Argument>(Def));
1858ff0cc061SDimitry Andric       Store->insertAfter(cast<Instruction>(Alloca));
1859ff0cc061SDimitry Andric     }
1860ff0cc061SDimitry Andric   }
1861ff0cc061SDimitry Andric 
1862ff0cc061SDimitry Andric   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1863ff0cc061SDimitry Andric          "we must have the same allocas with lives");
1864ff0cc061SDimitry Andric   if (!PromotableAllocas.empty()) {
18657d523365SDimitry Andric     // Apply mem2reg to promote alloca to SSA
1866ff0cc061SDimitry Andric     PromoteMemToReg(PromotableAllocas, DT);
1867ff0cc061SDimitry Andric   }
1868ff0cc061SDimitry Andric 
1869ff0cc061SDimitry Andric #ifndef NDEBUG
18707d523365SDimitry Andric   for (auto &I : F.getEntryBlock())
18717d523365SDimitry Andric     if (isa<AllocaInst>(I))
1872ff0cc061SDimitry Andric       InitialAllocaNum--;
1873ff0cc061SDimitry Andric   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1874ff0cc061SDimitry Andric #endif
1875ff0cc061SDimitry Andric }
1876ff0cc061SDimitry Andric 
1877ff0cc061SDimitry Andric /// Implement a unique function which doesn't require we sort the input
1878ff0cc061SDimitry Andric /// vector.  Doing so has the effect of changing the output of a couple of
1879ff0cc061SDimitry Andric /// tests in ways which make them less useful in testing fused safepoints.
1880ff0cc061SDimitry Andric template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
18818f0fd8f6SDimitry Andric   SmallSet<T, 8> Seen;
1882d88c1a5aSDimitry Andric   Vec.erase(remove_if(Vec, [&](const T &V) { return !Seen.insert(V).second; }),
1883d88c1a5aSDimitry Andric             Vec.end());
1884ff0cc061SDimitry Andric }
1885ff0cc061SDimitry Andric 
1886ff0cc061SDimitry Andric /// Insert holders so that each Value is obviously live through the entire
1887ff0cc061SDimitry Andric /// lifetime of the call.
1888ff0cc061SDimitry Andric static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1889ff0cc061SDimitry Andric                                  SmallVectorImpl<CallInst *> &Holders) {
1890ff0cc061SDimitry Andric   if (Values.empty())
1891ff0cc061SDimitry Andric     // No values to hold live, might as well not insert the empty holder
1892ff0cc061SDimitry Andric     return;
1893ff0cc061SDimitry Andric 
18947d523365SDimitry Andric   Module *M = CS.getInstruction()->getModule();
1895ff0cc061SDimitry Andric   // Use a dummy vararg function to actually hold the values live
1896ff0cc061SDimitry Andric   Function *Func = cast<Function>(M->getOrInsertFunction(
1897ff0cc061SDimitry Andric       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1898ff0cc061SDimitry Andric   if (CS.isCall()) {
1899ff0cc061SDimitry Andric     // For call safepoints insert dummy calls right after safepoint
19007d523365SDimitry Andric     Holders.push_back(CallInst::Create(Func, Values, "",
19017d523365SDimitry Andric                                        &*++CS.getInstruction()->getIterator()));
1902ff0cc061SDimitry Andric     return;
1903ff0cc061SDimitry Andric   }
1904ff0cc061SDimitry Andric   // For invoke safepooints insert dummy calls both in normal and
1905ff0cc061SDimitry Andric   // exceptional destination blocks
1906ff0cc061SDimitry Andric   auto *II = cast<InvokeInst>(CS.getInstruction());
1907ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
19087d523365SDimitry Andric       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
1909ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
19107d523365SDimitry Andric       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
1911ff0cc061SDimitry Andric }
1912ff0cc061SDimitry Andric 
1913ff0cc061SDimitry Andric static void findLiveReferences(
19147d523365SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1915ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1916ff0cc061SDimitry Andric   GCPtrLivenessData OriginalLivenessData;
1917ff0cc061SDimitry Andric   computeLiveInValues(DT, F, OriginalLivenessData);
1918ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1919ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
19203ca95b02SDimitry Andric     analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
19213dac3a9bSDimitry Andric   }
1922ff0cc061SDimitry Andric }
1923ff0cc061SDimitry Andric 
1924ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". It walks use chain
1925d88c1a5aSDimitry Andric // starting from the "CurrentValue" until it reaches the root of the chain, i.e.
1926d88c1a5aSDimitry Andric // the base or a value it cannot process. Only "simple" values are processed
1927d88c1a5aSDimitry Andric // (currently it is GEP's and casts). The returned root is  examined by the
1928d88c1a5aSDimitry Andric // callers of findRematerializableChainToBasePointer.  Fills "ChainToBase" array
1929d88c1a5aSDimitry Andric // with all visited values.
1930d88c1a5aSDimitry Andric static Value* findRematerializableChainToBasePointer(
1931ff0cc061SDimitry Andric   SmallVectorImpl<Instruction*> &ChainToBase,
1932d88c1a5aSDimitry Andric   Value *CurrentValue) {
1933ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1934ff0cc061SDimitry Andric     ChainToBase.push_back(GEP);
1935ff0cc061SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
1936d88c1a5aSDimitry Andric                                                   GEP->getPointerOperand());
1937ff0cc061SDimitry Andric   }
1938ff0cc061SDimitry Andric 
1939ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1940ff0cc061SDimitry Andric     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1941d88c1a5aSDimitry Andric       return CI;
1942ff0cc061SDimitry Andric 
1943ff0cc061SDimitry Andric     ChainToBase.push_back(CI);
19447d523365SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
1945d88c1a5aSDimitry Andric                                                   CI->getOperand(0));
1946ff0cc061SDimitry Andric   }
1947ff0cc061SDimitry Andric 
1948d88c1a5aSDimitry Andric   // We have reached the root of the chain, which is either equal to the base or
1949d88c1a5aSDimitry Andric   // is the first unsupported value along the use chain.
1950d88c1a5aSDimitry Andric   return CurrentValue;
1951ff0cc061SDimitry Andric }
1952ff0cc061SDimitry Andric 
1953ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". Compute cost of the use
1954ff0cc061SDimitry Andric // chain we are going to rematerialize.
1955ff0cc061SDimitry Andric static unsigned
1956ff0cc061SDimitry Andric chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1957ff0cc061SDimitry Andric                        TargetTransformInfo &TTI) {
1958ff0cc061SDimitry Andric   unsigned Cost = 0;
1959ff0cc061SDimitry Andric 
1960ff0cc061SDimitry Andric   for (Instruction *Instr : Chain) {
1961ff0cc061SDimitry Andric     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1962ff0cc061SDimitry Andric       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1963ff0cc061SDimitry Andric              "non noop cast is found during rematerialization");
1964ff0cc061SDimitry Andric 
1965ff0cc061SDimitry Andric       Type *SrcTy = CI->getOperand(0)->getType();
19667a7e6055SDimitry Andric       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy, CI);
1967ff0cc061SDimitry Andric 
1968ff0cc061SDimitry Andric     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1969ff0cc061SDimitry Andric       // Cost of the address calculation
19703ca95b02SDimitry Andric       Type *ValTy = GEP->getSourceElementType();
1971ff0cc061SDimitry Andric       Cost += TTI.getAddressComputationCost(ValTy);
1972ff0cc061SDimitry Andric 
1973ff0cc061SDimitry Andric       // And cost of the GEP itself
1974ff0cc061SDimitry Andric       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1975ff0cc061SDimitry Andric       //       allowed for the external usage)
1976ff0cc061SDimitry Andric       if (!GEP->hasAllConstantIndices())
1977ff0cc061SDimitry Andric         Cost += 2;
1978ff0cc061SDimitry Andric 
1979ff0cc061SDimitry Andric     } else {
1980ff0cc061SDimitry Andric       llvm_unreachable("unsupported instruciton type during rematerialization");
1981ff0cc061SDimitry Andric     }
1982ff0cc061SDimitry Andric   }
1983ff0cc061SDimitry Andric 
1984ff0cc061SDimitry Andric   return Cost;
1985ff0cc061SDimitry Andric }
1986ff0cc061SDimitry Andric 
1987d88c1a5aSDimitry Andric static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
1988d88c1a5aSDimitry Andric   unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
1989d88c1a5aSDimitry Andric   if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
1990d88c1a5aSDimitry Andric       OrigRootPhi.getParent() != AlternateRootPhi.getParent())
1991d88c1a5aSDimitry Andric     return false;
1992d88c1a5aSDimitry Andric   // Map of incoming values and their corresponding basic blocks of
1993d88c1a5aSDimitry Andric   // OrigRootPhi.
1994d88c1a5aSDimitry Andric   SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
1995d88c1a5aSDimitry Andric   for (unsigned i = 0; i < PhiNum; i++)
1996d88c1a5aSDimitry Andric     CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
1997d88c1a5aSDimitry Andric         OrigRootPhi.getIncomingBlock(i);
1998d88c1a5aSDimitry Andric 
1999d88c1a5aSDimitry Andric   // Both current and base PHIs should have same incoming values and
2000d88c1a5aSDimitry Andric   // the same basic blocks corresponding to the incoming values.
2001d88c1a5aSDimitry Andric   for (unsigned i = 0; i < PhiNum; i++) {
2002d88c1a5aSDimitry Andric     auto CIVI =
2003d88c1a5aSDimitry Andric         CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
2004d88c1a5aSDimitry Andric     if (CIVI == CurrentIncomingValues.end())
2005d88c1a5aSDimitry Andric       return false;
2006d88c1a5aSDimitry Andric     BasicBlock *CurrentIncomingBB = CIVI->second;
2007d88c1a5aSDimitry Andric     if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
2008d88c1a5aSDimitry Andric       return false;
2009d88c1a5aSDimitry Andric   }
2010d88c1a5aSDimitry Andric   return true;
2011d88c1a5aSDimitry Andric }
2012d88c1a5aSDimitry Andric 
20137d523365SDimitry Andric // From the statepoint live set pick values that are cheaper to recompute then
20147d523365SDimitry Andric // to relocate. Remove this values from the live set, rematerialize them after
2015ff0cc061SDimitry Andric // statepoint and record them in "Info" structure. Note that similar to
2016ff0cc061SDimitry Andric // relocated values we don't do any user adjustments here.
2017ff0cc061SDimitry Andric static void rematerializeLiveValues(CallSite CS,
2018ff0cc061SDimitry Andric                                     PartiallyConstructedSafepointRecord &Info,
2019ff0cc061SDimitry Andric                                     TargetTransformInfo &TTI) {
2020ff0cc061SDimitry Andric   const unsigned int ChainLengthThreshold = 10;
2021ff0cc061SDimitry Andric 
2022ff0cc061SDimitry Andric   // Record values we are going to delete from this statepoint live set.
2023ff0cc061SDimitry Andric   // We can not di this in following loop due to iterator invalidation.
2024ff0cc061SDimitry Andric   SmallVector<Value *, 32> LiveValuesToBeDeleted;
2025ff0cc061SDimitry Andric 
20267d523365SDimitry Andric   for (Value *LiveValue: Info.LiveSet) {
2027ff0cc061SDimitry Andric     // For each live pointer find it's defining chain
2028ff0cc061SDimitry Andric     SmallVector<Instruction *, 3> ChainToBase;
20297d523365SDimitry Andric     assert(Info.PointerToBase.count(LiveValue));
2030d88c1a5aSDimitry Andric     Value *RootOfChain =
2031ff0cc061SDimitry Andric       findRematerializableChainToBasePointer(ChainToBase,
2032d88c1a5aSDimitry Andric                                              LiveValue);
2033d88c1a5aSDimitry Andric 
2034ff0cc061SDimitry Andric     // Nothing to do, or chain is too long
2035d88c1a5aSDimitry Andric     if ( ChainToBase.size() == 0 ||
2036ff0cc061SDimitry Andric         ChainToBase.size() > ChainLengthThreshold)
2037ff0cc061SDimitry Andric       continue;
2038ff0cc061SDimitry Andric 
2039d88c1a5aSDimitry Andric     // Handle the scenario where the RootOfChain is not equal to the
2040d88c1a5aSDimitry Andric     // Base Value, but they are essentially the same phi values.
2041d88c1a5aSDimitry Andric     if (RootOfChain != Info.PointerToBase[LiveValue]) {
2042d88c1a5aSDimitry Andric       PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
2043d88c1a5aSDimitry Andric       PHINode *AlternateRootPhi = dyn_cast<PHINode>(Info.PointerToBase[LiveValue]);
2044d88c1a5aSDimitry Andric       if (!OrigRootPhi || !AlternateRootPhi)
2045d88c1a5aSDimitry Andric         continue;
2046d88c1a5aSDimitry Andric       // PHI nodes that have the same incoming values, and belonging to the same
2047d88c1a5aSDimitry Andric       // basic blocks are essentially the same SSA value.  When the original phi
2048d88c1a5aSDimitry Andric       // has incoming values with different base pointers, the original phi is
2049d88c1a5aSDimitry Andric       // marked as conflict, and an additional `AlternateRootPhi` with the same
2050d88c1a5aSDimitry Andric       // incoming values get generated by the findBasePointer function. We need
2051d88c1a5aSDimitry Andric       // to identify the newly generated AlternateRootPhi (.base version of phi)
2052d88c1a5aSDimitry Andric       // and RootOfChain (the original phi node itself) are the same, so that we
2053d88c1a5aSDimitry Andric       // can rematerialize the gep and casts. This is a workaround for the
2054a580b014SDimitry Andric       // deficiency in the findBasePointer algorithm.
2055d88c1a5aSDimitry Andric       if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
2056d88c1a5aSDimitry Andric         continue;
2057d88c1a5aSDimitry Andric       // Now that the phi nodes are proved to be the same, assert that
2058d88c1a5aSDimitry Andric       // findBasePointer's newly generated AlternateRootPhi is present in the
2059d88c1a5aSDimitry Andric       // liveset of the call.
2060d88c1a5aSDimitry Andric       assert(Info.LiveSet.count(AlternateRootPhi));
2061d88c1a5aSDimitry Andric     }
2062ff0cc061SDimitry Andric     // Compute cost of this chain
2063ff0cc061SDimitry Andric     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2064ff0cc061SDimitry Andric     // TODO: We can also account for cases when we will be able to remove some
2065ff0cc061SDimitry Andric     //       of the rematerialized values by later optimization passes. I.e if
2066ff0cc061SDimitry Andric     //       we rematerialized several intersecting chains. Or if original values
2067ff0cc061SDimitry Andric     //       don't have any uses besides this statepoint.
2068ff0cc061SDimitry Andric 
2069ff0cc061SDimitry Andric     // For invokes we need to rematerialize each chain twice - for normal and
2070ff0cc061SDimitry Andric     // for unwind basic blocks. Model this by multiplying cost by two.
2071ff0cc061SDimitry Andric     if (CS.isInvoke()) {
2072ff0cc061SDimitry Andric       Cost *= 2;
2073ff0cc061SDimitry Andric     }
2074ff0cc061SDimitry Andric     // If it's too expensive - skip it
2075ff0cc061SDimitry Andric     if (Cost >= RematerializationThreshold)
2076ff0cc061SDimitry Andric       continue;
2077ff0cc061SDimitry Andric 
2078ff0cc061SDimitry Andric     // Remove value from the live set
2079ff0cc061SDimitry Andric     LiveValuesToBeDeleted.push_back(LiveValue);
2080ff0cc061SDimitry Andric 
2081ff0cc061SDimitry Andric     // Clone instructions and record them inside "Info" structure
2082ff0cc061SDimitry Andric 
2083ff0cc061SDimitry Andric     // Walk backwards to visit top-most instructions first
2084ff0cc061SDimitry Andric     std::reverse(ChainToBase.begin(), ChainToBase.end());
2085ff0cc061SDimitry Andric 
2086ff0cc061SDimitry Andric     // Utility function which clones all instructions from "ChainToBase"
2087ff0cc061SDimitry Andric     // and inserts them before "InsertBefore". Returns rematerialized value
2088ff0cc061SDimitry Andric     // which should be used after statepoint.
2089d88c1a5aSDimitry Andric     auto rematerializeChain = [&ChainToBase](
2090d88c1a5aSDimitry Andric         Instruction *InsertBefore, Value *RootOfChain, Value *AlternateLiveBase) {
2091ff0cc061SDimitry Andric       Instruction *LastClonedValue = nullptr;
2092ff0cc061SDimitry Andric       Instruction *LastValue = nullptr;
2093ff0cc061SDimitry Andric       for (Instruction *Instr: ChainToBase) {
2094c4394386SDimitry Andric         // Only GEP's and casts are supported as we need to be careful to not
2095ff0cc061SDimitry Andric         // introduce any new uses of pointers not in the liveset.
2096ff0cc061SDimitry Andric         // Note that it's fine to introduce new uses of pointers which were
2097ff0cc061SDimitry Andric         // otherwise not used after this statepoint.
2098ff0cc061SDimitry Andric         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2099ff0cc061SDimitry Andric 
2100ff0cc061SDimitry Andric         Instruction *ClonedValue = Instr->clone();
2101ff0cc061SDimitry Andric         ClonedValue->insertBefore(InsertBefore);
2102ff0cc061SDimitry Andric         ClonedValue->setName(Instr->getName() + ".remat");
2103ff0cc061SDimitry Andric 
2104ff0cc061SDimitry Andric         // If it is not first instruction in the chain then it uses previously
2105ff0cc061SDimitry Andric         // cloned value. We should update it to use cloned value.
2106ff0cc061SDimitry Andric         if (LastClonedValue) {
2107ff0cc061SDimitry Andric           assert(LastValue);
2108ff0cc061SDimitry Andric           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2109ff0cc061SDimitry Andric #ifndef NDEBUG
2110d88c1a5aSDimitry Andric           for (auto OpValue : ClonedValue->operand_values()) {
2111ff0cc061SDimitry Andric             // Assert that cloned instruction does not use any instructions from
2112ff0cc061SDimitry Andric             // this chain other than LastClonedValue
2113d88c1a5aSDimitry Andric             assert(!is_contained(ChainToBase, OpValue) &&
2114ff0cc061SDimitry Andric                    "incorrect use in rematerialization chain");
2115d88c1a5aSDimitry Andric             // Assert that the cloned instruction does not use the RootOfChain
2116d88c1a5aSDimitry Andric             // or the AlternateLiveBase.
2117d88c1a5aSDimitry Andric             assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
2118ff0cc061SDimitry Andric           }
2119ff0cc061SDimitry Andric #endif
2120d88c1a5aSDimitry Andric         } else {
2121d88c1a5aSDimitry Andric           // For the first instruction, replace the use of unrelocated base i.e.
2122d88c1a5aSDimitry Andric           // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
2123d88c1a5aSDimitry Andric           // live set. They have been proved to be the same PHI nodes.  Note
2124d88c1a5aSDimitry Andric           // that the *only* use of the RootOfChain in the ChainToBase list is
2125d88c1a5aSDimitry Andric           // the first Value in the list.
2126d88c1a5aSDimitry Andric           if (RootOfChain != AlternateLiveBase)
2127d88c1a5aSDimitry Andric             ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
2128ff0cc061SDimitry Andric         }
2129ff0cc061SDimitry Andric 
2130ff0cc061SDimitry Andric         LastClonedValue = ClonedValue;
2131ff0cc061SDimitry Andric         LastValue = Instr;
2132ff0cc061SDimitry Andric       }
2133ff0cc061SDimitry Andric       assert(LastClonedValue);
2134ff0cc061SDimitry Andric       return LastClonedValue;
2135ff0cc061SDimitry Andric     };
2136ff0cc061SDimitry Andric 
2137ff0cc061SDimitry Andric     // Different cases for calls and invokes. For invokes we need to clone
2138ff0cc061SDimitry Andric     // instructions both on normal and unwind path.
2139ff0cc061SDimitry Andric     if (CS.isCall()) {
2140ff0cc061SDimitry Andric       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2141ff0cc061SDimitry Andric       assert(InsertBefore);
2142d88c1a5aSDimitry Andric       Instruction *RematerializedValue = rematerializeChain(
2143d88c1a5aSDimitry Andric           InsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2144ff0cc061SDimitry Andric       Info.RematerializedValues[RematerializedValue] = LiveValue;
2145ff0cc061SDimitry Andric     } else {
2146ff0cc061SDimitry Andric       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2147ff0cc061SDimitry Andric 
2148ff0cc061SDimitry Andric       Instruction *NormalInsertBefore =
21497d523365SDimitry Andric           &*Invoke->getNormalDest()->getFirstInsertionPt();
2150ff0cc061SDimitry Andric       Instruction *UnwindInsertBefore =
21517d523365SDimitry Andric           &*Invoke->getUnwindDest()->getFirstInsertionPt();
2152ff0cc061SDimitry Andric 
2153d88c1a5aSDimitry Andric       Instruction *NormalRematerializedValue = rematerializeChain(
2154d88c1a5aSDimitry Andric           NormalInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2155d88c1a5aSDimitry Andric       Instruction *UnwindRematerializedValue = rematerializeChain(
2156d88c1a5aSDimitry Andric           UnwindInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2157ff0cc061SDimitry Andric 
2158ff0cc061SDimitry Andric       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2159ff0cc061SDimitry Andric       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2160ff0cc061SDimitry Andric     }
2161ff0cc061SDimitry Andric   }
2162ff0cc061SDimitry Andric 
2163ff0cc061SDimitry Andric   // Remove rematerializaed values from the live set
2164ff0cc061SDimitry Andric   for (auto LiveValue: LiveValuesToBeDeleted) {
21653ca95b02SDimitry Andric     Info.LiveSet.remove(LiveValue);
2166ff0cc061SDimitry Andric   }
2167ff0cc061SDimitry Andric }
2168ff0cc061SDimitry Andric 
21697d523365SDimitry Andric static bool insertParsePoints(Function &F, DominatorTree &DT,
21707d523365SDimitry Andric                               TargetTransformInfo &TTI,
21717d523365SDimitry Andric                               SmallVectorImpl<CallSite> &ToUpdate) {
2172ff0cc061SDimitry Andric #ifndef NDEBUG
2173ff0cc061SDimitry Andric   // sanity check the input
21747d523365SDimitry Andric   std::set<CallSite> Uniqued;
21757d523365SDimitry Andric   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
21767d523365SDimitry Andric   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2177ff0cc061SDimitry Andric 
21783ca95b02SDimitry Andric   for (CallSite CS : ToUpdate)
21793ca95b02SDimitry Andric     assert(CS.getInstruction()->getFunction() == &F);
2180ff0cc061SDimitry Andric #endif
2181ff0cc061SDimitry Andric 
2182ff0cc061SDimitry Andric   // When inserting gc.relocates for invokes, we need to be able to insert at
2183ff0cc061SDimitry Andric   // the top of the successor blocks.  See the comment on
2184ff0cc061SDimitry Andric   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2185ff0cc061SDimitry Andric   // may restructure the CFG.
21867d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2187ff0cc061SDimitry Andric     if (!CS.isInvoke())
2188ff0cc061SDimitry Andric       continue;
21897d523365SDimitry Andric     auto *II = cast<InvokeInst>(CS.getInstruction());
21907d523365SDimitry Andric     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
21917d523365SDimitry Andric     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2192ff0cc061SDimitry Andric   }
2193ff0cc061SDimitry Andric 
2194ff0cc061SDimitry Andric   // A list of dummy calls added to the IR to keep various values obviously
2195ff0cc061SDimitry Andric   // live in the IR.  We'll remove all of these when done.
21967d523365SDimitry Andric   SmallVector<CallInst *, 64> Holders;
2197ff0cc061SDimitry Andric 
21986d97bb29SDimitry Andric   // Insert a dummy call with all of the deopt operands we'll need for the
21996d97bb29SDimitry Andric   // actual safepoint insertion as arguments.  This ensures reference operands
22006d97bb29SDimitry Andric   // in the deopt argument list are considered live through the safepoint (and
2201ff0cc061SDimitry Andric   // thus makes sure they get relocated.)
22027d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2203ff0cc061SDimitry Andric     SmallVector<Value *, 64> DeoptValues;
22047d523365SDimitry Andric 
22053ca95b02SDimitry Andric     for (Value *Arg : GetDeoptBundleOperands(CS)) {
2206ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2207ff0cc061SDimitry Andric              "support for FCA unimplemented");
2208ff0cc061SDimitry Andric       if (isHandledGCPointerType(Arg->getType()))
2209ff0cc061SDimitry Andric         DeoptValues.push_back(Arg);
2210ff0cc061SDimitry Andric     }
22117d523365SDimitry Andric 
22127d523365SDimitry Andric     insertUseHolderAfter(CS, DeoptValues, Holders);
2213ff0cc061SDimitry Andric   }
2214ff0cc061SDimitry Andric 
22157d523365SDimitry Andric   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2216ff0cc061SDimitry Andric 
22177d523365SDimitry Andric   // A) Identify all gc pointers which are statically live at the given call
2218ff0cc061SDimitry Andric   // site.
22197d523365SDimitry Andric   findLiveReferences(F, DT, ToUpdate, Records);
2220ff0cc061SDimitry Andric 
2221ff0cc061SDimitry Andric   // B) Find the base pointers for each live pointer
2222ff0cc061SDimitry Andric   /* scope for caching */ {
2223ff0cc061SDimitry Andric     // Cache the 'defining value' relation used in the computation and
2224ff0cc061SDimitry Andric     // insertion of base phis and selects.  This ensures that we don't insert
2225ff0cc061SDimitry Andric     // large numbers of duplicate base_phis.
2226ff0cc061SDimitry Andric     DefiningValueMapTy DVCache;
2227ff0cc061SDimitry Andric 
22287d523365SDimitry Andric     for (size_t i = 0; i < Records.size(); i++) {
22297d523365SDimitry Andric       PartiallyConstructedSafepointRecord &info = Records[i];
22307d523365SDimitry Andric       findBasePointers(DT, DVCache, ToUpdate[i], info);
2231ff0cc061SDimitry Andric     }
2232ff0cc061SDimitry Andric   } // end of cache scope
2233ff0cc061SDimitry Andric 
2234ff0cc061SDimitry Andric   // The base phi insertion logic (for any safepoint) may have inserted new
2235ff0cc061SDimitry Andric   // instructions which are now live at some safepoint.  The simplest such
2236ff0cc061SDimitry Andric   // example is:
2237ff0cc061SDimitry Andric   // loop:
2238ff0cc061SDimitry Andric   //   phi a  <-- will be a new base_phi here
2239ff0cc061SDimitry Andric   //   safepoint 1 <-- that needs to be live here
2240ff0cc061SDimitry Andric   //   gep a + 1
2241ff0cc061SDimitry Andric   //   safepoint 2
2242ff0cc061SDimitry Andric   //   br loop
2243ff0cc061SDimitry Andric   // We insert some dummy calls after each safepoint to definitely hold live
2244ff0cc061SDimitry Andric   // the base pointers which were identified for that safepoint.  We'll then
2245ff0cc061SDimitry Andric   // ask liveness for _every_ base inserted to see what is now live.  Then we
2246ff0cc061SDimitry Andric   // remove the dummy calls.
22477d523365SDimitry Andric   Holders.reserve(Holders.size() + Records.size());
22487d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
22497d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
2250ff0cc061SDimitry Andric 
2251ff0cc061SDimitry Andric     SmallVector<Value *, 128> Bases;
22527d523365SDimitry Andric     for (auto Pair : Info.PointerToBase)
2253ff0cc061SDimitry Andric       Bases.push_back(Pair.second);
22547d523365SDimitry Andric 
22557d523365SDimitry Andric     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2256ff0cc061SDimitry Andric   }
2257ff0cc061SDimitry Andric 
2258ff0cc061SDimitry Andric   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2259ff0cc061SDimitry Andric   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2260ff0cc061SDimitry Andric   // not the key issue.
22617d523365SDimitry Andric   recomputeLiveInValues(F, DT, ToUpdate, Records);
2262ff0cc061SDimitry Andric 
2263ff0cc061SDimitry Andric   if (PrintBasePointers) {
22647d523365SDimitry Andric     for (auto &Info : Records) {
2265ff0cc061SDimitry Andric       errs() << "Base Pairs: (w/Relocation)\n";
22667d523365SDimitry Andric       for (auto Pair : Info.PointerToBase) {
22677d523365SDimitry Andric         errs() << " derived ";
22687d523365SDimitry Andric         Pair.first->printAsOperand(errs(), false);
22697d523365SDimitry Andric         errs() << " base ";
22707d523365SDimitry Andric         Pair.second->printAsOperand(errs(), false);
22717d523365SDimitry Andric         errs() << "\n";
2272ff0cc061SDimitry Andric       }
2273ff0cc061SDimitry Andric     }
2274ff0cc061SDimitry Andric   }
22757d523365SDimitry Andric 
22767d523365SDimitry Andric   // It is possible that non-constant live variables have a constant base.  For
22777d523365SDimitry Andric   // example, a GEP with a variable offset from a global.  In this case we can
22787d523365SDimitry Andric   // remove it from the liveset.  We already don't add constants to the liveset
22797d523365SDimitry Andric   // because we assume they won't move at runtime and the GC doesn't need to be
22807d523365SDimitry Andric   // informed about them.  The same reasoning applies if the base is constant.
22817d523365SDimitry Andric   // Note that the relocation placement code relies on this filtering for
22827d523365SDimitry Andric   // correctness as it expects the base to be in the liveset, which isn't true
22837d523365SDimitry Andric   // if the base is constant.
22847d523365SDimitry Andric   for (auto &Info : Records)
22857d523365SDimitry Andric     for (auto &BasePair : Info.PointerToBase)
22867d523365SDimitry Andric       if (isa<Constant>(BasePair.second))
22873ca95b02SDimitry Andric         Info.LiveSet.remove(BasePair.first);
22887d523365SDimitry Andric 
22897d523365SDimitry Andric   for (CallInst *CI : Holders)
22907d523365SDimitry Andric     CI->eraseFromParent();
22917d523365SDimitry Andric 
22927d523365SDimitry Andric   Holders.clear();
2293ff0cc061SDimitry Andric 
2294ff0cc061SDimitry Andric   // In order to reduce live set of statepoint we might choose to rematerialize
22957d523365SDimitry Andric   // some values instead of relocating them. This is purely an optimization and
2296ff0cc061SDimitry Andric   // does not influence correctness.
22977d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++)
22987d523365SDimitry Andric     rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
2299ff0cc061SDimitry Andric 
23007d523365SDimitry Andric   // We need this to safely RAUW and delete call or invoke return values that
23017d523365SDimitry Andric   // may themselves be live over a statepoint.  For details, please see usage in
23027d523365SDimitry Andric   // makeStatepointExplicitImpl.
23037d523365SDimitry Andric   std::vector<DeferredReplacement> Replacements;
2304ff0cc061SDimitry Andric 
2305ff0cc061SDimitry Andric   // Now run through and replace the existing statepoints with new ones with
2306ff0cc061SDimitry Andric   // the live variables listed.  We do not yet update uses of the values being
2307ff0cc061SDimitry Andric   // relocated. We have references to live variables that need to
2308ff0cc061SDimitry Andric   // survive to the last iteration of this loop.  (By construction, the
2309ff0cc061SDimitry Andric   // previous statepoint can not be a live variable, thus we can and remove
2310ff0cc061SDimitry Andric   // the old statepoint calls as we go.)
23117d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++)
23127d523365SDimitry Andric     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
23137d523365SDimitry Andric 
23147d523365SDimitry Andric   ToUpdate.clear(); // prevent accident use of invalid CallSites
23157d523365SDimitry Andric 
23167d523365SDimitry Andric   for (auto &PR : Replacements)
23177d523365SDimitry Andric     PR.doReplacement();
23187d523365SDimitry Andric 
23197d523365SDimitry Andric   Replacements.clear();
23207d523365SDimitry Andric 
23217d523365SDimitry Andric   for (auto &Info : Records) {
23227d523365SDimitry Andric     // These live sets may contain state Value pointers, since we replaced calls
23237d523365SDimitry Andric     // with operand bundles with calls wrapped in gc.statepoint, and some of
23247d523365SDimitry Andric     // those calls may have been def'ing live gc pointers.  Clear these out to
23257d523365SDimitry Andric     // avoid accidentally using them.
23267d523365SDimitry Andric     //
23277d523365SDimitry Andric     // TODO: We should create a separate data structure that does not contain
23287d523365SDimitry Andric     // these live sets, and migrate to using that data structure from this point
23297d523365SDimitry Andric     // onward.
23307d523365SDimitry Andric     Info.LiveSet.clear();
23317d523365SDimitry Andric     Info.PointerToBase.clear();
2332ff0cc061SDimitry Andric   }
2333ff0cc061SDimitry Andric 
2334ff0cc061SDimitry Andric   // Do all the fixups of the original live variables to their relocated selves
23357d523365SDimitry Andric   SmallVector<Value *, 128> Live;
23367d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
23377d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
23387d523365SDimitry Andric 
2339ff0cc061SDimitry Andric     // We can't simply save the live set from the original insertion.  One of
2340ff0cc061SDimitry Andric     // the live values might be the result of a call which needs a safepoint.
2341ff0cc061SDimitry Andric     // That Value* no longer exists and we need to use the new gc_result.
2342ff0cc061SDimitry Andric     // Thankfully, the live set is embedded in the statepoint (and updated), so
2343ff0cc061SDimitry Andric     // we just grab that.
23447d523365SDimitry Andric     Statepoint Statepoint(Info.StatepointToken);
23457d523365SDimitry Andric     Live.insert(Live.end(), Statepoint.gc_args_begin(),
23467d523365SDimitry Andric                 Statepoint.gc_args_end());
2347ff0cc061SDimitry Andric #ifndef NDEBUG
2348ff0cc061SDimitry Andric     // Do some basic sanity checks on our liveness results before performing
2349ff0cc061SDimitry Andric     // relocation.  Relocation can and will turn mistakes in liveness results
2350ff0cc061SDimitry Andric     // into non-sensical code which is must harder to debug.
2351ff0cc061SDimitry Andric     // TODO: It would be nice to test consistency as well
23527d523365SDimitry Andric     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2353ff0cc061SDimitry Andric            "statepoint must be reachable or liveness is meaningless");
23547d523365SDimitry Andric     for (Value *V : Statepoint.gc_args()) {
2355ff0cc061SDimitry Andric       if (!isa<Instruction>(V))
2356ff0cc061SDimitry Andric         // Non-instruction values trivial dominate all possible uses
2357ff0cc061SDimitry Andric         continue;
23587d523365SDimitry Andric       auto *LiveInst = cast<Instruction>(V);
2359ff0cc061SDimitry Andric       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2360ff0cc061SDimitry Andric              "unreachable values should never be live");
23617d523365SDimitry Andric       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2362ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2363ff0cc061SDimitry Andric     }
2364ff0cc061SDimitry Andric #endif
2365ff0cc061SDimitry Andric   }
23667d523365SDimitry Andric   unique_unsorted(Live);
2367ff0cc061SDimitry Andric 
2368ff0cc061SDimitry Andric #ifndef NDEBUG
2369ff0cc061SDimitry Andric   // sanity check
23707d523365SDimitry Andric   for (auto *Ptr : Live)
2371444ed5c5SDimitry Andric     assert(isHandledGCPointerType(Ptr->getType()) &&
2372444ed5c5SDimitry Andric            "must be a gc pointer type");
2373ff0cc061SDimitry Andric #endif
2374ff0cc061SDimitry Andric 
23757d523365SDimitry Andric   relocationViaAlloca(F, DT, Live, Records);
23767d523365SDimitry Andric   return !Records.empty();
2377ff0cc061SDimitry Andric }
2378ff0cc061SDimitry Andric 
237997bc6c73SDimitry Andric // Handles both return values and arguments for Functions and CallSites.
238097bc6c73SDimitry Andric template <typename AttrHolder>
23817d523365SDimitry Andric static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
238297bc6c73SDimitry Andric                                       unsigned Index) {
238397bc6c73SDimitry Andric   AttrBuilder R;
238497bc6c73SDimitry Andric   if (AH.getDereferenceableBytes(Index))
238597bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
238697bc6c73SDimitry Andric                                   AH.getDereferenceableBytes(Index)));
238797bc6c73SDimitry Andric   if (AH.getDereferenceableOrNullBytes(Index))
238897bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
238997bc6c73SDimitry Andric                                   AH.getDereferenceableOrNullBytes(Index)));
2390f37b6182SDimitry Andric   if (AH.getAttributes().hasAttribute(Index, Attribute::NoAlias))
23917d523365SDimitry Andric     R.addAttribute(Attribute::NoAlias);
239297bc6c73SDimitry Andric 
239397bc6c73SDimitry Andric   if (!R.empty())
2394f37b6182SDimitry Andric     AH.setAttributes(AH.getAttributes().removeAttributes(Ctx, Index, R));
239597bc6c73SDimitry Andric }
239697bc6c73SDimitry Andric 
23972cab237bSDimitry Andric static void stripNonValidAttributesFromPrototype(Function &F) {
239897bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
239997bc6c73SDimitry Andric 
240097bc6c73SDimitry Andric   for (Argument &A : F.args())
240197bc6c73SDimitry Andric     if (isa<PointerType>(A.getType()))
2402f37b6182SDimitry Andric       RemoveNonValidAttrAtIndex(Ctx, F,
2403f37b6182SDimitry Andric                                 A.getArgNo() + AttributeList::FirstArgIndex);
240497bc6c73SDimitry Andric 
240597bc6c73SDimitry Andric   if (isa<PointerType>(F.getReturnType()))
24067a7e6055SDimitry Andric     RemoveNonValidAttrAtIndex(Ctx, F, AttributeList::ReturnIndex);
240797bc6c73SDimitry Andric }
240897bc6c73SDimitry Andric 
24092cab237bSDimitry Andric /// Certain metadata on instructions are invalid after running RS4GC.
24102cab237bSDimitry Andric /// Optimizations that run after RS4GC can incorrectly use this metadata to
24112cab237bSDimitry Andric /// optimize functions. We drop such metadata on the instruction.
24122cab237bSDimitry Andric static void stripInvalidMetadataFromInstruction(Instruction &I) {
241324d58133SDimitry Andric   if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
241424d58133SDimitry Andric     return;
241524d58133SDimitry Andric   // These are the attributes that are still valid on loads and stores after
241624d58133SDimitry Andric   // RS4GC.
241724d58133SDimitry Andric   // The metadata implying dereferenceability and noalias are (conservatively)
241824d58133SDimitry Andric   // dropped.  This is because semantically, after RewriteStatepointsForGC runs,
241924d58133SDimitry Andric   // all calls to gc.statepoint "free" the entire heap. Also, gc.statepoint can
242024d58133SDimitry Andric   // touch the entire heap including noalias objects. Note: The reasoning is
242124d58133SDimitry Andric   // same as stripping the dereferenceability and noalias attributes that are
242224d58133SDimitry Andric   // analogous to the metadata counterparts.
242324d58133SDimitry Andric   // We also drop the invariant.load metadata on the load because that metadata
242424d58133SDimitry Andric   // implies the address operand to the load points to memory that is never
242524d58133SDimitry Andric   // changed once it became dereferenceable. This is no longer true after RS4GC.
242624d58133SDimitry Andric   // Similar reasoning applies to invariant.group metadata, which applies to
242724d58133SDimitry Andric   // loads within a group.
242824d58133SDimitry Andric   unsigned ValidMetadataAfterRS4GC[] = {LLVMContext::MD_tbaa,
242924d58133SDimitry Andric                          LLVMContext::MD_range,
243024d58133SDimitry Andric                          LLVMContext::MD_alias_scope,
243124d58133SDimitry Andric                          LLVMContext::MD_nontemporal,
243224d58133SDimitry Andric                          LLVMContext::MD_nonnull,
243324d58133SDimitry Andric                          LLVMContext::MD_align,
243424d58133SDimitry Andric                          LLVMContext::MD_type};
243524d58133SDimitry Andric 
243624d58133SDimitry Andric   // Drops all metadata on the instruction other than ValidMetadataAfterRS4GC.
243724d58133SDimitry Andric   I.dropUnknownNonDebugMetadata(ValidMetadataAfterRS4GC);
243824d58133SDimitry Andric }
243924d58133SDimitry Andric 
24402cab237bSDimitry Andric static void stripNonValidDataFromBody(Function &F) {
244197bc6c73SDimitry Andric   if (F.empty())
244297bc6c73SDimitry Andric     return;
244397bc6c73SDimitry Andric 
244497bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
244597bc6c73SDimitry Andric   MDBuilder Builder(Ctx);
244697bc6c73SDimitry Andric 
24472cab237bSDimitry Andric   // Set of invariantstart instructions that we need to remove.
24482cab237bSDimitry Andric   // Use this to avoid invalidating the instruction iterator.
24492cab237bSDimitry Andric   SmallVector<IntrinsicInst*, 12> InvariantStartInstructions;
245024d58133SDimitry Andric 
24517d523365SDimitry Andric   for (Instruction &I : instructions(F)) {
24522cab237bSDimitry Andric     // invariant.start on memory location implies that the referenced memory
24532cab237bSDimitry Andric     // location is constant and unchanging. This is no longer true after
24542cab237bSDimitry Andric     // RewriteStatepointsForGC runs because there can be calls to gc.statepoint
24552cab237bSDimitry Andric     // which frees the entire heap and the presence of invariant.start allows
24562cab237bSDimitry Andric     // the optimizer to sink the load of a memory location past a statepoint,
24572cab237bSDimitry Andric     // which is incorrect.
24582cab237bSDimitry Andric     if (auto *II = dyn_cast<IntrinsicInst>(&I))
24592cab237bSDimitry Andric       if (II->getIntrinsicID() == Intrinsic::invariant_start) {
24602cab237bSDimitry Andric         InvariantStartInstructions.push_back(II);
24612cab237bSDimitry Andric         continue;
24622cab237bSDimitry Andric       }
24632cab237bSDimitry Andric 
246497bc6c73SDimitry Andric     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
246597bc6c73SDimitry Andric       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
246697bc6c73SDimitry Andric       bool IsImmutableTBAA =
246797bc6c73SDimitry Andric           MD->getNumOperands() == 4 &&
246897bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
246997bc6c73SDimitry Andric 
247097bc6c73SDimitry Andric       if (!IsImmutableTBAA)
247197bc6c73SDimitry Andric         continue; // no work to do, MD_tbaa is already marked mutable
247297bc6c73SDimitry Andric 
247397bc6c73SDimitry Andric       MDNode *Base = cast<MDNode>(MD->getOperand(0));
247497bc6c73SDimitry Andric       MDNode *Access = cast<MDNode>(MD->getOperand(1));
247597bc6c73SDimitry Andric       uint64_t Offset =
247697bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
247797bc6c73SDimitry Andric 
247897bc6c73SDimitry Andric       MDNode *MutableTBAA =
247997bc6c73SDimitry Andric           Builder.createTBAAStructTagNode(Base, Access, Offset);
248097bc6c73SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
248197bc6c73SDimitry Andric     }
248297bc6c73SDimitry Andric 
248324d58133SDimitry Andric     stripInvalidMetadataFromInstruction(I);
248424d58133SDimitry Andric 
248597bc6c73SDimitry Andric     if (CallSite CS = CallSite(&I)) {
248697bc6c73SDimitry Andric       for (int i = 0, e = CS.arg_size(); i != e; i++)
248797bc6c73SDimitry Andric         if (isa<PointerType>(CS.getArgument(i)->getType()))
2488f37b6182SDimitry Andric           RemoveNonValidAttrAtIndex(Ctx, CS, i + AttributeList::FirstArgIndex);
248997bc6c73SDimitry Andric       if (isa<PointerType>(CS.getType()))
24907a7e6055SDimitry Andric         RemoveNonValidAttrAtIndex(Ctx, CS, AttributeList::ReturnIndex);
249197bc6c73SDimitry Andric     }
249297bc6c73SDimitry Andric   }
24932cab237bSDimitry Andric 
24942cab237bSDimitry Andric   // Delete the invariant.start instructions and RAUW undef.
24952cab237bSDimitry Andric   for (auto *II : InvariantStartInstructions) {
24962cab237bSDimitry Andric     II->replaceAllUsesWith(UndefValue::get(II->getType()));
24972cab237bSDimitry Andric     II->eraseFromParent();
24982cab237bSDimitry Andric   }
249997bc6c73SDimitry Andric }
250097bc6c73SDimitry Andric 
2501ff0cc061SDimitry Andric /// Returns true if this function should be rewritten by this pass.  The main
2502ff0cc061SDimitry Andric /// point of this function is as an extension point for custom logic.
2503ff0cc061SDimitry Andric static bool shouldRewriteStatepointsIn(Function &F) {
2504ff0cc061SDimitry Andric   // TODO: This should check the GCStrategy
2505ff0cc061SDimitry Andric   if (F.hasGC()) {
2506444ed5c5SDimitry Andric     const auto &FunctionGCName = F.getGC();
2507ff0cc061SDimitry Andric     const StringRef StatepointExampleName("statepoint-example");
2508ff0cc061SDimitry Andric     const StringRef CoreCLRName("coreclr");
2509ff0cc061SDimitry Andric     return (StatepointExampleName == FunctionGCName) ||
2510ff0cc061SDimitry Andric            (CoreCLRName == FunctionGCName);
2511ff0cc061SDimitry Andric   } else
2512ff0cc061SDimitry Andric     return false;
2513ff0cc061SDimitry Andric }
2514ff0cc061SDimitry Andric 
25152cab237bSDimitry Andric static void stripNonValidData(Module &M) {
251697bc6c73SDimitry Andric #ifndef NDEBUG
25172cab237bSDimitry Andric   assert(llvm::any_of(M, shouldRewriteStatepointsIn) && "precondition!");
251897bc6c73SDimitry Andric #endif
251997bc6c73SDimitry Andric 
252097bc6c73SDimitry Andric   for (Function &F : M)
25217d523365SDimitry Andric     stripNonValidAttributesFromPrototype(F);
252297bc6c73SDimitry Andric 
252397bc6c73SDimitry Andric   for (Function &F : M)
25242cab237bSDimitry Andric     stripNonValidDataFromBody(F);
252597bc6c73SDimitry Andric }
252697bc6c73SDimitry Andric 
25272cab237bSDimitry Andric bool RewriteStatepointsForGC::runOnFunction(Function &F, DominatorTree &DT,
25282cab237bSDimitry Andric                                             TargetTransformInfo &TTI,
25292cab237bSDimitry Andric                                             const TargetLibraryInfo &TLI) {
25302cab237bSDimitry Andric   assert(!F.isDeclaration() && !F.empty() &&
25312cab237bSDimitry Andric          "need function body to rewrite statepoints in");
25322cab237bSDimitry Andric   assert(shouldRewriteStatepointsIn(F) && "mismatch in rewrite decision");
2533ff0cc061SDimitry Andric 
25342cab237bSDimitry Andric   auto NeedsRewrite = [&TLI](Instruction &I) {
25357d523365SDimitry Andric     if (ImmutableCallSite CS = ImmutableCallSite(&I))
25362cab237bSDimitry Andric       return !callsGCLeafFunction(CS, TLI) && !isStatepoint(CS);
25377d523365SDimitry Andric     return false;
25387d523365SDimitry Andric   };
2539ff0cc061SDimitry Andric 
2540ff0cc061SDimitry Andric   // Gather all the statepoints which need rewritten.  Be careful to only
2541ff0cc061SDimitry Andric   // consider those in reachable code since we need to ask dominance queries
2542ff0cc061SDimitry Andric   // when rewriting.  We'll delete the unreachable ones in a moment.
2543ff0cc061SDimitry Andric   SmallVector<CallSite, 64> ParsePointNeeded;
2544ff0cc061SDimitry Andric   bool HasUnreachableStatepoint = false;
25457d523365SDimitry Andric   for (Instruction &I : instructions(F)) {
2546ff0cc061SDimitry Andric     // TODO: only the ones with the flag set!
25477d523365SDimitry Andric     if (NeedsRewrite(I)) {
2548ff0cc061SDimitry Andric       if (DT.isReachableFromEntry(I.getParent()))
2549ff0cc061SDimitry Andric         ParsePointNeeded.push_back(CallSite(&I));
2550ff0cc061SDimitry Andric       else
2551ff0cc061SDimitry Andric         HasUnreachableStatepoint = true;
2552ff0cc061SDimitry Andric     }
2553ff0cc061SDimitry Andric   }
2554ff0cc061SDimitry Andric 
2555ff0cc061SDimitry Andric   bool MadeChange = false;
2556ff0cc061SDimitry Andric 
2557ff0cc061SDimitry Andric   // Delete any unreachable statepoints so that we don't have unrewritten
2558ff0cc061SDimitry Andric   // statepoints surviving this pass.  This makes testing easier and the
2559ff0cc061SDimitry Andric   // resulting IR less confusing to human readers.  Rather than be fancy, we
2560ff0cc061SDimitry Andric   // just reuse a utility function which removes the unreachable blocks.
2561ff0cc061SDimitry Andric   if (HasUnreachableStatepoint)
2562ff0cc061SDimitry Andric     MadeChange |= removeUnreachableBlocks(F);
2563ff0cc061SDimitry Andric 
2564ff0cc061SDimitry Andric   // Return early if no work to do.
2565ff0cc061SDimitry Andric   if (ParsePointNeeded.empty())
2566ff0cc061SDimitry Andric     return MadeChange;
2567ff0cc061SDimitry Andric 
2568ff0cc061SDimitry Andric   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2569ff0cc061SDimitry Andric   // These are created by LCSSA.  They have the effect of increasing the size
2570ff0cc061SDimitry Andric   // of liveness sets for no good reason.  It may be harder to do this post
2571ff0cc061SDimitry Andric   // insertion since relocations and base phis can confuse things.
2572ff0cc061SDimitry Andric   for (BasicBlock &BB : F)
2573ff0cc061SDimitry Andric     if (BB.getUniquePredecessor()) {
2574ff0cc061SDimitry Andric       MadeChange = true;
2575ff0cc061SDimitry Andric       FoldSingleEntryPHINodes(&BB);
2576ff0cc061SDimitry Andric     }
2577ff0cc061SDimitry Andric 
25787d523365SDimitry Andric   // Before we start introducing relocations, we want to tweak the IR a bit to
25797d523365SDimitry Andric   // avoid unfortunate code generation effects.  The main example is that we
25807d523365SDimitry Andric   // want to try to make sure the comparison feeding a branch is after any
25817d523365SDimitry Andric   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
25827d523365SDimitry Andric   // values feeding a branch after relocation.  This is semantically correct,
25837d523365SDimitry Andric   // but results in extra register pressure since both the pre-relocation and
25847d523365SDimitry Andric   // post-relocation copies must be available in registers.  For code without
25857d523365SDimitry Andric   // relocations this is handled elsewhere, but teaching the scheduler to
25867d523365SDimitry Andric   // reverse the transform we're about to do would be slightly complex.
25877d523365SDimitry Andric   // Note: This may extend the live range of the inputs to the icmp and thus
25887d523365SDimitry Andric   // increase the liveset of any statepoint we move over.  This is profitable
25897d523365SDimitry Andric   // as long as all statepoints are in rare blocks.  If we had in-register
25907d523365SDimitry Andric   // lowering for live values this would be a much safer transform.
25917d523365SDimitry Andric   auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
25927d523365SDimitry Andric     if (auto *BI = dyn_cast<BranchInst>(TI))
25937d523365SDimitry Andric       if (BI->isConditional())
25947d523365SDimitry Andric         return dyn_cast<Instruction>(BI->getCondition());
25957d523365SDimitry Andric     // TODO: Extend this to handle switches
25967d523365SDimitry Andric     return nullptr;
25977d523365SDimitry Andric   };
25987d523365SDimitry Andric   for (BasicBlock &BB : F) {
25997d523365SDimitry Andric     TerminatorInst *TI = BB.getTerminator();
26007d523365SDimitry Andric     if (auto *Cond = getConditionInst(TI))
26017d523365SDimitry Andric       // TODO: Handle more than just ICmps here.  We should be able to move
26027d523365SDimitry Andric       // most instructions without side effects or memory access.
26037d523365SDimitry Andric       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
26047d523365SDimitry Andric         MadeChange = true;
26057d523365SDimitry Andric         Cond->moveBefore(TI);
26067d523365SDimitry Andric       }
26077d523365SDimitry Andric   }
26087d523365SDimitry Andric 
26097d523365SDimitry Andric   MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
2610ff0cc061SDimitry Andric   return MadeChange;
2611ff0cc061SDimitry Andric }
2612ff0cc061SDimitry Andric 
2613ff0cc061SDimitry Andric // liveness computation via standard dataflow
2614ff0cc061SDimitry Andric // -------------------------------------------------------------------
2615ff0cc061SDimitry Andric 
2616ff0cc061SDimitry Andric // TODO: Consider using bitvectors for liveness, the set of potentially
2617ff0cc061SDimitry Andric // interesting values should be small and easy to pre-compute.
2618ff0cc061SDimitry Andric 
2619ff0cc061SDimitry Andric /// Compute the live-in set for the location rbegin starting from
2620ff0cc061SDimitry Andric /// the live-out set of the basic block
26213ca95b02SDimitry Andric static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
26223ca95b02SDimitry Andric                                 BasicBlock::reverse_iterator End,
26233ca95b02SDimitry Andric                                 SetVector<Value *> &LiveTmp) {
26243ca95b02SDimitry Andric   for (auto &I : make_range(Begin, End)) {
2625ff0cc061SDimitry Andric     // KILL/Def - Remove this definition from LiveIn
26263ca95b02SDimitry Andric     LiveTmp.remove(&I);
2627ff0cc061SDimitry Andric 
2628ff0cc061SDimitry Andric     // Don't consider *uses* in PHI nodes, we handle their contribution to
2629ff0cc061SDimitry Andric     // predecessor blocks when we seed the LiveOut sets
2630ff0cc061SDimitry Andric     if (isa<PHINode>(I))
2631ff0cc061SDimitry Andric       continue;
2632ff0cc061SDimitry Andric 
2633ff0cc061SDimitry Andric     // USE - Add to the LiveIn set for this instruction
26343ca95b02SDimitry Andric     for (Value *V : I.operands()) {
2635ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2636ff0cc061SDimitry Andric              "support for FCA unimplemented");
2637ff0cc061SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2638ff0cc061SDimitry Andric         // The choice to exclude all things constant here is slightly subtle.
26397d523365SDimitry Andric         // There are two independent reasons:
2640ff0cc061SDimitry Andric         // - We assume that things which are constant (from LLVM's definition)
2641ff0cc061SDimitry Andric         // do not move at runtime.  For example, the address of a global
2642ff0cc061SDimitry Andric         // variable is fixed, even though it's contents may not be.
2643ff0cc061SDimitry Andric         // - Second, we can't disallow arbitrary inttoptr constants even
2644ff0cc061SDimitry Andric         // if the language frontend does.  Optimization passes are free to
2645ff0cc061SDimitry Andric         // locally exploit facts without respect to global reachability.  This
2646ff0cc061SDimitry Andric         // can create sections of code which are dynamically unreachable and
2647ff0cc061SDimitry Andric         // contain just about anything.  (see constants.ll in tests)
2648ff0cc061SDimitry Andric         LiveTmp.insert(V);
2649ff0cc061SDimitry Andric       }
2650ff0cc061SDimitry Andric     }
2651ff0cc061SDimitry Andric   }
2652ff0cc061SDimitry Andric }
2653ff0cc061SDimitry Andric 
26543ca95b02SDimitry Andric static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
2655ff0cc061SDimitry Andric   for (BasicBlock *Succ : successors(BB)) {
26563ca95b02SDimitry Andric     for (auto &I : *Succ) {
26573ca95b02SDimitry Andric       PHINode *PN = dyn_cast<PHINode>(&I);
26583ca95b02SDimitry Andric       if (!PN)
26593ca95b02SDimitry Andric         break;
26603ca95b02SDimitry Andric 
26613ca95b02SDimitry Andric       Value *V = PN->getIncomingValueForBlock(BB);
2662ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2663ff0cc061SDimitry Andric              "support for FCA unimplemented");
26643ca95b02SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V))
2665ff0cc061SDimitry Andric         LiveTmp.insert(V);
2666ff0cc061SDimitry Andric     }
2667ff0cc061SDimitry Andric   }
2668ff0cc061SDimitry Andric }
2669ff0cc061SDimitry Andric 
26703ca95b02SDimitry Andric static SetVector<Value *> computeKillSet(BasicBlock *BB) {
26713ca95b02SDimitry Andric   SetVector<Value *> KillSet;
2672ff0cc061SDimitry Andric   for (Instruction &I : *BB)
2673ff0cc061SDimitry Andric     if (isHandledGCPointerType(I.getType()))
2674ff0cc061SDimitry Andric       KillSet.insert(&I);
2675ff0cc061SDimitry Andric   return KillSet;
2676ff0cc061SDimitry Andric }
2677ff0cc061SDimitry Andric 
2678ff0cc061SDimitry Andric #ifndef NDEBUG
2679ff0cc061SDimitry Andric /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2680ff0cc061SDimitry Andric /// sanity check for the liveness computation.
26813ca95b02SDimitry Andric static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
2682ff0cc061SDimitry Andric                           TerminatorInst *TI, bool TermOkay = false) {
2683ff0cc061SDimitry Andric   for (Value *V : Live) {
2684ff0cc061SDimitry Andric     if (auto *I = dyn_cast<Instruction>(V)) {
2685ff0cc061SDimitry Andric       // The terminator can be a member of the LiveOut set.  LLVM's definition
2686ff0cc061SDimitry Andric       // of instruction dominance states that V does not dominate itself.  As
2687ff0cc061SDimitry Andric       // such, we need to special case this to allow it.
2688ff0cc061SDimitry Andric       if (TermOkay && TI == I)
2689ff0cc061SDimitry Andric         continue;
2690ff0cc061SDimitry Andric       assert(DT.dominates(I, TI) &&
2691ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2692ff0cc061SDimitry Andric     }
2693ff0cc061SDimitry Andric   }
2694ff0cc061SDimitry Andric }
2695ff0cc061SDimitry Andric 
2696ff0cc061SDimitry Andric /// Check that all the liveness sets used during the computation of liveness
2697ff0cc061SDimitry Andric /// obey basic SSA properties.  This is useful for finding cases where we miss
2698ff0cc061SDimitry Andric /// a def.
2699ff0cc061SDimitry Andric static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2700ff0cc061SDimitry Andric                           BasicBlock &BB) {
2701ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2702ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2703ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2704ff0cc061SDimitry Andric }
2705ff0cc061SDimitry Andric #endif
2706ff0cc061SDimitry Andric 
2707ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
2708ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data) {
27093ca95b02SDimitry Andric   SmallSetVector<BasicBlock *, 32> Worklist;
2710ff0cc061SDimitry Andric 
2711ff0cc061SDimitry Andric   // Seed the liveness for each individual block
2712ff0cc061SDimitry Andric   for (BasicBlock &BB : F) {
2713ff0cc061SDimitry Andric     Data.KillSet[&BB] = computeKillSet(&BB);
2714ff0cc061SDimitry Andric     Data.LiveSet[&BB].clear();
2715ff0cc061SDimitry Andric     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2716ff0cc061SDimitry Andric 
2717ff0cc061SDimitry Andric #ifndef NDEBUG
2718ff0cc061SDimitry Andric     for (Value *Kill : Data.KillSet[&BB])
2719ff0cc061SDimitry Andric       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2720ff0cc061SDimitry Andric #endif
2721ff0cc061SDimitry Andric 
27223ca95b02SDimitry Andric     Data.LiveOut[&BB] = SetVector<Value *>();
2723ff0cc061SDimitry Andric     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2724ff0cc061SDimitry Andric     Data.LiveIn[&BB] = Data.LiveSet[&BB];
27253ca95b02SDimitry Andric     Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
27263ca95b02SDimitry Andric     Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
2727ff0cc061SDimitry Andric     if (!Data.LiveIn[&BB].empty())
27283ca95b02SDimitry Andric       Worklist.insert(pred_begin(&BB), pred_end(&BB));
2729ff0cc061SDimitry Andric   }
2730ff0cc061SDimitry Andric 
2731ff0cc061SDimitry Andric   // Propagate that liveness until stable
2732ff0cc061SDimitry Andric   while (!Worklist.empty()) {
27333ca95b02SDimitry Andric     BasicBlock *BB = Worklist.pop_back_val();
2734ff0cc061SDimitry Andric 
27353ca95b02SDimitry Andric     // Compute our new liveout set, then exit early if it hasn't changed despite
27363ca95b02SDimitry Andric     // the contribution of our successor.
27373ca95b02SDimitry Andric     SetVector<Value *> LiveOut = Data.LiveOut[BB];
2738ff0cc061SDimitry Andric     const auto OldLiveOutSize = LiveOut.size();
2739ff0cc061SDimitry Andric     for (BasicBlock *Succ : successors(BB)) {
2740ff0cc061SDimitry Andric       assert(Data.LiveIn.count(Succ));
27413ca95b02SDimitry Andric       LiveOut.set_union(Data.LiveIn[Succ]);
2742ff0cc061SDimitry Andric     }
2743ff0cc061SDimitry Andric     // assert OutLiveOut is a subset of LiveOut
2744ff0cc061SDimitry Andric     if (OldLiveOutSize == LiveOut.size()) {
2745ff0cc061SDimitry Andric       // If the sets are the same size, then we didn't actually add anything
27463ca95b02SDimitry Andric       // when unioning our successors LiveIn.  Thus, the LiveIn of this block
2747ff0cc061SDimitry Andric       // hasn't changed.
2748ff0cc061SDimitry Andric       continue;
2749ff0cc061SDimitry Andric     }
2750ff0cc061SDimitry Andric     Data.LiveOut[BB] = LiveOut;
2751ff0cc061SDimitry Andric 
2752ff0cc061SDimitry Andric     // Apply the effects of this basic block
27533ca95b02SDimitry Andric     SetVector<Value *> LiveTmp = LiveOut;
27543ca95b02SDimitry Andric     LiveTmp.set_union(Data.LiveSet[BB]);
27553ca95b02SDimitry Andric     LiveTmp.set_subtract(Data.KillSet[BB]);
2756ff0cc061SDimitry Andric 
2757ff0cc061SDimitry Andric     assert(Data.LiveIn.count(BB));
27583ca95b02SDimitry Andric     const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
2759ff0cc061SDimitry Andric     // assert: OldLiveIn is a subset of LiveTmp
2760ff0cc061SDimitry Andric     if (OldLiveIn.size() != LiveTmp.size()) {
2761ff0cc061SDimitry Andric       Data.LiveIn[BB] = LiveTmp;
27623ca95b02SDimitry Andric       Worklist.insert(pred_begin(BB), pred_end(BB));
2763ff0cc061SDimitry Andric     }
27643ca95b02SDimitry Andric   } // while (!Worklist.empty())
2765ff0cc061SDimitry Andric 
2766ff0cc061SDimitry Andric #ifndef NDEBUG
27677d523365SDimitry Andric   // Sanity check our output against SSA properties.  This helps catch any
2768ff0cc061SDimitry Andric   // missing kills during the above iteration.
27693ca95b02SDimitry Andric   for (BasicBlock &BB : F)
2770ff0cc061SDimitry Andric     checkBasicSSA(DT, Data, BB);
2771ff0cc061SDimitry Andric #endif
2772ff0cc061SDimitry Andric }
2773ff0cc061SDimitry Andric 
2774ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2775ff0cc061SDimitry Andric                               StatepointLiveSetTy &Out) {
2776ff0cc061SDimitry Andric   BasicBlock *BB = Inst->getParent();
2777ff0cc061SDimitry Andric 
2778ff0cc061SDimitry Andric   // Note: The copy is intentional and required
2779ff0cc061SDimitry Andric   assert(Data.LiveOut.count(BB));
27803ca95b02SDimitry Andric   SetVector<Value *> LiveOut = Data.LiveOut[BB];
2781ff0cc061SDimitry Andric 
2782ff0cc061SDimitry Andric   // We want to handle the statepoint itself oddly.  It's
2783ff0cc061SDimitry Andric   // call result is not live (normal), nor are it's arguments
2784ff0cc061SDimitry Andric   // (unless they're used again later).  This adjustment is
2785ff0cc061SDimitry Andric   // specifically what we need to relocate
2786d88c1a5aSDimitry Andric   computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
2787d88c1a5aSDimitry Andric                       LiveOut);
27883ca95b02SDimitry Andric   LiveOut.remove(Inst);
2789ff0cc061SDimitry Andric   Out.insert(LiveOut.begin(), LiveOut.end());
2790ff0cc061SDimitry Andric }
2791ff0cc061SDimitry Andric 
2792ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
27933ca95b02SDimitry Andric                                   CallSite CS,
2794ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &Info) {
2795ff0cc061SDimitry Andric   Instruction *Inst = CS.getInstruction();
2796ff0cc061SDimitry Andric   StatepointLiveSetTy Updated;
2797ff0cc061SDimitry Andric   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2798ff0cc061SDimitry Andric 
2799ff0cc061SDimitry Andric #ifndef NDEBUG
2800ff0cc061SDimitry Andric   DenseSet<Value *> Bases;
28013ca95b02SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2802ff0cc061SDimitry Andric     Bases.insert(KVPair.second);
2803ff0cc061SDimitry Andric #endif
28043ca95b02SDimitry Andric 
2805ff0cc061SDimitry Andric   // We may have base pointers which are now live that weren't before.  We need
2806ff0cc061SDimitry Andric   // to update the PointerToBase structure to reflect this.
2807ff0cc061SDimitry Andric   for (auto V : Updated)
28083ca95b02SDimitry Andric     if (Info.PointerToBase.insert({V, V}).second) {
28093ca95b02SDimitry Andric       assert(Bases.count(V) && "Can't find base for unexpected live value!");
2810ff0cc061SDimitry Andric       continue;
2811ff0cc061SDimitry Andric     }
2812ff0cc061SDimitry Andric 
2813ff0cc061SDimitry Andric #ifndef NDEBUG
28143ca95b02SDimitry Andric   for (auto V : Updated)
2815ff0cc061SDimitry Andric     assert(Info.PointerToBase.count(V) &&
28163ca95b02SDimitry Andric            "Must be able to find base for live value!");
2817ff0cc061SDimitry Andric #endif
2818ff0cc061SDimitry Andric 
2819ff0cc061SDimitry Andric   // Remove any stale base mappings - this can happen since our liveness is
28203ca95b02SDimitry Andric   // more precise then the one inherent in the base pointer analysis.
2821ff0cc061SDimitry Andric   DenseSet<Value *> ToErase;
2822ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2823ff0cc061SDimitry Andric     if (!Updated.count(KVPair.first))
2824ff0cc061SDimitry Andric       ToErase.insert(KVPair.first);
28253ca95b02SDimitry Andric 
28263ca95b02SDimitry Andric   for (auto *V : ToErase)
2827ff0cc061SDimitry Andric     Info.PointerToBase.erase(V);
2828ff0cc061SDimitry Andric 
2829ff0cc061SDimitry Andric #ifndef NDEBUG
2830ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2831ff0cc061SDimitry Andric     assert(Updated.count(KVPair.first) && "record for non-live value");
2832ff0cc061SDimitry Andric #endif
2833ff0cc061SDimitry Andric 
28347d523365SDimitry Andric   Info.LiveSet = Updated;
2835ff0cc061SDimitry Andric }
2836