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 //
10ff0cc061SDimitry Andric // Rewrite an existing set of gc.statepoints such that they make potential
11ff0cc061SDimitry Andric // relocations performed by the garbage collector explicit in the IR.
12ff0cc061SDimitry Andric //
13ff0cc061SDimitry Andric //===----------------------------------------------------------------------===//
14ff0cc061SDimitry Andric 
15ff0cc061SDimitry Andric #include "llvm/Pass.h"
16ff0cc061SDimitry Andric #include "llvm/Analysis/CFG.h"
17ff0cc061SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
18ff0cc061SDimitry Andric #include "llvm/ADT/SetOperations.h"
19ff0cc061SDimitry Andric #include "llvm/ADT/Statistic.h"
20ff0cc061SDimitry Andric #include "llvm/ADT/DenseSet.h"
21ff0cc061SDimitry Andric #include "llvm/ADT/SetVector.h"
22ff0cc061SDimitry Andric #include "llvm/ADT/StringRef.h"
237d523365SDimitry Andric #include "llvm/ADT/MapVector.h"
24ff0cc061SDimitry Andric #include "llvm/IR/BasicBlock.h"
25ff0cc061SDimitry Andric #include "llvm/IR/CallSite.h"
26ff0cc061SDimitry Andric #include "llvm/IR/Dominators.h"
27ff0cc061SDimitry Andric #include "llvm/IR/Function.h"
28ff0cc061SDimitry Andric #include "llvm/IR/IRBuilder.h"
29ff0cc061SDimitry Andric #include "llvm/IR/InstIterator.h"
30ff0cc061SDimitry Andric #include "llvm/IR/Instructions.h"
31ff0cc061SDimitry Andric #include "llvm/IR/Intrinsics.h"
32ff0cc061SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
33ff0cc061SDimitry Andric #include "llvm/IR/Module.h"
3497bc6c73SDimitry Andric #include "llvm/IR/MDBuilder.h"
35ff0cc061SDimitry Andric #include "llvm/IR/Statepoint.h"
36ff0cc061SDimitry Andric #include "llvm/IR/Value.h"
37ff0cc061SDimitry Andric #include "llvm/IR/Verifier.h"
38ff0cc061SDimitry Andric #include "llvm/Support/Debug.h"
39ff0cc061SDimitry Andric #include "llvm/Support/CommandLine.h"
40ff0cc061SDimitry Andric #include "llvm/Transforms/Scalar.h"
41ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
43ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
44ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
45ff0cc061SDimitry Andric 
46ff0cc061SDimitry Andric #define DEBUG_TYPE "rewrite-statepoints-for-gc"
47ff0cc061SDimitry Andric 
48ff0cc061SDimitry Andric using namespace llvm;
49ff0cc061SDimitry Andric 
50ff0cc061SDimitry Andric // Print the liveset found at the insert location
51ff0cc061SDimitry Andric static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
52ff0cc061SDimitry Andric                                   cl::init(false));
53ff0cc061SDimitry Andric static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
54ff0cc061SDimitry Andric                                       cl::init(false));
55ff0cc061SDimitry Andric // Print out the base pointers for debugging
56ff0cc061SDimitry Andric static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
57ff0cc061SDimitry Andric                                        cl::init(false));
58ff0cc061SDimitry Andric 
59ff0cc061SDimitry Andric // Cost threshold measuring when it is profitable to rematerialize value instead
60ff0cc061SDimitry Andric // of relocating it
61ff0cc061SDimitry Andric static cl::opt<unsigned>
62ff0cc061SDimitry Andric RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
63ff0cc061SDimitry Andric                            cl::init(6));
64ff0cc061SDimitry Andric 
653ca95b02SDimitry Andric #ifdef EXPENSIVE_CHECKS
66ff0cc061SDimitry Andric static bool ClobberNonLive = true;
67ff0cc061SDimitry Andric #else
68ff0cc061SDimitry Andric static bool ClobberNonLive = false;
69ff0cc061SDimitry Andric #endif
70ff0cc061SDimitry Andric static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
71ff0cc061SDimitry Andric                                                   cl::location(ClobberNonLive),
72ff0cc061SDimitry Andric                                                   cl::Hidden);
73ff0cc061SDimitry Andric 
747d523365SDimitry Andric static cl::opt<bool>
757d523365SDimitry Andric     AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
767d523365SDimitry Andric                                    cl::Hidden, cl::init(true));
777d523365SDimitry Andric 
78ff0cc061SDimitry Andric namespace {
7997bc6c73SDimitry Andric struct RewriteStatepointsForGC : public ModulePass {
80ff0cc061SDimitry Andric   static char ID; // Pass identification, replacement for typeid
81ff0cc061SDimitry Andric 
8297bc6c73SDimitry Andric   RewriteStatepointsForGC() : ModulePass(ID) {
83ff0cc061SDimitry Andric     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
84ff0cc061SDimitry Andric   }
8597bc6c73SDimitry Andric   bool runOnFunction(Function &F);
8697bc6c73SDimitry Andric   bool runOnModule(Module &M) override {
8797bc6c73SDimitry Andric     bool Changed = false;
8897bc6c73SDimitry Andric     for (Function &F : M)
8997bc6c73SDimitry Andric       Changed |= runOnFunction(F);
9097bc6c73SDimitry Andric 
9197bc6c73SDimitry Andric     if (Changed) {
927d523365SDimitry Andric       // stripNonValidAttributes asserts that shouldRewriteStatepointsIn
9397bc6c73SDimitry Andric       // returns true for at least one function in the module.  Since at least
9497bc6c73SDimitry Andric       // one function changed, we know that the precondition is satisfied.
957d523365SDimitry Andric       stripNonValidAttributes(M);
9697bc6c73SDimitry Andric     }
9797bc6c73SDimitry Andric 
9897bc6c73SDimitry Andric     return Changed;
9997bc6c73SDimitry Andric   }
100ff0cc061SDimitry Andric 
101ff0cc061SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
102ff0cc061SDimitry Andric     // We add and rewrite a bunch of instructions, but don't really do much
103ff0cc061SDimitry Andric     // else.  We could in theory preserve a lot more analyses here.
104ff0cc061SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
105ff0cc061SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
106ff0cc061SDimitry Andric   }
10797bc6c73SDimitry Andric 
10897bc6c73SDimitry Andric   /// The IR fed into RewriteStatepointsForGC may have had attributes implying
10997bc6c73SDimitry Andric   /// dereferenceability that are no longer valid/correct after
11097bc6c73SDimitry Andric   /// RewriteStatepointsForGC has run.  This is because semantically, after
11197bc6c73SDimitry Andric   /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
1127d523365SDimitry Andric   /// heap.  stripNonValidAttributes (conservatively) restores correctness
11397bc6c73SDimitry Andric   /// by erasing all attributes in the module that externally imply
11497bc6c73SDimitry Andric   /// dereferenceability.
1157d523365SDimitry Andric   /// Similar reasoning also applies to the noalias attributes. gc.statepoint
1167d523365SDimitry Andric   /// can touch the entire heap including noalias objects.
1177d523365SDimitry Andric   void stripNonValidAttributes(Module &M);
11897bc6c73SDimitry Andric 
1197d523365SDimitry Andric   // Helpers for stripNonValidAttributes
1207d523365SDimitry Andric   void stripNonValidAttributesFromBody(Function &F);
1217d523365SDimitry Andric   void stripNonValidAttributesFromPrototype(Function &F);
122ff0cc061SDimitry Andric };
123ff0cc061SDimitry Andric } // namespace
124ff0cc061SDimitry Andric 
125ff0cc061SDimitry Andric char RewriteStatepointsForGC::ID = 0;
126ff0cc061SDimitry Andric 
12797bc6c73SDimitry Andric ModulePass *llvm::createRewriteStatepointsForGCPass() {
128ff0cc061SDimitry Andric   return new RewriteStatepointsForGC();
129ff0cc061SDimitry Andric }
130ff0cc061SDimitry Andric 
131ff0cc061SDimitry Andric INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
132ff0cc061SDimitry Andric                       "Make relocations explicit at statepoints", false, false)
133ff0cc061SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1343ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
135ff0cc061SDimitry Andric INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
136ff0cc061SDimitry Andric                     "Make relocations explicit at statepoints", false, false)
137ff0cc061SDimitry Andric 
138ff0cc061SDimitry Andric namespace {
139ff0cc061SDimitry Andric struct GCPtrLivenessData {
140ff0cc061SDimitry Andric   /// Values defined in this block.
1413ca95b02SDimitry Andric   MapVector<BasicBlock *, SetVector<Value *>> KillSet;
142ff0cc061SDimitry Andric   /// Values used in this block (and thus live); does not included values
143ff0cc061SDimitry Andric   /// killed within this block.
1443ca95b02SDimitry Andric   MapVector<BasicBlock *, SetVector<Value *>> LiveSet;
145ff0cc061SDimitry Andric 
146ff0cc061SDimitry Andric   /// Values live into this basic block (i.e. used by any
147ff0cc061SDimitry Andric   /// instruction in this basic block or ones reachable from here)
1483ca95b02SDimitry Andric   MapVector<BasicBlock *, SetVector<Value *>> LiveIn;
149ff0cc061SDimitry Andric 
150ff0cc061SDimitry Andric   /// Values live out of this basic block (i.e. live into
151ff0cc061SDimitry Andric   /// any successor block)
1523ca95b02SDimitry Andric   MapVector<BasicBlock *, SetVector<Value *>> LiveOut;
153ff0cc061SDimitry Andric };
154ff0cc061SDimitry Andric 
155ff0cc061SDimitry Andric // The type of the internal cache used inside the findBasePointers family
156ff0cc061SDimitry Andric // of functions.  From the callers perspective, this is an opaque type and
157ff0cc061SDimitry Andric // should not be inspected.
158ff0cc061SDimitry Andric //
159ff0cc061SDimitry Andric // In the actual implementation this caches two relations:
160ff0cc061SDimitry Andric // - The base relation itself (i.e. this pointer is based on that one)
161ff0cc061SDimitry Andric // - The base defining value relation (i.e. before base_phi insertion)
162ff0cc061SDimitry Andric // Generally, after the execution of a full findBasePointer call, only the
163ff0cc061SDimitry Andric // base relation will remain.  Internally, we add a mixture of the two
164ff0cc061SDimitry Andric // types, then update all the second type to the first type
1653ca95b02SDimitry Andric typedef MapVector<Value *, Value *> DefiningValueMapTy;
1663ca95b02SDimitry Andric typedef SetVector<Value *> StatepointLiveSetTy;
1673ca95b02SDimitry Andric typedef MapVector<AssertingVH<Instruction>, AssertingVH<Value>>
1687d523365SDimitry Andric   RematerializedValueMapTy;
169ff0cc061SDimitry Andric 
170ff0cc061SDimitry Andric struct PartiallyConstructedSafepointRecord {
1717d523365SDimitry Andric   /// The set of values known to be live across this safepoint
1727d523365SDimitry Andric   StatepointLiveSetTy LiveSet;
173ff0cc061SDimitry Andric 
174ff0cc061SDimitry Andric   /// Mapping from live pointers to a base-defining-value
1753ca95b02SDimitry Andric   MapVector<Value *, Value *> PointerToBase;
176ff0cc061SDimitry Andric 
177ff0cc061SDimitry Andric   /// The *new* gc.statepoint instruction itself.  This produces the token
178ff0cc061SDimitry Andric   /// that normal path gc.relocates and the gc.result are tied to.
179ff0cc061SDimitry Andric   Instruction *StatepointToken;
180ff0cc061SDimitry Andric 
181ff0cc061SDimitry Andric   /// Instruction to which exceptional gc relocates are attached
182ff0cc061SDimitry Andric   /// Makes it easier to iterate through them during relocationViaAlloca.
183ff0cc061SDimitry Andric   Instruction *UnwindToken;
184ff0cc061SDimitry Andric 
185ff0cc061SDimitry Andric   /// Record live values we are rematerialized instead of relocating.
1867d523365SDimitry Andric   /// They are not included into 'LiveSet' field.
187ff0cc061SDimitry Andric   /// Maps rematerialized copy to it's original value.
188ff0cc061SDimitry Andric   RematerializedValueMapTy RematerializedValues;
189ff0cc061SDimitry Andric };
1903dac3a9bSDimitry Andric }
191ff0cc061SDimitry Andric 
1927d523365SDimitry Andric static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
1933ca95b02SDimitry Andric   Optional<OperandBundleUse> DeoptBundle =
1943ca95b02SDimitry Andric       CS.getOperandBundle(LLVMContext::OB_deopt);
1957d523365SDimitry Andric 
1967d523365SDimitry Andric   if (!DeoptBundle.hasValue()) {
1977d523365SDimitry Andric     assert(AllowStatepointWithNoDeoptInfo &&
1987d523365SDimitry Andric            "Found non-leaf call without deopt info!");
1997d523365SDimitry Andric     return None;
2007d523365SDimitry Andric   }
2017d523365SDimitry Andric 
2027d523365SDimitry Andric   return DeoptBundle.getValue().Inputs;
2037d523365SDimitry Andric }
2047d523365SDimitry Andric 
205ff0cc061SDimitry Andric /// Compute the live-in set for every basic block in the function
206ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
207ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data);
208ff0cc061SDimitry Andric 
209ff0cc061SDimitry Andric /// Given results from the dataflow liveness computation, find the set of live
210ff0cc061SDimitry Andric /// Values at a particular instruction.
211ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
212ff0cc061SDimitry Andric                               StatepointLiveSetTy &out);
213ff0cc061SDimitry Andric 
214ff0cc061SDimitry Andric // TODO: Once we can get to the GCStrategy, this becomes
2157d523365SDimitry Andric // Optional<bool> isGCManagedPointer(const Type *Ty) const override {
216ff0cc061SDimitry Andric 
2177d523365SDimitry Andric static bool isGCPointerType(Type *T) {
2187d523365SDimitry Andric   if (auto *PT = dyn_cast<PointerType>(T))
219ff0cc061SDimitry Andric     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
220ff0cc061SDimitry Andric     // GC managed heap.  We know that a pointer into this heap needs to be
221ff0cc061SDimitry Andric     // updated and that no other pointer does.
2223ca95b02SDimitry Andric     return PT->getAddressSpace() == 1;
223ff0cc061SDimitry Andric   return false;
224ff0cc061SDimitry Andric }
225ff0cc061SDimitry Andric 
226ff0cc061SDimitry Andric // Return true if this type is one which a) is a gc pointer or contains a GC
227ff0cc061SDimitry Andric // pointer and b) is of a type this code expects to encounter as a live value.
228ff0cc061SDimitry Andric // (The insertion code will assert that a type which matches (a) and not (b)
229ff0cc061SDimitry Andric // is not encountered.)
230ff0cc061SDimitry Andric static bool isHandledGCPointerType(Type *T) {
231ff0cc061SDimitry Andric   // We fully support gc pointers
232ff0cc061SDimitry Andric   if (isGCPointerType(T))
233ff0cc061SDimitry Andric     return true;
234ff0cc061SDimitry Andric   // We partially support vectors of gc pointers. The code will assert if it
235ff0cc061SDimitry Andric   // can't handle something.
236ff0cc061SDimitry Andric   if (auto VT = dyn_cast<VectorType>(T))
237ff0cc061SDimitry Andric     if (isGCPointerType(VT->getElementType()))
238ff0cc061SDimitry Andric       return true;
239ff0cc061SDimitry Andric   return false;
240ff0cc061SDimitry Andric }
241ff0cc061SDimitry Andric 
242ff0cc061SDimitry Andric #ifndef NDEBUG
243ff0cc061SDimitry Andric /// Returns true if this type contains a gc pointer whether we know how to
244ff0cc061SDimitry Andric /// handle that type or not.
245ff0cc061SDimitry Andric static bool containsGCPtrType(Type *Ty) {
246ff0cc061SDimitry Andric   if (isGCPointerType(Ty))
247ff0cc061SDimitry Andric     return true;
248ff0cc061SDimitry Andric   if (VectorType *VT = dyn_cast<VectorType>(Ty))
249ff0cc061SDimitry Andric     return isGCPointerType(VT->getScalarType());
250ff0cc061SDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
251ff0cc061SDimitry Andric     return containsGCPtrType(AT->getElementType());
252ff0cc061SDimitry Andric   if (StructType *ST = dyn_cast<StructType>(Ty))
2533ca95b02SDimitry Andric     return any_of(ST->subtypes(), containsGCPtrType);
254ff0cc061SDimitry Andric   return false;
255ff0cc061SDimitry Andric }
256ff0cc061SDimitry Andric 
257ff0cc061SDimitry Andric // Returns true if this is a type which a) is a gc pointer or contains a GC
258ff0cc061SDimitry Andric // pointer and b) is of a type which the code doesn't expect (i.e. first class
259ff0cc061SDimitry Andric // aggregates).  Used to trip assertions.
260ff0cc061SDimitry Andric static bool isUnhandledGCPointerType(Type *Ty) {
261ff0cc061SDimitry Andric   return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
262ff0cc061SDimitry Andric }
263ff0cc061SDimitry Andric #endif
264ff0cc061SDimitry Andric 
2657d523365SDimitry Andric // Return the name of the value suffixed with the provided value, or if the
2667d523365SDimitry Andric // value didn't have a name, the default value specified.
2677d523365SDimitry Andric static std::string suffixed_name_or(Value *V, StringRef Suffix,
2687d523365SDimitry Andric                                     StringRef DefaultName) {
2697d523365SDimitry Andric   return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
2707d523365SDimitry Andric }
2717d523365SDimitry Andric 
272ff0cc061SDimitry Andric // Conservatively identifies any definitions which might be live at the
273ff0cc061SDimitry Andric // given instruction. The  analysis is performed immediately before the
274ff0cc061SDimitry Andric // given instruction. Values defined by that instruction are not considered
275ff0cc061SDimitry Andric // live.  Values used by that instruction are considered live.
2763ca95b02SDimitry Andric static void
2773ca95b02SDimitry Andric analyzeParsePointLiveness(DominatorTree &DT,
2783ca95b02SDimitry Andric                           GCPtrLivenessData &OriginalLivenessData, CallSite CS,
2793ca95b02SDimitry Andric                           PartiallyConstructedSafepointRecord &Result) {
2803ca95b02SDimitry Andric   Instruction *Inst = CS.getInstruction();
281ff0cc061SDimitry Andric 
2827d523365SDimitry Andric   StatepointLiveSetTy LiveSet;
2833ca95b02SDimitry Andric   findLiveSetAtInst(Inst, OriginalLivenessData, LiveSet);
284ff0cc061SDimitry Andric 
285ff0cc061SDimitry Andric   if (PrintLiveSet) {
2863ca95b02SDimitry Andric     dbgs() << "Live Variables:\n";
2873ca95b02SDimitry Andric     for (Value *V : LiveSet)
2887d523365SDimitry Andric       dbgs() << " " << V->getName() << " " << *V << "\n";
289ff0cc061SDimitry Andric   }
290ff0cc061SDimitry Andric   if (PrintLiveSetSize) {
2913ca95b02SDimitry Andric     dbgs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
2923ca95b02SDimitry Andric     dbgs() << "Number live values: " << LiveSet.size() << "\n";
293ff0cc061SDimitry Andric   }
2943ca95b02SDimitry Andric   Result.LiveSet = LiveSet;
295ff0cc061SDimitry Andric }
296ff0cc061SDimitry Andric 
2977d523365SDimitry Andric static bool isKnownBaseResult(Value *V);
2987d523365SDimitry Andric namespace {
2997d523365SDimitry Andric /// A single base defining value - An immediate base defining value for an
3007d523365SDimitry Andric /// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
3017d523365SDimitry Andric /// For instructions which have multiple pointer [vector] inputs or that
3027d523365SDimitry Andric /// transition between vector and scalar types, there is no immediate base
3037d523365SDimitry Andric /// defining value.  The 'base defining value' for 'Def' is the transitive
3047d523365SDimitry Andric /// closure of this relation stopping at the first instruction which has no
3057d523365SDimitry Andric /// immediate base defining value.  The b.d.v. might itself be a base pointer,
3067d523365SDimitry Andric /// but it can also be an arbitrary derived pointer.
3077d523365SDimitry Andric struct BaseDefiningValueResult {
3087d523365SDimitry Andric   /// Contains the value which is the base defining value.
3097d523365SDimitry Andric   Value * const BDV;
3107d523365SDimitry Andric   /// True if the base defining value is also known to be an actual base
3117d523365SDimitry Andric   /// pointer.
3127d523365SDimitry Andric   const bool IsKnownBase;
3137d523365SDimitry Andric   BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
3147d523365SDimitry Andric     : BDV(BDV), IsKnownBase(IsKnownBase) {
3157d523365SDimitry Andric #ifndef NDEBUG
3167d523365SDimitry Andric     // Check consistency between new and old means of checking whether a BDV is
3177d523365SDimitry Andric     // a base.
3187d523365SDimitry Andric     bool MustBeBase = isKnownBaseResult(BDV);
3197d523365SDimitry Andric     assert(!MustBeBase || MustBeBase == IsKnownBase);
3207d523365SDimitry Andric #endif
3217d523365SDimitry Andric   }
3227d523365SDimitry Andric };
3237d523365SDimitry Andric }
3247d523365SDimitry Andric 
3257d523365SDimitry Andric static BaseDefiningValueResult findBaseDefiningValue(Value *I);
326ff0cc061SDimitry Andric 
3273dac3a9bSDimitry Andric /// Return a base defining value for the 'Index' element of the given vector
3283dac3a9bSDimitry Andric /// instruction 'I'.  If Index is null, returns a BDV for the entire vector
3293dac3a9bSDimitry Andric /// 'I'.  As an optimization, this method will try to determine when the
3303dac3a9bSDimitry Andric /// element is known to already be a base pointer.  If this can be established,
3313dac3a9bSDimitry Andric /// the second value in the returned pair will be true.  Note that either a
3323dac3a9bSDimitry Andric /// vector or a pointer typed value can be returned.  For the former, the
3333dac3a9bSDimitry Andric /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
3343dac3a9bSDimitry Andric /// If the later, the return pointer is a BDV (or possibly a base) for the
3353dac3a9bSDimitry Andric /// particular element in 'I'.
3367d523365SDimitry Andric static BaseDefiningValueResult
3377d523365SDimitry Andric findBaseDefiningValueOfVector(Value *I) {
338ff0cc061SDimitry Andric   // Each case parallels findBaseDefiningValue below, see that code for
339ff0cc061SDimitry Andric   // detailed motivation.
340ff0cc061SDimitry Andric 
341ff0cc061SDimitry Andric   if (isa<Argument>(I))
342ff0cc061SDimitry Andric     // An incoming argument to the function is a base pointer
3437d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
344ff0cc061SDimitry Andric 
345444ed5c5SDimitry Andric   if (isa<Constant>(I))
3463ca95b02SDimitry Andric     // Base of constant vector consists only of constant null pointers.
3473ca95b02SDimitry Andric     // For reasoning see similar case inside 'findBaseDefiningValue' function.
3483ca95b02SDimitry Andric     return BaseDefiningValueResult(ConstantAggregateZero::get(I->getType()),
3493ca95b02SDimitry Andric                                    true);
350ff0cc061SDimitry Andric 
351ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
3527d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
353ff0cc061SDimitry Andric 
3547d523365SDimitry Andric   if (isa<InsertElementInst>(I))
3553dac3a9bSDimitry Andric     // We don't know whether this vector contains entirely base pointers or
3563dac3a9bSDimitry Andric     // not.  To be conservatively correct, we treat it as a BDV and will
3573dac3a9bSDimitry Andric     // duplicate code as needed to construct a parallel vector of bases.
3587d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
359ff0cc061SDimitry Andric 
3603dac3a9bSDimitry Andric   if (isa<ShuffleVectorInst>(I))
3613dac3a9bSDimitry Andric     // We don't know whether this vector contains entirely base pointers or
3623dac3a9bSDimitry Andric     // not.  To be conservatively correct, we treat it as a BDV and will
3633dac3a9bSDimitry Andric     // duplicate code as needed to construct a parallel vector of bases.
3643dac3a9bSDimitry Andric     // TODO: There a number of local optimizations which could be applied here
3653dac3a9bSDimitry Andric     // for particular sufflevector patterns.
3667d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
3673dac3a9bSDimitry Andric 
3683dac3a9bSDimitry Andric   // A PHI or Select is a base defining value.  The outer findBasePointer
3693dac3a9bSDimitry Andric   // algorithm is responsible for constructing a base value for this BDV.
3703dac3a9bSDimitry Andric   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
3713dac3a9bSDimitry Andric          "unknown vector instruction - no base found for vector element");
3727d523365SDimitry Andric   return BaseDefiningValueResult(I, false);
3733dac3a9bSDimitry Andric }
3743dac3a9bSDimitry Andric 
375ff0cc061SDimitry Andric /// Helper function for findBasePointer - Will return a value which either a)
3767d523365SDimitry Andric /// defines the base pointer for the input, b) blocks the simple search
3777d523365SDimitry Andric /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
3787d523365SDimitry Andric /// from pointer to vector type or back.
3797d523365SDimitry Andric static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
380444ed5c5SDimitry Andric   assert(I->getType()->isPtrOrPtrVectorTy() &&
381444ed5c5SDimitry Andric          "Illegal to ask for the base pointer of a non-pointer type");
382444ed5c5SDimitry Andric 
3833dac3a9bSDimitry Andric   if (I->getType()->isVectorTy())
3847d523365SDimitry Andric     return findBaseDefiningValueOfVector(I);
3853dac3a9bSDimitry Andric 
386ff0cc061SDimitry Andric   if (isa<Argument>(I))
387ff0cc061SDimitry Andric     // An incoming argument to the function is a base pointer
388ff0cc061SDimitry Andric     // We should have never reached here if this argument isn't an gc value
3897d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
390ff0cc061SDimitry Andric 
3913ca95b02SDimitry Andric   if (isa<Constant>(I)) {
3924d0b32cdSDimitry Andric     // We assume that objects with a constant base (e.g. a global) can't move
3934d0b32cdSDimitry Andric     // and don't need to be reported to the collector because they are always
3943ca95b02SDimitry Andric     // live. Besides global references, all kinds of constants (e.g. undef,
3953ca95b02SDimitry Andric     // constant expressions, null pointers) can be introduced by the inliner or
3963ca95b02SDimitry Andric     // the optimizer, especially on dynamically dead paths.
3973ca95b02SDimitry Andric     // Here we treat all of them as having single null base. By doing this we
3983ca95b02SDimitry Andric     // trying to avoid problems reporting various conflicts in a form of
3993ca95b02SDimitry Andric     // "phi (const1, const2)" or "phi (const, regular gc ptr)".
4003ca95b02SDimitry Andric     // See constant.ll file for relevant test cases.
4013ca95b02SDimitry Andric 
4023ca95b02SDimitry Andric     return BaseDefiningValueResult(
4033ca95b02SDimitry Andric         ConstantPointerNull::get(cast<PointerType>(I->getType())), true);
4043ca95b02SDimitry Andric   }
405ff0cc061SDimitry Andric 
406ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(I)) {
407ff0cc061SDimitry Andric     Value *Def = CI->stripPointerCasts();
4087d523365SDimitry Andric     // If stripping pointer casts changes the address space there is an
4097d523365SDimitry Andric     // addrspacecast in between.
4107d523365SDimitry Andric     assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
4117d523365SDimitry Andric                cast<PointerType>(CI->getType())->getAddressSpace() &&
4127d523365SDimitry Andric            "unsupported addrspacecast");
413ff0cc061SDimitry Andric     // If we find a cast instruction here, it means we've found a cast which is
414ff0cc061SDimitry Andric     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
415ff0cc061SDimitry Andric     // handle int->ptr conversion.
416ff0cc061SDimitry Andric     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
417ff0cc061SDimitry Andric     return findBaseDefiningValue(Def);
418ff0cc061SDimitry Andric   }
419ff0cc061SDimitry Andric 
420ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
4217d523365SDimitry Andric     // The value loaded is an gc base itself
4227d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
4237d523365SDimitry Andric 
424ff0cc061SDimitry Andric 
425ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
426ff0cc061SDimitry Andric     // The base of this GEP is the base
427ff0cc061SDimitry Andric     return findBaseDefiningValue(GEP->getPointerOperand());
428ff0cc061SDimitry Andric 
429ff0cc061SDimitry Andric   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
430ff0cc061SDimitry Andric     switch (II->getIntrinsicID()) {
431ff0cc061SDimitry Andric     default:
432ff0cc061SDimitry Andric       // fall through to general call handling
433ff0cc061SDimitry Andric       break;
434ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_statepoint:
4357d523365SDimitry Andric       llvm_unreachable("statepoints don't produce pointers");
436ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_relocate: {
437ff0cc061SDimitry Andric       // Rerunning safepoint insertion after safepoints are already
438ff0cc061SDimitry Andric       // inserted is not supported.  It could probably be made to work,
439ff0cc061SDimitry Andric       // but why are you doing this?  There's no good reason.
440ff0cc061SDimitry Andric       llvm_unreachable("repeat safepoint insertion is not supported");
441ff0cc061SDimitry Andric     }
442ff0cc061SDimitry Andric     case Intrinsic::gcroot:
443ff0cc061SDimitry Andric       // Currently, this mechanism hasn't been extended to work with gcroot.
444ff0cc061SDimitry Andric       // There's no reason it couldn't be, but I haven't thought about the
445ff0cc061SDimitry Andric       // implications much.
446ff0cc061SDimitry Andric       llvm_unreachable(
447ff0cc061SDimitry Andric           "interaction with the gcroot mechanism is not supported");
448ff0cc061SDimitry Andric     }
449ff0cc061SDimitry Andric   }
450ff0cc061SDimitry Andric   // We assume that functions in the source language only return base
451ff0cc061SDimitry Andric   // pointers.  This should probably be generalized via attributes to support
452ff0cc061SDimitry Andric   // both source language and internal functions.
453ff0cc061SDimitry Andric   if (isa<CallInst>(I) || isa<InvokeInst>(I))
4547d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
455ff0cc061SDimitry Andric 
456d88c1a5aSDimitry Andric   // TODO: I have absolutely no idea how to implement this part yet.  It's not
4577d523365SDimitry Andric   // necessarily hard, I just haven't really looked at it yet.
458ff0cc061SDimitry Andric   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
459ff0cc061SDimitry Andric 
460ff0cc061SDimitry Andric   if (isa<AtomicCmpXchgInst>(I))
461ff0cc061SDimitry Andric     // A CAS is effectively a atomic store and load combined under a
462ff0cc061SDimitry Andric     // predicate.  From the perspective of base pointers, we just treat it
463ff0cc061SDimitry Andric     // like a load.
4647d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
465ff0cc061SDimitry Andric 
466ff0cc061SDimitry Andric   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
467ff0cc061SDimitry Andric                                    "binary ops which don't apply to pointers");
468ff0cc061SDimitry Andric 
469ff0cc061SDimitry Andric   // The aggregate ops.  Aggregates can either be in the heap or on the
470ff0cc061SDimitry Andric   // stack, but in either case, this is simply a field load.  As a result,
471ff0cc061SDimitry Andric   // this is a defining definition of the base just like a load is.
472ff0cc061SDimitry Andric   if (isa<ExtractValueInst>(I))
4737d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
474ff0cc061SDimitry Andric 
475ff0cc061SDimitry Andric   // We should never see an insert vector since that would require we be
476ff0cc061SDimitry Andric   // tracing back a struct value not a pointer value.
477ff0cc061SDimitry Andric   assert(!isa<InsertValueInst>(I) &&
478ff0cc061SDimitry Andric          "Base pointer for a struct is meaningless");
479ff0cc061SDimitry Andric 
4807d523365SDimitry Andric   // An extractelement produces a base result exactly when it's input does.
4817d523365SDimitry Andric   // We may need to insert a parallel instruction to extract the appropriate
4827d523365SDimitry Andric   // element out of the base vector corresponding to the input. Given this,
4837d523365SDimitry Andric   // it's analogous to the phi and select case even though it's not a merge.
4847d523365SDimitry Andric   if (isa<ExtractElementInst>(I))
4857d523365SDimitry Andric     // Note: There a lot of obvious peephole cases here.  This are deliberately
4867d523365SDimitry Andric     // handled after the main base pointer inference algorithm to make writing
4877d523365SDimitry Andric     // test cases to exercise that code easier.
4887d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
4897d523365SDimitry Andric 
490ff0cc061SDimitry Andric   // The last two cases here don't return a base pointer.  Instead, they
4917d523365SDimitry Andric   // return a value which dynamically selects from among several base
492ff0cc061SDimitry Andric   // derived pointers (each with it's own base potentially).  It's the job of
493ff0cc061SDimitry Andric   // the caller to resolve these.
494ff0cc061SDimitry Andric   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
495ff0cc061SDimitry Andric          "missing instruction case in findBaseDefiningValing");
4967d523365SDimitry Andric   return BaseDefiningValueResult(I, false);
497ff0cc061SDimitry Andric }
498ff0cc061SDimitry Andric 
499ff0cc061SDimitry Andric /// Returns the base defining value for this value.
500ff0cc061SDimitry Andric static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
501ff0cc061SDimitry Andric   Value *&Cached = Cache[I];
502ff0cc061SDimitry Andric   if (!Cached) {
5037d523365SDimitry Andric     Cached = findBaseDefiningValue(I).BDV;
5047d523365SDimitry Andric     DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
5057d523365SDimitry Andric                  << Cached->getName() << "\n");
506ff0cc061SDimitry Andric   }
507ff0cc061SDimitry Andric   assert(Cache[I] != nullptr);
508ff0cc061SDimitry Andric   return Cached;
509ff0cc061SDimitry Andric }
510ff0cc061SDimitry Andric 
511ff0cc061SDimitry Andric /// Return a base pointer for this value if known.  Otherwise, return it's
512ff0cc061SDimitry Andric /// base defining value.
513ff0cc061SDimitry Andric static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
514ff0cc061SDimitry Andric   Value *Def = findBaseDefiningValueCached(I, Cache);
515ff0cc061SDimitry Andric   auto Found = Cache.find(Def);
516ff0cc061SDimitry Andric   if (Found != Cache.end()) {
517ff0cc061SDimitry Andric     // Either a base-of relation, or a self reference.  Caller must check.
518ff0cc061SDimitry Andric     return Found->second;
519ff0cc061SDimitry Andric   }
520ff0cc061SDimitry Andric   // Only a BDV available
521ff0cc061SDimitry Andric   return Def;
522ff0cc061SDimitry Andric }
523ff0cc061SDimitry Andric 
524ff0cc061SDimitry Andric /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
525ff0cc061SDimitry Andric /// is it known to be a base pointer?  Or do we need to continue searching.
526ff0cc061SDimitry Andric static bool isKnownBaseResult(Value *V) {
5277d523365SDimitry Andric   if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
5287d523365SDimitry Andric       !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
5297d523365SDimitry Andric       !isa<ShuffleVectorInst>(V)) {
530ff0cc061SDimitry Andric     // no recursion possible
531ff0cc061SDimitry Andric     return true;
532ff0cc061SDimitry Andric   }
533ff0cc061SDimitry Andric   if (isa<Instruction>(V) &&
534ff0cc061SDimitry Andric       cast<Instruction>(V)->getMetadata("is_base_value")) {
535ff0cc061SDimitry Andric     // This is a previously inserted base phi or select.  We know
536ff0cc061SDimitry Andric     // that this is a base value.
537ff0cc061SDimitry Andric     return true;
538ff0cc061SDimitry Andric   }
539ff0cc061SDimitry Andric 
540ff0cc061SDimitry Andric   // We need to keep searching
541ff0cc061SDimitry Andric   return false;
542ff0cc061SDimitry Andric }
543ff0cc061SDimitry Andric 
544ff0cc061SDimitry Andric namespace {
5457d523365SDimitry Andric /// Models the state of a single base defining value in the findBasePointer
5467d523365SDimitry Andric /// algorithm for determining where a new instruction is needed to propagate
5477d523365SDimitry Andric /// the base of this BDV.
5487d523365SDimitry Andric class BDVState {
549ff0cc061SDimitry Andric public:
550ff0cc061SDimitry Andric   enum Status { Unknown, Base, Conflict };
551ff0cc061SDimitry Andric 
5523ca95b02SDimitry Andric   BDVState() : Status(Unknown), BaseValue(nullptr) {}
553ff0cc061SDimitry Andric 
5543ca95b02SDimitry Andric   explicit BDVState(Status Status, Value *BaseValue = nullptr)
5553ca95b02SDimitry Andric       : Status(Status), BaseValue(BaseValue) {
5563ca95b02SDimitry Andric     assert(Status != Base || BaseValue);
5573ca95b02SDimitry Andric   }
5583ca95b02SDimitry Andric 
5593ca95b02SDimitry Andric   explicit BDVState(Value *BaseValue) : Status(Base), BaseValue(BaseValue) {}
5603ca95b02SDimitry Andric 
5613ca95b02SDimitry Andric   Status getStatus() const { return Status; }
5623ca95b02SDimitry Andric   Value *getBaseValue() const { return BaseValue; }
563ff0cc061SDimitry Andric 
564ff0cc061SDimitry Andric   bool isBase() const { return getStatus() == Base; }
565ff0cc061SDimitry Andric   bool isUnknown() const { return getStatus() == Unknown; }
566ff0cc061SDimitry Andric   bool isConflict() const { return getStatus() == Conflict; }
567ff0cc061SDimitry Andric 
5683ca95b02SDimitry Andric   bool operator==(const BDVState &Other) const {
5693ca95b02SDimitry Andric     return BaseValue == Other.BaseValue && Status == Other.Status;
570ff0cc061SDimitry Andric   }
571ff0cc061SDimitry Andric 
5727d523365SDimitry Andric   bool operator!=(const BDVState &other) const { return !(*this == other); }
573ff0cc061SDimitry Andric 
5747d523365SDimitry Andric   LLVM_DUMP_METHOD
5753ca95b02SDimitry Andric   void dump() const {
5763ca95b02SDimitry Andric     print(dbgs());
5773ca95b02SDimitry Andric     dbgs() << '\n';
5783ca95b02SDimitry Andric   }
5797d523365SDimitry Andric 
5807d523365SDimitry Andric   void print(raw_ostream &OS) const {
5813ca95b02SDimitry Andric     switch (getStatus()) {
5827d523365SDimitry Andric     case Unknown:
5837d523365SDimitry Andric       OS << "U";
5847d523365SDimitry Andric       break;
5857d523365SDimitry Andric     case Base:
5867d523365SDimitry Andric       OS << "B";
5877d523365SDimitry Andric       break;
5887d523365SDimitry Andric     case Conflict:
5897d523365SDimitry Andric       OS << "C";
5907d523365SDimitry Andric       break;
5917d523365SDimitry Andric     };
5923ca95b02SDimitry Andric     OS << " (" << getBaseValue() << " - "
5933ca95b02SDimitry Andric        << (getBaseValue() ? getBaseValue()->getName() : "nullptr") << "): ";
594ff0cc061SDimitry Andric   }
595ff0cc061SDimitry Andric 
596ff0cc061SDimitry Andric private:
5973ca95b02SDimitry Andric   Status Status;
5983ca95b02SDimitry Andric   AssertingVH<Value> BaseValue; // Non-null only if Status == Base.
599ff0cc061SDimitry Andric };
600ff0cc061SDimitry Andric }
601ff0cc061SDimitry Andric 
6027d523365SDimitry Andric #ifndef NDEBUG
6037d523365SDimitry Andric static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
6047d523365SDimitry Andric   State.print(OS);
6057d523365SDimitry Andric   return OS;
6067d523365SDimitry Andric }
6077d523365SDimitry Andric #endif
6087d523365SDimitry Andric 
6093ca95b02SDimitry Andric static BDVState meetBDVStateImpl(const BDVState &LHS, const BDVState &RHS) {
6103ca95b02SDimitry Andric   switch (LHS.getStatus()) {
6117d523365SDimitry Andric   case BDVState::Unknown:
6123ca95b02SDimitry Andric     return RHS;
613ff0cc061SDimitry Andric 
6147d523365SDimitry Andric   case BDVState::Base:
6153ca95b02SDimitry Andric     assert(LHS.getBaseValue() && "can't be null");
6163ca95b02SDimitry Andric     if (RHS.isUnknown())
6173ca95b02SDimitry Andric       return LHS;
618ff0cc061SDimitry Andric 
6193ca95b02SDimitry Andric     if (RHS.isBase()) {
6203ca95b02SDimitry Andric       if (LHS.getBaseValue() == RHS.getBaseValue()) {
6213ca95b02SDimitry Andric         assert(LHS == RHS && "equality broken!");
6223ca95b02SDimitry Andric         return LHS;
623ff0cc061SDimitry Andric       }
6247d523365SDimitry Andric       return BDVState(BDVState::Conflict);
625ff0cc061SDimitry Andric     }
6263ca95b02SDimitry Andric     assert(RHS.isConflict() && "only three states!");
6277d523365SDimitry Andric     return BDVState(BDVState::Conflict);
628ff0cc061SDimitry Andric 
6297d523365SDimitry Andric   case BDVState::Conflict:
6303ca95b02SDimitry Andric     return LHS;
631ff0cc061SDimitry Andric   }
632ff0cc061SDimitry Andric   llvm_unreachable("only three states!");
633ff0cc061SDimitry Andric }
6343ca95b02SDimitry Andric 
6353ca95b02SDimitry Andric // Values of type BDVState form a lattice, and this function implements the meet
6363ca95b02SDimitry Andric // operation.
6373ca95b02SDimitry Andric static BDVState meetBDVState(BDVState LHS, BDVState RHS) {
6383ca95b02SDimitry Andric   BDVState Result = meetBDVStateImpl(LHS, RHS);
6393ca95b02SDimitry Andric   assert(Result == meetBDVStateImpl(RHS, LHS) &&
6403ca95b02SDimitry Andric          "Math is wrong: meet does not commute!");
6413ca95b02SDimitry Andric   return Result;
6423dac3a9bSDimitry Andric }
6437d523365SDimitry Andric 
6443ca95b02SDimitry Andric /// For a given value or instruction, figure out what base ptr its derived from.
6453ca95b02SDimitry Andric /// For gc objects, this is simply itself.  On success, returns a value which is
6463ca95b02SDimitry Andric /// the base pointer.  (This is reliable and can be used for relocation.)  On
6473ca95b02SDimitry Andric /// failure, returns nullptr.
6483ca95b02SDimitry Andric static Value *findBasePointer(Value *I, DefiningValueMapTy &Cache) {
6493ca95b02SDimitry Andric   Value *Def = findBaseOrBDV(I, Cache);
6507d523365SDimitry Andric 
6513ca95b02SDimitry Andric   if (isKnownBaseResult(Def))
6523ca95b02SDimitry Andric     return Def;
653ff0cc061SDimitry Andric 
654ff0cc061SDimitry Andric   // Here's the rough algorithm:
655ff0cc061SDimitry Andric   // - For every SSA value, construct a mapping to either an actual base
656ff0cc061SDimitry Andric   //   pointer or a PHI which obscures the base pointer.
657ff0cc061SDimitry Andric   // - Construct a mapping from PHI to unknown TOP state.  Use an
658ff0cc061SDimitry Andric   //   optimistic algorithm to propagate base pointer information.  Lattice
659ff0cc061SDimitry Andric   //   looks like:
660ff0cc061SDimitry Andric   //   UNKNOWN
661ff0cc061SDimitry Andric   //   b1 b2 b3 b4
662ff0cc061SDimitry Andric   //   CONFLICT
663ff0cc061SDimitry Andric   //   When algorithm terminates, all PHIs will either have a single concrete
664ff0cc061SDimitry Andric   //   base or be in a conflict state.
665ff0cc061SDimitry Andric   // - For every conflict, insert a dummy PHI node without arguments.  Add
666ff0cc061SDimitry Andric   //   these to the base[Instruction] = BasePtr mapping.  For every
667ff0cc061SDimitry Andric   //   non-conflict, add the actual base.
668ff0cc061SDimitry Andric   //  - For every conflict, add arguments for the base[a] of each input
669ff0cc061SDimitry Andric   //   arguments.
670ff0cc061SDimitry Andric   //
671ff0cc061SDimitry Andric   // Note: A simpler form of this would be to add the conflict form of all
672ff0cc061SDimitry Andric   // PHIs without running the optimistic algorithm.  This would be
6737d523365SDimitry Andric   // analogous to pessimistic data flow and would likely lead to an
674ff0cc061SDimitry Andric   // overall worse solution.
675ff0cc061SDimitry Andric 
6767d523365SDimitry Andric #ifndef NDEBUG
6777d523365SDimitry Andric   auto isExpectedBDVType = [](Value *BDV) {
6787d523365SDimitry Andric     return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
679d88c1a5aSDimitry Andric            isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
680d88c1a5aSDimitry Andric            isa<ShuffleVectorInst>(BDV);
6817d523365SDimitry Andric   };
6827d523365SDimitry Andric #endif
6837d523365SDimitry Andric 
6847d523365SDimitry Andric   // Once populated, will contain a mapping from each potentially non-base BDV
6857d523365SDimitry Andric   // to a lattice value (described above) which corresponds to that BDV.
6867d523365SDimitry Andric   // We use the order of insertion (DFS over the def/use graph) to provide a
6877d523365SDimitry Andric   // stable deterministic ordering for visiting DenseMaps (which are unordered)
6887d523365SDimitry Andric   // below.  This is important for deterministic compilation.
6897d523365SDimitry Andric   MapVector<Value *, BDVState> States;
6907d523365SDimitry Andric 
6917d523365SDimitry Andric   // Recursively fill in all base defining values reachable from the initial
6927d523365SDimitry Andric   // one for which we don't already know a definite base value for
6937d523365SDimitry Andric   /* scope */ {
6947d523365SDimitry Andric     SmallVector<Value*, 16> Worklist;
6953ca95b02SDimitry Andric     Worklist.push_back(Def);
6963ca95b02SDimitry Andric     States.insert({Def, BDVState()});
6977d523365SDimitry Andric     while (!Worklist.empty()) {
6987d523365SDimitry Andric       Value *Current = Worklist.pop_back_val();
6997d523365SDimitry Andric       assert(!isKnownBaseResult(Current) && "why did it get added?");
7007d523365SDimitry Andric 
7017d523365SDimitry Andric       auto visitIncomingValue = [&](Value *InVal) {
7023ca95b02SDimitry Andric         Value *Base = findBaseOrBDV(InVal, Cache);
7037d523365SDimitry Andric         if (isKnownBaseResult(Base))
7047d523365SDimitry Andric           // Known bases won't need new instructions introduced and can be
7057d523365SDimitry Andric           // ignored safely
7067d523365SDimitry Andric           return;
7077d523365SDimitry Andric         assert(isExpectedBDVType(Base) && "the only non-base values "
7087d523365SDimitry Andric                "we see should be base defining values");
7097d523365SDimitry Andric         if (States.insert(std::make_pair(Base, BDVState())).second)
7107d523365SDimitry Andric           Worklist.push_back(Base);
7117d523365SDimitry Andric       };
7123ca95b02SDimitry Andric       if (PHINode *PN = dyn_cast<PHINode>(Current)) {
7133ca95b02SDimitry Andric         for (Value *InVal : PN->incoming_values())
7147d523365SDimitry Andric           visitIncomingValue(InVal);
7153ca95b02SDimitry Andric       } else if (SelectInst *SI = dyn_cast<SelectInst>(Current)) {
7163ca95b02SDimitry Andric         visitIncomingValue(SI->getTrueValue());
7173ca95b02SDimitry Andric         visitIncomingValue(SI->getFalseValue());
7187d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
7197d523365SDimitry Andric         visitIncomingValue(EE->getVectorOperand());
7207d523365SDimitry Andric       } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
7217d523365SDimitry Andric         visitIncomingValue(IE->getOperand(0)); // vector operand
7227d523365SDimitry Andric         visitIncomingValue(IE->getOperand(1)); // scalar operand
723d88c1a5aSDimitry Andric       } else if (auto *SV = dyn_cast<ShuffleVectorInst>(Current)) {
724d88c1a5aSDimitry Andric         visitIncomingValue(SV->getOperand(0));
725d88c1a5aSDimitry Andric         visitIncomingValue(SV->getOperand(1));
726d88c1a5aSDimitry Andric       }
727d88c1a5aSDimitry Andric       else {
7283ca95b02SDimitry Andric         llvm_unreachable("Unimplemented instruction case");
729ff0cc061SDimitry Andric       }
730ff0cc061SDimitry Andric     }
731ff0cc061SDimitry Andric   }
732ff0cc061SDimitry Andric 
7337d523365SDimitry Andric #ifndef NDEBUG
7347d523365SDimitry Andric   DEBUG(dbgs() << "States after initialization:\n");
7357d523365SDimitry Andric   for (auto Pair : States) {
7367d523365SDimitry Andric     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
737ff0cc061SDimitry Andric   }
7387d523365SDimitry Andric #endif
739ff0cc061SDimitry Andric 
7407d523365SDimitry Andric   // Return a phi state for a base defining value.  We'll generate a new
7417d523365SDimitry Andric   // base state for known bases and expect to find a cached state otherwise.
7427d523365SDimitry Andric   auto getStateForBDV = [&](Value *baseValue) {
7437d523365SDimitry Andric     if (isKnownBaseResult(baseValue))
7447d523365SDimitry Andric       return BDVState(baseValue);
7457d523365SDimitry Andric     auto I = States.find(baseValue);
7467d523365SDimitry Andric     assert(I != States.end() && "lookup failed!");
7477d523365SDimitry Andric     return I->second;
7487d523365SDimitry Andric   };
749ff0cc061SDimitry Andric 
7503ca95b02SDimitry Andric   bool Progress = true;
7513ca95b02SDimitry Andric   while (Progress) {
752ff0cc061SDimitry Andric #ifndef NDEBUG
7533ca95b02SDimitry Andric     const size_t OldSize = States.size();
754ff0cc061SDimitry Andric #endif
7553ca95b02SDimitry Andric     Progress = false;
7567d523365SDimitry Andric     // We're only changing values in this loop, thus safe to keep iterators.
7577d523365SDimitry Andric     // Since this is computing a fixed point, the order of visit does not
7587d523365SDimitry Andric     // effect the result.  TODO: We could use a worklist here and make this run
7597d523365SDimitry Andric     // much faster.
7607d523365SDimitry Andric     for (auto Pair : States) {
7617d523365SDimitry Andric       Value *BDV = Pair.first;
7627d523365SDimitry Andric       assert(!isKnownBaseResult(BDV) && "why did it get added?");
763ff0cc061SDimitry Andric 
7647d523365SDimitry Andric       // Given an input value for the current instruction, return a BDVState
7657d523365SDimitry Andric       // instance which represents the BDV of that value.
7667d523365SDimitry Andric       auto getStateForInput = [&](Value *V) mutable {
7673ca95b02SDimitry Andric         Value *BDV = findBaseOrBDV(V, Cache);
7687d523365SDimitry Andric         return getStateForBDV(BDV);
7697d523365SDimitry Andric       };
7707d523365SDimitry Andric 
7713ca95b02SDimitry Andric       BDVState NewState;
7723ca95b02SDimitry Andric       if (SelectInst *SI = dyn_cast<SelectInst>(BDV)) {
7733ca95b02SDimitry Andric         NewState = meetBDVState(NewState, getStateForInput(SI->getTrueValue()));
7743ca95b02SDimitry Andric         NewState =
7753ca95b02SDimitry Andric             meetBDVState(NewState, getStateForInput(SI->getFalseValue()));
7763ca95b02SDimitry Andric       } else if (PHINode *PN = dyn_cast<PHINode>(BDV)) {
7773ca95b02SDimitry Andric         for (Value *Val : PN->incoming_values())
7783ca95b02SDimitry Andric           NewState = meetBDVState(NewState, getStateForInput(Val));
7797d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
7807d523365SDimitry Andric         // The 'meet' for an extractelement is slightly trivial, but it's still
7817d523365SDimitry Andric         // useful in that it drives us to conflict if our input is.
7823ca95b02SDimitry Andric         NewState =
7833ca95b02SDimitry Andric             meetBDVState(NewState, getStateForInput(EE->getVectorOperand()));
784d88c1a5aSDimitry Andric       } else if (auto *IE = dyn_cast<InsertElementInst>(BDV)){
7857d523365SDimitry Andric         // Given there's a inherent type mismatch between the operands, will
7867d523365SDimitry Andric         // *always* produce Conflict.
7873ca95b02SDimitry Andric         NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(0)));
7883ca95b02SDimitry Andric         NewState = meetBDVState(NewState, getStateForInput(IE->getOperand(1)));
789d88c1a5aSDimitry Andric       } else {
790d88c1a5aSDimitry Andric         // The only instance this does not return a Conflict is when both the
791d88c1a5aSDimitry Andric         // vector operands are the same vector.
792d88c1a5aSDimitry Andric         auto *SV = cast<ShuffleVectorInst>(BDV);
793d88c1a5aSDimitry Andric         NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(0)));
794d88c1a5aSDimitry Andric         NewState = meetBDVState(NewState, getStateForInput(SV->getOperand(1)));
7957d523365SDimitry Andric       }
7967d523365SDimitry Andric 
7973ca95b02SDimitry Andric       BDVState OldState = States[BDV];
7983ca95b02SDimitry Andric       if (OldState != NewState) {
7993ca95b02SDimitry Andric         Progress = true;
8003ca95b02SDimitry Andric         States[BDV] = NewState;
801ff0cc061SDimitry Andric       }
802ff0cc061SDimitry Andric     }
803ff0cc061SDimitry Andric 
8043ca95b02SDimitry Andric     assert(OldSize == States.size() &&
8057d523365SDimitry Andric            "fixed point shouldn't be adding any new nodes to state");
806ff0cc061SDimitry Andric   }
807ff0cc061SDimitry Andric 
8087d523365SDimitry Andric #ifndef NDEBUG
8097d523365SDimitry Andric   DEBUG(dbgs() << "States after meet iteration:\n");
8107d523365SDimitry Andric   for (auto Pair : States) {
8117d523365SDimitry Andric     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
812ff0cc061SDimitry Andric   }
8137d523365SDimitry Andric #endif
814ff0cc061SDimitry Andric 
815ff0cc061SDimitry Andric   // Insert Phis for all conflicts
816ff0cc061SDimitry Andric   // TODO: adjust naming patterns to avoid this order of iteration dependency
8177d523365SDimitry Andric   for (auto Pair : States) {
8187d523365SDimitry Andric     Instruction *I = cast<Instruction>(Pair.first);
8197d523365SDimitry Andric     BDVState State = Pair.second;
8207d523365SDimitry Andric     assert(!isKnownBaseResult(I) && "why did it get added?");
8217d523365SDimitry Andric     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
8227d523365SDimitry Andric 
8237d523365SDimitry Andric     // extractelement instructions are a bit special in that we may need to
8247d523365SDimitry Andric     // insert an extract even when we know an exact base for the instruction.
8257d523365SDimitry Andric     // The problem is that we need to convert from a vector base to a scalar
8267d523365SDimitry Andric     // base for the particular indice we're interested in.
8277d523365SDimitry Andric     if (State.isBase() && isa<ExtractElementInst>(I) &&
8283ca95b02SDimitry Andric         isa<VectorType>(State.getBaseValue()->getType())) {
8297d523365SDimitry Andric       auto *EE = cast<ExtractElementInst>(I);
8307d523365SDimitry Andric       // TODO: In many cases, the new instruction is just EE itself.  We should
8317d523365SDimitry Andric       // exploit this, but can't do it here since it would break the invariant
8327d523365SDimitry Andric       // about the BDV not being known to be a base.
8333ca95b02SDimitry Andric       auto *BaseInst = ExtractElementInst::Create(
8343ca95b02SDimitry Andric           State.getBaseValue(), EE->getIndexOperand(), "base_ee", EE);
8357d523365SDimitry Andric       BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
8367d523365SDimitry Andric       States[I] = BDVState(BDVState::Base, BaseInst);
8377d523365SDimitry Andric     }
8387d523365SDimitry Andric 
8397d523365SDimitry Andric     // Since we're joining a vector and scalar base, they can never be the
8407d523365SDimitry Andric     // same.  As a result, we should always see insert element having reached
8417d523365SDimitry Andric     // the conflict state.
8423ca95b02SDimitry Andric     assert(!isa<InsertElementInst>(I) || State.isConflict());
8437d523365SDimitry Andric 
8447d523365SDimitry Andric     if (!State.isConflict())
845ff0cc061SDimitry Andric       continue;
846ff0cc061SDimitry Andric 
8477d523365SDimitry Andric     /// Create and insert a new instruction which will represent the base of
8487d523365SDimitry Andric     /// the given instruction 'I'.
8497d523365SDimitry Andric     auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
8507d523365SDimitry Andric       if (isa<PHINode>(I)) {
8517d523365SDimitry Andric         BasicBlock *BB = I->getParent();
8527d523365SDimitry Andric         int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
8537d523365SDimitry Andric         assert(NumPreds > 0 && "how did we reach here");
8547d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_phi");
8557d523365SDimitry Andric         return PHINode::Create(I->getType(), NumPreds, Name, I);
8563ca95b02SDimitry Andric       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
857ff0cc061SDimitry Andric         // The undef will be replaced later
8583ca95b02SDimitry Andric         UndefValue *Undef = UndefValue::get(SI->getType());
8597d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_select");
8603ca95b02SDimitry Andric         return SelectInst::Create(SI->getCondition(), Undef, Undef, Name, SI);
8617d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
8627d523365SDimitry Andric         UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
8637d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_ee");
8647d523365SDimitry Andric         return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
8657d523365SDimitry Andric                                           EE);
866d88c1a5aSDimitry Andric       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
8677d523365SDimitry Andric         UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
8687d523365SDimitry Andric         UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
8697d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_ie");
8707d523365SDimitry Andric         return InsertElementInst::Create(VecUndef, ScalarUndef,
8717d523365SDimitry Andric                                          IE->getOperand(2), Name, IE);
872d88c1a5aSDimitry Andric       } else {
873d88c1a5aSDimitry Andric         auto *SV = cast<ShuffleVectorInst>(I);
874d88c1a5aSDimitry Andric         UndefValue *VecUndef = UndefValue::get(SV->getOperand(0)->getType());
875d88c1a5aSDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_sv");
876d88c1a5aSDimitry Andric         return new ShuffleVectorInst(VecUndef, VecUndef, SV->getOperand(2),
877d88c1a5aSDimitry Andric                                      Name, SV);
8787d523365SDimitry Andric       }
8797d523365SDimitry Andric     };
8807d523365SDimitry Andric     Instruction *BaseInst = MakeBaseInstPlaceholder(I);
881ff0cc061SDimitry Andric     // Add metadata marking this as a base value
8827d523365SDimitry Andric     BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
8837d523365SDimitry Andric     States[I] = BDVState(BDVState::Conflict, BaseInst);
884ff0cc061SDimitry Andric   }
885ff0cc061SDimitry Andric 
8867d523365SDimitry Andric   // Returns a instruction which produces the base pointer for a given
8877d523365SDimitry Andric   // instruction.  The instruction is assumed to be an input to one of the BDVs
8887d523365SDimitry Andric   // seen in the inference algorithm above.  As such, we must either already
8897d523365SDimitry Andric   // know it's base defining value is a base, or have inserted a new
8907d523365SDimitry Andric   // instruction to propagate the base of it's BDV and have entered that newly
8917d523365SDimitry Andric   // introduced instruction into the state table.  In either case, we are
8927d523365SDimitry Andric   // assured to be able to determine an instruction which produces it's base
8937d523365SDimitry Andric   // pointer.
8947d523365SDimitry Andric   auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
8953ca95b02SDimitry Andric     Value *BDV = findBaseOrBDV(Input, Cache);
8967d523365SDimitry Andric     Value *Base = nullptr;
8977d523365SDimitry Andric     if (isKnownBaseResult(BDV)) {
8987d523365SDimitry Andric       Base = BDV;
8997d523365SDimitry Andric     } else {
9007d523365SDimitry Andric       // Either conflict or base.
9017d523365SDimitry Andric       assert(States.count(BDV));
9023ca95b02SDimitry Andric       Base = States[BDV].getBaseValue();
9037d523365SDimitry Andric     }
9043ca95b02SDimitry Andric     assert(Base && "Can't be null");
9057d523365SDimitry Andric     // The cast is needed since base traversal may strip away bitcasts
9063ca95b02SDimitry Andric     if (Base->getType() != Input->getType() && InsertPt)
9073ca95b02SDimitry Andric       Base = new BitCastInst(Base, Input->getType(), "cast", InsertPt);
9087d523365SDimitry Andric     return Base;
9097d523365SDimitry Andric   };
910ff0cc061SDimitry Andric 
9117d523365SDimitry Andric   // Fixup all the inputs of the new PHIs.  Visit order needs to be
9127d523365SDimitry Andric   // deterministic and predictable because we're naming newly created
9137d523365SDimitry Andric   // instructions.
9147d523365SDimitry Andric   for (auto Pair : States) {
9157d523365SDimitry Andric     Instruction *BDV = cast<Instruction>(Pair.first);
9167d523365SDimitry Andric     BDVState State = Pair.second;
9177d523365SDimitry Andric 
9187d523365SDimitry Andric     assert(!isKnownBaseResult(BDV) && "why did it get added?");
9197d523365SDimitry Andric     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
9207d523365SDimitry Andric     if (!State.isConflict())
921ff0cc061SDimitry Andric       continue;
922ff0cc061SDimitry Andric 
9233ca95b02SDimitry Andric     if (PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
9243ca95b02SDimitry Andric       PHINode *PN = cast<PHINode>(BDV);
9253ca95b02SDimitry Andric       unsigned NumPHIValues = PN->getNumIncomingValues();
926ff0cc061SDimitry Andric       for (unsigned i = 0; i < NumPHIValues; i++) {
9273ca95b02SDimitry Andric         Value *InVal = PN->getIncomingValue(i);
9283ca95b02SDimitry Andric         BasicBlock *InBB = PN->getIncomingBlock(i);
929ff0cc061SDimitry Andric 
930ff0cc061SDimitry Andric         // If we've already seen InBB, add the same incoming value
931ff0cc061SDimitry Andric         // we added for it earlier.  The IR verifier requires phi
932ff0cc061SDimitry Andric         // nodes with multiple entries from the same basic block
933ff0cc061SDimitry Andric         // to have the same incoming value for each of those
934ff0cc061SDimitry Andric         // entries.  If we don't do this check here and basephi
935ff0cc061SDimitry Andric         // has a different type than base, we'll end up adding two
936ff0cc061SDimitry Andric         // bitcasts (and hence two distinct values) as incoming
937ff0cc061SDimitry Andric         // values for the same basic block.
938ff0cc061SDimitry Andric 
9393ca95b02SDimitry Andric         int BlockIndex = BasePHI->getBasicBlockIndex(InBB);
9403ca95b02SDimitry Andric         if (BlockIndex != -1) {
9413ca95b02SDimitry Andric           Value *OldBase = BasePHI->getIncomingValue(BlockIndex);
9423ca95b02SDimitry Andric           BasePHI->addIncoming(OldBase, InBB);
943ff0cc061SDimitry Andric 
9447d523365SDimitry Andric #ifndef NDEBUG
9457d523365SDimitry Andric           Value *Base = getBaseForInput(InVal, nullptr);
9463ca95b02SDimitry Andric           // In essence this assert states: the only way two values
9473ca95b02SDimitry Andric           // incoming from the same basic block may be different is by
9483ca95b02SDimitry Andric           // being different bitcasts of the same value.  A cleanup
9493ca95b02SDimitry Andric           // that remains TODO is changing findBaseOrBDV to return an
9503ca95b02SDimitry Andric           // llvm::Value of the correct type (and still remain pure).
9513ca95b02SDimitry Andric           // This will remove the need to add bitcasts.
9523ca95b02SDimitry Andric           assert(Base->stripPointerCasts() == OldBase->stripPointerCasts() &&
9533ca95b02SDimitry Andric                  "Sanity -- findBaseOrBDV should be pure!");
954ff0cc061SDimitry Andric #endif
955ff0cc061SDimitry Andric           continue;
956ff0cc061SDimitry Andric         }
957ff0cc061SDimitry Andric 
9587d523365SDimitry Andric         // Find the instruction which produces the base for each input.  We may
9597d523365SDimitry Andric         // need to insert a bitcast in the incoming block.
9607d523365SDimitry Andric         // TODO: Need to split critical edges if insertion is needed
9617d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, InBB->getTerminator());
9623ca95b02SDimitry Andric         BasePHI->addIncoming(Base, InBB);
963ff0cc061SDimitry Andric       }
9643ca95b02SDimitry Andric       assert(BasePHI->getNumIncomingValues() == NumPHIValues);
9653ca95b02SDimitry Andric     } else if (SelectInst *BaseSI =
9663ca95b02SDimitry Andric                    dyn_cast<SelectInst>(State.getBaseValue())) {
9673ca95b02SDimitry Andric       SelectInst *SI = cast<SelectInst>(BDV);
9683ca95b02SDimitry Andric 
9693ca95b02SDimitry Andric       // Find the instruction which produces the base for each input.
9703ca95b02SDimitry Andric       // We may need to insert a bitcast.
9713ca95b02SDimitry Andric       BaseSI->setTrueValue(getBaseForInput(SI->getTrueValue(), BaseSI));
9723ca95b02SDimitry Andric       BaseSI->setFalseValue(getBaseForInput(SI->getFalseValue(), BaseSI));
9733ca95b02SDimitry Andric     } else if (auto *BaseEE =
9743ca95b02SDimitry Andric                    dyn_cast<ExtractElementInst>(State.getBaseValue())) {
9757d523365SDimitry Andric       Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
9767d523365SDimitry Andric       // Find the instruction which produces the base for each input.  We may
9777d523365SDimitry Andric       // need to insert a bitcast.
9783ca95b02SDimitry Andric       BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
979d88c1a5aSDimitry Andric     } else if (auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
9807d523365SDimitry Andric       auto *BdvIE = cast<InsertElementInst>(BDV);
9817d523365SDimitry Andric       auto UpdateOperand = [&](int OperandIdx) {
9827d523365SDimitry Andric         Value *InVal = BdvIE->getOperand(OperandIdx);
9837d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, BaseIE);
9847d523365SDimitry Andric         BaseIE->setOperand(OperandIdx, Base);
9857d523365SDimitry Andric       };
9867d523365SDimitry Andric       UpdateOperand(0); // vector operand
9877d523365SDimitry Andric       UpdateOperand(1); // scalar operand
988d88c1a5aSDimitry Andric     } else {
989d88c1a5aSDimitry Andric       auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
990d88c1a5aSDimitry Andric       auto *BdvSV = cast<ShuffleVectorInst>(BDV);
991d88c1a5aSDimitry Andric       auto UpdateOperand = [&](int OperandIdx) {
992d88c1a5aSDimitry Andric         Value *InVal = BdvSV->getOperand(OperandIdx);
993d88c1a5aSDimitry Andric         Value *Base = getBaseForInput(InVal, BaseSV);
994d88c1a5aSDimitry Andric         BaseSV->setOperand(OperandIdx, Base);
995d88c1a5aSDimitry Andric       };
996d88c1a5aSDimitry Andric       UpdateOperand(0); // vector operand
997d88c1a5aSDimitry Andric       UpdateOperand(1); // vector operand
998ff0cc061SDimitry Andric     }
999ff0cc061SDimitry Andric   }
1000ff0cc061SDimitry Andric 
1001ff0cc061SDimitry Andric   // Cache all of our results so we can cheaply reuse them
1002ff0cc061SDimitry Andric   // NOTE: This is actually two caches: one of the base defining value
1003ff0cc061SDimitry Andric   // relation and one of the base pointer relation!  FIXME
10047d523365SDimitry Andric   for (auto Pair : States) {
10057d523365SDimitry Andric     auto *BDV = Pair.first;
10063ca95b02SDimitry Andric     Value *Base = Pair.second.getBaseValue();
10073ca95b02SDimitry Andric     assert(BDV && Base);
10083ca95b02SDimitry Andric     assert(!isKnownBaseResult(BDV) && "why did it get added?");
1009ff0cc061SDimitry Andric 
10107d523365SDimitry Andric     DEBUG(dbgs() << "Updating base value cache"
10113ca95b02SDimitry Andric                  << " for: " << BDV->getName() << " from: "
10123ca95b02SDimitry Andric                  << (Cache.count(BDV) ? Cache[BDV]->getName().str() : "none")
10133ca95b02SDimitry Andric                  << " to: " << Base->getName() << "\n");
1014ff0cc061SDimitry Andric 
10153ca95b02SDimitry Andric     if (Cache.count(BDV)) {
10163ca95b02SDimitry Andric       assert(isKnownBaseResult(Base) &&
10173ca95b02SDimitry Andric              "must be something we 'know' is a base pointer");
10183ca95b02SDimitry Andric       // Once we transition from the BDV relation being store in the Cache to
1019ff0cc061SDimitry Andric       // the base relation being stored, it must be stable
10203ca95b02SDimitry Andric       assert((!isKnownBaseResult(Cache[BDV]) || Cache[BDV] == Base) &&
1021ff0cc061SDimitry Andric              "base relation should be stable");
1022ff0cc061SDimitry Andric     }
10233ca95b02SDimitry Andric     Cache[BDV] = Base;
1024ff0cc061SDimitry Andric   }
10253ca95b02SDimitry Andric   assert(Cache.count(Def));
10263ca95b02SDimitry Andric   return Cache[Def];
1027ff0cc061SDimitry Andric }
1028ff0cc061SDimitry Andric 
1029ff0cc061SDimitry Andric // For a set of live pointers (base and/or derived), identify the base
1030ff0cc061SDimitry Andric // pointer of the object which they are derived from.  This routine will
1031ff0cc061SDimitry Andric // mutate the IR graph as needed to make the 'base' pointer live at the
1032ff0cc061SDimitry Andric // definition site of 'derived'.  This ensures that any use of 'derived' can
1033ff0cc061SDimitry Andric // also use 'base'.  This may involve the insertion of a number of
1034ff0cc061SDimitry Andric // additional PHI nodes.
1035ff0cc061SDimitry Andric //
1036ff0cc061SDimitry Andric // preconditions: live is a set of pointer type Values
1037ff0cc061SDimitry Andric //
1038ff0cc061SDimitry Andric // side effects: may insert PHI nodes into the existing CFG, will preserve
1039ff0cc061SDimitry Andric // CFG, will not remove or mutate any existing nodes
1040ff0cc061SDimitry Andric //
1041ff0cc061SDimitry Andric // post condition: PointerToBase contains one (derived, base) pair for every
1042ff0cc061SDimitry Andric // pointer in live.  Note that derived can be equal to base if the original
1043ff0cc061SDimitry Andric // pointer was a base pointer.
1044ff0cc061SDimitry Andric static void
1045ff0cc061SDimitry Andric findBasePointers(const StatepointLiveSetTy &live,
10463ca95b02SDimitry Andric                  MapVector<Value *, Value *> &PointerToBase,
1047ff0cc061SDimitry Andric                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
10483ca95b02SDimitry Andric   for (Value *ptr : live) {
1049ff0cc061SDimitry Andric     Value *base = findBasePointer(ptr, DVCache);
1050ff0cc061SDimitry Andric     assert(base && "failed to find base pointer");
1051ff0cc061SDimitry Andric     PointerToBase[ptr] = base;
1052ff0cc061SDimitry Andric     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1053ff0cc061SDimitry Andric             DT->dominates(cast<Instruction>(base)->getParent(),
1054ff0cc061SDimitry Andric                           cast<Instruction>(ptr)->getParent())) &&
1055ff0cc061SDimitry Andric            "The base we found better dominate the derived pointer");
1056ff0cc061SDimitry Andric   }
1057ff0cc061SDimitry Andric }
1058ff0cc061SDimitry Andric 
1059ff0cc061SDimitry Andric /// Find the required based pointers (and adjust the live set) for the given
1060ff0cc061SDimitry Andric /// parse point.
1061ff0cc061SDimitry Andric static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
10623ca95b02SDimitry Andric                              CallSite CS,
1063ff0cc061SDimitry Andric                              PartiallyConstructedSafepointRecord &result) {
10643ca95b02SDimitry Andric   MapVector<Value *, Value *> PointerToBase;
10657d523365SDimitry Andric   findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
1066ff0cc061SDimitry Andric 
1067ff0cc061SDimitry Andric   if (PrintBasePointers) {
1068ff0cc061SDimitry Andric     errs() << "Base Pairs (w/o Relocation):\n";
10693ca95b02SDimitry Andric     for (auto &Pair : PointerToBase) {
10707d523365SDimitry Andric       errs() << " derived ";
10713ca95b02SDimitry Andric       Pair.first->printAsOperand(errs(), false);
10727d523365SDimitry Andric       errs() << " base ";
10733ca95b02SDimitry Andric       Pair.second->printAsOperand(errs(), false);
10747d523365SDimitry Andric       errs() << "\n";;
1075ff0cc061SDimitry Andric     }
1076ff0cc061SDimitry Andric   }
1077ff0cc061SDimitry Andric 
1078ff0cc061SDimitry Andric   result.PointerToBase = PointerToBase;
1079ff0cc061SDimitry Andric }
1080ff0cc061SDimitry Andric 
1081ff0cc061SDimitry Andric /// Given an updated version of the dataflow liveness results, update the
1082ff0cc061SDimitry Andric /// liveset and base pointer maps for the call site CS.
1083ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
10843ca95b02SDimitry Andric                                   CallSite CS,
1085ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &result);
1086ff0cc061SDimitry Andric 
1087ff0cc061SDimitry Andric static void recomputeLiveInValues(
10887d523365SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1089ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1090ff0cc061SDimitry Andric   // TODO-PERF: reuse the original liveness, then simply run the dataflow
10917d523365SDimitry Andric   // again.  The old values are still live and will help it stabilize quickly.
1092ff0cc061SDimitry Andric   GCPtrLivenessData RevisedLivenessData;
1093ff0cc061SDimitry Andric   computeLiveInValues(DT, F, RevisedLivenessData);
1094ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1095ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
10963ca95b02SDimitry Andric     recomputeLiveInValues(RevisedLivenessData, toUpdate[i], info);
1097ff0cc061SDimitry Andric   }
1098ff0cc061SDimitry Andric }
1099ff0cc061SDimitry Andric 
11007d523365SDimitry Andric // When inserting gc.relocate and gc.result calls, we need to ensure there are
11017d523365SDimitry Andric // no uses of the original value / return value between the gc.statepoint and
11027d523365SDimitry Andric // the gc.relocate / gc.result call.  One case which can arise is a phi node
11037d523365SDimitry Andric // starting one of the successor blocks.  We also need to be able to insert the
11047d523365SDimitry Andric // gc.relocates only on the path which goes through the statepoint.  We might
11057d523365SDimitry Andric // need to split an edge to make this possible.
1106ff0cc061SDimitry Andric static BasicBlock *
110797bc6c73SDimitry Andric normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
110897bc6c73SDimitry Andric                             DominatorTree &DT) {
1109ff0cc061SDimitry Andric   BasicBlock *Ret = BB;
11107d523365SDimitry Andric   if (!BB->getUniquePredecessor())
11117d523365SDimitry Andric     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1112ff0cc061SDimitry Andric 
11137d523365SDimitry Andric   // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1114ff0cc061SDimitry Andric   // from it
1115ff0cc061SDimitry Andric   FoldSingleEntryPHINodes(Ret);
11167d523365SDimitry Andric   assert(!isa<PHINode>(Ret->begin()) &&
11177d523365SDimitry Andric          "All PHI nodes should have been removed!");
1118ff0cc061SDimitry Andric 
11197d523365SDimitry Andric   // At this point, we can safely insert a gc.relocate or gc.result as the first
11207d523365SDimitry Andric   // instruction in Ret if needed.
1121ff0cc061SDimitry Andric   return Ret;
1122ff0cc061SDimitry Andric }
1123ff0cc061SDimitry Andric 
11247d523365SDimitry Andric // Create new attribute set containing only attributes which can be transferred
1125ff0cc061SDimitry Andric // from original call to the safepoint.
1126ff0cc061SDimitry Andric static AttributeSet legalizeCallAttributes(AttributeSet AS) {
11277d523365SDimitry Andric   AttributeSet Ret;
1128ff0cc061SDimitry Andric 
1129ff0cc061SDimitry Andric   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
11307d523365SDimitry Andric     unsigned Index = AS.getSlotIndex(Slot);
1131ff0cc061SDimitry Andric 
11327d523365SDimitry Andric     if (Index == AttributeSet::ReturnIndex ||
11337d523365SDimitry Andric         Index == AttributeSet::FunctionIndex) {
1134ff0cc061SDimitry Andric 
11357d523365SDimitry Andric       for (Attribute Attr : make_range(AS.begin(Slot), AS.end(Slot))) {
1136ff0cc061SDimitry Andric 
1137ff0cc061SDimitry Andric         // Do not allow certain attributes - just skip them
1138ff0cc061SDimitry Andric         // Safepoint can not be read only or read none.
11397d523365SDimitry Andric         if (Attr.hasAttribute(Attribute::ReadNone) ||
11407d523365SDimitry Andric             Attr.hasAttribute(Attribute::ReadOnly))
1141ff0cc061SDimitry Andric           continue;
1142ff0cc061SDimitry Andric 
11437d523365SDimitry Andric         // These attributes control the generation of the gc.statepoint call /
11447d523365SDimitry Andric         // invoke itself; and once the gc.statepoint is in place, they're of no
11457d523365SDimitry Andric         // use.
11463ca95b02SDimitry Andric         if (isStatepointDirectiveAttr(Attr))
11477d523365SDimitry Andric           continue;
11487d523365SDimitry Andric 
11497d523365SDimitry Andric         Ret = Ret.addAttributes(
11507d523365SDimitry Andric             AS.getContext(), Index,
11517d523365SDimitry Andric             AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
1152ff0cc061SDimitry Andric       }
1153ff0cc061SDimitry Andric     }
1154ff0cc061SDimitry Andric 
1155ff0cc061SDimitry Andric     // Just skip parameter attributes for now
1156ff0cc061SDimitry Andric   }
1157ff0cc061SDimitry Andric 
11587d523365SDimitry Andric   return Ret;
1159ff0cc061SDimitry Andric }
1160ff0cc061SDimitry Andric 
1161ff0cc061SDimitry Andric /// Helper function to place all gc relocates necessary for the given
1162ff0cc061SDimitry Andric /// statepoint.
1163ff0cc061SDimitry Andric /// Inputs:
1164ff0cc061SDimitry Andric ///   liveVariables - list of variables to be relocated.
1165ff0cc061SDimitry Andric ///   liveStart - index of the first live variable.
1166ff0cc061SDimitry Andric ///   basePtrs - base pointers.
1167ff0cc061SDimitry Andric ///   statepointToken - statepoint instruction to which relocates should be
1168ff0cc061SDimitry Andric ///   bound.
1169ff0cc061SDimitry Andric ///   Builder - Llvm IR builder to be used to construct new calls.
11707d523365SDimitry Andric static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1171ff0cc061SDimitry Andric                               const int LiveStart,
11727d523365SDimitry Andric                               ArrayRef<Value *> BasePtrs,
1173ff0cc061SDimitry Andric                               Instruction *StatepointToken,
1174ff0cc061SDimitry Andric                               IRBuilder<> Builder) {
11757d523365SDimitry Andric   if (LiveVariables.empty())
11767d523365SDimitry Andric     return;
1177ff0cc061SDimitry Andric 
11787d523365SDimitry Andric   auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1179d88c1a5aSDimitry Andric     auto ValIt = find(LiveVec, Val);
11807d523365SDimitry Andric     assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
11817d523365SDimitry Andric     size_t Index = std::distance(LiveVec.begin(), ValIt);
11827d523365SDimitry Andric     assert(Index < LiveVec.size() && "Bug in std::find?");
11837d523365SDimitry Andric     return Index;
11847d523365SDimitry Andric   };
11857d523365SDimitry Andric   Module *M = StatepointToken->getModule();
1186444ed5c5SDimitry Andric 
1187444ed5c5SDimitry Andric   // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1188444ed5c5SDimitry Andric   // element type is i8 addrspace(1)*). We originally generated unique
1189444ed5c5SDimitry Andric   // declarations for each pointer type, but this proved problematic because
1190444ed5c5SDimitry Andric   // the intrinsic mangling code is incomplete and fragile.  Since we're moving
1191444ed5c5SDimitry Andric   // towards a single unified pointer type anyways, we can just cast everything
1192444ed5c5SDimitry Andric   // to an i8* of the right address space.  A bitcast is added later to convert
1193444ed5c5SDimitry Andric   // gc_relocate to the actual value's type.
1194444ed5c5SDimitry Andric   auto getGCRelocateDecl = [&] (Type *Ty) {
1195444ed5c5SDimitry Andric     assert(isHandledGCPointerType(Ty));
1196444ed5c5SDimitry Andric     auto AS = Ty->getScalarType()->getPointerAddressSpace();
1197444ed5c5SDimitry Andric     Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1198444ed5c5SDimitry Andric     if (auto *VT = dyn_cast<VectorType>(Ty))
1199444ed5c5SDimitry Andric       NewTy = VectorType::get(NewTy, VT->getNumElements());
1200444ed5c5SDimitry Andric     return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1201444ed5c5SDimitry Andric                                      {NewTy});
1202444ed5c5SDimitry Andric   };
1203444ed5c5SDimitry Andric 
1204444ed5c5SDimitry Andric   // Lazily populated map from input types to the canonicalized form mentioned
1205444ed5c5SDimitry Andric   // in the comment above.  This should probably be cached somewhere more
1206444ed5c5SDimitry Andric   // broadly.
1207444ed5c5SDimitry Andric   DenseMap<Type*, Value*> TypeToDeclMap;
1208ff0cc061SDimitry Andric 
1209ff0cc061SDimitry Andric   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1210ff0cc061SDimitry Andric     // Generate the gc.relocate call and save the result
1211ff0cc061SDimitry Andric     Value *BaseIdx =
12127d523365SDimitry Andric       Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
12137d523365SDimitry Andric     Value *LiveIdx = Builder.getInt32(LiveStart + i);
1214ff0cc061SDimitry Andric 
1215444ed5c5SDimitry Andric     Type *Ty = LiveVariables[i]->getType();
1216444ed5c5SDimitry Andric     if (!TypeToDeclMap.count(Ty))
1217444ed5c5SDimitry Andric       TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1218444ed5c5SDimitry Andric     Value *GCRelocateDecl = TypeToDeclMap[Ty];
1219444ed5c5SDimitry Andric 
1220ff0cc061SDimitry Andric     // only specify a debug name if we can give a useful one
12217d523365SDimitry Andric     CallInst *Reloc = Builder.CreateCall(
1222ff0cc061SDimitry Andric         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
12237d523365SDimitry Andric         suffixed_name_or(LiveVariables[i], ".relocated", ""));
1224ff0cc061SDimitry Andric     // Trick CodeGen into thinking there are lots of free registers at this
1225ff0cc061SDimitry Andric     // fake call.
12267d523365SDimitry Andric     Reloc->setCallingConv(CallingConv::Cold);
1227ff0cc061SDimitry Andric   }
12287d523365SDimitry Andric }
12297d523365SDimitry Andric 
12307d523365SDimitry Andric namespace {
12317d523365SDimitry Andric 
12327d523365SDimitry Andric /// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
12337d523365SDimitry Andric /// avoids having to worry about keeping around dangling pointers to Values.
12347d523365SDimitry Andric class DeferredReplacement {
12357d523365SDimitry Andric   AssertingVH<Instruction> Old;
12367d523365SDimitry Andric   AssertingVH<Instruction> New;
12373ca95b02SDimitry Andric   bool IsDeoptimize = false;
12383ca95b02SDimitry Andric 
12393ca95b02SDimitry Andric   DeferredReplacement() {}
12407d523365SDimitry Andric 
12417d523365SDimitry Andric public:
12423ca95b02SDimitry Andric   static DeferredReplacement createRAUW(Instruction *Old, Instruction *New) {
12433ca95b02SDimitry Andric     assert(Old != New && Old && New &&
12443ca95b02SDimitry Andric            "Cannot RAUW equal values or to / from null!");
12453ca95b02SDimitry Andric 
12463ca95b02SDimitry Andric     DeferredReplacement D;
12473ca95b02SDimitry Andric     D.Old = Old;
12483ca95b02SDimitry Andric     D.New = New;
12493ca95b02SDimitry Andric     return D;
12503ca95b02SDimitry Andric   }
12513ca95b02SDimitry Andric 
12523ca95b02SDimitry Andric   static DeferredReplacement createDelete(Instruction *ToErase) {
12533ca95b02SDimitry Andric     DeferredReplacement D;
12543ca95b02SDimitry Andric     D.Old = ToErase;
12553ca95b02SDimitry Andric     return D;
12563ca95b02SDimitry Andric   }
12573ca95b02SDimitry Andric 
12583ca95b02SDimitry Andric   static DeferredReplacement createDeoptimizeReplacement(Instruction *Old) {
12593ca95b02SDimitry Andric #ifndef NDEBUG
12603ca95b02SDimitry Andric     auto *F = cast<CallInst>(Old)->getCalledFunction();
12613ca95b02SDimitry Andric     assert(F && F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
12623ca95b02SDimitry Andric            "Only way to construct a deoptimize deferred replacement");
12633ca95b02SDimitry Andric #endif
12643ca95b02SDimitry Andric     DeferredReplacement D;
12653ca95b02SDimitry Andric     D.Old = Old;
12663ca95b02SDimitry Andric     D.IsDeoptimize = true;
12673ca95b02SDimitry Andric     return D;
12687d523365SDimitry Andric   }
12697d523365SDimitry Andric 
12707d523365SDimitry Andric   /// Does the task represented by this instance.
12717d523365SDimitry Andric   void doReplacement() {
12727d523365SDimitry Andric     Instruction *OldI = Old;
12737d523365SDimitry Andric     Instruction *NewI = New;
12747d523365SDimitry Andric 
12757d523365SDimitry Andric     assert(OldI != NewI && "Disallowed at construction?!");
12763ca95b02SDimitry Andric     assert((!IsDeoptimize || !New) &&
12773ca95b02SDimitry Andric            "Deoptimize instrinsics are not replaced!");
12787d523365SDimitry Andric 
12797d523365SDimitry Andric     Old = nullptr;
12807d523365SDimitry Andric     New = nullptr;
12817d523365SDimitry Andric 
12827d523365SDimitry Andric     if (NewI)
12837d523365SDimitry Andric       OldI->replaceAllUsesWith(NewI);
12843ca95b02SDimitry Andric 
12853ca95b02SDimitry Andric     if (IsDeoptimize) {
12863ca95b02SDimitry Andric       // Note: we've inserted instructions, so the call to llvm.deoptimize may
12873ca95b02SDimitry Andric       // not necessarilly be followed by the matching return.
12883ca95b02SDimitry Andric       auto *RI = cast<ReturnInst>(OldI->getParent()->getTerminator());
12893ca95b02SDimitry Andric       new UnreachableInst(RI->getContext(), RI);
12903ca95b02SDimitry Andric       RI->eraseFromParent();
12913ca95b02SDimitry Andric     }
12923ca95b02SDimitry Andric 
12937d523365SDimitry Andric     OldI->eraseFromParent();
12947d523365SDimitry Andric   }
12957d523365SDimitry Andric };
1296ff0cc061SDimitry Andric }
1297ff0cc061SDimitry Andric 
1298d88c1a5aSDimitry Andric static StringRef getDeoptLowering(CallSite CS) {
1299d88c1a5aSDimitry Andric   const char *DeoptLowering = "deopt-lowering";
1300d88c1a5aSDimitry Andric   if (CS.hasFnAttr(DeoptLowering)) {
1301d88c1a5aSDimitry Andric     // FIXME: CallSite has a *really* confusing interface around attributes
1302d88c1a5aSDimitry Andric     // with values.
1303d88c1a5aSDimitry Andric     const AttributeSet &CSAS = CS.getAttributes();
1304d88c1a5aSDimitry Andric     if (CSAS.hasAttribute(AttributeSet::FunctionIndex,
1305d88c1a5aSDimitry Andric                           DeoptLowering))
1306d88c1a5aSDimitry Andric       return CSAS.getAttribute(AttributeSet::FunctionIndex,
1307d88c1a5aSDimitry Andric                                DeoptLowering).getValueAsString();
1308d88c1a5aSDimitry Andric     Function *F = CS.getCalledFunction();
1309d88c1a5aSDimitry Andric     assert(F && F->hasFnAttribute(DeoptLowering));
1310d88c1a5aSDimitry Andric     return F->getFnAttribute(DeoptLowering).getValueAsString();
1311d88c1a5aSDimitry Andric   }
1312d88c1a5aSDimitry Andric   return "live-through";
1313d88c1a5aSDimitry Andric }
1314d88c1a5aSDimitry Andric 
1315d88c1a5aSDimitry Andric 
1316ff0cc061SDimitry Andric static void
13177d523365SDimitry Andric makeStatepointExplicitImpl(const CallSite CS, /* to replace */
13187d523365SDimitry Andric                            const SmallVectorImpl<Value *> &BasePtrs,
13197d523365SDimitry Andric                            const SmallVectorImpl<Value *> &LiveVariables,
13207d523365SDimitry Andric                            PartiallyConstructedSafepointRecord &Result,
13217d523365SDimitry Andric                            std::vector<DeferredReplacement> &Replacements) {
13227d523365SDimitry Andric   assert(BasePtrs.size() == LiveVariables.size());
1323ff0cc061SDimitry Andric 
1324ff0cc061SDimitry Andric   // Then go ahead and use the builder do actually do the inserts.  We insert
1325ff0cc061SDimitry Andric   // immediately before the previous instruction under the assumption that all
1326ff0cc061SDimitry Andric   // arguments will be available here.  We can't insert afterwards since we may
1327ff0cc061SDimitry Andric   // be replacing a terminator.
13287d523365SDimitry Andric   Instruction *InsertBefore = CS.getInstruction();
13297d523365SDimitry Andric   IRBuilder<> Builder(InsertBefore);
1330ff0cc061SDimitry Andric 
13317d523365SDimitry Andric   ArrayRef<Value *> GCArgs(LiveVariables);
13323ca95b02SDimitry Andric   uint64_t StatepointID = StatepointDirectives::DefaultStatepointID;
13337d523365SDimitry Andric   uint32_t NumPatchBytes = 0;
13347d523365SDimitry Andric   uint32_t Flags = uint32_t(StatepointFlags::None);
13357d523365SDimitry Andric 
13363ca95b02SDimitry Andric   ArrayRef<Use> CallArgs(CS.arg_begin(), CS.arg_end());
13373ca95b02SDimitry Andric   ArrayRef<Use> DeoptArgs = GetDeoptBundleOperands(CS);
13387d523365SDimitry Andric   ArrayRef<Use> TransitionArgs;
13393ca95b02SDimitry Andric   if (auto TransitionBundle =
13403ca95b02SDimitry Andric       CS.getOperandBundle(LLVMContext::OB_gc_transition)) {
13413ca95b02SDimitry Andric     Flags |= uint32_t(StatepointFlags::GCTransition);
13423ca95b02SDimitry Andric     TransitionArgs = TransitionBundle->Inputs;
13433ca95b02SDimitry Andric   }
13447d523365SDimitry Andric 
13453ca95b02SDimitry Andric   // Instead of lowering calls to @llvm.experimental.deoptimize as normal calls
13463ca95b02SDimitry Andric   // with a return value, we lower then as never returning calls to
13473ca95b02SDimitry Andric   // __llvm_deoptimize that are followed by unreachable to get better codegen.
13483ca95b02SDimitry Andric   bool IsDeoptimize = false;
13497d523365SDimitry Andric 
13503ca95b02SDimitry Andric   StatepointDirectives SD =
13513ca95b02SDimitry Andric       parseStatepointDirectivesFromAttrs(CS.getAttributes());
13523ca95b02SDimitry Andric   if (SD.NumPatchBytes)
13533ca95b02SDimitry Andric     NumPatchBytes = *SD.NumPatchBytes;
13543ca95b02SDimitry Andric   if (SD.StatepointID)
13553ca95b02SDimitry Andric     StatepointID = *SD.StatepointID;
13567d523365SDimitry Andric 
1357d88c1a5aSDimitry Andric   // Pass through the requested lowering if any.  The default is live-through.
1358d88c1a5aSDimitry Andric   StringRef DeoptLowering = getDeoptLowering(CS);
1359d88c1a5aSDimitry Andric   if (DeoptLowering.equals("live-in"))
1360d88c1a5aSDimitry Andric     Flags |= uint32_t(StatepointFlags::DeoptLiveIn);
1361d88c1a5aSDimitry Andric   else {
1362d88c1a5aSDimitry Andric     assert(DeoptLowering.equals("live-through") && "Unsupported value!");
1363d88c1a5aSDimitry Andric   }
1364d88c1a5aSDimitry Andric 
13653ca95b02SDimitry Andric   Value *CallTarget = CS.getCalledValue();
13663ca95b02SDimitry Andric   if (Function *F = dyn_cast<Function>(CallTarget)) {
13673ca95b02SDimitry Andric     if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize) {
13683ca95b02SDimitry Andric       // Calls to llvm.experimental.deoptimize are lowered to calls to the
13693ca95b02SDimitry Andric       // __llvm_deoptimize symbol.  We want to resolve this now, since the
13703ca95b02SDimitry Andric       // verifier does not allow taking the address of an intrinsic function.
13717d523365SDimitry Andric 
13723ca95b02SDimitry Andric       SmallVector<Type *, 8> DomainTy;
13733ca95b02SDimitry Andric       for (Value *Arg : CallArgs)
13743ca95b02SDimitry Andric         DomainTy.push_back(Arg->getType());
13753ca95b02SDimitry Andric       auto *FTy = FunctionType::get(Type::getVoidTy(F->getContext()), DomainTy,
13763ca95b02SDimitry Andric                                     /* isVarArg = */ false);
13777d523365SDimitry Andric 
13783ca95b02SDimitry Andric       // Note: CallTarget can be a bitcast instruction of a symbol if there are
13793ca95b02SDimitry Andric       // calls to @llvm.experimental.deoptimize with different argument types in
13803ca95b02SDimitry Andric       // the same module.  This is fine -- we assume the frontend knew what it
13813ca95b02SDimitry Andric       // was doing when generating this kind of IR.
13823ca95b02SDimitry Andric       CallTarget =
13833ca95b02SDimitry Andric           F->getParent()->getOrInsertFunction("__llvm_deoptimize", FTy);
13847d523365SDimitry Andric 
13853ca95b02SDimitry Andric       IsDeoptimize = true;
13863ca95b02SDimitry Andric     }
13877d523365SDimitry Andric   }
1388ff0cc061SDimitry Andric 
1389ff0cc061SDimitry Andric   // Create the statepoint given all the arguments
13907d523365SDimitry Andric   Instruction *Token = nullptr;
13917d523365SDimitry Andric   AttributeSet ReturnAttrs;
1392ff0cc061SDimitry Andric   if (CS.isCall()) {
13937d523365SDimitry Andric     CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
13947d523365SDimitry Andric     CallInst *Call = Builder.CreateGCStatepointCall(
13957d523365SDimitry Andric         StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
13967d523365SDimitry Andric         TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
13977d523365SDimitry Andric 
1398d88c1a5aSDimitry Andric     Call->setTailCallKind(ToReplace->getTailCallKind());
13997d523365SDimitry Andric     Call->setCallingConv(ToReplace->getCallingConv());
1400ff0cc061SDimitry Andric 
1401ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1402ff0cc061SDimitry Andric     // function attributes.
14037d523365SDimitry Andric     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
14047d523365SDimitry Andric     // In case if we can handle this set of attributes - set up function attrs
1405ff0cc061SDimitry Andric     // directly on statepoint and return attrs later for gc_result intrinsic.
14067d523365SDimitry Andric     Call->setAttributes(NewAttrs.getFnAttributes());
14077d523365SDimitry Andric     ReturnAttrs = NewAttrs.getRetAttributes();
1408ff0cc061SDimitry Andric 
14097d523365SDimitry Andric     Token = Call;
1410ff0cc061SDimitry Andric 
1411ff0cc061SDimitry Andric     // Put the following gc_result and gc_relocate calls immediately after the
1412ff0cc061SDimitry Andric     // the old call (which we're about to delete)
14137d523365SDimitry Andric     assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
14147d523365SDimitry Andric     Builder.SetInsertPoint(ToReplace->getNextNode());
14157d523365SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
1416ff0cc061SDimitry Andric   } else {
14177d523365SDimitry Andric     InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
1418ff0cc061SDimitry Andric 
1419ff0cc061SDimitry Andric     // Insert the new invoke into the old block.  We'll remove the old one in a
1420ff0cc061SDimitry Andric     // moment at which point this will become the new terminator for the
1421ff0cc061SDimitry Andric     // original block.
14227d523365SDimitry Andric     InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
14237d523365SDimitry Andric         StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
14247d523365SDimitry Andric         ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
14257d523365SDimitry Andric         GCArgs, "statepoint_token");
14267d523365SDimitry Andric 
14277d523365SDimitry Andric     Invoke->setCallingConv(ToReplace->getCallingConv());
1428ff0cc061SDimitry Andric 
1429ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1430ff0cc061SDimitry Andric     // function attributes.
14317d523365SDimitry Andric     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
14327d523365SDimitry Andric     // In case if we can handle this set of attributes - set up function attrs
1433ff0cc061SDimitry Andric     // directly on statepoint and return attrs later for gc_result intrinsic.
14347d523365SDimitry Andric     Invoke->setAttributes(NewAttrs.getFnAttributes());
14357d523365SDimitry Andric     ReturnAttrs = NewAttrs.getRetAttributes();
1436ff0cc061SDimitry Andric 
14377d523365SDimitry Andric     Token = Invoke;
1438ff0cc061SDimitry Andric 
1439ff0cc061SDimitry Andric     // Generate gc relocates in exceptional path
14407d523365SDimitry Andric     BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
14417d523365SDimitry Andric     assert(!isa<PHINode>(UnwindBlock->begin()) &&
14427d523365SDimitry Andric            UnwindBlock->getUniquePredecessor() &&
1443ff0cc061SDimitry Andric            "can't safely insert in this block!");
1444ff0cc061SDimitry Andric 
14457d523365SDimitry Andric     Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
14467d523365SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1447ff0cc061SDimitry Andric 
14487d523365SDimitry Andric     // Attach exceptional gc relocates to the landingpad.
14497d523365SDimitry Andric     Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
14507d523365SDimitry Andric     Result.UnwindToken = ExceptionalToken;
1451ff0cc061SDimitry Andric 
14527d523365SDimitry Andric     const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
14537d523365SDimitry Andric     CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
14547d523365SDimitry Andric                       Builder);
1455ff0cc061SDimitry Andric 
1456ff0cc061SDimitry Andric     // Generate gc relocates and returns for normal block
14577d523365SDimitry Andric     BasicBlock *NormalDest = ToReplace->getNormalDest();
14587d523365SDimitry Andric     assert(!isa<PHINode>(NormalDest->begin()) &&
14597d523365SDimitry Andric            NormalDest->getUniquePredecessor() &&
1460ff0cc061SDimitry Andric            "can't safely insert in this block!");
1461ff0cc061SDimitry Andric 
14627d523365SDimitry Andric     Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
1463ff0cc061SDimitry Andric 
1464ff0cc061SDimitry Andric     // gc relocates will be generated later as if it were regular call
1465ff0cc061SDimitry Andric     // statepoint
1466ff0cc061SDimitry Andric   }
14677d523365SDimitry Andric   assert(Token && "Should be set in one of the above branches!");
1468ff0cc061SDimitry Andric 
14693ca95b02SDimitry Andric   if (IsDeoptimize) {
14703ca95b02SDimitry Andric     // If we're wrapping an @llvm.experimental.deoptimize in a statepoint, we
14713ca95b02SDimitry Andric     // transform the tail-call like structure to a call to a void function
14723ca95b02SDimitry Andric     // followed by unreachable to get better codegen.
14733ca95b02SDimitry Andric     Replacements.push_back(
14743ca95b02SDimitry Andric         DeferredReplacement::createDeoptimizeReplacement(CS.getInstruction()));
14753ca95b02SDimitry Andric   } else {
14767d523365SDimitry Andric     Token->setName("statepoint_token");
14777d523365SDimitry Andric     if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
14787d523365SDimitry Andric       StringRef Name =
14797d523365SDimitry Andric           CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
14807d523365SDimitry Andric       CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
14817d523365SDimitry Andric       GCResult->setAttributes(CS.getAttributes().getRetAttributes());
1482ff0cc061SDimitry Andric 
14837d523365SDimitry Andric       // We cannot RAUW or delete CS.getInstruction() because it could be in the
14847d523365SDimitry Andric       // live set of some other safepoint, in which case that safepoint's
14857d523365SDimitry Andric       // PartiallyConstructedSafepointRecord will hold a raw pointer to this
14867d523365SDimitry Andric       // llvm::Instruction.  Instead, we defer the replacement and deletion to
14877d523365SDimitry Andric       // after the live sets have been made explicit in the IR, and we no longer
14887d523365SDimitry Andric       // have raw pointers to worry about.
14893ca95b02SDimitry Andric       Replacements.emplace_back(
14903ca95b02SDimitry Andric           DeferredReplacement::createRAUW(CS.getInstruction(), GCResult));
14917d523365SDimitry Andric     } else {
14923ca95b02SDimitry Andric       Replacements.emplace_back(
14933ca95b02SDimitry Andric           DeferredReplacement::createDelete(CS.getInstruction()));
14947d523365SDimitry Andric     }
14957d523365SDimitry Andric   }
1496ff0cc061SDimitry Andric 
14977d523365SDimitry Andric   Result.StatepointToken = Token;
1498ff0cc061SDimitry Andric 
1499ff0cc061SDimitry Andric   // Second, create a gc.relocate for every live variable
15007d523365SDimitry Andric   const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
15017d523365SDimitry Andric   CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
1502ff0cc061SDimitry Andric }
1503ff0cc061SDimitry Andric 
1504ff0cc061SDimitry Andric // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1505ff0cc061SDimitry Andric // which make the relocations happening at this safepoint explicit.
1506ff0cc061SDimitry Andric //
1507ff0cc061SDimitry Andric // WARNING: Does not do any fixup to adjust users of the original live
1508ff0cc061SDimitry Andric // values.  That's the callers responsibility.
1509ff0cc061SDimitry Andric static void
15103ca95b02SDimitry Andric makeStatepointExplicit(DominatorTree &DT, CallSite CS,
15117d523365SDimitry Andric                        PartiallyConstructedSafepointRecord &Result,
15127d523365SDimitry Andric                        std::vector<DeferredReplacement> &Replacements) {
15137d523365SDimitry Andric   const auto &LiveSet = Result.LiveSet;
15147d523365SDimitry Andric   const auto &PointerToBase = Result.PointerToBase;
1515ff0cc061SDimitry Andric 
1516ff0cc061SDimitry Andric   // Convert to vector for efficient cross referencing.
15177d523365SDimitry Andric   SmallVector<Value *, 64> BaseVec, LiveVec;
15187d523365SDimitry Andric   LiveVec.reserve(LiveSet.size());
15197d523365SDimitry Andric   BaseVec.reserve(LiveSet.size());
15207d523365SDimitry Andric   for (Value *L : LiveSet) {
15217d523365SDimitry Andric     LiveVec.push_back(L);
15227d523365SDimitry Andric     assert(PointerToBase.count(L));
15237d523365SDimitry Andric     Value *Base = PointerToBase.find(L)->second;
15247d523365SDimitry Andric     BaseVec.push_back(Base);
1525ff0cc061SDimitry Andric   }
15267d523365SDimitry Andric   assert(LiveVec.size() == BaseVec.size());
1527ff0cc061SDimitry Andric 
1528ff0cc061SDimitry Andric   // Do the actual rewriting and delete the old statepoint
15297d523365SDimitry Andric   makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
1530ff0cc061SDimitry Andric }
1531ff0cc061SDimitry Andric 
1532ff0cc061SDimitry Andric // Helper function for the relocationViaAlloca.
15337d523365SDimitry Andric //
15347d523365SDimitry Andric // It receives iterator to the statepoint gc relocates and emits a store to the
15357d523365SDimitry Andric // assigned location (via allocaMap) for the each one of them.  It adds the
15367d523365SDimitry Andric // visited values into the visitedLiveValues set, which we will later use them
15377d523365SDimitry Andric // for sanity checking.
1538ff0cc061SDimitry Andric static void
1539ff0cc061SDimitry Andric insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1540ff0cc061SDimitry Andric                        DenseMap<Value *, Value *> &AllocaMap,
1541ff0cc061SDimitry Andric                        DenseSet<Value *> &VisitedLiveValues) {
1542ff0cc061SDimitry Andric 
1543ff0cc061SDimitry Andric   for (User *U : GCRelocs) {
15444d0b32cdSDimitry Andric     GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
15454d0b32cdSDimitry Andric     if (!Relocate)
1546ff0cc061SDimitry Andric       continue;
1547ff0cc061SDimitry Andric 
15483ca95b02SDimitry Andric     Value *OriginalValue = Relocate->getDerivedPtr();
1549ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue));
1550ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1551ff0cc061SDimitry Andric 
1552ff0cc061SDimitry Andric     // Emit store into the related alloca
15537d523365SDimitry Andric     // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1554ff0cc061SDimitry Andric     // the correct type according to alloca.
15554d0b32cdSDimitry Andric     assert(Relocate->getNextNode() &&
15567d523365SDimitry Andric            "Should always have one since it's not a terminator");
15574d0b32cdSDimitry Andric     IRBuilder<> Builder(Relocate->getNextNode());
1558ff0cc061SDimitry Andric     Value *CastedRelocatedValue =
15594d0b32cdSDimitry Andric       Builder.CreateBitCast(Relocate,
15607d523365SDimitry Andric                             cast<AllocaInst>(Alloca)->getAllocatedType(),
15614d0b32cdSDimitry Andric                             suffixed_name_or(Relocate, ".casted", ""));
1562ff0cc061SDimitry Andric 
1563ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1564ff0cc061SDimitry Andric     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1565ff0cc061SDimitry Andric 
1566ff0cc061SDimitry Andric #ifndef NDEBUG
1567ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1568ff0cc061SDimitry Andric #endif
1569ff0cc061SDimitry Andric   }
1570ff0cc061SDimitry Andric }
1571ff0cc061SDimitry Andric 
1572ff0cc061SDimitry Andric // Helper function for the "relocationViaAlloca". Similar to the
1573ff0cc061SDimitry Andric // "insertRelocationStores" but works for rematerialized values.
15743ca95b02SDimitry Andric static void insertRematerializationStores(
15753ca95b02SDimitry Andric     const RematerializedValueMapTy &RematerializedValues,
1576ff0cc061SDimitry Andric     DenseMap<Value *, Value *> &AllocaMap,
1577ff0cc061SDimitry Andric     DenseSet<Value *> &VisitedLiveValues) {
1578ff0cc061SDimitry Andric 
1579ff0cc061SDimitry Andric   for (auto RematerializedValuePair: RematerializedValues) {
1580ff0cc061SDimitry Andric     Instruction *RematerializedValue = RematerializedValuePair.first;
1581ff0cc061SDimitry Andric     Value *OriginalValue = RematerializedValuePair.second;
1582ff0cc061SDimitry Andric 
1583ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue) &&
1584ff0cc061SDimitry Andric            "Can not find alloca for rematerialized value");
1585ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1586ff0cc061SDimitry Andric 
1587ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1588ff0cc061SDimitry Andric     Store->insertAfter(RematerializedValue);
1589ff0cc061SDimitry Andric 
1590ff0cc061SDimitry Andric #ifndef NDEBUG
1591ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1592ff0cc061SDimitry Andric #endif
1593ff0cc061SDimitry Andric   }
1594ff0cc061SDimitry Andric }
1595ff0cc061SDimitry Andric 
15967d523365SDimitry Andric /// Do all the relocation update via allocas and mem2reg
1597ff0cc061SDimitry Andric static void relocationViaAlloca(
1598ff0cc061SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
15997d523365SDimitry Andric     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1600ff0cc061SDimitry Andric #ifndef NDEBUG
1601ff0cc061SDimitry Andric   // record initial number of (static) allocas; we'll check we have the same
1602ff0cc061SDimitry Andric   // number when we get done.
1603ff0cc061SDimitry Andric   int InitialAllocaNum = 0;
16043ca95b02SDimitry Andric   for (Instruction &I : F.getEntryBlock())
16053ca95b02SDimitry Andric     if (isa<AllocaInst>(I))
1606ff0cc061SDimitry Andric       InitialAllocaNum++;
1607ff0cc061SDimitry Andric #endif
1608ff0cc061SDimitry Andric 
1609ff0cc061SDimitry Andric   // TODO-PERF: change data structures, reserve
1610ff0cc061SDimitry Andric   DenseMap<Value *, Value *> AllocaMap;
1611ff0cc061SDimitry Andric   SmallVector<AllocaInst *, 200> PromotableAllocas;
1612ff0cc061SDimitry Andric   // Used later to chack that we have enough allocas to store all values
1613ff0cc061SDimitry Andric   std::size_t NumRematerializedValues = 0;
1614ff0cc061SDimitry Andric   PromotableAllocas.reserve(Live.size());
1615ff0cc061SDimitry Andric 
1616ff0cc061SDimitry Andric   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1617ff0cc061SDimitry Andric   // "PromotableAllocas"
1618ff0cc061SDimitry Andric   auto emitAllocaFor = [&](Value *LiveValue) {
1619ff0cc061SDimitry Andric     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1620ff0cc061SDimitry Andric                                         F.getEntryBlock().getFirstNonPHI());
1621ff0cc061SDimitry Andric     AllocaMap[LiveValue] = Alloca;
1622ff0cc061SDimitry Andric     PromotableAllocas.push_back(Alloca);
1623ff0cc061SDimitry Andric   };
1624ff0cc061SDimitry Andric 
16257d523365SDimitry Andric   // Emit alloca for each live gc pointer
16267d523365SDimitry Andric   for (Value *V : Live)
16277d523365SDimitry Andric     emitAllocaFor(V);
1628ff0cc061SDimitry Andric 
16297d523365SDimitry Andric   // Emit allocas for rematerialized values
16307d523365SDimitry Andric   for (const auto &Info : Records)
1631ff0cc061SDimitry Andric     for (auto RematerializedValuePair : Info.RematerializedValues) {
1632ff0cc061SDimitry Andric       Value *OriginalValue = RematerializedValuePair.second;
1633ff0cc061SDimitry Andric       if (AllocaMap.count(OriginalValue) != 0)
1634ff0cc061SDimitry Andric         continue;
1635ff0cc061SDimitry Andric 
1636ff0cc061SDimitry Andric       emitAllocaFor(OriginalValue);
1637ff0cc061SDimitry Andric       ++NumRematerializedValues;
1638ff0cc061SDimitry Andric     }
1639ff0cc061SDimitry Andric 
1640ff0cc061SDimitry Andric   // The next two loops are part of the same conceptual operation.  We need to
1641ff0cc061SDimitry Andric   // insert a store to the alloca after the original def and at each
1642ff0cc061SDimitry Andric   // redefinition.  We need to insert a load before each use.  These are split
1643ff0cc061SDimitry Andric   // into distinct loops for performance reasons.
1644ff0cc061SDimitry Andric 
16457d523365SDimitry Andric   // Update gc pointer after each statepoint: either store a relocated value or
16467d523365SDimitry Andric   // null (if no relocated value was found for this gc pointer and it is not a
16477d523365SDimitry Andric   // gc_result).  This must happen before we update the statepoint with load of
16487d523365SDimitry Andric   // alloca otherwise we lose the link between statepoint and old def.
16497d523365SDimitry Andric   for (const auto &Info : Records) {
1650ff0cc061SDimitry Andric     Value *Statepoint = Info.StatepointToken;
1651ff0cc061SDimitry Andric 
1652ff0cc061SDimitry Andric     // This will be used for consistency check
1653ff0cc061SDimitry Andric     DenseSet<Value *> VisitedLiveValues;
1654ff0cc061SDimitry Andric 
1655ff0cc061SDimitry Andric     // Insert stores for normal statepoint gc relocates
1656ff0cc061SDimitry Andric     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1657ff0cc061SDimitry Andric 
1658ff0cc061SDimitry Andric     // In case if it was invoke statepoint
1659ff0cc061SDimitry Andric     // we will insert stores for exceptional path gc relocates.
1660ff0cc061SDimitry Andric     if (isa<InvokeInst>(Statepoint)) {
1661ff0cc061SDimitry Andric       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1662ff0cc061SDimitry Andric                              VisitedLiveValues);
1663ff0cc061SDimitry Andric     }
1664ff0cc061SDimitry Andric 
1665ff0cc061SDimitry Andric     // Do similar thing with rematerialized values
1666ff0cc061SDimitry Andric     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1667ff0cc061SDimitry Andric                                   VisitedLiveValues);
1668ff0cc061SDimitry Andric 
1669ff0cc061SDimitry Andric     if (ClobberNonLive) {
16707d523365SDimitry Andric       // As a debugging aid, pretend that an unrelocated pointer becomes null at
1671ff0cc061SDimitry Andric       // the gc.statepoint.  This will turn some subtle GC problems into
1672ff0cc061SDimitry Andric       // slightly easier to debug SEGVs.  Note that on large IR files with
1673ff0cc061SDimitry Andric       // lots of gc.statepoints this is extremely costly both memory and time
1674ff0cc061SDimitry Andric       // wise.
1675ff0cc061SDimitry Andric       SmallVector<AllocaInst *, 64> ToClobber;
1676ff0cc061SDimitry Andric       for (auto Pair : AllocaMap) {
1677ff0cc061SDimitry Andric         Value *Def = Pair.first;
1678ff0cc061SDimitry Andric         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1679ff0cc061SDimitry Andric 
1680ff0cc061SDimitry Andric         // This value was relocated
1681ff0cc061SDimitry Andric         if (VisitedLiveValues.count(Def)) {
1682ff0cc061SDimitry Andric           continue;
1683ff0cc061SDimitry Andric         }
1684ff0cc061SDimitry Andric         ToClobber.push_back(Alloca);
1685ff0cc061SDimitry Andric       }
1686ff0cc061SDimitry Andric 
1687ff0cc061SDimitry Andric       auto InsertClobbersAt = [&](Instruction *IP) {
1688ff0cc061SDimitry Andric         for (auto *AI : ToClobber) {
16893ca95b02SDimitry Andric           auto PT = cast<PointerType>(AI->getAllocatedType());
1690ff0cc061SDimitry Andric           Constant *CPN = ConstantPointerNull::get(PT);
1691ff0cc061SDimitry Andric           StoreInst *Store = new StoreInst(CPN, AI);
1692ff0cc061SDimitry Andric           Store->insertBefore(IP);
1693ff0cc061SDimitry Andric         }
1694ff0cc061SDimitry Andric       };
1695ff0cc061SDimitry Andric 
1696ff0cc061SDimitry Andric       // Insert the clobbering stores.  These may get intermixed with the
1697ff0cc061SDimitry Andric       // gc.results and gc.relocates, but that's fine.
1698ff0cc061SDimitry Andric       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
16997d523365SDimitry Andric         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
17007d523365SDimitry Andric         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1701ff0cc061SDimitry Andric       } else {
17027d523365SDimitry Andric         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1703ff0cc061SDimitry Andric       }
1704ff0cc061SDimitry Andric     }
1705ff0cc061SDimitry Andric   }
17067d523365SDimitry Andric 
17077d523365SDimitry Andric   // Update use with load allocas and add store for gc_relocated.
1708ff0cc061SDimitry Andric   for (auto Pair : AllocaMap) {
1709ff0cc061SDimitry Andric     Value *Def = Pair.first;
1710ff0cc061SDimitry Andric     Value *Alloca = Pair.second;
1711ff0cc061SDimitry Andric 
17127d523365SDimitry Andric     // We pre-record the uses of allocas so that we dont have to worry about
17137d523365SDimitry Andric     // later update that changes the user information..
17147d523365SDimitry Andric 
1715ff0cc061SDimitry Andric     SmallVector<Instruction *, 20> Uses;
1716ff0cc061SDimitry Andric     // PERF: trade a linear scan for repeated reallocation
1717ff0cc061SDimitry Andric     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1718ff0cc061SDimitry Andric     for (User *U : Def->users()) {
1719ff0cc061SDimitry Andric       if (!isa<ConstantExpr>(U)) {
1720ff0cc061SDimitry Andric         // If the def has a ConstantExpr use, then the def is either a
1721ff0cc061SDimitry Andric         // ConstantExpr use itself or null.  In either case
1722ff0cc061SDimitry Andric         // (recursively in the first, directly in the second), the oop
1723ff0cc061SDimitry Andric         // it is ultimately dependent on is null and this particular
1724ff0cc061SDimitry Andric         // use does not need to be fixed up.
1725ff0cc061SDimitry Andric         Uses.push_back(cast<Instruction>(U));
1726ff0cc061SDimitry Andric       }
1727ff0cc061SDimitry Andric     }
1728ff0cc061SDimitry Andric 
1729ff0cc061SDimitry Andric     std::sort(Uses.begin(), Uses.end());
1730ff0cc061SDimitry Andric     auto Last = std::unique(Uses.begin(), Uses.end());
1731ff0cc061SDimitry Andric     Uses.erase(Last, Uses.end());
1732ff0cc061SDimitry Andric 
1733ff0cc061SDimitry Andric     for (Instruction *Use : Uses) {
1734ff0cc061SDimitry Andric       if (isa<PHINode>(Use)) {
1735ff0cc061SDimitry Andric         PHINode *Phi = cast<PHINode>(Use);
1736ff0cc061SDimitry Andric         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1737ff0cc061SDimitry Andric           if (Def == Phi->getIncomingValue(i)) {
1738ff0cc061SDimitry Andric             LoadInst *Load = new LoadInst(
1739ff0cc061SDimitry Andric                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1740ff0cc061SDimitry Andric             Phi->setIncomingValue(i, Load);
1741ff0cc061SDimitry Andric           }
1742ff0cc061SDimitry Andric         }
1743ff0cc061SDimitry Andric       } else {
1744ff0cc061SDimitry Andric         LoadInst *Load = new LoadInst(Alloca, "", Use);
1745ff0cc061SDimitry Andric         Use->replaceUsesOfWith(Def, Load);
1746ff0cc061SDimitry Andric       }
1747ff0cc061SDimitry Andric     }
1748ff0cc061SDimitry Andric 
17497d523365SDimitry Andric     // Emit store for the initial gc value.  Store must be inserted after load,
17507d523365SDimitry Andric     // otherwise store will be in alloca's use list and an extra load will be
17517d523365SDimitry Andric     // inserted before it.
1752ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(Def, Alloca);
1753ff0cc061SDimitry Andric     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1754ff0cc061SDimitry Andric       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1755ff0cc061SDimitry Andric         // InvokeInst is a TerminatorInst so the store need to be inserted
1756ff0cc061SDimitry Andric         // into its normal destination block.
1757ff0cc061SDimitry Andric         BasicBlock *NormalDest = Invoke->getNormalDest();
1758ff0cc061SDimitry Andric         Store->insertBefore(NormalDest->getFirstNonPHI());
1759ff0cc061SDimitry Andric       } else {
1760ff0cc061SDimitry Andric         assert(!Inst->isTerminator() &&
1761ff0cc061SDimitry Andric                "The only TerminatorInst that can produce a value is "
1762ff0cc061SDimitry Andric                "InvokeInst which is handled above.");
1763ff0cc061SDimitry Andric         Store->insertAfter(Inst);
1764ff0cc061SDimitry Andric       }
1765ff0cc061SDimitry Andric     } else {
1766ff0cc061SDimitry Andric       assert(isa<Argument>(Def));
1767ff0cc061SDimitry Andric       Store->insertAfter(cast<Instruction>(Alloca));
1768ff0cc061SDimitry Andric     }
1769ff0cc061SDimitry Andric   }
1770ff0cc061SDimitry Andric 
1771ff0cc061SDimitry Andric   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1772ff0cc061SDimitry Andric          "we must have the same allocas with lives");
1773ff0cc061SDimitry Andric   if (!PromotableAllocas.empty()) {
17747d523365SDimitry Andric     // Apply mem2reg to promote alloca to SSA
1775ff0cc061SDimitry Andric     PromoteMemToReg(PromotableAllocas, DT);
1776ff0cc061SDimitry Andric   }
1777ff0cc061SDimitry Andric 
1778ff0cc061SDimitry Andric #ifndef NDEBUG
17797d523365SDimitry Andric   for (auto &I : F.getEntryBlock())
17807d523365SDimitry Andric     if (isa<AllocaInst>(I))
1781ff0cc061SDimitry Andric       InitialAllocaNum--;
1782ff0cc061SDimitry Andric   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1783ff0cc061SDimitry Andric #endif
1784ff0cc061SDimitry Andric }
1785ff0cc061SDimitry Andric 
1786ff0cc061SDimitry Andric /// Implement a unique function which doesn't require we sort the input
1787ff0cc061SDimitry Andric /// vector.  Doing so has the effect of changing the output of a couple of
1788ff0cc061SDimitry Andric /// tests in ways which make them less useful in testing fused safepoints.
1789ff0cc061SDimitry Andric template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
17908f0fd8f6SDimitry Andric   SmallSet<T, 8> Seen;
1791d88c1a5aSDimitry Andric   Vec.erase(remove_if(Vec, [&](const T &V) { return !Seen.insert(V).second; }),
1792d88c1a5aSDimitry Andric             Vec.end());
1793ff0cc061SDimitry Andric }
1794ff0cc061SDimitry Andric 
1795ff0cc061SDimitry Andric /// Insert holders so that each Value is obviously live through the entire
1796ff0cc061SDimitry Andric /// lifetime of the call.
1797ff0cc061SDimitry Andric static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1798ff0cc061SDimitry Andric                                  SmallVectorImpl<CallInst *> &Holders) {
1799ff0cc061SDimitry Andric   if (Values.empty())
1800ff0cc061SDimitry Andric     // No values to hold live, might as well not insert the empty holder
1801ff0cc061SDimitry Andric     return;
1802ff0cc061SDimitry Andric 
18037d523365SDimitry Andric   Module *M = CS.getInstruction()->getModule();
1804ff0cc061SDimitry Andric   // Use a dummy vararg function to actually hold the values live
1805ff0cc061SDimitry Andric   Function *Func = cast<Function>(M->getOrInsertFunction(
1806ff0cc061SDimitry Andric       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1807ff0cc061SDimitry Andric   if (CS.isCall()) {
1808ff0cc061SDimitry Andric     // For call safepoints insert dummy calls right after safepoint
18097d523365SDimitry Andric     Holders.push_back(CallInst::Create(Func, Values, "",
18107d523365SDimitry Andric                                        &*++CS.getInstruction()->getIterator()));
1811ff0cc061SDimitry Andric     return;
1812ff0cc061SDimitry Andric   }
1813ff0cc061SDimitry Andric   // For invoke safepooints insert dummy calls both in normal and
1814ff0cc061SDimitry Andric   // exceptional destination blocks
1815ff0cc061SDimitry Andric   auto *II = cast<InvokeInst>(CS.getInstruction());
1816ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
18177d523365SDimitry Andric       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
1818ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
18197d523365SDimitry Andric       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
1820ff0cc061SDimitry Andric }
1821ff0cc061SDimitry Andric 
1822ff0cc061SDimitry Andric static void findLiveReferences(
18237d523365SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1824ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1825ff0cc061SDimitry Andric   GCPtrLivenessData OriginalLivenessData;
1826ff0cc061SDimitry Andric   computeLiveInValues(DT, F, OriginalLivenessData);
1827ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1828ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
18293ca95b02SDimitry Andric     analyzeParsePointLiveness(DT, OriginalLivenessData, toUpdate[i], info);
18303dac3a9bSDimitry Andric   }
1831ff0cc061SDimitry Andric }
1832ff0cc061SDimitry Andric 
1833ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". It walks use chain
1834d88c1a5aSDimitry Andric // starting from the "CurrentValue" until it reaches the root of the chain, i.e.
1835d88c1a5aSDimitry Andric // the base or a value it cannot process. Only "simple" values are processed
1836d88c1a5aSDimitry Andric // (currently it is GEP's and casts). The returned root is  examined by the
1837d88c1a5aSDimitry Andric // callers of findRematerializableChainToBasePointer.  Fills "ChainToBase" array
1838d88c1a5aSDimitry Andric // with all visited values.
1839d88c1a5aSDimitry Andric static Value* findRematerializableChainToBasePointer(
1840ff0cc061SDimitry Andric   SmallVectorImpl<Instruction*> &ChainToBase,
1841d88c1a5aSDimitry Andric   Value *CurrentValue) {
1842ff0cc061SDimitry Andric 
1843ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1844ff0cc061SDimitry Andric     ChainToBase.push_back(GEP);
1845ff0cc061SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
1846d88c1a5aSDimitry Andric                                                   GEP->getPointerOperand());
1847ff0cc061SDimitry Andric   }
1848ff0cc061SDimitry Andric 
1849ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1850ff0cc061SDimitry Andric     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1851d88c1a5aSDimitry Andric       return CI;
1852ff0cc061SDimitry Andric 
1853ff0cc061SDimitry Andric     ChainToBase.push_back(CI);
18547d523365SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
1855d88c1a5aSDimitry Andric                                                   CI->getOperand(0));
1856ff0cc061SDimitry Andric   }
1857ff0cc061SDimitry Andric 
1858d88c1a5aSDimitry Andric   // We have reached the root of the chain, which is either equal to the base or
1859d88c1a5aSDimitry Andric   // is the first unsupported value along the use chain.
1860d88c1a5aSDimitry Andric   return CurrentValue;
1861ff0cc061SDimitry Andric }
1862ff0cc061SDimitry Andric 
1863ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". Compute cost of the use
1864ff0cc061SDimitry Andric // chain we are going to rematerialize.
1865ff0cc061SDimitry Andric static unsigned
1866ff0cc061SDimitry Andric chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1867ff0cc061SDimitry Andric                        TargetTransformInfo &TTI) {
1868ff0cc061SDimitry Andric   unsigned Cost = 0;
1869ff0cc061SDimitry Andric 
1870ff0cc061SDimitry Andric   for (Instruction *Instr : Chain) {
1871ff0cc061SDimitry Andric     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1872ff0cc061SDimitry Andric       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1873ff0cc061SDimitry Andric              "non noop cast is found during rematerialization");
1874ff0cc061SDimitry Andric 
1875ff0cc061SDimitry Andric       Type *SrcTy = CI->getOperand(0)->getType();
1876ff0cc061SDimitry Andric       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1877ff0cc061SDimitry Andric 
1878ff0cc061SDimitry Andric     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1879ff0cc061SDimitry Andric       // Cost of the address calculation
18803ca95b02SDimitry Andric       Type *ValTy = GEP->getSourceElementType();
1881ff0cc061SDimitry Andric       Cost += TTI.getAddressComputationCost(ValTy);
1882ff0cc061SDimitry Andric 
1883ff0cc061SDimitry Andric       // And cost of the GEP itself
1884ff0cc061SDimitry Andric       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1885ff0cc061SDimitry Andric       //       allowed for the external usage)
1886ff0cc061SDimitry Andric       if (!GEP->hasAllConstantIndices())
1887ff0cc061SDimitry Andric         Cost += 2;
1888ff0cc061SDimitry Andric 
1889ff0cc061SDimitry Andric     } else {
1890ff0cc061SDimitry Andric       llvm_unreachable("unsupported instruciton type during rematerialization");
1891ff0cc061SDimitry Andric     }
1892ff0cc061SDimitry Andric   }
1893ff0cc061SDimitry Andric 
1894ff0cc061SDimitry Andric   return Cost;
1895ff0cc061SDimitry Andric }
1896ff0cc061SDimitry Andric 
1897d88c1a5aSDimitry Andric static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi) {
1898d88c1a5aSDimitry Andric 
1899d88c1a5aSDimitry Andric   unsigned PhiNum = OrigRootPhi.getNumIncomingValues();
1900d88c1a5aSDimitry Andric   if (PhiNum != AlternateRootPhi.getNumIncomingValues() ||
1901d88c1a5aSDimitry Andric       OrigRootPhi.getParent() != AlternateRootPhi.getParent())
1902d88c1a5aSDimitry Andric     return false;
1903d88c1a5aSDimitry Andric   // Map of incoming values and their corresponding basic blocks of
1904d88c1a5aSDimitry Andric   // OrigRootPhi.
1905d88c1a5aSDimitry Andric   SmallDenseMap<Value *, BasicBlock *, 8> CurrentIncomingValues;
1906d88c1a5aSDimitry Andric   for (unsigned i = 0; i < PhiNum; i++)
1907d88c1a5aSDimitry Andric     CurrentIncomingValues[OrigRootPhi.getIncomingValue(i)] =
1908d88c1a5aSDimitry Andric         OrigRootPhi.getIncomingBlock(i);
1909d88c1a5aSDimitry Andric 
1910d88c1a5aSDimitry Andric   // Both current and base PHIs should have same incoming values and
1911d88c1a5aSDimitry Andric   // the same basic blocks corresponding to the incoming values.
1912d88c1a5aSDimitry Andric   for (unsigned i = 0; i < PhiNum; i++) {
1913d88c1a5aSDimitry Andric     auto CIVI =
1914d88c1a5aSDimitry Andric         CurrentIncomingValues.find(AlternateRootPhi.getIncomingValue(i));
1915d88c1a5aSDimitry Andric     if (CIVI == CurrentIncomingValues.end())
1916d88c1a5aSDimitry Andric       return false;
1917d88c1a5aSDimitry Andric     BasicBlock *CurrentIncomingBB = CIVI->second;
1918d88c1a5aSDimitry Andric     if (CurrentIncomingBB != AlternateRootPhi.getIncomingBlock(i))
1919d88c1a5aSDimitry Andric       return false;
1920d88c1a5aSDimitry Andric   }
1921d88c1a5aSDimitry Andric   return true;
1922d88c1a5aSDimitry Andric 
1923d88c1a5aSDimitry Andric }
1924d88c1a5aSDimitry Andric 
19257d523365SDimitry Andric // From the statepoint live set pick values that are cheaper to recompute then
19267d523365SDimitry Andric // to relocate. Remove this values from the live set, rematerialize them after
1927ff0cc061SDimitry Andric // statepoint and record them in "Info" structure. Note that similar to
1928ff0cc061SDimitry Andric // relocated values we don't do any user adjustments here.
1929ff0cc061SDimitry Andric static void rematerializeLiveValues(CallSite CS,
1930ff0cc061SDimitry Andric                                     PartiallyConstructedSafepointRecord &Info,
1931ff0cc061SDimitry Andric                                     TargetTransformInfo &TTI) {
1932ff0cc061SDimitry Andric   const unsigned int ChainLengthThreshold = 10;
1933ff0cc061SDimitry Andric 
1934ff0cc061SDimitry Andric   // Record values we are going to delete from this statepoint live set.
1935ff0cc061SDimitry Andric   // We can not di this in following loop due to iterator invalidation.
1936ff0cc061SDimitry Andric   SmallVector<Value *, 32> LiveValuesToBeDeleted;
1937ff0cc061SDimitry Andric 
19387d523365SDimitry Andric   for (Value *LiveValue: Info.LiveSet) {
1939ff0cc061SDimitry Andric     // For each live pointer find it's defining chain
1940ff0cc061SDimitry Andric     SmallVector<Instruction *, 3> ChainToBase;
19417d523365SDimitry Andric     assert(Info.PointerToBase.count(LiveValue));
1942d88c1a5aSDimitry Andric     Value *RootOfChain =
1943ff0cc061SDimitry Andric       findRematerializableChainToBasePointer(ChainToBase,
1944d88c1a5aSDimitry Andric                                              LiveValue);
1945d88c1a5aSDimitry Andric 
1946ff0cc061SDimitry Andric     // Nothing to do, or chain is too long
1947d88c1a5aSDimitry Andric     if ( ChainToBase.size() == 0 ||
1948ff0cc061SDimitry Andric         ChainToBase.size() > ChainLengthThreshold)
1949ff0cc061SDimitry Andric       continue;
1950ff0cc061SDimitry Andric 
1951d88c1a5aSDimitry Andric     // Handle the scenario where the RootOfChain is not equal to the
1952d88c1a5aSDimitry Andric     // Base Value, but they are essentially the same phi values.
1953d88c1a5aSDimitry Andric     if (RootOfChain != Info.PointerToBase[LiveValue]) {
1954d88c1a5aSDimitry Andric       PHINode *OrigRootPhi = dyn_cast<PHINode>(RootOfChain);
1955d88c1a5aSDimitry Andric       PHINode *AlternateRootPhi = dyn_cast<PHINode>(Info.PointerToBase[LiveValue]);
1956d88c1a5aSDimitry Andric       if (!OrigRootPhi || !AlternateRootPhi)
1957d88c1a5aSDimitry Andric         continue;
1958d88c1a5aSDimitry Andric       // PHI nodes that have the same incoming values, and belonging to the same
1959d88c1a5aSDimitry Andric       // basic blocks are essentially the same SSA value.  When the original phi
1960d88c1a5aSDimitry Andric       // has incoming values with different base pointers, the original phi is
1961d88c1a5aSDimitry Andric       // marked as conflict, and an additional `AlternateRootPhi` with the same
1962d88c1a5aSDimitry Andric       // incoming values get generated by the findBasePointer function. We need
1963d88c1a5aSDimitry Andric       // to identify the newly generated AlternateRootPhi (.base version of phi)
1964d88c1a5aSDimitry Andric       // and RootOfChain (the original phi node itself) are the same, so that we
1965d88c1a5aSDimitry Andric       // can rematerialize the gep and casts. This is a workaround for the
1966d88c1a5aSDimitry Andric       // deficieny in the findBasePointer algorithm.
1967d88c1a5aSDimitry Andric       if (!AreEquivalentPhiNodes(*OrigRootPhi, *AlternateRootPhi))
1968d88c1a5aSDimitry Andric         continue;
1969d88c1a5aSDimitry Andric       // Now that the phi nodes are proved to be the same, assert that
1970d88c1a5aSDimitry Andric       // findBasePointer's newly generated AlternateRootPhi is present in the
1971d88c1a5aSDimitry Andric       // liveset of the call.
1972d88c1a5aSDimitry Andric       assert(Info.LiveSet.count(AlternateRootPhi));
1973d88c1a5aSDimitry Andric     }
1974ff0cc061SDimitry Andric     // Compute cost of this chain
1975ff0cc061SDimitry Andric     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1976ff0cc061SDimitry Andric     // TODO: We can also account for cases when we will be able to remove some
1977ff0cc061SDimitry Andric     //       of the rematerialized values by later optimization passes. I.e if
1978ff0cc061SDimitry Andric     //       we rematerialized several intersecting chains. Or if original values
1979ff0cc061SDimitry Andric     //       don't have any uses besides this statepoint.
1980ff0cc061SDimitry Andric 
1981ff0cc061SDimitry Andric     // For invokes we need to rematerialize each chain twice - for normal and
1982ff0cc061SDimitry Andric     // for unwind basic blocks. Model this by multiplying cost by two.
1983ff0cc061SDimitry Andric     if (CS.isInvoke()) {
1984ff0cc061SDimitry Andric       Cost *= 2;
1985ff0cc061SDimitry Andric     }
1986ff0cc061SDimitry Andric     // If it's too expensive - skip it
1987ff0cc061SDimitry Andric     if (Cost >= RematerializationThreshold)
1988ff0cc061SDimitry Andric       continue;
1989ff0cc061SDimitry Andric 
1990ff0cc061SDimitry Andric     // Remove value from the live set
1991ff0cc061SDimitry Andric     LiveValuesToBeDeleted.push_back(LiveValue);
1992ff0cc061SDimitry Andric 
1993ff0cc061SDimitry Andric     // Clone instructions and record them inside "Info" structure
1994ff0cc061SDimitry Andric 
1995ff0cc061SDimitry Andric     // Walk backwards to visit top-most instructions first
1996ff0cc061SDimitry Andric     std::reverse(ChainToBase.begin(), ChainToBase.end());
1997ff0cc061SDimitry Andric 
1998ff0cc061SDimitry Andric     // Utility function which clones all instructions from "ChainToBase"
1999ff0cc061SDimitry Andric     // and inserts them before "InsertBefore". Returns rematerialized value
2000ff0cc061SDimitry Andric     // which should be used after statepoint.
2001d88c1a5aSDimitry Andric     auto rematerializeChain = [&ChainToBase](
2002d88c1a5aSDimitry Andric         Instruction *InsertBefore, Value *RootOfChain, Value *AlternateLiveBase) {
2003ff0cc061SDimitry Andric       Instruction *LastClonedValue = nullptr;
2004ff0cc061SDimitry Andric       Instruction *LastValue = nullptr;
2005ff0cc061SDimitry Andric       for (Instruction *Instr: ChainToBase) {
2006ff0cc061SDimitry Andric         // Only GEP's and casts are suported as we need to be careful to not
2007ff0cc061SDimitry Andric         // introduce any new uses of pointers not in the liveset.
2008ff0cc061SDimitry Andric         // Note that it's fine to introduce new uses of pointers which were
2009ff0cc061SDimitry Andric         // otherwise not used after this statepoint.
2010ff0cc061SDimitry Andric         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2011ff0cc061SDimitry Andric 
2012ff0cc061SDimitry Andric         Instruction *ClonedValue = Instr->clone();
2013ff0cc061SDimitry Andric         ClonedValue->insertBefore(InsertBefore);
2014ff0cc061SDimitry Andric         ClonedValue->setName(Instr->getName() + ".remat");
2015ff0cc061SDimitry Andric 
2016ff0cc061SDimitry Andric         // If it is not first instruction in the chain then it uses previously
2017ff0cc061SDimitry Andric         // cloned value. We should update it to use cloned value.
2018ff0cc061SDimitry Andric         if (LastClonedValue) {
2019ff0cc061SDimitry Andric           assert(LastValue);
2020ff0cc061SDimitry Andric           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2021ff0cc061SDimitry Andric #ifndef NDEBUG
2022d88c1a5aSDimitry Andric           for (auto OpValue : ClonedValue->operand_values()) {
2023ff0cc061SDimitry Andric             // Assert that cloned instruction does not use any instructions from
2024ff0cc061SDimitry Andric             // this chain other than LastClonedValue
2025d88c1a5aSDimitry Andric             assert(!is_contained(ChainToBase, OpValue) &&
2026ff0cc061SDimitry Andric                    "incorrect use in rematerialization chain");
2027d88c1a5aSDimitry Andric             // Assert that the cloned instruction does not use the RootOfChain
2028d88c1a5aSDimitry Andric             // or the AlternateLiveBase.
2029d88c1a5aSDimitry Andric             assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
2030ff0cc061SDimitry Andric           }
2031ff0cc061SDimitry Andric #endif
2032d88c1a5aSDimitry Andric         } else {
2033d88c1a5aSDimitry Andric           // For the first instruction, replace the use of unrelocated base i.e.
2034d88c1a5aSDimitry Andric           // RootOfChain/OrigRootPhi, with the corresponding PHI present in the
2035d88c1a5aSDimitry Andric           // live set. They have been proved to be the same PHI nodes.  Note
2036d88c1a5aSDimitry Andric           // that the *only* use of the RootOfChain in the ChainToBase list is
2037d88c1a5aSDimitry Andric           // the first Value in the list.
2038d88c1a5aSDimitry Andric           if (RootOfChain != AlternateLiveBase)
2039d88c1a5aSDimitry Andric             ClonedValue->replaceUsesOfWith(RootOfChain, AlternateLiveBase);
2040ff0cc061SDimitry Andric         }
2041ff0cc061SDimitry Andric 
2042ff0cc061SDimitry Andric         LastClonedValue = ClonedValue;
2043ff0cc061SDimitry Andric         LastValue = Instr;
2044ff0cc061SDimitry Andric       }
2045ff0cc061SDimitry Andric       assert(LastClonedValue);
2046ff0cc061SDimitry Andric       return LastClonedValue;
2047ff0cc061SDimitry Andric     };
2048ff0cc061SDimitry Andric 
2049ff0cc061SDimitry Andric     // Different cases for calls and invokes. For invokes we need to clone
2050ff0cc061SDimitry Andric     // instructions both on normal and unwind path.
2051ff0cc061SDimitry Andric     if (CS.isCall()) {
2052ff0cc061SDimitry Andric       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2053ff0cc061SDimitry Andric       assert(InsertBefore);
2054d88c1a5aSDimitry Andric       Instruction *RematerializedValue = rematerializeChain(
2055d88c1a5aSDimitry Andric           InsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2056ff0cc061SDimitry Andric       Info.RematerializedValues[RematerializedValue] = LiveValue;
2057ff0cc061SDimitry Andric     } else {
2058ff0cc061SDimitry Andric       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2059ff0cc061SDimitry Andric 
2060ff0cc061SDimitry Andric       Instruction *NormalInsertBefore =
20617d523365SDimitry Andric           &*Invoke->getNormalDest()->getFirstInsertionPt();
2062ff0cc061SDimitry Andric       Instruction *UnwindInsertBefore =
20637d523365SDimitry Andric           &*Invoke->getUnwindDest()->getFirstInsertionPt();
2064ff0cc061SDimitry Andric 
2065d88c1a5aSDimitry Andric       Instruction *NormalRematerializedValue = rematerializeChain(
2066d88c1a5aSDimitry Andric           NormalInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2067d88c1a5aSDimitry Andric       Instruction *UnwindRematerializedValue = rematerializeChain(
2068d88c1a5aSDimitry Andric           UnwindInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2069ff0cc061SDimitry Andric 
2070ff0cc061SDimitry Andric       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2071ff0cc061SDimitry Andric       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2072ff0cc061SDimitry Andric     }
2073ff0cc061SDimitry Andric   }
2074ff0cc061SDimitry Andric 
2075ff0cc061SDimitry Andric   // Remove rematerializaed values from the live set
2076ff0cc061SDimitry Andric   for (auto LiveValue: LiveValuesToBeDeleted) {
20773ca95b02SDimitry Andric     Info.LiveSet.remove(LiveValue);
2078ff0cc061SDimitry Andric   }
2079ff0cc061SDimitry Andric }
2080ff0cc061SDimitry Andric 
20817d523365SDimitry Andric static bool insertParsePoints(Function &F, DominatorTree &DT,
20827d523365SDimitry Andric                               TargetTransformInfo &TTI,
20837d523365SDimitry Andric                               SmallVectorImpl<CallSite> &ToUpdate) {
2084ff0cc061SDimitry Andric #ifndef NDEBUG
2085ff0cc061SDimitry Andric   // sanity check the input
20867d523365SDimitry Andric   std::set<CallSite> Uniqued;
20877d523365SDimitry Andric   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
20887d523365SDimitry Andric   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2089ff0cc061SDimitry Andric 
20903ca95b02SDimitry Andric   for (CallSite CS : ToUpdate)
20913ca95b02SDimitry Andric     assert(CS.getInstruction()->getFunction() == &F);
2092ff0cc061SDimitry Andric #endif
2093ff0cc061SDimitry Andric 
2094ff0cc061SDimitry Andric   // When inserting gc.relocates for invokes, we need to be able to insert at
2095ff0cc061SDimitry Andric   // the top of the successor blocks.  See the comment on
2096ff0cc061SDimitry Andric   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2097ff0cc061SDimitry Andric   // may restructure the CFG.
20987d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2099ff0cc061SDimitry Andric     if (!CS.isInvoke())
2100ff0cc061SDimitry Andric       continue;
21017d523365SDimitry Andric     auto *II = cast<InvokeInst>(CS.getInstruction());
21027d523365SDimitry Andric     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
21037d523365SDimitry Andric     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2104ff0cc061SDimitry Andric   }
2105ff0cc061SDimitry Andric 
2106ff0cc061SDimitry Andric   // A list of dummy calls added to the IR to keep various values obviously
2107ff0cc061SDimitry Andric   // live in the IR.  We'll remove all of these when done.
21087d523365SDimitry Andric   SmallVector<CallInst *, 64> Holders;
2109ff0cc061SDimitry Andric 
2110ff0cc061SDimitry Andric   // Insert a dummy call with all of the arguments to the vm_state we'll need
2111ff0cc061SDimitry Andric   // for the actual safepoint insertion.  This ensures reference arguments in
2112ff0cc061SDimitry Andric   // the deopt argument list are considered live through the safepoint (and
2113ff0cc061SDimitry Andric   // thus makes sure they get relocated.)
21147d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2115ff0cc061SDimitry Andric     SmallVector<Value *, 64> DeoptValues;
21167d523365SDimitry Andric 
21173ca95b02SDimitry Andric     for (Value *Arg : GetDeoptBundleOperands(CS)) {
2118ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2119ff0cc061SDimitry Andric              "support for FCA unimplemented");
2120ff0cc061SDimitry Andric       if (isHandledGCPointerType(Arg->getType()))
2121ff0cc061SDimitry Andric         DeoptValues.push_back(Arg);
2122ff0cc061SDimitry Andric     }
21237d523365SDimitry Andric 
21247d523365SDimitry Andric     insertUseHolderAfter(CS, DeoptValues, Holders);
2125ff0cc061SDimitry Andric   }
2126ff0cc061SDimitry Andric 
21277d523365SDimitry Andric   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2128ff0cc061SDimitry Andric 
21297d523365SDimitry Andric   // A) Identify all gc pointers which are statically live at the given call
2130ff0cc061SDimitry Andric   // site.
21317d523365SDimitry Andric   findLiveReferences(F, DT, ToUpdate, Records);
2132ff0cc061SDimitry Andric 
2133ff0cc061SDimitry Andric   // B) Find the base pointers for each live pointer
2134ff0cc061SDimitry Andric   /* scope for caching */ {
2135ff0cc061SDimitry Andric     // Cache the 'defining value' relation used in the computation and
2136ff0cc061SDimitry Andric     // insertion of base phis and selects.  This ensures that we don't insert
2137ff0cc061SDimitry Andric     // large numbers of duplicate base_phis.
2138ff0cc061SDimitry Andric     DefiningValueMapTy DVCache;
2139ff0cc061SDimitry Andric 
21407d523365SDimitry Andric     for (size_t i = 0; i < Records.size(); i++) {
21417d523365SDimitry Andric       PartiallyConstructedSafepointRecord &info = Records[i];
21427d523365SDimitry Andric       findBasePointers(DT, DVCache, ToUpdate[i], info);
2143ff0cc061SDimitry Andric     }
2144ff0cc061SDimitry Andric   } // end of cache scope
2145ff0cc061SDimitry Andric 
2146ff0cc061SDimitry Andric   // The base phi insertion logic (for any safepoint) may have inserted new
2147ff0cc061SDimitry Andric   // instructions which are now live at some safepoint.  The simplest such
2148ff0cc061SDimitry Andric   // example is:
2149ff0cc061SDimitry Andric   // loop:
2150ff0cc061SDimitry Andric   //   phi a  <-- will be a new base_phi here
2151ff0cc061SDimitry Andric   //   safepoint 1 <-- that needs to be live here
2152ff0cc061SDimitry Andric   //   gep a + 1
2153ff0cc061SDimitry Andric   //   safepoint 2
2154ff0cc061SDimitry Andric   //   br loop
2155ff0cc061SDimitry Andric   // We insert some dummy calls after each safepoint to definitely hold live
2156ff0cc061SDimitry Andric   // the base pointers which were identified for that safepoint.  We'll then
2157ff0cc061SDimitry Andric   // ask liveness for _every_ base inserted to see what is now live.  Then we
2158ff0cc061SDimitry Andric   // remove the dummy calls.
21597d523365SDimitry Andric   Holders.reserve(Holders.size() + Records.size());
21607d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
21617d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
2162ff0cc061SDimitry Andric 
2163ff0cc061SDimitry Andric     SmallVector<Value *, 128> Bases;
21647d523365SDimitry Andric     for (auto Pair : Info.PointerToBase)
2165ff0cc061SDimitry Andric       Bases.push_back(Pair.second);
21667d523365SDimitry Andric 
21677d523365SDimitry Andric     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2168ff0cc061SDimitry Andric   }
2169ff0cc061SDimitry Andric 
2170ff0cc061SDimitry Andric   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2171ff0cc061SDimitry Andric   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2172ff0cc061SDimitry Andric   // not the key issue.
21737d523365SDimitry Andric   recomputeLiveInValues(F, DT, ToUpdate, Records);
2174ff0cc061SDimitry Andric 
2175ff0cc061SDimitry Andric   if (PrintBasePointers) {
21767d523365SDimitry Andric     for (auto &Info : Records) {
2177ff0cc061SDimitry Andric       errs() << "Base Pairs: (w/Relocation)\n";
21787d523365SDimitry Andric       for (auto Pair : Info.PointerToBase) {
21797d523365SDimitry Andric         errs() << " derived ";
21807d523365SDimitry Andric         Pair.first->printAsOperand(errs(), false);
21817d523365SDimitry Andric         errs() << " base ";
21827d523365SDimitry Andric         Pair.second->printAsOperand(errs(), false);
21837d523365SDimitry Andric         errs() << "\n";
2184ff0cc061SDimitry Andric       }
2185ff0cc061SDimitry Andric     }
2186ff0cc061SDimitry Andric   }
21877d523365SDimitry Andric 
21887d523365SDimitry Andric   // It is possible that non-constant live variables have a constant base.  For
21897d523365SDimitry Andric   // example, a GEP with a variable offset from a global.  In this case we can
21907d523365SDimitry Andric   // remove it from the liveset.  We already don't add constants to the liveset
21917d523365SDimitry Andric   // because we assume they won't move at runtime and the GC doesn't need to be
21927d523365SDimitry Andric   // informed about them.  The same reasoning applies if the base is constant.
21937d523365SDimitry Andric   // Note that the relocation placement code relies on this filtering for
21947d523365SDimitry Andric   // correctness as it expects the base to be in the liveset, which isn't true
21957d523365SDimitry Andric   // if the base is constant.
21967d523365SDimitry Andric   for (auto &Info : Records)
21977d523365SDimitry Andric     for (auto &BasePair : Info.PointerToBase)
21987d523365SDimitry Andric       if (isa<Constant>(BasePair.second))
21993ca95b02SDimitry Andric         Info.LiveSet.remove(BasePair.first);
22007d523365SDimitry Andric 
22017d523365SDimitry Andric   for (CallInst *CI : Holders)
22027d523365SDimitry Andric     CI->eraseFromParent();
22037d523365SDimitry Andric 
22047d523365SDimitry Andric   Holders.clear();
2205ff0cc061SDimitry Andric 
2206ff0cc061SDimitry Andric   // In order to reduce live set of statepoint we might choose to rematerialize
22077d523365SDimitry Andric   // some values instead of relocating them. This is purely an optimization and
2208ff0cc061SDimitry Andric   // does not influence correctness.
22097d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++)
22107d523365SDimitry Andric     rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
2211ff0cc061SDimitry Andric 
22127d523365SDimitry Andric   // We need this to safely RAUW and delete call or invoke return values that
22137d523365SDimitry Andric   // may themselves be live over a statepoint.  For details, please see usage in
22147d523365SDimitry Andric   // makeStatepointExplicitImpl.
22157d523365SDimitry Andric   std::vector<DeferredReplacement> Replacements;
2216ff0cc061SDimitry Andric 
2217ff0cc061SDimitry Andric   // Now run through and replace the existing statepoints with new ones with
2218ff0cc061SDimitry Andric   // the live variables listed.  We do not yet update uses of the values being
2219ff0cc061SDimitry Andric   // relocated. We have references to live variables that need to
2220ff0cc061SDimitry Andric   // survive to the last iteration of this loop.  (By construction, the
2221ff0cc061SDimitry Andric   // previous statepoint can not be a live variable, thus we can and remove
2222ff0cc061SDimitry Andric   // the old statepoint calls as we go.)
22237d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++)
22247d523365SDimitry Andric     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
22257d523365SDimitry Andric 
22267d523365SDimitry Andric   ToUpdate.clear(); // prevent accident use of invalid CallSites
22277d523365SDimitry Andric 
22287d523365SDimitry Andric   for (auto &PR : Replacements)
22297d523365SDimitry Andric     PR.doReplacement();
22307d523365SDimitry Andric 
22317d523365SDimitry Andric   Replacements.clear();
22327d523365SDimitry Andric 
22337d523365SDimitry Andric   for (auto &Info : Records) {
22347d523365SDimitry Andric     // These live sets may contain state Value pointers, since we replaced calls
22357d523365SDimitry Andric     // with operand bundles with calls wrapped in gc.statepoint, and some of
22367d523365SDimitry Andric     // those calls may have been def'ing live gc pointers.  Clear these out to
22377d523365SDimitry Andric     // avoid accidentally using them.
22387d523365SDimitry Andric     //
22397d523365SDimitry Andric     // TODO: We should create a separate data structure that does not contain
22407d523365SDimitry Andric     // these live sets, and migrate to using that data structure from this point
22417d523365SDimitry Andric     // onward.
22427d523365SDimitry Andric     Info.LiveSet.clear();
22437d523365SDimitry Andric     Info.PointerToBase.clear();
2244ff0cc061SDimitry Andric   }
2245ff0cc061SDimitry Andric 
2246ff0cc061SDimitry Andric   // Do all the fixups of the original live variables to their relocated selves
22477d523365SDimitry Andric   SmallVector<Value *, 128> Live;
22487d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
22497d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
22507d523365SDimitry Andric 
2251ff0cc061SDimitry Andric     // We can't simply save the live set from the original insertion.  One of
2252ff0cc061SDimitry Andric     // the live values might be the result of a call which needs a safepoint.
2253ff0cc061SDimitry Andric     // That Value* no longer exists and we need to use the new gc_result.
2254ff0cc061SDimitry Andric     // Thankfully, the live set is embedded in the statepoint (and updated), so
2255ff0cc061SDimitry Andric     // we just grab that.
22567d523365SDimitry Andric     Statepoint Statepoint(Info.StatepointToken);
22577d523365SDimitry Andric     Live.insert(Live.end(), Statepoint.gc_args_begin(),
22587d523365SDimitry Andric                 Statepoint.gc_args_end());
2259ff0cc061SDimitry Andric #ifndef NDEBUG
2260ff0cc061SDimitry Andric     // Do some basic sanity checks on our liveness results before performing
2261ff0cc061SDimitry Andric     // relocation.  Relocation can and will turn mistakes in liveness results
2262ff0cc061SDimitry Andric     // into non-sensical code which is must harder to debug.
2263ff0cc061SDimitry Andric     // TODO: It would be nice to test consistency as well
22647d523365SDimitry Andric     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2265ff0cc061SDimitry Andric            "statepoint must be reachable or liveness is meaningless");
22667d523365SDimitry Andric     for (Value *V : Statepoint.gc_args()) {
2267ff0cc061SDimitry Andric       if (!isa<Instruction>(V))
2268ff0cc061SDimitry Andric         // Non-instruction values trivial dominate all possible uses
2269ff0cc061SDimitry Andric         continue;
22707d523365SDimitry Andric       auto *LiveInst = cast<Instruction>(V);
2271ff0cc061SDimitry Andric       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2272ff0cc061SDimitry Andric              "unreachable values should never be live");
22737d523365SDimitry Andric       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2274ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2275ff0cc061SDimitry Andric     }
2276ff0cc061SDimitry Andric #endif
2277ff0cc061SDimitry Andric   }
22787d523365SDimitry Andric   unique_unsorted(Live);
2279ff0cc061SDimitry Andric 
2280ff0cc061SDimitry Andric #ifndef NDEBUG
2281ff0cc061SDimitry Andric   // sanity check
22827d523365SDimitry Andric   for (auto *Ptr : Live)
2283444ed5c5SDimitry Andric     assert(isHandledGCPointerType(Ptr->getType()) &&
2284444ed5c5SDimitry Andric            "must be a gc pointer type");
2285ff0cc061SDimitry Andric #endif
2286ff0cc061SDimitry Andric 
22877d523365SDimitry Andric   relocationViaAlloca(F, DT, Live, Records);
22887d523365SDimitry Andric   return !Records.empty();
2289ff0cc061SDimitry Andric }
2290ff0cc061SDimitry Andric 
229197bc6c73SDimitry Andric // Handles both return values and arguments for Functions and CallSites.
229297bc6c73SDimitry Andric template <typename AttrHolder>
22937d523365SDimitry Andric static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
229497bc6c73SDimitry Andric                                       unsigned Index) {
229597bc6c73SDimitry Andric   AttrBuilder R;
229697bc6c73SDimitry Andric   if (AH.getDereferenceableBytes(Index))
229797bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
229897bc6c73SDimitry Andric                                   AH.getDereferenceableBytes(Index)));
229997bc6c73SDimitry Andric   if (AH.getDereferenceableOrNullBytes(Index))
230097bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
230197bc6c73SDimitry Andric                                   AH.getDereferenceableOrNullBytes(Index)));
23027d523365SDimitry Andric   if (AH.doesNotAlias(Index))
23037d523365SDimitry Andric     R.addAttribute(Attribute::NoAlias);
230497bc6c73SDimitry Andric 
230597bc6c73SDimitry Andric   if (!R.empty())
230697bc6c73SDimitry Andric     AH.setAttributes(AH.getAttributes().removeAttributes(
230797bc6c73SDimitry Andric         Ctx, Index, AttributeSet::get(Ctx, Index, R)));
230897bc6c73SDimitry Andric }
230997bc6c73SDimitry Andric 
231097bc6c73SDimitry Andric void
23117d523365SDimitry Andric RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
231297bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
231397bc6c73SDimitry Andric 
231497bc6c73SDimitry Andric   for (Argument &A : F.args())
231597bc6c73SDimitry Andric     if (isa<PointerType>(A.getType()))
23167d523365SDimitry Andric       RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
231797bc6c73SDimitry Andric 
231897bc6c73SDimitry Andric   if (isa<PointerType>(F.getReturnType()))
23197d523365SDimitry Andric     RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
232097bc6c73SDimitry Andric }
232197bc6c73SDimitry Andric 
23227d523365SDimitry Andric void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
232397bc6c73SDimitry Andric   if (F.empty())
232497bc6c73SDimitry Andric     return;
232597bc6c73SDimitry Andric 
232697bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
232797bc6c73SDimitry Andric   MDBuilder Builder(Ctx);
232897bc6c73SDimitry Andric 
23297d523365SDimitry Andric   for (Instruction &I : instructions(F)) {
233097bc6c73SDimitry Andric     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
233197bc6c73SDimitry Andric       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
233297bc6c73SDimitry Andric       bool IsImmutableTBAA =
233397bc6c73SDimitry Andric           MD->getNumOperands() == 4 &&
233497bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
233597bc6c73SDimitry Andric 
233697bc6c73SDimitry Andric       if (!IsImmutableTBAA)
233797bc6c73SDimitry Andric         continue; // no work to do, MD_tbaa is already marked mutable
233897bc6c73SDimitry Andric 
233997bc6c73SDimitry Andric       MDNode *Base = cast<MDNode>(MD->getOperand(0));
234097bc6c73SDimitry Andric       MDNode *Access = cast<MDNode>(MD->getOperand(1));
234197bc6c73SDimitry Andric       uint64_t Offset =
234297bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
234397bc6c73SDimitry Andric 
234497bc6c73SDimitry Andric       MDNode *MutableTBAA =
234597bc6c73SDimitry Andric           Builder.createTBAAStructTagNode(Base, Access, Offset);
234697bc6c73SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
234797bc6c73SDimitry Andric     }
234897bc6c73SDimitry Andric 
234997bc6c73SDimitry Andric     if (CallSite CS = CallSite(&I)) {
235097bc6c73SDimitry Andric       for (int i = 0, e = CS.arg_size(); i != e; i++)
235197bc6c73SDimitry Andric         if (isa<PointerType>(CS.getArgument(i)->getType()))
23527d523365SDimitry Andric           RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
235397bc6c73SDimitry Andric       if (isa<PointerType>(CS.getType()))
23547d523365SDimitry Andric         RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
235597bc6c73SDimitry Andric     }
235697bc6c73SDimitry Andric   }
235797bc6c73SDimitry Andric }
235897bc6c73SDimitry Andric 
2359ff0cc061SDimitry Andric /// Returns true if this function should be rewritten by this pass.  The main
2360ff0cc061SDimitry Andric /// point of this function is as an extension point for custom logic.
2361ff0cc061SDimitry Andric static bool shouldRewriteStatepointsIn(Function &F) {
2362ff0cc061SDimitry Andric   // TODO: This should check the GCStrategy
2363ff0cc061SDimitry Andric   if (F.hasGC()) {
2364444ed5c5SDimitry Andric     const auto &FunctionGCName = F.getGC();
2365ff0cc061SDimitry Andric     const StringRef StatepointExampleName("statepoint-example");
2366ff0cc061SDimitry Andric     const StringRef CoreCLRName("coreclr");
2367ff0cc061SDimitry Andric     return (StatepointExampleName == FunctionGCName) ||
2368ff0cc061SDimitry Andric            (CoreCLRName == FunctionGCName);
2369ff0cc061SDimitry Andric   } else
2370ff0cc061SDimitry Andric     return false;
2371ff0cc061SDimitry Andric }
2372ff0cc061SDimitry Andric 
23737d523365SDimitry Andric void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
237497bc6c73SDimitry Andric #ifndef NDEBUG
2375d88c1a5aSDimitry Andric   assert(any_of(M, shouldRewriteStatepointsIn) && "precondition!");
237697bc6c73SDimitry Andric #endif
237797bc6c73SDimitry Andric 
237897bc6c73SDimitry Andric   for (Function &F : M)
23797d523365SDimitry Andric     stripNonValidAttributesFromPrototype(F);
238097bc6c73SDimitry Andric 
238197bc6c73SDimitry Andric   for (Function &F : M)
23827d523365SDimitry Andric     stripNonValidAttributesFromBody(F);
238397bc6c73SDimitry Andric }
238497bc6c73SDimitry Andric 
2385ff0cc061SDimitry Andric bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2386ff0cc061SDimitry Andric   // Nothing to do for declarations.
2387ff0cc061SDimitry Andric   if (F.isDeclaration() || F.empty())
2388ff0cc061SDimitry Andric     return false;
2389ff0cc061SDimitry Andric 
2390ff0cc061SDimitry Andric   // Policy choice says not to rewrite - the most common reason is that we're
2391ff0cc061SDimitry Andric   // compiling code without a GCStrategy.
2392ff0cc061SDimitry Andric   if (!shouldRewriteStatepointsIn(F))
2393ff0cc061SDimitry Andric     return false;
2394ff0cc061SDimitry Andric 
239597bc6c73SDimitry Andric   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
23967d523365SDimitry Andric   TargetTransformInfo &TTI =
23977d523365SDimitry Andric       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
23987d523365SDimitry Andric 
23997d523365SDimitry Andric   auto NeedsRewrite = [](Instruction &I) {
24007d523365SDimitry Andric     if (ImmutableCallSite CS = ImmutableCallSite(&I))
24013ca95b02SDimitry Andric       return !callsGCLeafFunction(CS) && !isStatepoint(CS);
24027d523365SDimitry Andric     return false;
24037d523365SDimitry Andric   };
2404ff0cc061SDimitry Andric 
2405ff0cc061SDimitry Andric   // Gather all the statepoints which need rewritten.  Be careful to only
2406ff0cc061SDimitry Andric   // consider those in reachable code since we need to ask dominance queries
2407ff0cc061SDimitry Andric   // when rewriting.  We'll delete the unreachable ones in a moment.
2408ff0cc061SDimitry Andric   SmallVector<CallSite, 64> ParsePointNeeded;
2409ff0cc061SDimitry Andric   bool HasUnreachableStatepoint = false;
24107d523365SDimitry Andric   for (Instruction &I : instructions(F)) {
2411ff0cc061SDimitry Andric     // TODO: only the ones with the flag set!
24127d523365SDimitry Andric     if (NeedsRewrite(I)) {
2413ff0cc061SDimitry Andric       if (DT.isReachableFromEntry(I.getParent()))
2414ff0cc061SDimitry Andric         ParsePointNeeded.push_back(CallSite(&I));
2415ff0cc061SDimitry Andric       else
2416ff0cc061SDimitry Andric         HasUnreachableStatepoint = true;
2417ff0cc061SDimitry Andric     }
2418ff0cc061SDimitry Andric   }
2419ff0cc061SDimitry Andric 
2420ff0cc061SDimitry Andric   bool MadeChange = false;
2421ff0cc061SDimitry Andric 
2422ff0cc061SDimitry Andric   // Delete any unreachable statepoints so that we don't have unrewritten
2423ff0cc061SDimitry Andric   // statepoints surviving this pass.  This makes testing easier and the
2424ff0cc061SDimitry Andric   // resulting IR less confusing to human readers.  Rather than be fancy, we
2425ff0cc061SDimitry Andric   // just reuse a utility function which removes the unreachable blocks.
2426ff0cc061SDimitry Andric   if (HasUnreachableStatepoint)
2427ff0cc061SDimitry Andric     MadeChange |= removeUnreachableBlocks(F);
2428ff0cc061SDimitry Andric 
2429ff0cc061SDimitry Andric   // Return early if no work to do.
2430ff0cc061SDimitry Andric   if (ParsePointNeeded.empty())
2431ff0cc061SDimitry Andric     return MadeChange;
2432ff0cc061SDimitry Andric 
2433ff0cc061SDimitry Andric   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2434ff0cc061SDimitry Andric   // These are created by LCSSA.  They have the effect of increasing the size
2435ff0cc061SDimitry Andric   // of liveness sets for no good reason.  It may be harder to do this post
2436ff0cc061SDimitry Andric   // insertion since relocations and base phis can confuse things.
2437ff0cc061SDimitry Andric   for (BasicBlock &BB : F)
2438ff0cc061SDimitry Andric     if (BB.getUniquePredecessor()) {
2439ff0cc061SDimitry Andric       MadeChange = true;
2440ff0cc061SDimitry Andric       FoldSingleEntryPHINodes(&BB);
2441ff0cc061SDimitry Andric     }
2442ff0cc061SDimitry Andric 
24437d523365SDimitry Andric   // Before we start introducing relocations, we want to tweak the IR a bit to
24447d523365SDimitry Andric   // avoid unfortunate code generation effects.  The main example is that we
24457d523365SDimitry Andric   // want to try to make sure the comparison feeding a branch is after any
24467d523365SDimitry Andric   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
24477d523365SDimitry Andric   // values feeding a branch after relocation.  This is semantically correct,
24487d523365SDimitry Andric   // but results in extra register pressure since both the pre-relocation and
24497d523365SDimitry Andric   // post-relocation copies must be available in registers.  For code without
24507d523365SDimitry Andric   // relocations this is handled elsewhere, but teaching the scheduler to
24517d523365SDimitry Andric   // reverse the transform we're about to do would be slightly complex.
24527d523365SDimitry Andric   // Note: This may extend the live range of the inputs to the icmp and thus
24537d523365SDimitry Andric   // increase the liveset of any statepoint we move over.  This is profitable
24547d523365SDimitry Andric   // as long as all statepoints are in rare blocks.  If we had in-register
24557d523365SDimitry Andric   // lowering for live values this would be a much safer transform.
24567d523365SDimitry Andric   auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
24577d523365SDimitry Andric     if (auto *BI = dyn_cast<BranchInst>(TI))
24587d523365SDimitry Andric       if (BI->isConditional())
24597d523365SDimitry Andric         return dyn_cast<Instruction>(BI->getCondition());
24607d523365SDimitry Andric     // TODO: Extend this to handle switches
24617d523365SDimitry Andric     return nullptr;
24627d523365SDimitry Andric   };
24637d523365SDimitry Andric   for (BasicBlock &BB : F) {
24647d523365SDimitry Andric     TerminatorInst *TI = BB.getTerminator();
24657d523365SDimitry Andric     if (auto *Cond = getConditionInst(TI))
24667d523365SDimitry Andric       // TODO: Handle more than just ICmps here.  We should be able to move
24677d523365SDimitry Andric       // most instructions without side effects or memory access.
24687d523365SDimitry Andric       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
24697d523365SDimitry Andric         MadeChange = true;
24707d523365SDimitry Andric         Cond->moveBefore(TI);
24717d523365SDimitry Andric       }
24727d523365SDimitry Andric   }
24737d523365SDimitry Andric 
24747d523365SDimitry Andric   MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
2475ff0cc061SDimitry Andric   return MadeChange;
2476ff0cc061SDimitry Andric }
2477ff0cc061SDimitry Andric 
2478ff0cc061SDimitry Andric // liveness computation via standard dataflow
2479ff0cc061SDimitry Andric // -------------------------------------------------------------------
2480ff0cc061SDimitry Andric 
2481ff0cc061SDimitry Andric // TODO: Consider using bitvectors for liveness, the set of potentially
2482ff0cc061SDimitry Andric // interesting values should be small and easy to pre-compute.
2483ff0cc061SDimitry Andric 
2484ff0cc061SDimitry Andric /// Compute the live-in set for the location rbegin starting from
2485ff0cc061SDimitry Andric /// the live-out set of the basic block
24863ca95b02SDimitry Andric static void computeLiveInValues(BasicBlock::reverse_iterator Begin,
24873ca95b02SDimitry Andric                                 BasicBlock::reverse_iterator End,
24883ca95b02SDimitry Andric                                 SetVector<Value *> &LiveTmp) {
24893ca95b02SDimitry Andric   for (auto &I : make_range(Begin, End)) {
2490ff0cc061SDimitry Andric     // KILL/Def - Remove this definition from LiveIn
24913ca95b02SDimitry Andric     LiveTmp.remove(&I);
2492ff0cc061SDimitry Andric 
2493ff0cc061SDimitry Andric     // Don't consider *uses* in PHI nodes, we handle their contribution to
2494ff0cc061SDimitry Andric     // predecessor blocks when we seed the LiveOut sets
2495ff0cc061SDimitry Andric     if (isa<PHINode>(I))
2496ff0cc061SDimitry Andric       continue;
2497ff0cc061SDimitry Andric 
2498ff0cc061SDimitry Andric     // USE - Add to the LiveIn set for this instruction
24993ca95b02SDimitry Andric     for (Value *V : I.operands()) {
2500ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2501ff0cc061SDimitry Andric              "support for FCA unimplemented");
2502ff0cc061SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2503ff0cc061SDimitry Andric         // The choice to exclude all things constant here is slightly subtle.
25047d523365SDimitry Andric         // There are two independent reasons:
2505ff0cc061SDimitry Andric         // - We assume that things which are constant (from LLVM's definition)
2506ff0cc061SDimitry Andric         // do not move at runtime.  For example, the address of a global
2507ff0cc061SDimitry Andric         // variable is fixed, even though it's contents may not be.
2508ff0cc061SDimitry Andric         // - Second, we can't disallow arbitrary inttoptr constants even
2509ff0cc061SDimitry Andric         // if the language frontend does.  Optimization passes are free to
2510ff0cc061SDimitry Andric         // locally exploit facts without respect to global reachability.  This
2511ff0cc061SDimitry Andric         // can create sections of code which are dynamically unreachable and
2512ff0cc061SDimitry Andric         // contain just about anything.  (see constants.ll in tests)
2513ff0cc061SDimitry Andric         LiveTmp.insert(V);
2514ff0cc061SDimitry Andric       }
2515ff0cc061SDimitry Andric     }
2516ff0cc061SDimitry Andric   }
2517ff0cc061SDimitry Andric }
2518ff0cc061SDimitry Andric 
25193ca95b02SDimitry Andric static void computeLiveOutSeed(BasicBlock *BB, SetVector<Value *> &LiveTmp) {
2520ff0cc061SDimitry Andric   for (BasicBlock *Succ : successors(BB)) {
25213ca95b02SDimitry Andric     for (auto &I : *Succ) {
25223ca95b02SDimitry Andric       PHINode *PN = dyn_cast<PHINode>(&I);
25233ca95b02SDimitry Andric       if (!PN)
25243ca95b02SDimitry Andric         break;
25253ca95b02SDimitry Andric 
25263ca95b02SDimitry Andric       Value *V = PN->getIncomingValueForBlock(BB);
2527ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2528ff0cc061SDimitry Andric              "support for FCA unimplemented");
25293ca95b02SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V))
2530ff0cc061SDimitry Andric         LiveTmp.insert(V);
2531ff0cc061SDimitry Andric     }
2532ff0cc061SDimitry Andric   }
2533ff0cc061SDimitry Andric }
2534ff0cc061SDimitry Andric 
25353ca95b02SDimitry Andric static SetVector<Value *> computeKillSet(BasicBlock *BB) {
25363ca95b02SDimitry Andric   SetVector<Value *> KillSet;
2537ff0cc061SDimitry Andric   for (Instruction &I : *BB)
2538ff0cc061SDimitry Andric     if (isHandledGCPointerType(I.getType()))
2539ff0cc061SDimitry Andric       KillSet.insert(&I);
2540ff0cc061SDimitry Andric   return KillSet;
2541ff0cc061SDimitry Andric }
2542ff0cc061SDimitry Andric 
2543ff0cc061SDimitry Andric #ifndef NDEBUG
2544ff0cc061SDimitry Andric /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2545ff0cc061SDimitry Andric /// sanity check for the liveness computation.
25463ca95b02SDimitry Andric static void checkBasicSSA(DominatorTree &DT, SetVector<Value *> &Live,
2547ff0cc061SDimitry Andric                           TerminatorInst *TI, bool TermOkay = false) {
2548ff0cc061SDimitry Andric   for (Value *V : Live) {
2549ff0cc061SDimitry Andric     if (auto *I = dyn_cast<Instruction>(V)) {
2550ff0cc061SDimitry Andric       // The terminator can be a member of the LiveOut set.  LLVM's definition
2551ff0cc061SDimitry Andric       // of instruction dominance states that V does not dominate itself.  As
2552ff0cc061SDimitry Andric       // such, we need to special case this to allow it.
2553ff0cc061SDimitry Andric       if (TermOkay && TI == I)
2554ff0cc061SDimitry Andric         continue;
2555ff0cc061SDimitry Andric       assert(DT.dominates(I, TI) &&
2556ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2557ff0cc061SDimitry Andric     }
2558ff0cc061SDimitry Andric   }
2559ff0cc061SDimitry Andric }
2560ff0cc061SDimitry Andric 
2561ff0cc061SDimitry Andric /// Check that all the liveness sets used during the computation of liveness
2562ff0cc061SDimitry Andric /// obey basic SSA properties.  This is useful for finding cases where we miss
2563ff0cc061SDimitry Andric /// a def.
2564ff0cc061SDimitry Andric static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2565ff0cc061SDimitry Andric                           BasicBlock &BB) {
2566ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2567ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2568ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2569ff0cc061SDimitry Andric }
2570ff0cc061SDimitry Andric #endif
2571ff0cc061SDimitry Andric 
2572ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
2573ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data) {
25743ca95b02SDimitry Andric   SmallSetVector<BasicBlock *, 32> Worklist;
2575ff0cc061SDimitry Andric 
2576ff0cc061SDimitry Andric   // Seed the liveness for each individual block
2577ff0cc061SDimitry Andric   for (BasicBlock &BB : F) {
2578ff0cc061SDimitry Andric     Data.KillSet[&BB] = computeKillSet(&BB);
2579ff0cc061SDimitry Andric     Data.LiveSet[&BB].clear();
2580ff0cc061SDimitry Andric     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2581ff0cc061SDimitry Andric 
2582ff0cc061SDimitry Andric #ifndef NDEBUG
2583ff0cc061SDimitry Andric     for (Value *Kill : Data.KillSet[&BB])
2584ff0cc061SDimitry Andric       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2585ff0cc061SDimitry Andric #endif
2586ff0cc061SDimitry Andric 
25873ca95b02SDimitry Andric     Data.LiveOut[&BB] = SetVector<Value *>();
2588ff0cc061SDimitry Andric     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2589ff0cc061SDimitry Andric     Data.LiveIn[&BB] = Data.LiveSet[&BB];
25903ca95b02SDimitry Andric     Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
25913ca95b02SDimitry Andric     Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
2592ff0cc061SDimitry Andric     if (!Data.LiveIn[&BB].empty())
25933ca95b02SDimitry Andric       Worklist.insert(pred_begin(&BB), pred_end(&BB));
2594ff0cc061SDimitry Andric   }
2595ff0cc061SDimitry Andric 
2596ff0cc061SDimitry Andric   // Propagate that liveness until stable
2597ff0cc061SDimitry Andric   while (!Worklist.empty()) {
25983ca95b02SDimitry Andric     BasicBlock *BB = Worklist.pop_back_val();
2599ff0cc061SDimitry Andric 
26003ca95b02SDimitry Andric     // Compute our new liveout set, then exit early if it hasn't changed despite
26013ca95b02SDimitry Andric     // the contribution of our successor.
26023ca95b02SDimitry Andric     SetVector<Value *> LiveOut = Data.LiveOut[BB];
2603ff0cc061SDimitry Andric     const auto OldLiveOutSize = LiveOut.size();
2604ff0cc061SDimitry Andric     for (BasicBlock *Succ : successors(BB)) {
2605ff0cc061SDimitry Andric       assert(Data.LiveIn.count(Succ));
26063ca95b02SDimitry Andric       LiveOut.set_union(Data.LiveIn[Succ]);
2607ff0cc061SDimitry Andric     }
2608ff0cc061SDimitry Andric     // assert OutLiveOut is a subset of LiveOut
2609ff0cc061SDimitry Andric     if (OldLiveOutSize == LiveOut.size()) {
2610ff0cc061SDimitry Andric       // If the sets are the same size, then we didn't actually add anything
26113ca95b02SDimitry Andric       // when unioning our successors LiveIn.  Thus, the LiveIn of this block
2612ff0cc061SDimitry Andric       // hasn't changed.
2613ff0cc061SDimitry Andric       continue;
2614ff0cc061SDimitry Andric     }
2615ff0cc061SDimitry Andric     Data.LiveOut[BB] = LiveOut;
2616ff0cc061SDimitry Andric 
2617ff0cc061SDimitry Andric     // Apply the effects of this basic block
26183ca95b02SDimitry Andric     SetVector<Value *> LiveTmp = LiveOut;
26193ca95b02SDimitry Andric     LiveTmp.set_union(Data.LiveSet[BB]);
26203ca95b02SDimitry Andric     LiveTmp.set_subtract(Data.KillSet[BB]);
2621ff0cc061SDimitry Andric 
2622ff0cc061SDimitry Andric     assert(Data.LiveIn.count(BB));
26233ca95b02SDimitry Andric     const SetVector<Value *> &OldLiveIn = Data.LiveIn[BB];
2624ff0cc061SDimitry Andric     // assert: OldLiveIn is a subset of LiveTmp
2625ff0cc061SDimitry Andric     if (OldLiveIn.size() != LiveTmp.size()) {
2626ff0cc061SDimitry Andric       Data.LiveIn[BB] = LiveTmp;
26273ca95b02SDimitry Andric       Worklist.insert(pred_begin(BB), pred_end(BB));
2628ff0cc061SDimitry Andric     }
26293ca95b02SDimitry Andric   } // while (!Worklist.empty())
2630ff0cc061SDimitry Andric 
2631ff0cc061SDimitry Andric #ifndef NDEBUG
26327d523365SDimitry Andric   // Sanity check our output against SSA properties.  This helps catch any
2633ff0cc061SDimitry Andric   // missing kills during the above iteration.
26343ca95b02SDimitry Andric   for (BasicBlock &BB : F)
2635ff0cc061SDimitry Andric     checkBasicSSA(DT, Data, BB);
2636ff0cc061SDimitry Andric #endif
2637ff0cc061SDimitry Andric }
2638ff0cc061SDimitry Andric 
2639ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2640ff0cc061SDimitry Andric                               StatepointLiveSetTy &Out) {
2641ff0cc061SDimitry Andric 
2642ff0cc061SDimitry Andric   BasicBlock *BB = Inst->getParent();
2643ff0cc061SDimitry Andric 
2644ff0cc061SDimitry Andric   // Note: The copy is intentional and required
2645ff0cc061SDimitry Andric   assert(Data.LiveOut.count(BB));
26463ca95b02SDimitry Andric   SetVector<Value *> LiveOut = Data.LiveOut[BB];
2647ff0cc061SDimitry Andric 
2648ff0cc061SDimitry Andric   // We want to handle the statepoint itself oddly.  It's
2649ff0cc061SDimitry Andric   // call result is not live (normal), nor are it's arguments
2650ff0cc061SDimitry Andric   // (unless they're used again later).  This adjustment is
2651ff0cc061SDimitry Andric   // specifically what we need to relocate
2652d88c1a5aSDimitry Andric   computeLiveInValues(BB->rbegin(), ++Inst->getIterator().getReverse(),
2653d88c1a5aSDimitry Andric                       LiveOut);
26543ca95b02SDimitry Andric   LiveOut.remove(Inst);
2655ff0cc061SDimitry Andric   Out.insert(LiveOut.begin(), LiveOut.end());
2656ff0cc061SDimitry Andric }
2657ff0cc061SDimitry Andric 
2658ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
26593ca95b02SDimitry Andric                                   CallSite CS,
2660ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &Info) {
2661ff0cc061SDimitry Andric   Instruction *Inst = CS.getInstruction();
2662ff0cc061SDimitry Andric   StatepointLiveSetTy Updated;
2663ff0cc061SDimitry Andric   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2664ff0cc061SDimitry Andric 
2665ff0cc061SDimitry Andric #ifndef NDEBUG
2666ff0cc061SDimitry Andric   DenseSet<Value *> Bases;
26673ca95b02SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2668ff0cc061SDimitry Andric     Bases.insert(KVPair.second);
2669ff0cc061SDimitry Andric #endif
26703ca95b02SDimitry Andric 
2671ff0cc061SDimitry Andric   // We may have base pointers which are now live that weren't before.  We need
2672ff0cc061SDimitry Andric   // to update the PointerToBase structure to reflect this.
2673ff0cc061SDimitry Andric   for (auto V : Updated)
26743ca95b02SDimitry Andric     if (Info.PointerToBase.insert({V, V}).second) {
26753ca95b02SDimitry Andric       assert(Bases.count(V) && "Can't find base for unexpected live value!");
2676ff0cc061SDimitry Andric       continue;
2677ff0cc061SDimitry Andric     }
2678ff0cc061SDimitry Andric 
2679ff0cc061SDimitry Andric #ifndef NDEBUG
26803ca95b02SDimitry Andric   for (auto V : Updated)
2681ff0cc061SDimitry Andric     assert(Info.PointerToBase.count(V) &&
26823ca95b02SDimitry Andric            "Must be able to find base for live value!");
2683ff0cc061SDimitry Andric #endif
2684ff0cc061SDimitry Andric 
2685ff0cc061SDimitry Andric   // Remove any stale base mappings - this can happen since our liveness is
26863ca95b02SDimitry Andric   // more precise then the one inherent in the base pointer analysis.
2687ff0cc061SDimitry Andric   DenseSet<Value *> ToErase;
2688ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2689ff0cc061SDimitry Andric     if (!Updated.count(KVPair.first))
2690ff0cc061SDimitry Andric       ToErase.insert(KVPair.first);
26913ca95b02SDimitry Andric 
26923ca95b02SDimitry Andric   for (auto *V : ToErase)
2693ff0cc061SDimitry Andric     Info.PointerToBase.erase(V);
2694ff0cc061SDimitry Andric 
2695ff0cc061SDimitry Andric #ifndef NDEBUG
2696ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2697ff0cc061SDimitry Andric     assert(Updated.count(KVPair.first) && "record for non-live value");
2698ff0cc061SDimitry Andric #endif
2699ff0cc061SDimitry Andric 
27007d523365SDimitry Andric   Info.LiveSet = Updated;
2701ff0cc061SDimitry Andric }
2702