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"
177d523365SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
18ff0cc061SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
19ff0cc061SDimitry Andric #include "llvm/ADT/SetOperations.h"
20ff0cc061SDimitry Andric #include "llvm/ADT/Statistic.h"
21ff0cc061SDimitry Andric #include "llvm/ADT/DenseSet.h"
22ff0cc061SDimitry Andric #include "llvm/ADT/SetVector.h"
23ff0cc061SDimitry Andric #include "llvm/ADT/StringRef.h"
247d523365SDimitry Andric #include "llvm/ADT/MapVector.h"
25ff0cc061SDimitry Andric #include "llvm/IR/BasicBlock.h"
26ff0cc061SDimitry Andric #include "llvm/IR/CallSite.h"
27ff0cc061SDimitry Andric #include "llvm/IR/Dominators.h"
28ff0cc061SDimitry Andric #include "llvm/IR/Function.h"
29ff0cc061SDimitry Andric #include "llvm/IR/IRBuilder.h"
30ff0cc061SDimitry Andric #include "llvm/IR/InstIterator.h"
31ff0cc061SDimitry Andric #include "llvm/IR/Instructions.h"
32ff0cc061SDimitry Andric #include "llvm/IR/Intrinsics.h"
33ff0cc061SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
34ff0cc061SDimitry Andric #include "llvm/IR/Module.h"
3597bc6c73SDimitry Andric #include "llvm/IR/MDBuilder.h"
36ff0cc061SDimitry Andric #include "llvm/IR/Statepoint.h"
37ff0cc061SDimitry Andric #include "llvm/IR/Value.h"
38ff0cc061SDimitry Andric #include "llvm/IR/Verifier.h"
39ff0cc061SDimitry Andric #include "llvm/Support/Debug.h"
40ff0cc061SDimitry Andric #include "llvm/Support/CommandLine.h"
41ff0cc061SDimitry Andric #include "llvm/Transforms/Scalar.h"
42ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
44ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
45ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
46ff0cc061SDimitry Andric 
47ff0cc061SDimitry Andric #define DEBUG_TYPE "rewrite-statepoints-for-gc"
48ff0cc061SDimitry Andric 
49ff0cc061SDimitry Andric using namespace llvm;
50ff0cc061SDimitry Andric 
51ff0cc061SDimitry Andric // Print the liveset found at the insert location
52ff0cc061SDimitry Andric static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
53ff0cc061SDimitry Andric                                   cl::init(false));
54ff0cc061SDimitry Andric static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
55ff0cc061SDimitry Andric                                       cl::init(false));
56ff0cc061SDimitry Andric // Print out the base pointers for debugging
57ff0cc061SDimitry Andric static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
58ff0cc061SDimitry Andric                                        cl::init(false));
59ff0cc061SDimitry Andric 
60ff0cc061SDimitry Andric // Cost threshold measuring when it is profitable to rematerialize value instead
61ff0cc061SDimitry Andric // of relocating it
62ff0cc061SDimitry Andric static cl::opt<unsigned>
63ff0cc061SDimitry Andric RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
64ff0cc061SDimitry Andric                            cl::init(6));
65ff0cc061SDimitry Andric 
66ff0cc061SDimitry Andric #ifdef XDEBUG
67ff0cc061SDimitry Andric static bool ClobberNonLive = true;
68ff0cc061SDimitry Andric #else
69ff0cc061SDimitry Andric static bool ClobberNonLive = false;
70ff0cc061SDimitry Andric #endif
71ff0cc061SDimitry Andric static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
72ff0cc061SDimitry Andric                                                   cl::location(ClobberNonLive),
73ff0cc061SDimitry Andric                                                   cl::Hidden);
74ff0cc061SDimitry Andric 
757d523365SDimitry Andric static cl::opt<bool> UseDeoptBundles("rs4gc-use-deopt-bundles", cl::Hidden,
767d523365SDimitry Andric                                      cl::init(false));
777d523365SDimitry Andric static cl::opt<bool>
787d523365SDimitry Andric     AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
797d523365SDimitry Andric                                    cl::Hidden, cl::init(true));
807d523365SDimitry Andric 
81444ed5c5SDimitry Andric /// Should we split vectors of pointers into their individual elements?  This
82444ed5c5SDimitry Andric /// is known to be buggy, but the alternate implementation isn't yet ready.
83444ed5c5SDimitry Andric /// This is purely to provide a debugging and dianostic hook until the vector
84444ed5c5SDimitry Andric /// split is replaced with vector relocations.
85444ed5c5SDimitry Andric static cl::opt<bool> UseVectorSplit("rs4gc-split-vector-values", cl::Hidden,
86444ed5c5SDimitry Andric                                     cl::init(true));
87444ed5c5SDimitry Andric 
88ff0cc061SDimitry Andric namespace {
8997bc6c73SDimitry Andric struct RewriteStatepointsForGC : public ModulePass {
90ff0cc061SDimitry Andric   static char ID; // Pass identification, replacement for typeid
91ff0cc061SDimitry Andric 
9297bc6c73SDimitry Andric   RewriteStatepointsForGC() : ModulePass(ID) {
93ff0cc061SDimitry Andric     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
94ff0cc061SDimitry Andric   }
9597bc6c73SDimitry Andric   bool runOnFunction(Function &F);
9697bc6c73SDimitry Andric   bool runOnModule(Module &M) override {
9797bc6c73SDimitry Andric     bool Changed = false;
9897bc6c73SDimitry Andric     for (Function &F : M)
9997bc6c73SDimitry Andric       Changed |= runOnFunction(F);
10097bc6c73SDimitry Andric 
10197bc6c73SDimitry Andric     if (Changed) {
1027d523365SDimitry Andric       // stripNonValidAttributes asserts that shouldRewriteStatepointsIn
10397bc6c73SDimitry Andric       // returns true for at least one function in the module.  Since at least
10497bc6c73SDimitry Andric       // one function changed, we know that the precondition is satisfied.
1057d523365SDimitry Andric       stripNonValidAttributes(M);
10697bc6c73SDimitry Andric     }
10797bc6c73SDimitry Andric 
10897bc6c73SDimitry Andric     return Changed;
10997bc6c73SDimitry Andric   }
110ff0cc061SDimitry Andric 
111ff0cc061SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
112ff0cc061SDimitry Andric     // We add and rewrite a bunch of instructions, but don't really do much
113ff0cc061SDimitry Andric     // else.  We could in theory preserve a lot more analyses here.
114ff0cc061SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
115ff0cc061SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
116ff0cc061SDimitry Andric   }
11797bc6c73SDimitry Andric 
11897bc6c73SDimitry Andric   /// The IR fed into RewriteStatepointsForGC may have had attributes implying
11997bc6c73SDimitry Andric   /// dereferenceability that are no longer valid/correct after
12097bc6c73SDimitry Andric   /// RewriteStatepointsForGC has run.  This is because semantically, after
12197bc6c73SDimitry Andric   /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
1227d523365SDimitry Andric   /// heap.  stripNonValidAttributes (conservatively) restores correctness
12397bc6c73SDimitry Andric   /// by erasing all attributes in the module that externally imply
12497bc6c73SDimitry Andric   /// dereferenceability.
1257d523365SDimitry Andric   /// Similar reasoning also applies to the noalias attributes. gc.statepoint
1267d523365SDimitry Andric   /// can touch the entire heap including noalias objects.
1277d523365SDimitry Andric   void stripNonValidAttributes(Module &M);
12897bc6c73SDimitry Andric 
1297d523365SDimitry Andric   // Helpers for stripNonValidAttributes
1307d523365SDimitry Andric   void stripNonValidAttributesFromBody(Function &F);
1317d523365SDimitry Andric   void stripNonValidAttributesFromPrototype(Function &F);
132ff0cc061SDimitry Andric };
133ff0cc061SDimitry Andric } // namespace
134ff0cc061SDimitry Andric 
135ff0cc061SDimitry Andric char RewriteStatepointsForGC::ID = 0;
136ff0cc061SDimitry Andric 
13797bc6c73SDimitry Andric ModulePass *llvm::createRewriteStatepointsForGCPass() {
138ff0cc061SDimitry Andric   return new RewriteStatepointsForGC();
139ff0cc061SDimitry Andric }
140ff0cc061SDimitry Andric 
141ff0cc061SDimitry Andric INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
142ff0cc061SDimitry Andric                       "Make relocations explicit at statepoints", false, false)
143ff0cc061SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
144ff0cc061SDimitry Andric INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
145ff0cc061SDimitry Andric                     "Make relocations explicit at statepoints", false, false)
146ff0cc061SDimitry Andric 
147ff0cc061SDimitry Andric namespace {
148ff0cc061SDimitry Andric struct GCPtrLivenessData {
149ff0cc061SDimitry Andric   /// Values defined in this block.
150ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
151ff0cc061SDimitry Andric   /// Values used in this block (and thus live); does not included values
152ff0cc061SDimitry Andric   /// killed within this block.
153ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
154ff0cc061SDimitry Andric 
155ff0cc061SDimitry Andric   /// Values live into this basic block (i.e. used by any
156ff0cc061SDimitry Andric   /// instruction in this basic block or ones reachable from here)
157ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
158ff0cc061SDimitry Andric 
159ff0cc061SDimitry Andric   /// Values live out of this basic block (i.e. live into
160ff0cc061SDimitry Andric   /// any successor block)
161ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
162ff0cc061SDimitry Andric };
163ff0cc061SDimitry Andric 
164ff0cc061SDimitry Andric // The type of the internal cache used inside the findBasePointers family
165ff0cc061SDimitry Andric // of functions.  From the callers perspective, this is an opaque type and
166ff0cc061SDimitry Andric // should not be inspected.
167ff0cc061SDimitry Andric //
168ff0cc061SDimitry Andric // In the actual implementation this caches two relations:
169ff0cc061SDimitry Andric // - The base relation itself (i.e. this pointer is based on that one)
170ff0cc061SDimitry Andric // - The base defining value relation (i.e. before base_phi insertion)
171ff0cc061SDimitry Andric // Generally, after the execution of a full findBasePointer call, only the
172ff0cc061SDimitry Andric // base relation will remain.  Internally, we add a mixture of the two
173ff0cc061SDimitry Andric // types, then update all the second type to the first type
174ff0cc061SDimitry Andric typedef DenseMap<Value *, Value *> DefiningValueMapTy;
1757d523365SDimitry Andric typedef DenseSet<Value *> StatepointLiveSetTy;
1767d523365SDimitry Andric typedef DenseMap<AssertingVH<Instruction>, AssertingVH<Value>>
1777d523365SDimitry Andric   RematerializedValueMapTy;
178ff0cc061SDimitry Andric 
179ff0cc061SDimitry Andric struct PartiallyConstructedSafepointRecord {
1807d523365SDimitry Andric   /// The set of values known to be live across this safepoint
1817d523365SDimitry Andric   StatepointLiveSetTy LiveSet;
182ff0cc061SDimitry Andric 
183ff0cc061SDimitry Andric   /// Mapping from live pointers to a base-defining-value
1847d523365SDimitry Andric   DenseMap<Value *, Value *> PointerToBase;
185ff0cc061SDimitry Andric 
186ff0cc061SDimitry Andric   /// The *new* gc.statepoint instruction itself.  This produces the token
187ff0cc061SDimitry Andric   /// that normal path gc.relocates and the gc.result are tied to.
188ff0cc061SDimitry Andric   Instruction *StatepointToken;
189ff0cc061SDimitry Andric 
190ff0cc061SDimitry Andric   /// Instruction to which exceptional gc relocates are attached
191ff0cc061SDimitry Andric   /// Makes it easier to iterate through them during relocationViaAlloca.
192ff0cc061SDimitry Andric   Instruction *UnwindToken;
193ff0cc061SDimitry Andric 
194ff0cc061SDimitry Andric   /// Record live values we are rematerialized instead of relocating.
1957d523365SDimitry Andric   /// They are not included into 'LiveSet' field.
196ff0cc061SDimitry Andric   /// Maps rematerialized copy to it's original value.
197ff0cc061SDimitry Andric   RematerializedValueMapTy RematerializedValues;
198ff0cc061SDimitry Andric };
1993dac3a9bSDimitry Andric }
200ff0cc061SDimitry Andric 
2017d523365SDimitry Andric static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
2027d523365SDimitry Andric   assert(UseDeoptBundles && "Should not be called otherwise!");
2037d523365SDimitry Andric 
2047d523365SDimitry Andric   Optional<OperandBundleUse> DeoptBundle = CS.getOperandBundle("deopt");
2057d523365SDimitry Andric 
2067d523365SDimitry Andric   if (!DeoptBundle.hasValue()) {
2077d523365SDimitry Andric     assert(AllowStatepointWithNoDeoptInfo &&
2087d523365SDimitry Andric            "Found non-leaf call without deopt info!");
2097d523365SDimitry Andric     return None;
2107d523365SDimitry Andric   }
2117d523365SDimitry Andric 
2127d523365SDimitry Andric   return DeoptBundle.getValue().Inputs;
2137d523365SDimitry Andric }
2147d523365SDimitry Andric 
215ff0cc061SDimitry Andric /// Compute the live-in set for every basic block in the function
216ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
217ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data);
218ff0cc061SDimitry Andric 
219ff0cc061SDimitry Andric /// Given results from the dataflow liveness computation, find the set of live
220ff0cc061SDimitry Andric /// Values at a particular instruction.
221ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
222ff0cc061SDimitry Andric                               StatepointLiveSetTy &out);
223ff0cc061SDimitry Andric 
224ff0cc061SDimitry Andric // TODO: Once we can get to the GCStrategy, this becomes
2257d523365SDimitry Andric // Optional<bool> isGCManagedPointer(const Type *Ty) const override {
226ff0cc061SDimitry Andric 
2277d523365SDimitry Andric static bool isGCPointerType(Type *T) {
2287d523365SDimitry Andric   if (auto *PT = dyn_cast<PointerType>(T))
229ff0cc061SDimitry Andric     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
230ff0cc061SDimitry Andric     // GC managed heap.  We know that a pointer into this heap needs to be
231ff0cc061SDimitry Andric     // updated and that no other pointer does.
232ff0cc061SDimitry Andric     return (1 == PT->getAddressSpace());
233ff0cc061SDimitry Andric   return false;
234ff0cc061SDimitry Andric }
235ff0cc061SDimitry Andric 
236ff0cc061SDimitry Andric // Return true if this type is one which a) is a gc pointer or contains a GC
237ff0cc061SDimitry Andric // pointer and b) is of a type this code expects to encounter as a live value.
238ff0cc061SDimitry Andric // (The insertion code will assert that a type which matches (a) and not (b)
239ff0cc061SDimitry Andric // is not encountered.)
240ff0cc061SDimitry Andric static bool isHandledGCPointerType(Type *T) {
241ff0cc061SDimitry Andric   // We fully support gc pointers
242ff0cc061SDimitry Andric   if (isGCPointerType(T))
243ff0cc061SDimitry Andric     return true;
244ff0cc061SDimitry Andric   // We partially support vectors of gc pointers. The code will assert if it
245ff0cc061SDimitry Andric   // can't handle something.
246ff0cc061SDimitry Andric   if (auto VT = dyn_cast<VectorType>(T))
247ff0cc061SDimitry Andric     if (isGCPointerType(VT->getElementType()))
248ff0cc061SDimitry Andric       return true;
249ff0cc061SDimitry Andric   return false;
250ff0cc061SDimitry Andric }
251ff0cc061SDimitry Andric 
252ff0cc061SDimitry Andric #ifndef NDEBUG
253ff0cc061SDimitry Andric /// Returns true if this type contains a gc pointer whether we know how to
254ff0cc061SDimitry Andric /// handle that type or not.
255ff0cc061SDimitry Andric static bool containsGCPtrType(Type *Ty) {
256ff0cc061SDimitry Andric   if (isGCPointerType(Ty))
257ff0cc061SDimitry Andric     return true;
258ff0cc061SDimitry Andric   if (VectorType *VT = dyn_cast<VectorType>(Ty))
259ff0cc061SDimitry Andric     return isGCPointerType(VT->getScalarType());
260ff0cc061SDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
261ff0cc061SDimitry Andric     return containsGCPtrType(AT->getElementType());
262ff0cc061SDimitry Andric   if (StructType *ST = dyn_cast<StructType>(Ty))
2637d523365SDimitry Andric     return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
2647d523365SDimitry Andric                        containsGCPtrType);
265ff0cc061SDimitry Andric   return false;
266ff0cc061SDimitry Andric }
267ff0cc061SDimitry Andric 
268ff0cc061SDimitry Andric // Returns true if this is a type which a) is a gc pointer or contains a GC
269ff0cc061SDimitry Andric // pointer and b) is of a type which the code doesn't expect (i.e. first class
270ff0cc061SDimitry Andric // aggregates).  Used to trip assertions.
271ff0cc061SDimitry Andric static bool isUnhandledGCPointerType(Type *Ty) {
272ff0cc061SDimitry Andric   return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
273ff0cc061SDimitry Andric }
274ff0cc061SDimitry Andric #endif
275ff0cc061SDimitry Andric 
2767d523365SDimitry Andric static bool order_by_name(Value *a, Value *b) {
277ff0cc061SDimitry Andric   if (a->hasName() && b->hasName()) {
278ff0cc061SDimitry Andric     return -1 == a->getName().compare(b->getName());
279ff0cc061SDimitry Andric   } else if (a->hasName() && !b->hasName()) {
280ff0cc061SDimitry Andric     return true;
281ff0cc061SDimitry Andric   } else if (!a->hasName() && b->hasName()) {
282ff0cc061SDimitry Andric     return false;
283ff0cc061SDimitry Andric   } else {
284ff0cc061SDimitry Andric     // Better than nothing, but not stable
285ff0cc061SDimitry Andric     return a < b;
286ff0cc061SDimitry Andric   }
287ff0cc061SDimitry Andric }
288ff0cc061SDimitry Andric 
2897d523365SDimitry Andric // Return the name of the value suffixed with the provided value, or if the
2907d523365SDimitry Andric // value didn't have a name, the default value specified.
2917d523365SDimitry Andric static std::string suffixed_name_or(Value *V, StringRef Suffix,
2927d523365SDimitry Andric                                     StringRef DefaultName) {
2937d523365SDimitry Andric   return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
2947d523365SDimitry Andric }
2957d523365SDimitry Andric 
296ff0cc061SDimitry Andric // Conservatively identifies any definitions which might be live at the
297ff0cc061SDimitry Andric // given instruction. The  analysis is performed immediately before the
298ff0cc061SDimitry Andric // given instruction. Values defined by that instruction are not considered
299ff0cc061SDimitry Andric // live.  Values used by that instruction are considered live.
300ff0cc061SDimitry Andric static void analyzeParsePointLiveness(
301ff0cc061SDimitry Andric     DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
302ff0cc061SDimitry Andric     const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
303ff0cc061SDimitry Andric   Instruction *inst = CS.getInstruction();
304ff0cc061SDimitry Andric 
3057d523365SDimitry Andric   StatepointLiveSetTy LiveSet;
3067d523365SDimitry Andric   findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
307ff0cc061SDimitry Andric 
308ff0cc061SDimitry Andric   if (PrintLiveSet) {
309ff0cc061SDimitry Andric     // Note: This output is used by several of the test cases
3107d523365SDimitry Andric     // The order of elements in a set is not stable, put them in a vec and sort
311ff0cc061SDimitry Andric     // by name
3127d523365SDimitry Andric     SmallVector<Value *, 64> Temp;
3137d523365SDimitry Andric     Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
3147d523365SDimitry Andric     std::sort(Temp.begin(), Temp.end(), order_by_name);
315ff0cc061SDimitry Andric     errs() << "Live Variables:\n";
3167d523365SDimitry Andric     for (Value *V : Temp)
3177d523365SDimitry Andric       dbgs() << " " << V->getName() << " " << *V << "\n";
318ff0cc061SDimitry Andric   }
319ff0cc061SDimitry Andric   if (PrintLiveSetSize) {
320ff0cc061SDimitry Andric     errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
3217d523365SDimitry Andric     errs() << "Number live values: " << LiveSet.size() << "\n";
322ff0cc061SDimitry Andric   }
3237d523365SDimitry Andric   result.LiveSet = LiveSet;
324ff0cc061SDimitry Andric }
325ff0cc061SDimitry Andric 
3267d523365SDimitry Andric static bool isKnownBaseResult(Value *V);
3277d523365SDimitry Andric namespace {
3287d523365SDimitry Andric /// A single base defining value - An immediate base defining value for an
3297d523365SDimitry Andric /// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
3307d523365SDimitry Andric /// For instructions which have multiple pointer [vector] inputs or that
3317d523365SDimitry Andric /// transition between vector and scalar types, there is no immediate base
3327d523365SDimitry Andric /// defining value.  The 'base defining value' for 'Def' is the transitive
3337d523365SDimitry Andric /// closure of this relation stopping at the first instruction which has no
3347d523365SDimitry Andric /// immediate base defining value.  The b.d.v. might itself be a base pointer,
3357d523365SDimitry Andric /// but it can also be an arbitrary derived pointer.
3367d523365SDimitry Andric struct BaseDefiningValueResult {
3377d523365SDimitry Andric   /// Contains the value which is the base defining value.
3387d523365SDimitry Andric   Value * const BDV;
3397d523365SDimitry Andric   /// True if the base defining value is also known to be an actual base
3407d523365SDimitry Andric   /// pointer.
3417d523365SDimitry Andric   const bool IsKnownBase;
3427d523365SDimitry Andric   BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
3437d523365SDimitry Andric     : BDV(BDV), IsKnownBase(IsKnownBase) {
3447d523365SDimitry Andric #ifndef NDEBUG
3457d523365SDimitry Andric     // Check consistency between new and old means of checking whether a BDV is
3467d523365SDimitry Andric     // a base.
3477d523365SDimitry Andric     bool MustBeBase = isKnownBaseResult(BDV);
3487d523365SDimitry Andric     assert(!MustBeBase || MustBeBase == IsKnownBase);
3497d523365SDimitry Andric #endif
3507d523365SDimitry Andric   }
3517d523365SDimitry Andric };
3527d523365SDimitry Andric }
3537d523365SDimitry Andric 
3547d523365SDimitry Andric static BaseDefiningValueResult findBaseDefiningValue(Value *I);
355ff0cc061SDimitry Andric 
3563dac3a9bSDimitry Andric /// Return a base defining value for the 'Index' element of the given vector
3573dac3a9bSDimitry Andric /// instruction 'I'.  If Index is null, returns a BDV for the entire vector
3583dac3a9bSDimitry Andric /// 'I'.  As an optimization, this method will try to determine when the
3593dac3a9bSDimitry Andric /// element is known to already be a base pointer.  If this can be established,
3603dac3a9bSDimitry Andric /// the second value in the returned pair will be true.  Note that either a
3613dac3a9bSDimitry Andric /// vector or a pointer typed value can be returned.  For the former, the
3623dac3a9bSDimitry Andric /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
3633dac3a9bSDimitry Andric /// If the later, the return pointer is a BDV (or possibly a base) for the
3643dac3a9bSDimitry Andric /// particular element in 'I'.
3657d523365SDimitry Andric static BaseDefiningValueResult
3667d523365SDimitry Andric findBaseDefiningValueOfVector(Value *I) {
367ff0cc061SDimitry Andric   // Each case parallels findBaseDefiningValue below, see that code for
368ff0cc061SDimitry Andric   // detailed motivation.
369ff0cc061SDimitry Andric 
370ff0cc061SDimitry Andric   if (isa<Argument>(I))
371ff0cc061SDimitry Andric     // An incoming argument to the function is a base pointer
3727d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
373ff0cc061SDimitry Andric 
374444ed5c5SDimitry Andric   if (isa<Constant>(I))
375444ed5c5SDimitry Andric     // Constant vectors consist only of constant pointers.
3767d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
377ff0cc061SDimitry Andric 
378ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
3797d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
380ff0cc061SDimitry Andric 
3817d523365SDimitry Andric   if (isa<InsertElementInst>(I))
3823dac3a9bSDimitry Andric     // We don't know whether this vector contains entirely base pointers or
3833dac3a9bSDimitry Andric     // not.  To be conservatively correct, we treat it as a BDV and will
3843dac3a9bSDimitry Andric     // duplicate code as needed to construct a parallel vector of bases.
3857d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
386ff0cc061SDimitry Andric 
3873dac3a9bSDimitry Andric   if (isa<ShuffleVectorInst>(I))
3883dac3a9bSDimitry Andric     // We don't know whether this vector contains entirely base pointers or
3893dac3a9bSDimitry Andric     // not.  To be conservatively correct, we treat it as a BDV and will
3903dac3a9bSDimitry Andric     // duplicate code as needed to construct a parallel vector of bases.
3913dac3a9bSDimitry Andric     // TODO: There a number of local optimizations which could be applied here
3923dac3a9bSDimitry Andric     // for particular sufflevector patterns.
3937d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
3943dac3a9bSDimitry Andric 
3953dac3a9bSDimitry Andric   // A PHI or Select is a base defining value.  The outer findBasePointer
3963dac3a9bSDimitry Andric   // algorithm is responsible for constructing a base value for this BDV.
3973dac3a9bSDimitry Andric   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
3983dac3a9bSDimitry Andric          "unknown vector instruction - no base found for vector element");
3997d523365SDimitry Andric   return BaseDefiningValueResult(I, false);
4003dac3a9bSDimitry Andric }
4013dac3a9bSDimitry Andric 
402ff0cc061SDimitry Andric /// Helper function for findBasePointer - Will return a value which either a)
4037d523365SDimitry Andric /// defines the base pointer for the input, b) blocks the simple search
4047d523365SDimitry Andric /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
4057d523365SDimitry Andric /// from pointer to vector type or back.
4067d523365SDimitry Andric static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
407444ed5c5SDimitry Andric   assert(I->getType()->isPtrOrPtrVectorTy() &&
408444ed5c5SDimitry Andric          "Illegal to ask for the base pointer of a non-pointer type");
409444ed5c5SDimitry Andric 
4103dac3a9bSDimitry Andric   if (I->getType()->isVectorTy())
4117d523365SDimitry Andric     return findBaseDefiningValueOfVector(I);
4123dac3a9bSDimitry Andric 
413ff0cc061SDimitry Andric   if (isa<Argument>(I))
414ff0cc061SDimitry Andric     // An incoming argument to the function is a base pointer
415ff0cc061SDimitry Andric     // We should have never reached here if this argument isn't an gc value
4167d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
417ff0cc061SDimitry Andric 
4184d0b32cdSDimitry Andric   if (isa<Constant>(I))
4194d0b32cdSDimitry Andric     // We assume that objects with a constant base (e.g. a global) can't move
4204d0b32cdSDimitry Andric     // and don't need to be reported to the collector because they are always
4214d0b32cdSDimitry Andric     // live.  All constants have constant bases.  Besides global references, all
4224d0b32cdSDimitry Andric     // kinds of constants (e.g. undef, constant expressions, null pointers) can
4234d0b32cdSDimitry Andric     // be introduced by the inliner or the optimizer, especially on dynamically
4244d0b32cdSDimitry Andric     // dead paths.  See e.g. test4 in constants.ll.
4257d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
426ff0cc061SDimitry Andric 
427ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(I)) {
428ff0cc061SDimitry Andric     Value *Def = CI->stripPointerCasts();
4297d523365SDimitry Andric     // If stripping pointer casts changes the address space there is an
4307d523365SDimitry Andric     // addrspacecast in between.
4317d523365SDimitry Andric     assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
4327d523365SDimitry Andric                cast<PointerType>(CI->getType())->getAddressSpace() &&
4337d523365SDimitry Andric            "unsupported addrspacecast");
434ff0cc061SDimitry Andric     // If we find a cast instruction here, it means we've found a cast which is
435ff0cc061SDimitry Andric     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
436ff0cc061SDimitry Andric     // handle int->ptr conversion.
437ff0cc061SDimitry Andric     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
438ff0cc061SDimitry Andric     return findBaseDefiningValue(Def);
439ff0cc061SDimitry Andric   }
440ff0cc061SDimitry Andric 
441ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
4427d523365SDimitry Andric     // The value loaded is an gc base itself
4437d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
4447d523365SDimitry Andric 
445ff0cc061SDimitry Andric 
446ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
447ff0cc061SDimitry Andric     // The base of this GEP is the base
448ff0cc061SDimitry Andric     return findBaseDefiningValue(GEP->getPointerOperand());
449ff0cc061SDimitry Andric 
450ff0cc061SDimitry Andric   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
451ff0cc061SDimitry Andric     switch (II->getIntrinsicID()) {
452ff0cc061SDimitry Andric     default:
453ff0cc061SDimitry Andric       // fall through to general call handling
454ff0cc061SDimitry Andric       break;
455ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_statepoint:
4567d523365SDimitry Andric       llvm_unreachable("statepoints don't produce pointers");
457ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_relocate: {
458ff0cc061SDimitry Andric       // Rerunning safepoint insertion after safepoints are already
459ff0cc061SDimitry Andric       // inserted is not supported.  It could probably be made to work,
460ff0cc061SDimitry Andric       // but why are you doing this?  There's no good reason.
461ff0cc061SDimitry Andric       llvm_unreachable("repeat safepoint insertion is not supported");
462ff0cc061SDimitry Andric     }
463ff0cc061SDimitry Andric     case Intrinsic::gcroot:
464ff0cc061SDimitry Andric       // Currently, this mechanism hasn't been extended to work with gcroot.
465ff0cc061SDimitry Andric       // There's no reason it couldn't be, but I haven't thought about the
466ff0cc061SDimitry Andric       // implications much.
467ff0cc061SDimitry Andric       llvm_unreachable(
468ff0cc061SDimitry Andric           "interaction with the gcroot mechanism is not supported");
469ff0cc061SDimitry Andric     }
470ff0cc061SDimitry Andric   }
471ff0cc061SDimitry Andric   // We assume that functions in the source language only return base
472ff0cc061SDimitry Andric   // pointers.  This should probably be generalized via attributes to support
473ff0cc061SDimitry Andric   // both source language and internal functions.
474ff0cc061SDimitry Andric   if (isa<CallInst>(I) || isa<InvokeInst>(I))
4757d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
476ff0cc061SDimitry Andric 
477ff0cc061SDimitry Andric   // I have absolutely no idea how to implement this part yet.  It's not
4787d523365SDimitry Andric   // necessarily hard, I just haven't really looked at it yet.
479ff0cc061SDimitry Andric   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
480ff0cc061SDimitry Andric 
481ff0cc061SDimitry Andric   if (isa<AtomicCmpXchgInst>(I))
482ff0cc061SDimitry Andric     // A CAS is effectively a atomic store and load combined under a
483ff0cc061SDimitry Andric     // predicate.  From the perspective of base pointers, we just treat it
484ff0cc061SDimitry Andric     // like a load.
4857d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
486ff0cc061SDimitry Andric 
487ff0cc061SDimitry Andric   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
488ff0cc061SDimitry Andric                                    "binary ops which don't apply to pointers");
489ff0cc061SDimitry Andric 
490ff0cc061SDimitry Andric   // The aggregate ops.  Aggregates can either be in the heap or on the
491ff0cc061SDimitry Andric   // stack, but in either case, this is simply a field load.  As a result,
492ff0cc061SDimitry Andric   // this is a defining definition of the base just like a load is.
493ff0cc061SDimitry Andric   if (isa<ExtractValueInst>(I))
4947d523365SDimitry Andric     return BaseDefiningValueResult(I, true);
495ff0cc061SDimitry Andric 
496ff0cc061SDimitry Andric   // We should never see an insert vector since that would require we be
497ff0cc061SDimitry Andric   // tracing back a struct value not a pointer value.
498ff0cc061SDimitry Andric   assert(!isa<InsertValueInst>(I) &&
499ff0cc061SDimitry Andric          "Base pointer for a struct is meaningless");
500ff0cc061SDimitry Andric 
5017d523365SDimitry Andric   // An extractelement produces a base result exactly when it's input does.
5027d523365SDimitry Andric   // We may need to insert a parallel instruction to extract the appropriate
5037d523365SDimitry Andric   // element out of the base vector corresponding to the input. Given this,
5047d523365SDimitry Andric   // it's analogous to the phi and select case even though it's not a merge.
5057d523365SDimitry Andric   if (isa<ExtractElementInst>(I))
5067d523365SDimitry Andric     // Note: There a lot of obvious peephole cases here.  This are deliberately
5077d523365SDimitry Andric     // handled after the main base pointer inference algorithm to make writing
5087d523365SDimitry Andric     // test cases to exercise that code easier.
5097d523365SDimitry Andric     return BaseDefiningValueResult(I, false);
5107d523365SDimitry Andric 
511ff0cc061SDimitry Andric   // The last two cases here don't return a base pointer.  Instead, they
5127d523365SDimitry Andric   // return a value which dynamically selects from among several base
513ff0cc061SDimitry Andric   // derived pointers (each with it's own base potentially).  It's the job of
514ff0cc061SDimitry Andric   // the caller to resolve these.
515ff0cc061SDimitry Andric   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
516ff0cc061SDimitry Andric          "missing instruction case in findBaseDefiningValing");
5177d523365SDimitry Andric   return BaseDefiningValueResult(I, false);
518ff0cc061SDimitry Andric }
519ff0cc061SDimitry Andric 
520ff0cc061SDimitry Andric /// Returns the base defining value for this value.
521ff0cc061SDimitry Andric static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
522ff0cc061SDimitry Andric   Value *&Cached = Cache[I];
523ff0cc061SDimitry Andric   if (!Cached) {
5247d523365SDimitry Andric     Cached = findBaseDefiningValue(I).BDV;
5257d523365SDimitry Andric     DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
5267d523365SDimitry Andric                  << Cached->getName() << "\n");
527ff0cc061SDimitry Andric   }
528ff0cc061SDimitry Andric   assert(Cache[I] != nullptr);
529ff0cc061SDimitry Andric   return Cached;
530ff0cc061SDimitry Andric }
531ff0cc061SDimitry Andric 
532ff0cc061SDimitry Andric /// Return a base pointer for this value if known.  Otherwise, return it's
533ff0cc061SDimitry Andric /// base defining value.
534ff0cc061SDimitry Andric static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
535ff0cc061SDimitry Andric   Value *Def = findBaseDefiningValueCached(I, Cache);
536ff0cc061SDimitry Andric   auto Found = Cache.find(Def);
537ff0cc061SDimitry Andric   if (Found != Cache.end()) {
538ff0cc061SDimitry Andric     // Either a base-of relation, or a self reference.  Caller must check.
539ff0cc061SDimitry Andric     return Found->second;
540ff0cc061SDimitry Andric   }
541ff0cc061SDimitry Andric   // Only a BDV available
542ff0cc061SDimitry Andric   return Def;
543ff0cc061SDimitry Andric }
544ff0cc061SDimitry Andric 
545ff0cc061SDimitry Andric /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
546ff0cc061SDimitry Andric /// is it known to be a base pointer?  Or do we need to continue searching.
547ff0cc061SDimitry Andric static bool isKnownBaseResult(Value *V) {
5487d523365SDimitry Andric   if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
5497d523365SDimitry Andric       !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
5507d523365SDimitry Andric       !isa<ShuffleVectorInst>(V)) {
551ff0cc061SDimitry Andric     // no recursion possible
552ff0cc061SDimitry Andric     return true;
553ff0cc061SDimitry Andric   }
554ff0cc061SDimitry Andric   if (isa<Instruction>(V) &&
555ff0cc061SDimitry Andric       cast<Instruction>(V)->getMetadata("is_base_value")) {
556ff0cc061SDimitry Andric     // This is a previously inserted base phi or select.  We know
557ff0cc061SDimitry Andric     // that this is a base value.
558ff0cc061SDimitry Andric     return true;
559ff0cc061SDimitry Andric   }
560ff0cc061SDimitry Andric 
561ff0cc061SDimitry Andric   // We need to keep searching
562ff0cc061SDimitry Andric   return false;
563ff0cc061SDimitry Andric }
564ff0cc061SDimitry Andric 
565ff0cc061SDimitry Andric namespace {
5667d523365SDimitry Andric /// Models the state of a single base defining value in the findBasePointer
5677d523365SDimitry Andric /// algorithm for determining where a new instruction is needed to propagate
5687d523365SDimitry Andric /// the base of this BDV.
5697d523365SDimitry Andric class BDVState {
570ff0cc061SDimitry Andric public:
571ff0cc061SDimitry Andric   enum Status { Unknown, Base, Conflict };
572ff0cc061SDimitry Andric 
5737d523365SDimitry Andric   BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
574ff0cc061SDimitry Andric     assert(status != Base || b);
575ff0cc061SDimitry Andric   }
5767d523365SDimitry Andric   explicit BDVState(Value *b) : status(Base), base(b) {}
5777d523365SDimitry Andric   BDVState() : status(Unknown), base(nullptr) {}
578ff0cc061SDimitry Andric 
579ff0cc061SDimitry Andric   Status getStatus() const { return status; }
580ff0cc061SDimitry Andric   Value *getBase() const { return base; }
581ff0cc061SDimitry Andric 
582ff0cc061SDimitry Andric   bool isBase() const { return getStatus() == Base; }
583ff0cc061SDimitry Andric   bool isUnknown() const { return getStatus() == Unknown; }
584ff0cc061SDimitry Andric   bool isConflict() const { return getStatus() == Conflict; }
585ff0cc061SDimitry Andric 
5867d523365SDimitry Andric   bool operator==(const BDVState &other) const {
587ff0cc061SDimitry Andric     return base == other.base && status == other.status;
588ff0cc061SDimitry Andric   }
589ff0cc061SDimitry Andric 
5907d523365SDimitry Andric   bool operator!=(const BDVState &other) const { return !(*this == other); }
591ff0cc061SDimitry Andric 
5927d523365SDimitry Andric   LLVM_DUMP_METHOD
5937d523365SDimitry Andric   void dump() const { print(dbgs()); dbgs() << '\n'; }
5947d523365SDimitry Andric 
5957d523365SDimitry Andric   void print(raw_ostream &OS) const {
5967d523365SDimitry Andric     switch (status) {
5977d523365SDimitry Andric     case Unknown:
5987d523365SDimitry Andric       OS << "U";
5997d523365SDimitry Andric       break;
6007d523365SDimitry Andric     case Base:
6017d523365SDimitry Andric       OS << "B";
6027d523365SDimitry Andric       break;
6037d523365SDimitry Andric     case Conflict:
6047d523365SDimitry Andric       OS << "C";
6057d523365SDimitry Andric       break;
6067d523365SDimitry Andric     };
6077d523365SDimitry Andric     OS << " (" << base << " - "
608ff0cc061SDimitry Andric        << (base ? base->getName() : "nullptr") << "): ";
609ff0cc061SDimitry Andric   }
610ff0cc061SDimitry Andric 
611ff0cc061SDimitry Andric private:
612ff0cc061SDimitry Andric   Status status;
6137d523365SDimitry Andric   AssertingVH<Value> base; // non null only if status == base
614ff0cc061SDimitry Andric };
615ff0cc061SDimitry Andric }
616ff0cc061SDimitry Andric 
6177d523365SDimitry Andric #ifndef NDEBUG
6187d523365SDimitry Andric static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
6197d523365SDimitry Andric   State.print(OS);
6207d523365SDimitry Andric   return OS;
6217d523365SDimitry Andric }
6227d523365SDimitry Andric #endif
6237d523365SDimitry Andric 
6247d523365SDimitry Andric namespace {
6257d523365SDimitry Andric // Values of type BDVState form a lattice, and this is a helper
6267d523365SDimitry Andric // class that implementes the meet operation.  The meat of the meet
6277d523365SDimitry Andric // operation is implemented in MeetBDVStates::pureMeet
6287d523365SDimitry Andric class MeetBDVStates {
6297d523365SDimitry Andric public:
6307d523365SDimitry Andric   /// Initializes the currentResult to the TOP state so that if can be met with
6317d523365SDimitry Andric   /// any other state to produce that state.
6327d523365SDimitry Andric   MeetBDVStates() {}
6337d523365SDimitry Andric 
6347d523365SDimitry Andric   // Destructively meet the current result with the given BDVState
6357d523365SDimitry Andric   void meetWith(BDVState otherState) {
6367d523365SDimitry Andric     currentResult = meet(otherState, currentResult);
6377d523365SDimitry Andric   }
6387d523365SDimitry Andric 
6397d523365SDimitry Andric   BDVState getResult() const { return currentResult; }
640ff0cc061SDimitry Andric 
641ff0cc061SDimitry Andric private:
6427d523365SDimitry Andric   BDVState currentResult;
643ff0cc061SDimitry Andric 
6447d523365SDimitry Andric   /// Perform a meet operation on two elements of the BDVState lattice.
6457d523365SDimitry Andric   static BDVState meet(BDVState LHS, BDVState RHS) {
6467d523365SDimitry Andric     assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
6477d523365SDimitry Andric            "math is wrong: meet does not commute!");
6487d523365SDimitry Andric     BDVState Result = pureMeet(LHS, RHS);
6497d523365SDimitry Andric     DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
6507d523365SDimitry Andric                  << " produced " << Result << "\n");
6517d523365SDimitry Andric     return Result;
652ff0cc061SDimitry Andric   }
653ff0cc061SDimitry Andric 
6547d523365SDimitry Andric   static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
655ff0cc061SDimitry Andric     switch (stateA.getStatus()) {
6567d523365SDimitry Andric     case BDVState::Unknown:
657ff0cc061SDimitry Andric       return stateB;
658ff0cc061SDimitry Andric 
6597d523365SDimitry Andric     case BDVState::Base:
660ff0cc061SDimitry Andric       assert(stateA.getBase() && "can't be null");
661ff0cc061SDimitry Andric       if (stateB.isUnknown())
662ff0cc061SDimitry Andric         return stateA;
663ff0cc061SDimitry Andric 
664ff0cc061SDimitry Andric       if (stateB.isBase()) {
665ff0cc061SDimitry Andric         if (stateA.getBase() == stateB.getBase()) {
666ff0cc061SDimitry Andric           assert(stateA == stateB && "equality broken!");
667ff0cc061SDimitry Andric           return stateA;
668ff0cc061SDimitry Andric         }
6697d523365SDimitry Andric         return BDVState(BDVState::Conflict);
670ff0cc061SDimitry Andric       }
671ff0cc061SDimitry Andric       assert(stateB.isConflict() && "only three states!");
6727d523365SDimitry Andric       return BDVState(BDVState::Conflict);
673ff0cc061SDimitry Andric 
6747d523365SDimitry Andric     case BDVState::Conflict:
675ff0cc061SDimitry Andric       return stateA;
676ff0cc061SDimitry Andric     }
677ff0cc061SDimitry Andric     llvm_unreachable("only three states!");
678ff0cc061SDimitry Andric   }
679ff0cc061SDimitry Andric };
6803dac3a9bSDimitry Andric }
6817d523365SDimitry Andric 
6827d523365SDimitry Andric 
683ff0cc061SDimitry Andric /// For a given value or instruction, figure out what base ptr it's derived
684ff0cc061SDimitry Andric /// from.  For gc objects, this is simply itself.  On success, returns a value
685ff0cc061SDimitry Andric /// which is the base pointer.  (This is reliable and can be used for
686ff0cc061SDimitry Andric /// relocation.)  On failure, returns nullptr.
687ff0cc061SDimitry Andric static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
688ff0cc061SDimitry Andric   Value *def = findBaseOrBDV(I, cache);
689ff0cc061SDimitry Andric 
690ff0cc061SDimitry Andric   if (isKnownBaseResult(def)) {
691ff0cc061SDimitry Andric     return def;
692ff0cc061SDimitry Andric   }
693ff0cc061SDimitry Andric 
694ff0cc061SDimitry Andric   // Here's the rough algorithm:
695ff0cc061SDimitry Andric   // - For every SSA value, construct a mapping to either an actual base
696ff0cc061SDimitry Andric   //   pointer or a PHI which obscures the base pointer.
697ff0cc061SDimitry Andric   // - Construct a mapping from PHI to unknown TOP state.  Use an
698ff0cc061SDimitry Andric   //   optimistic algorithm to propagate base pointer information.  Lattice
699ff0cc061SDimitry Andric   //   looks like:
700ff0cc061SDimitry Andric   //   UNKNOWN
701ff0cc061SDimitry Andric   //   b1 b2 b3 b4
702ff0cc061SDimitry Andric   //   CONFLICT
703ff0cc061SDimitry Andric   //   When algorithm terminates, all PHIs will either have a single concrete
704ff0cc061SDimitry Andric   //   base or be in a conflict state.
705ff0cc061SDimitry Andric   // - For every conflict, insert a dummy PHI node without arguments.  Add
706ff0cc061SDimitry Andric   //   these to the base[Instruction] = BasePtr mapping.  For every
707ff0cc061SDimitry Andric   //   non-conflict, add the actual base.
708ff0cc061SDimitry Andric   //  - For every conflict, add arguments for the base[a] of each input
709ff0cc061SDimitry Andric   //   arguments.
710ff0cc061SDimitry Andric   //
711ff0cc061SDimitry Andric   // Note: A simpler form of this would be to add the conflict form of all
712ff0cc061SDimitry Andric   // PHIs without running the optimistic algorithm.  This would be
7137d523365SDimitry Andric   // analogous to pessimistic data flow and would likely lead to an
714ff0cc061SDimitry Andric   // overall worse solution.
715ff0cc061SDimitry Andric 
7167d523365SDimitry Andric #ifndef NDEBUG
7177d523365SDimitry Andric   auto isExpectedBDVType = [](Value *BDV) {
7187d523365SDimitry Andric     return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
7197d523365SDimitry Andric            isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
7207d523365SDimitry Andric   };
7217d523365SDimitry Andric #endif
7227d523365SDimitry Andric 
7237d523365SDimitry Andric   // Once populated, will contain a mapping from each potentially non-base BDV
7247d523365SDimitry Andric   // to a lattice value (described above) which corresponds to that BDV.
7257d523365SDimitry Andric   // We use the order of insertion (DFS over the def/use graph) to provide a
7267d523365SDimitry Andric   // stable deterministic ordering for visiting DenseMaps (which are unordered)
7277d523365SDimitry Andric   // below.  This is important for deterministic compilation.
7287d523365SDimitry Andric   MapVector<Value *, BDVState> States;
7297d523365SDimitry Andric 
7307d523365SDimitry Andric   // Recursively fill in all base defining values reachable from the initial
7317d523365SDimitry Andric   // one for which we don't already know a definite base value for
7327d523365SDimitry Andric   /* scope */ {
7337d523365SDimitry Andric     SmallVector<Value*, 16> Worklist;
7347d523365SDimitry Andric     Worklist.push_back(def);
7357d523365SDimitry Andric     States.insert(std::make_pair(def, BDVState()));
7367d523365SDimitry Andric     while (!Worklist.empty()) {
7377d523365SDimitry Andric       Value *Current = Worklist.pop_back_val();
7387d523365SDimitry Andric       assert(!isKnownBaseResult(Current) && "why did it get added?");
7397d523365SDimitry Andric 
7407d523365SDimitry Andric       auto visitIncomingValue = [&](Value *InVal) {
7417d523365SDimitry Andric         Value *Base = findBaseOrBDV(InVal, cache);
7427d523365SDimitry Andric         if (isKnownBaseResult(Base))
7437d523365SDimitry Andric           // Known bases won't need new instructions introduced and can be
7447d523365SDimitry Andric           // ignored safely
7457d523365SDimitry Andric           return;
7467d523365SDimitry Andric         assert(isExpectedBDVType(Base) && "the only non-base values "
7477d523365SDimitry Andric                "we see should be base defining values");
7487d523365SDimitry Andric         if (States.insert(std::make_pair(Base, BDVState())).second)
7497d523365SDimitry Andric           Worklist.push_back(Base);
7507d523365SDimitry Andric       };
7517d523365SDimitry Andric       if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
7527d523365SDimitry Andric         for (Value *InVal : Phi->incoming_values())
7537d523365SDimitry Andric           visitIncomingValue(InVal);
7547d523365SDimitry Andric       } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
7557d523365SDimitry Andric         visitIncomingValue(Sel->getTrueValue());
7567d523365SDimitry Andric         visitIncomingValue(Sel->getFalseValue());
7577d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
7587d523365SDimitry Andric         visitIncomingValue(EE->getVectorOperand());
7597d523365SDimitry Andric       } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
7607d523365SDimitry Andric         visitIncomingValue(IE->getOperand(0)); // vector operand
7617d523365SDimitry Andric         visitIncomingValue(IE->getOperand(1)); // scalar operand
7627d523365SDimitry Andric       } else {
7637d523365SDimitry Andric         // There is one known class of instructions we know we don't handle.
7647d523365SDimitry Andric         assert(isa<ShuffleVectorInst>(Current));
7657d523365SDimitry Andric         llvm_unreachable("unimplemented instruction case");
766ff0cc061SDimitry Andric       }
767ff0cc061SDimitry Andric     }
768ff0cc061SDimitry Andric   }
769ff0cc061SDimitry Andric 
7707d523365SDimitry Andric #ifndef NDEBUG
7717d523365SDimitry Andric   DEBUG(dbgs() << "States after initialization:\n");
7727d523365SDimitry Andric   for (auto Pair : States) {
7737d523365SDimitry Andric     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
774ff0cc061SDimitry Andric   }
7757d523365SDimitry Andric #endif
776ff0cc061SDimitry Andric 
7777d523365SDimitry Andric   // Return a phi state for a base defining value.  We'll generate a new
7787d523365SDimitry Andric   // base state for known bases and expect to find a cached state otherwise.
7797d523365SDimitry Andric   auto getStateForBDV = [&](Value *baseValue) {
7807d523365SDimitry Andric     if (isKnownBaseResult(baseValue))
7817d523365SDimitry Andric       return BDVState(baseValue);
7827d523365SDimitry Andric     auto I = States.find(baseValue);
7837d523365SDimitry Andric     assert(I != States.end() && "lookup failed!");
7847d523365SDimitry Andric     return I->second;
7857d523365SDimitry Andric   };
786ff0cc061SDimitry Andric 
787ff0cc061SDimitry Andric   bool progress = true;
788ff0cc061SDimitry Andric   while (progress) {
789ff0cc061SDimitry Andric #ifndef NDEBUG
7907d523365SDimitry Andric     const size_t oldSize = States.size();
791ff0cc061SDimitry Andric #endif
792ff0cc061SDimitry Andric     progress = false;
7937d523365SDimitry Andric     // We're only changing values in this loop, thus safe to keep iterators.
7947d523365SDimitry Andric     // Since this is computing a fixed point, the order of visit does not
7957d523365SDimitry Andric     // effect the result.  TODO: We could use a worklist here and make this run
7967d523365SDimitry Andric     // much faster.
7977d523365SDimitry Andric     for (auto Pair : States) {
7987d523365SDimitry Andric       Value *BDV = Pair.first;
7997d523365SDimitry Andric       assert(!isKnownBaseResult(BDV) && "why did it get added?");
800ff0cc061SDimitry Andric 
8017d523365SDimitry Andric       // Given an input value for the current instruction, return a BDVState
8027d523365SDimitry Andric       // instance which represents the BDV of that value.
8037d523365SDimitry Andric       auto getStateForInput = [&](Value *V) mutable {
8047d523365SDimitry Andric         Value *BDV = findBaseOrBDV(V, cache);
8057d523365SDimitry Andric         return getStateForBDV(BDV);
8067d523365SDimitry Andric       };
8077d523365SDimitry Andric 
8087d523365SDimitry Andric       MeetBDVStates calculateMeet;
8097d523365SDimitry Andric       if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
8107d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
8117d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
8127d523365SDimitry Andric       } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
8137d523365SDimitry Andric         for (Value *Val : Phi->incoming_values())
8147d523365SDimitry Andric           calculateMeet.meetWith(getStateForInput(Val));
8157d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
8167d523365SDimitry Andric         // The 'meet' for an extractelement is slightly trivial, but it's still
8177d523365SDimitry Andric         // useful in that it drives us to conflict if our input is.
8187d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
8197d523365SDimitry Andric       } else {
8207d523365SDimitry Andric         // Given there's a inherent type mismatch between the operands, will
8217d523365SDimitry Andric         // *always* produce Conflict.
8227d523365SDimitry Andric         auto *IE = cast<InsertElementInst>(BDV);
8237d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
8247d523365SDimitry Andric         calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
8257d523365SDimitry Andric       }
8267d523365SDimitry Andric 
8277d523365SDimitry Andric       BDVState oldState = States[BDV];
8287d523365SDimitry Andric       BDVState newState = calculateMeet.getResult();
829ff0cc061SDimitry Andric       if (oldState != newState) {
830ff0cc061SDimitry Andric         progress = true;
8317d523365SDimitry Andric         States[BDV] = newState;
832ff0cc061SDimitry Andric       }
833ff0cc061SDimitry Andric     }
834ff0cc061SDimitry Andric 
8357d523365SDimitry Andric     assert(oldSize == States.size() &&
8367d523365SDimitry Andric            "fixed point shouldn't be adding any new nodes to state");
837ff0cc061SDimitry Andric   }
838ff0cc061SDimitry Andric 
8397d523365SDimitry Andric #ifndef NDEBUG
8407d523365SDimitry Andric   DEBUG(dbgs() << "States after meet iteration:\n");
8417d523365SDimitry Andric   for (auto Pair : States) {
8427d523365SDimitry Andric     DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
843ff0cc061SDimitry Andric   }
8447d523365SDimitry Andric #endif
845ff0cc061SDimitry Andric 
846ff0cc061SDimitry Andric   // Insert Phis for all conflicts
847ff0cc061SDimitry Andric   // TODO: adjust naming patterns to avoid this order of iteration dependency
8487d523365SDimitry Andric   for (auto Pair : States) {
8497d523365SDimitry Andric     Instruction *I = cast<Instruction>(Pair.first);
8507d523365SDimitry Andric     BDVState State = Pair.second;
8517d523365SDimitry Andric     assert(!isKnownBaseResult(I) && "why did it get added?");
8527d523365SDimitry Andric     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
8537d523365SDimitry Andric 
8547d523365SDimitry Andric     // extractelement instructions are a bit special in that we may need to
8557d523365SDimitry Andric     // insert an extract even when we know an exact base for the instruction.
8567d523365SDimitry Andric     // The problem is that we need to convert from a vector base to a scalar
8577d523365SDimitry Andric     // base for the particular indice we're interested in.
8587d523365SDimitry Andric     if (State.isBase() && isa<ExtractElementInst>(I) &&
8597d523365SDimitry Andric         isa<VectorType>(State.getBase()->getType())) {
8607d523365SDimitry Andric       auto *EE = cast<ExtractElementInst>(I);
8617d523365SDimitry Andric       // TODO: In many cases, the new instruction is just EE itself.  We should
8627d523365SDimitry Andric       // exploit this, but can't do it here since it would break the invariant
8637d523365SDimitry Andric       // about the BDV not being known to be a base.
8647d523365SDimitry Andric       auto *BaseInst = ExtractElementInst::Create(State.getBase(),
8657d523365SDimitry Andric                                                   EE->getIndexOperand(),
8667d523365SDimitry Andric                                                   "base_ee", EE);
8677d523365SDimitry Andric       BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
8687d523365SDimitry Andric       States[I] = BDVState(BDVState::Base, BaseInst);
8697d523365SDimitry Andric     }
8707d523365SDimitry Andric 
8717d523365SDimitry Andric     // Since we're joining a vector and scalar base, they can never be the
8727d523365SDimitry Andric     // same.  As a result, we should always see insert element having reached
8737d523365SDimitry Andric     // the conflict state.
8747d523365SDimitry Andric     if (isa<InsertElementInst>(I)) {
8757d523365SDimitry Andric       assert(State.isConflict());
8767d523365SDimitry Andric     }
8777d523365SDimitry Andric 
8787d523365SDimitry Andric     if (!State.isConflict())
879ff0cc061SDimitry Andric       continue;
880ff0cc061SDimitry Andric 
8817d523365SDimitry Andric     /// Create and insert a new instruction which will represent the base of
8827d523365SDimitry Andric     /// the given instruction 'I'.
8837d523365SDimitry Andric     auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
8847d523365SDimitry Andric       if (isa<PHINode>(I)) {
8857d523365SDimitry Andric         BasicBlock *BB = I->getParent();
8867d523365SDimitry Andric         int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
8877d523365SDimitry Andric         assert(NumPreds > 0 && "how did we reach here");
8887d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_phi");
8897d523365SDimitry Andric         return PHINode::Create(I->getType(), NumPreds, Name, I);
8907d523365SDimitry Andric       } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
891ff0cc061SDimitry Andric         // The undef will be replaced later
8927d523365SDimitry Andric         UndefValue *Undef = UndefValue::get(Sel->getType());
8937d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_select");
8947d523365SDimitry Andric         return SelectInst::Create(Sel->getCondition(), Undef,
8957d523365SDimitry Andric                                   Undef, Name, Sel);
8967d523365SDimitry Andric       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
8977d523365SDimitry Andric         UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
8987d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_ee");
8997d523365SDimitry Andric         return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
9007d523365SDimitry Andric                                           EE);
9017d523365SDimitry Andric       } else {
9027d523365SDimitry Andric         auto *IE = cast<InsertElementInst>(I);
9037d523365SDimitry Andric         UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
9047d523365SDimitry Andric         UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
9057d523365SDimitry Andric         std::string Name = suffixed_name_or(I, ".base", "base_ie");
9067d523365SDimitry Andric         return InsertElementInst::Create(VecUndef, ScalarUndef,
9077d523365SDimitry Andric                                          IE->getOperand(2), Name, IE);
9087d523365SDimitry Andric       }
9097d523365SDimitry Andric 
9107d523365SDimitry Andric     };
9117d523365SDimitry Andric     Instruction *BaseInst = MakeBaseInstPlaceholder(I);
912ff0cc061SDimitry Andric     // Add metadata marking this as a base value
9137d523365SDimitry Andric     BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
9147d523365SDimitry Andric     States[I] = BDVState(BDVState::Conflict, BaseInst);
915ff0cc061SDimitry Andric   }
916ff0cc061SDimitry Andric 
9177d523365SDimitry Andric   // Returns a instruction which produces the base pointer for a given
9187d523365SDimitry Andric   // instruction.  The instruction is assumed to be an input to one of the BDVs
9197d523365SDimitry Andric   // seen in the inference algorithm above.  As such, we must either already
9207d523365SDimitry Andric   // know it's base defining value is a base, or have inserted a new
9217d523365SDimitry Andric   // instruction to propagate the base of it's BDV and have entered that newly
9227d523365SDimitry Andric   // introduced instruction into the state table.  In either case, we are
9237d523365SDimitry Andric   // assured to be able to determine an instruction which produces it's base
9247d523365SDimitry Andric   // pointer.
9257d523365SDimitry Andric   auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
9267d523365SDimitry Andric     Value *BDV = findBaseOrBDV(Input, cache);
9277d523365SDimitry Andric     Value *Base = nullptr;
9287d523365SDimitry Andric     if (isKnownBaseResult(BDV)) {
9297d523365SDimitry Andric       Base = BDV;
9307d523365SDimitry Andric     } else {
9317d523365SDimitry Andric       // Either conflict or base.
9327d523365SDimitry Andric       assert(States.count(BDV));
9337d523365SDimitry Andric       Base = States[BDV].getBase();
9347d523365SDimitry Andric     }
9357d523365SDimitry Andric     assert(Base && "can't be null");
9367d523365SDimitry Andric     // The cast is needed since base traversal may strip away bitcasts
9377d523365SDimitry Andric     if (Base->getType() != Input->getType() &&
9387d523365SDimitry Andric         InsertPt) {
9397d523365SDimitry Andric       Base = new BitCastInst(Base, Input->getType(), "cast",
9407d523365SDimitry Andric                              InsertPt);
9417d523365SDimitry Andric     }
9427d523365SDimitry Andric     return Base;
9437d523365SDimitry Andric   };
944ff0cc061SDimitry Andric 
9457d523365SDimitry Andric   // Fixup all the inputs of the new PHIs.  Visit order needs to be
9467d523365SDimitry Andric   // deterministic and predictable because we're naming newly created
9477d523365SDimitry Andric   // instructions.
9487d523365SDimitry Andric   for (auto Pair : States) {
9497d523365SDimitry Andric     Instruction *BDV = cast<Instruction>(Pair.first);
9507d523365SDimitry Andric     BDVState State = Pair.second;
9517d523365SDimitry Andric 
9527d523365SDimitry Andric     assert(!isKnownBaseResult(BDV) && "why did it get added?");
9537d523365SDimitry Andric     assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
9547d523365SDimitry Andric     if (!State.isConflict())
955ff0cc061SDimitry Andric       continue;
956ff0cc061SDimitry Andric 
9577d523365SDimitry Andric     if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
9587d523365SDimitry Andric       PHINode *phi = cast<PHINode>(BDV);
959ff0cc061SDimitry Andric       unsigned NumPHIValues = phi->getNumIncomingValues();
960ff0cc061SDimitry Andric       for (unsigned i = 0; i < NumPHIValues; i++) {
961ff0cc061SDimitry Andric         Value *InVal = phi->getIncomingValue(i);
962ff0cc061SDimitry Andric         BasicBlock *InBB = phi->getIncomingBlock(i);
963ff0cc061SDimitry Andric 
964ff0cc061SDimitry Andric         // If we've already seen InBB, add the same incoming value
965ff0cc061SDimitry Andric         // we added for it earlier.  The IR verifier requires phi
966ff0cc061SDimitry Andric         // nodes with multiple entries from the same basic block
967ff0cc061SDimitry Andric         // to have the same incoming value for each of those
968ff0cc061SDimitry Andric         // entries.  If we don't do this check here and basephi
969ff0cc061SDimitry Andric         // has a different type than base, we'll end up adding two
970ff0cc061SDimitry Andric         // bitcasts (and hence two distinct values) as incoming
971ff0cc061SDimitry Andric         // values for the same basic block.
972ff0cc061SDimitry Andric 
973ff0cc061SDimitry Andric         int blockIndex = basephi->getBasicBlockIndex(InBB);
974ff0cc061SDimitry Andric         if (blockIndex != -1) {
975ff0cc061SDimitry Andric           Value *oldBase = basephi->getIncomingValue(blockIndex);
976ff0cc061SDimitry Andric           basephi->addIncoming(oldBase, InBB);
977ff0cc061SDimitry Andric 
9787d523365SDimitry Andric #ifndef NDEBUG
9797d523365SDimitry Andric           Value *Base = getBaseForInput(InVal, nullptr);
9807d523365SDimitry Andric           // In essence this assert states: the only way two
981ff0cc061SDimitry Andric           // values incoming from the same basic block may be
982ff0cc061SDimitry Andric           // different is by being different bitcasts of the same
983ff0cc061SDimitry Andric           // value.  A cleanup that remains TODO is changing
984ff0cc061SDimitry Andric           // findBaseOrBDV to return an llvm::Value of the correct
985ff0cc061SDimitry Andric           // type (and still remain pure).  This will remove the
986ff0cc061SDimitry Andric           // need to add bitcasts.
9877d523365SDimitry Andric           assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
988ff0cc061SDimitry Andric                  "sanity -- findBaseOrBDV should be pure!");
989ff0cc061SDimitry Andric #endif
990ff0cc061SDimitry Andric           continue;
991ff0cc061SDimitry Andric         }
992ff0cc061SDimitry Andric 
9937d523365SDimitry Andric         // Find the instruction which produces the base for each input.  We may
9947d523365SDimitry Andric         // need to insert a bitcast in the incoming block.
9957d523365SDimitry Andric         // TODO: Need to split critical edges if insertion is needed
9967d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, InBB->getTerminator());
9977d523365SDimitry Andric         basephi->addIncoming(Base, InBB);
998ff0cc061SDimitry Andric       }
999ff0cc061SDimitry Andric       assert(basephi->getNumIncomingValues() == NumPHIValues);
10007d523365SDimitry Andric     } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
10017d523365SDimitry Andric       SelectInst *Sel = cast<SelectInst>(BDV);
1002ff0cc061SDimitry Andric       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1003ff0cc061SDimitry Andric       // something more safe and less hacky.
1004ff0cc061SDimitry Andric       for (int i = 1; i <= 2; i++) {
10057d523365SDimitry Andric         Value *InVal = Sel->getOperand(i);
10067d523365SDimitry Andric         // Find the instruction which produces the base for each input.  We may
10077d523365SDimitry Andric         // need to insert a bitcast.
10087d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, BaseSel);
10097d523365SDimitry Andric         BaseSel->setOperand(i, Base);
1010ff0cc061SDimitry Andric       }
10117d523365SDimitry Andric     } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
10127d523365SDimitry Andric       Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
10137d523365SDimitry Andric       // Find the instruction which produces the base for each input.  We may
10147d523365SDimitry Andric       // need to insert a bitcast.
10157d523365SDimitry Andric       Value *Base = getBaseForInput(InVal, BaseEE);
10167d523365SDimitry Andric       BaseEE->setOperand(0, Base);
10177d523365SDimitry Andric     } else {
10187d523365SDimitry Andric       auto *BaseIE = cast<InsertElementInst>(State.getBase());
10197d523365SDimitry Andric       auto *BdvIE = cast<InsertElementInst>(BDV);
10207d523365SDimitry Andric       auto UpdateOperand = [&](int OperandIdx) {
10217d523365SDimitry Andric         Value *InVal = BdvIE->getOperand(OperandIdx);
10227d523365SDimitry Andric         Value *Base = getBaseForInput(InVal, BaseIE);
10237d523365SDimitry Andric         BaseIE->setOperand(OperandIdx, Base);
10247d523365SDimitry Andric       };
10257d523365SDimitry Andric       UpdateOperand(0); // vector operand
10267d523365SDimitry Andric       UpdateOperand(1); // scalar operand
1027ff0cc061SDimitry Andric     }
10287d523365SDimitry Andric 
1029ff0cc061SDimitry Andric   }
10307d523365SDimitry Andric 
10317d523365SDimitry Andric   // Now that we're done with the algorithm, see if we can optimize the
10327d523365SDimitry Andric   // results slightly by reducing the number of new instructions needed.
10337d523365SDimitry Andric   // Arguably, this should be integrated into the algorithm above, but
10347d523365SDimitry Andric   // doing as a post process step is easier to reason about for the moment.
10357d523365SDimitry Andric   DenseMap<Value *, Value *> ReverseMap;
10367d523365SDimitry Andric   SmallPtrSet<Instruction *, 16> NewInsts;
10377d523365SDimitry Andric   SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
10387d523365SDimitry Andric   // Note: We need to visit the states in a deterministic order.  We uses the
10397d523365SDimitry Andric   // Keys we sorted above for this purpose.  Note that we are papering over a
10407d523365SDimitry Andric   // bigger problem with the algorithm above - it's visit order is not
10417d523365SDimitry Andric   // deterministic.  A larger change is needed to fix this.
10427d523365SDimitry Andric   for (auto Pair : States) {
10437d523365SDimitry Andric     auto *BDV = Pair.first;
10447d523365SDimitry Andric     auto State = Pair.second;
10457d523365SDimitry Andric     Value *Base = State.getBase();
10467d523365SDimitry Andric     assert(BDV && Base);
10477d523365SDimitry Andric     assert(!isKnownBaseResult(BDV) && "why did it get added?");
10487d523365SDimitry Andric     assert(isKnownBaseResult(Base) &&
10497d523365SDimitry Andric            "must be something we 'know' is a base pointer");
10507d523365SDimitry Andric     if (!State.isConflict())
10517d523365SDimitry Andric       continue;
10527d523365SDimitry Andric 
10537d523365SDimitry Andric     ReverseMap[Base] = BDV;
10547d523365SDimitry Andric     if (auto *BaseI = dyn_cast<Instruction>(Base)) {
10557d523365SDimitry Andric       NewInsts.insert(BaseI);
10567d523365SDimitry Andric       Worklist.insert(BaseI);
10577d523365SDimitry Andric     }
10587d523365SDimitry Andric   }
10597d523365SDimitry Andric   auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
10607d523365SDimitry Andric                                  Value *Replacement) {
10617d523365SDimitry Andric     // Add users which are new instructions (excluding self references)
10627d523365SDimitry Andric     for (User *U : BaseI->users())
10637d523365SDimitry Andric       if (auto *UI = dyn_cast<Instruction>(U))
10647d523365SDimitry Andric         if (NewInsts.count(UI) && UI != BaseI)
10657d523365SDimitry Andric           Worklist.insert(UI);
10667d523365SDimitry Andric     // Then do the actual replacement
10677d523365SDimitry Andric     NewInsts.erase(BaseI);
10687d523365SDimitry Andric     ReverseMap.erase(BaseI);
10697d523365SDimitry Andric     BaseI->replaceAllUsesWith(Replacement);
10707d523365SDimitry Andric     assert(States.count(BDV));
10717d523365SDimitry Andric     assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
10727d523365SDimitry Andric     States[BDV] = BDVState(BDVState::Conflict, Replacement);
10737d523365SDimitry Andric     BaseI->eraseFromParent();
10747d523365SDimitry Andric   };
10757d523365SDimitry Andric   const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
10767d523365SDimitry Andric   while (!Worklist.empty()) {
10777d523365SDimitry Andric     Instruction *BaseI = Worklist.pop_back_val();
10787d523365SDimitry Andric     assert(NewInsts.count(BaseI));
10797d523365SDimitry Andric     Value *Bdv = ReverseMap[BaseI];
10807d523365SDimitry Andric     if (auto *BdvI = dyn_cast<Instruction>(Bdv))
10817d523365SDimitry Andric       if (BaseI->isIdenticalTo(BdvI)) {
10827d523365SDimitry Andric         DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
10837d523365SDimitry Andric         ReplaceBaseInstWith(Bdv, BaseI, Bdv);
10847d523365SDimitry Andric         continue;
10857d523365SDimitry Andric       }
10867d523365SDimitry Andric     if (Value *V = SimplifyInstruction(BaseI, DL)) {
10877d523365SDimitry Andric       DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
10887d523365SDimitry Andric       ReplaceBaseInstWith(Bdv, BaseI, V);
10897d523365SDimitry Andric       continue;
1090ff0cc061SDimitry Andric     }
1091ff0cc061SDimitry Andric   }
1092ff0cc061SDimitry Andric 
1093ff0cc061SDimitry Andric   // Cache all of our results so we can cheaply reuse them
1094ff0cc061SDimitry Andric   // NOTE: This is actually two caches: one of the base defining value
1095ff0cc061SDimitry Andric   // relation and one of the base pointer relation!  FIXME
10967d523365SDimitry Andric   for (auto Pair : States) {
10977d523365SDimitry Andric     auto *BDV = Pair.first;
10987d523365SDimitry Andric     Value *base = Pair.second.getBase();
10997d523365SDimitry Andric     assert(BDV && base);
1100ff0cc061SDimitry Andric 
11017d523365SDimitry Andric     std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
11027d523365SDimitry Andric     DEBUG(dbgs() << "Updating base value cache"
11037d523365SDimitry Andric           << " for: " << BDV->getName()
1104ff0cc061SDimitry Andric           << " from: " << fromstr
11057d523365SDimitry Andric           << " to: " << base->getName() << "\n");
1106ff0cc061SDimitry Andric 
11077d523365SDimitry Andric     if (cache.count(BDV)) {
1108ff0cc061SDimitry Andric       // Once we transition from the BDV relation being store in the cache to
1109ff0cc061SDimitry Andric       // the base relation being stored, it must be stable
11107d523365SDimitry Andric       assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
1111ff0cc061SDimitry Andric              "base relation should be stable");
1112ff0cc061SDimitry Andric     }
11137d523365SDimitry Andric     cache[BDV] = base;
1114ff0cc061SDimitry Andric   }
11157d523365SDimitry Andric   assert(cache.count(def));
1116ff0cc061SDimitry Andric   return cache[def];
1117ff0cc061SDimitry Andric }
1118ff0cc061SDimitry Andric 
1119ff0cc061SDimitry Andric // For a set of live pointers (base and/or derived), identify the base
1120ff0cc061SDimitry Andric // pointer of the object which they are derived from.  This routine will
1121ff0cc061SDimitry Andric // mutate the IR graph as needed to make the 'base' pointer live at the
1122ff0cc061SDimitry Andric // definition site of 'derived'.  This ensures that any use of 'derived' can
1123ff0cc061SDimitry Andric // also use 'base'.  This may involve the insertion of a number of
1124ff0cc061SDimitry Andric // additional PHI nodes.
1125ff0cc061SDimitry Andric //
1126ff0cc061SDimitry Andric // preconditions: live is a set of pointer type Values
1127ff0cc061SDimitry Andric //
1128ff0cc061SDimitry Andric // side effects: may insert PHI nodes into the existing CFG, will preserve
1129ff0cc061SDimitry Andric // CFG, will not remove or mutate any existing nodes
1130ff0cc061SDimitry Andric //
1131ff0cc061SDimitry Andric // post condition: PointerToBase contains one (derived, base) pair for every
1132ff0cc061SDimitry Andric // pointer in live.  Note that derived can be equal to base if the original
1133ff0cc061SDimitry Andric // pointer was a base pointer.
1134ff0cc061SDimitry Andric static void
1135ff0cc061SDimitry Andric findBasePointers(const StatepointLiveSetTy &live,
11367d523365SDimitry Andric                  DenseMap<Value *, Value *> &PointerToBase,
1137ff0cc061SDimitry Andric                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
1138ff0cc061SDimitry Andric   // For the naming of values inserted to be deterministic - which makes for
1139ff0cc061SDimitry Andric   // much cleaner and more stable tests - we need to assign an order to the
1140ff0cc061SDimitry Andric   // live values.  DenseSets do not provide a deterministic order across runs.
1141ff0cc061SDimitry Andric   SmallVector<Value *, 64> Temp;
1142ff0cc061SDimitry Andric   Temp.insert(Temp.end(), live.begin(), live.end());
1143ff0cc061SDimitry Andric   std::sort(Temp.begin(), Temp.end(), order_by_name);
1144ff0cc061SDimitry Andric   for (Value *ptr : Temp) {
1145ff0cc061SDimitry Andric     Value *base = findBasePointer(ptr, DVCache);
1146ff0cc061SDimitry Andric     assert(base && "failed to find base pointer");
1147ff0cc061SDimitry Andric     PointerToBase[ptr] = base;
1148ff0cc061SDimitry Andric     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1149ff0cc061SDimitry Andric             DT->dominates(cast<Instruction>(base)->getParent(),
1150ff0cc061SDimitry Andric                           cast<Instruction>(ptr)->getParent())) &&
1151ff0cc061SDimitry Andric            "The base we found better dominate the derived pointer");
1152ff0cc061SDimitry Andric 
1153ff0cc061SDimitry Andric     // If you see this trip and like to live really dangerously, the code should
1154ff0cc061SDimitry Andric     // be correct, just with idioms the verifier can't handle.  You can try
11557d523365SDimitry Andric     // disabling the verifier at your own substantial risk.
1156ff0cc061SDimitry Andric     assert(!isa<ConstantPointerNull>(base) &&
1157ff0cc061SDimitry Andric            "the relocation code needs adjustment to handle the relocation of "
1158ff0cc061SDimitry Andric            "a null pointer constant without causing false positives in the "
1159ff0cc061SDimitry Andric            "safepoint ir verifier.");
1160ff0cc061SDimitry Andric   }
1161ff0cc061SDimitry Andric }
1162ff0cc061SDimitry Andric 
1163ff0cc061SDimitry Andric /// Find the required based pointers (and adjust the live set) for the given
1164ff0cc061SDimitry Andric /// parse point.
1165ff0cc061SDimitry Andric static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1166ff0cc061SDimitry Andric                              const CallSite &CS,
1167ff0cc061SDimitry Andric                              PartiallyConstructedSafepointRecord &result) {
11687d523365SDimitry Andric   DenseMap<Value *, Value *> PointerToBase;
11697d523365SDimitry Andric   findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
1170ff0cc061SDimitry Andric 
1171ff0cc061SDimitry Andric   if (PrintBasePointers) {
1172ff0cc061SDimitry Andric     // Note: Need to print these in a stable order since this is checked in
1173ff0cc061SDimitry Andric     // some tests.
1174ff0cc061SDimitry Andric     errs() << "Base Pairs (w/o Relocation):\n";
1175ff0cc061SDimitry Andric     SmallVector<Value *, 64> Temp;
1176ff0cc061SDimitry Andric     Temp.reserve(PointerToBase.size());
1177ff0cc061SDimitry Andric     for (auto Pair : PointerToBase) {
1178ff0cc061SDimitry Andric       Temp.push_back(Pair.first);
1179ff0cc061SDimitry Andric     }
1180ff0cc061SDimitry Andric     std::sort(Temp.begin(), Temp.end(), order_by_name);
1181ff0cc061SDimitry Andric     for (Value *Ptr : Temp) {
1182ff0cc061SDimitry Andric       Value *Base = PointerToBase[Ptr];
11837d523365SDimitry Andric       errs() << " derived ";
11847d523365SDimitry Andric       Ptr->printAsOperand(errs(), false);
11857d523365SDimitry Andric       errs() << " base ";
11867d523365SDimitry Andric       Base->printAsOperand(errs(), false);
11877d523365SDimitry Andric       errs() << "\n";;
1188ff0cc061SDimitry Andric     }
1189ff0cc061SDimitry Andric   }
1190ff0cc061SDimitry Andric 
1191ff0cc061SDimitry Andric   result.PointerToBase = PointerToBase;
1192ff0cc061SDimitry Andric }
1193ff0cc061SDimitry Andric 
1194ff0cc061SDimitry Andric /// Given an updated version of the dataflow liveness results, update the
1195ff0cc061SDimitry Andric /// liveset and base pointer maps for the call site CS.
1196ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1197ff0cc061SDimitry Andric                                   const CallSite &CS,
1198ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &result);
1199ff0cc061SDimitry Andric 
1200ff0cc061SDimitry Andric static void recomputeLiveInValues(
12017d523365SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1202ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1203ff0cc061SDimitry Andric   // TODO-PERF: reuse the original liveness, then simply run the dataflow
12047d523365SDimitry Andric   // again.  The old values are still live and will help it stabilize quickly.
1205ff0cc061SDimitry Andric   GCPtrLivenessData RevisedLivenessData;
1206ff0cc061SDimitry Andric   computeLiveInValues(DT, F, RevisedLivenessData);
1207ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1208ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
1209ff0cc061SDimitry Andric     const CallSite &CS = toUpdate[i];
1210ff0cc061SDimitry Andric     recomputeLiveInValues(RevisedLivenessData, CS, info);
1211ff0cc061SDimitry Andric   }
1212ff0cc061SDimitry Andric }
1213ff0cc061SDimitry Andric 
12147d523365SDimitry Andric // When inserting gc.relocate and gc.result calls, we need to ensure there are
12157d523365SDimitry Andric // no uses of the original value / return value between the gc.statepoint and
12167d523365SDimitry Andric // the gc.relocate / gc.result call.  One case which can arise is a phi node
12177d523365SDimitry Andric // starting one of the successor blocks.  We also need to be able to insert the
12187d523365SDimitry Andric // gc.relocates only on the path which goes through the statepoint.  We might
12197d523365SDimitry Andric // need to split an edge to make this possible.
1220ff0cc061SDimitry Andric static BasicBlock *
122197bc6c73SDimitry Andric normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
122297bc6c73SDimitry Andric                             DominatorTree &DT) {
1223ff0cc061SDimitry Andric   BasicBlock *Ret = BB;
12247d523365SDimitry Andric   if (!BB->getUniquePredecessor())
12257d523365SDimitry Andric     Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1226ff0cc061SDimitry Andric 
12277d523365SDimitry Andric   // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
1228ff0cc061SDimitry Andric   // from it
1229ff0cc061SDimitry Andric   FoldSingleEntryPHINodes(Ret);
12307d523365SDimitry Andric   assert(!isa<PHINode>(Ret->begin()) &&
12317d523365SDimitry Andric          "All PHI nodes should have been removed!");
1232ff0cc061SDimitry Andric 
12337d523365SDimitry Andric   // At this point, we can safely insert a gc.relocate or gc.result as the first
12347d523365SDimitry Andric   // instruction in Ret if needed.
1235ff0cc061SDimitry Andric   return Ret;
1236ff0cc061SDimitry Andric }
1237ff0cc061SDimitry Andric 
12387d523365SDimitry Andric // Create new attribute set containing only attributes which can be transferred
1239ff0cc061SDimitry Andric // from original call to the safepoint.
1240ff0cc061SDimitry Andric static AttributeSet legalizeCallAttributes(AttributeSet AS) {
12417d523365SDimitry Andric   AttributeSet Ret;
1242ff0cc061SDimitry Andric 
1243ff0cc061SDimitry Andric   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
12447d523365SDimitry Andric     unsigned Index = AS.getSlotIndex(Slot);
1245ff0cc061SDimitry Andric 
12467d523365SDimitry Andric     if (Index == AttributeSet::ReturnIndex ||
12477d523365SDimitry Andric         Index == AttributeSet::FunctionIndex) {
1248ff0cc061SDimitry Andric 
12497d523365SDimitry Andric       for (Attribute Attr : make_range(AS.begin(Slot), AS.end(Slot))) {
1250ff0cc061SDimitry Andric 
1251ff0cc061SDimitry Andric         // Do not allow certain attributes - just skip them
1252ff0cc061SDimitry Andric         // Safepoint can not be read only or read none.
12537d523365SDimitry Andric         if (Attr.hasAttribute(Attribute::ReadNone) ||
12547d523365SDimitry Andric             Attr.hasAttribute(Attribute::ReadOnly))
1255ff0cc061SDimitry Andric           continue;
1256ff0cc061SDimitry Andric 
12577d523365SDimitry Andric         // These attributes control the generation of the gc.statepoint call /
12587d523365SDimitry Andric         // invoke itself; and once the gc.statepoint is in place, they're of no
12597d523365SDimitry Andric         // use.
12607d523365SDimitry Andric         if (Attr.hasAttribute("statepoint-num-patch-bytes") ||
12617d523365SDimitry Andric             Attr.hasAttribute("statepoint-id"))
12627d523365SDimitry Andric           continue;
12637d523365SDimitry Andric 
12647d523365SDimitry Andric         Ret = Ret.addAttributes(
12657d523365SDimitry Andric             AS.getContext(), Index,
12667d523365SDimitry Andric             AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
1267ff0cc061SDimitry Andric       }
1268ff0cc061SDimitry Andric     }
1269ff0cc061SDimitry Andric 
1270ff0cc061SDimitry Andric     // Just skip parameter attributes for now
1271ff0cc061SDimitry Andric   }
1272ff0cc061SDimitry Andric 
12737d523365SDimitry Andric   return Ret;
1274ff0cc061SDimitry Andric }
1275ff0cc061SDimitry Andric 
1276ff0cc061SDimitry Andric /// Helper function to place all gc relocates necessary for the given
1277ff0cc061SDimitry Andric /// statepoint.
1278ff0cc061SDimitry Andric /// Inputs:
1279ff0cc061SDimitry Andric ///   liveVariables - list of variables to be relocated.
1280ff0cc061SDimitry Andric ///   liveStart - index of the first live variable.
1281ff0cc061SDimitry Andric ///   basePtrs - base pointers.
1282ff0cc061SDimitry Andric ///   statepointToken - statepoint instruction to which relocates should be
1283ff0cc061SDimitry Andric ///   bound.
1284ff0cc061SDimitry Andric ///   Builder - Llvm IR builder to be used to construct new calls.
12857d523365SDimitry Andric static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
1286ff0cc061SDimitry Andric                               const int LiveStart,
12877d523365SDimitry Andric                               ArrayRef<Value *> BasePtrs,
1288ff0cc061SDimitry Andric                               Instruction *StatepointToken,
1289ff0cc061SDimitry Andric                               IRBuilder<> Builder) {
12907d523365SDimitry Andric   if (LiveVariables.empty())
12917d523365SDimitry Andric     return;
1292ff0cc061SDimitry Andric 
12937d523365SDimitry Andric   auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
12947d523365SDimitry Andric     auto ValIt = std::find(LiveVec.begin(), LiveVec.end(), Val);
12957d523365SDimitry Andric     assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
12967d523365SDimitry Andric     size_t Index = std::distance(LiveVec.begin(), ValIt);
12977d523365SDimitry Andric     assert(Index < LiveVec.size() && "Bug in std::find?");
12987d523365SDimitry Andric     return Index;
12997d523365SDimitry Andric   };
13007d523365SDimitry Andric   Module *M = StatepointToken->getModule();
1301444ed5c5SDimitry Andric 
1302444ed5c5SDimitry Andric   // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1303444ed5c5SDimitry Andric   // element type is i8 addrspace(1)*). We originally generated unique
1304444ed5c5SDimitry Andric   // declarations for each pointer type, but this proved problematic because
1305444ed5c5SDimitry Andric   // the intrinsic mangling code is incomplete and fragile.  Since we're moving
1306444ed5c5SDimitry Andric   // towards a single unified pointer type anyways, we can just cast everything
1307444ed5c5SDimitry Andric   // to an i8* of the right address space.  A bitcast is added later to convert
1308444ed5c5SDimitry Andric   // gc_relocate to the actual value's type.
1309444ed5c5SDimitry Andric   auto getGCRelocateDecl = [&] (Type *Ty) {
1310444ed5c5SDimitry Andric     assert(isHandledGCPointerType(Ty));
1311444ed5c5SDimitry Andric     auto AS = Ty->getScalarType()->getPointerAddressSpace();
1312444ed5c5SDimitry Andric     Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1313444ed5c5SDimitry Andric     if (auto *VT = dyn_cast<VectorType>(Ty))
1314444ed5c5SDimitry Andric       NewTy = VectorType::get(NewTy, VT->getNumElements());
1315444ed5c5SDimitry Andric     return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1316444ed5c5SDimitry Andric                                      {NewTy});
1317444ed5c5SDimitry Andric   };
1318444ed5c5SDimitry Andric 
1319444ed5c5SDimitry Andric   // Lazily populated map from input types to the canonicalized form mentioned
1320444ed5c5SDimitry Andric   // in the comment above.  This should probably be cached somewhere more
1321444ed5c5SDimitry Andric   // broadly.
1322444ed5c5SDimitry Andric   DenseMap<Type*, Value*> TypeToDeclMap;
1323ff0cc061SDimitry Andric 
1324ff0cc061SDimitry Andric   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1325ff0cc061SDimitry Andric     // Generate the gc.relocate call and save the result
1326ff0cc061SDimitry Andric     Value *BaseIdx =
13277d523365SDimitry Andric       Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
13287d523365SDimitry Andric     Value *LiveIdx = Builder.getInt32(LiveStart + i);
1329ff0cc061SDimitry Andric 
1330444ed5c5SDimitry Andric     Type *Ty = LiveVariables[i]->getType();
1331444ed5c5SDimitry Andric     if (!TypeToDeclMap.count(Ty))
1332444ed5c5SDimitry Andric       TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1333444ed5c5SDimitry Andric     Value *GCRelocateDecl = TypeToDeclMap[Ty];
1334444ed5c5SDimitry Andric 
1335ff0cc061SDimitry Andric     // only specify a debug name if we can give a useful one
13367d523365SDimitry Andric     CallInst *Reloc = Builder.CreateCall(
1337ff0cc061SDimitry Andric         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
13387d523365SDimitry Andric         suffixed_name_or(LiveVariables[i], ".relocated", ""));
1339ff0cc061SDimitry Andric     // Trick CodeGen into thinking there are lots of free registers at this
1340ff0cc061SDimitry Andric     // fake call.
13417d523365SDimitry Andric     Reloc->setCallingConv(CallingConv::Cold);
1342ff0cc061SDimitry Andric   }
13437d523365SDimitry Andric }
13447d523365SDimitry Andric 
13457d523365SDimitry Andric namespace {
13467d523365SDimitry Andric 
13477d523365SDimitry Andric /// This struct is used to defer RAUWs and `eraseFromParent` s.  Using this
13487d523365SDimitry Andric /// avoids having to worry about keeping around dangling pointers to Values.
13497d523365SDimitry Andric class DeferredReplacement {
13507d523365SDimitry Andric   AssertingVH<Instruction> Old;
13517d523365SDimitry Andric   AssertingVH<Instruction> New;
13527d523365SDimitry Andric 
13537d523365SDimitry Andric public:
13547d523365SDimitry Andric   explicit DeferredReplacement(Instruction *Old, Instruction *New) :
13557d523365SDimitry Andric     Old(Old), New(New) {
13567d523365SDimitry Andric     assert(Old != New && "Not allowed!");
13577d523365SDimitry Andric   }
13587d523365SDimitry Andric 
13597d523365SDimitry Andric   /// Does the task represented by this instance.
13607d523365SDimitry Andric   void doReplacement() {
13617d523365SDimitry Andric     Instruction *OldI = Old;
13627d523365SDimitry Andric     Instruction *NewI = New;
13637d523365SDimitry Andric 
13647d523365SDimitry Andric     assert(OldI != NewI && "Disallowed at construction?!");
13657d523365SDimitry Andric 
13667d523365SDimitry Andric     Old = nullptr;
13677d523365SDimitry Andric     New = nullptr;
13687d523365SDimitry Andric 
13697d523365SDimitry Andric     if (NewI)
13707d523365SDimitry Andric       OldI->replaceAllUsesWith(NewI);
13717d523365SDimitry Andric     OldI->eraseFromParent();
13727d523365SDimitry Andric   }
13737d523365SDimitry Andric };
1374ff0cc061SDimitry Andric }
1375ff0cc061SDimitry Andric 
1376ff0cc061SDimitry Andric static void
13777d523365SDimitry Andric makeStatepointExplicitImpl(const CallSite CS, /* to replace */
13787d523365SDimitry Andric                            const SmallVectorImpl<Value *> &BasePtrs,
13797d523365SDimitry Andric                            const SmallVectorImpl<Value *> &LiveVariables,
13807d523365SDimitry Andric                            PartiallyConstructedSafepointRecord &Result,
13817d523365SDimitry Andric                            std::vector<DeferredReplacement> &Replacements) {
13827d523365SDimitry Andric   assert(BasePtrs.size() == LiveVariables.size());
13837d523365SDimitry Andric   assert((UseDeoptBundles || isStatepoint(CS)) &&
1384ff0cc061SDimitry Andric          "This method expects to be rewriting a statepoint");
1385ff0cc061SDimitry Andric 
1386ff0cc061SDimitry Andric   // Then go ahead and use the builder do actually do the inserts.  We insert
1387ff0cc061SDimitry Andric   // immediately before the previous instruction under the assumption that all
1388ff0cc061SDimitry Andric   // arguments will be available here.  We can't insert afterwards since we may
1389ff0cc061SDimitry Andric   // be replacing a terminator.
13907d523365SDimitry Andric   Instruction *InsertBefore = CS.getInstruction();
13917d523365SDimitry Andric   IRBuilder<> Builder(InsertBefore);
1392ff0cc061SDimitry Andric 
13937d523365SDimitry Andric   ArrayRef<Value *> GCArgs(LiveVariables);
13947d523365SDimitry Andric   uint64_t StatepointID = 0xABCDEF00;
13957d523365SDimitry Andric   uint32_t NumPatchBytes = 0;
13967d523365SDimitry Andric   uint32_t Flags = uint32_t(StatepointFlags::None);
13977d523365SDimitry Andric 
13987d523365SDimitry Andric   ArrayRef<Use> CallArgs;
13997d523365SDimitry Andric   ArrayRef<Use> DeoptArgs;
14007d523365SDimitry Andric   ArrayRef<Use> TransitionArgs;
14017d523365SDimitry Andric 
14027d523365SDimitry Andric   Value *CallTarget = nullptr;
14037d523365SDimitry Andric 
14047d523365SDimitry Andric   if (UseDeoptBundles) {
14057d523365SDimitry Andric     CallArgs = {CS.arg_begin(), CS.arg_end()};
14067d523365SDimitry Andric     DeoptArgs = GetDeoptBundleOperands(CS);
14077d523365SDimitry Andric     // TODO: we don't fill in TransitionArgs or Flags in this branch, but we
14087d523365SDimitry Andric     // could have an operand bundle for that too.
14097d523365SDimitry Andric     AttributeSet OriginalAttrs = CS.getAttributes();
14107d523365SDimitry Andric 
14117d523365SDimitry Andric     Attribute AttrID = OriginalAttrs.getAttribute(AttributeSet::FunctionIndex,
14127d523365SDimitry Andric                                                   "statepoint-id");
14137d523365SDimitry Andric     if (AttrID.isStringAttribute())
14147d523365SDimitry Andric       AttrID.getValueAsString().getAsInteger(10, StatepointID);
14157d523365SDimitry Andric 
14167d523365SDimitry Andric     Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
14177d523365SDimitry Andric         AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
14187d523365SDimitry Andric     if (AttrNumPatchBytes.isStringAttribute())
14197d523365SDimitry Andric       AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
14207d523365SDimitry Andric 
14217d523365SDimitry Andric     CallTarget = CS.getCalledValue();
14227d523365SDimitry Andric   } else {
14237d523365SDimitry Andric     // This branch will be gone soon, and we will soon only support the
14247d523365SDimitry Andric     // UseDeoptBundles == true configuration.
14257d523365SDimitry Andric     Statepoint OldSP(CS);
14267d523365SDimitry Andric     StatepointID = OldSP.getID();
14277d523365SDimitry Andric     NumPatchBytes = OldSP.getNumPatchBytes();
14287d523365SDimitry Andric     Flags = OldSP.getFlags();
14297d523365SDimitry Andric 
14307d523365SDimitry Andric     CallArgs = {OldSP.arg_begin(), OldSP.arg_end()};
14317d523365SDimitry Andric     DeoptArgs = {OldSP.vm_state_begin(), OldSP.vm_state_end()};
14327d523365SDimitry Andric     TransitionArgs = {OldSP.gc_transition_args_begin(),
14337d523365SDimitry Andric                       OldSP.gc_transition_args_end()};
14347d523365SDimitry Andric     CallTarget = OldSP.getCalledValue();
14357d523365SDimitry Andric   }
1436ff0cc061SDimitry Andric 
1437ff0cc061SDimitry Andric   // Create the statepoint given all the arguments
14387d523365SDimitry Andric   Instruction *Token = nullptr;
14397d523365SDimitry Andric   AttributeSet ReturnAttrs;
1440ff0cc061SDimitry Andric   if (CS.isCall()) {
14417d523365SDimitry Andric     CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
14427d523365SDimitry Andric     CallInst *Call = Builder.CreateGCStatepointCall(
14437d523365SDimitry Andric         StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
14447d523365SDimitry Andric         TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
14457d523365SDimitry Andric 
14467d523365SDimitry Andric     Call->setTailCall(ToReplace->isTailCall());
14477d523365SDimitry Andric     Call->setCallingConv(ToReplace->getCallingConv());
1448ff0cc061SDimitry Andric 
1449ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1450ff0cc061SDimitry Andric     // function attributes.
14517d523365SDimitry Andric     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
14527d523365SDimitry Andric     // In case if we can handle this set of attributes - set up function attrs
1453ff0cc061SDimitry Andric     // directly on statepoint and return attrs later for gc_result intrinsic.
14547d523365SDimitry Andric     Call->setAttributes(NewAttrs.getFnAttributes());
14557d523365SDimitry Andric     ReturnAttrs = NewAttrs.getRetAttributes();
1456ff0cc061SDimitry Andric 
14577d523365SDimitry Andric     Token = Call;
1458ff0cc061SDimitry Andric 
1459ff0cc061SDimitry Andric     // Put the following gc_result and gc_relocate calls immediately after the
1460ff0cc061SDimitry Andric     // the old call (which we're about to delete)
14617d523365SDimitry Andric     assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
14627d523365SDimitry Andric     Builder.SetInsertPoint(ToReplace->getNextNode());
14637d523365SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
1464ff0cc061SDimitry Andric   } else {
14657d523365SDimitry Andric     InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
1466ff0cc061SDimitry Andric 
1467ff0cc061SDimitry Andric     // Insert the new invoke into the old block.  We'll remove the old one in a
1468ff0cc061SDimitry Andric     // moment at which point this will become the new terminator for the
1469ff0cc061SDimitry Andric     // original block.
14707d523365SDimitry Andric     InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
14717d523365SDimitry Andric         StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
14727d523365SDimitry Andric         ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
14737d523365SDimitry Andric         GCArgs, "statepoint_token");
14747d523365SDimitry Andric 
14757d523365SDimitry Andric     Invoke->setCallingConv(ToReplace->getCallingConv());
1476ff0cc061SDimitry Andric 
1477ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1478ff0cc061SDimitry Andric     // function attributes.
14797d523365SDimitry Andric     AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
14807d523365SDimitry Andric     // In case if we can handle this set of attributes - set up function attrs
1481ff0cc061SDimitry Andric     // directly on statepoint and return attrs later for gc_result intrinsic.
14827d523365SDimitry Andric     Invoke->setAttributes(NewAttrs.getFnAttributes());
14837d523365SDimitry Andric     ReturnAttrs = NewAttrs.getRetAttributes();
1484ff0cc061SDimitry Andric 
14857d523365SDimitry Andric     Token = Invoke;
1486ff0cc061SDimitry Andric 
1487ff0cc061SDimitry Andric     // Generate gc relocates in exceptional path
14887d523365SDimitry Andric     BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
14897d523365SDimitry Andric     assert(!isa<PHINode>(UnwindBlock->begin()) &&
14907d523365SDimitry Andric            UnwindBlock->getUniquePredecessor() &&
1491ff0cc061SDimitry Andric            "can't safely insert in this block!");
1492ff0cc061SDimitry Andric 
14937d523365SDimitry Andric     Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
14947d523365SDimitry Andric     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1495ff0cc061SDimitry Andric 
14967d523365SDimitry Andric     // Attach exceptional gc relocates to the landingpad.
14977d523365SDimitry Andric     Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
14987d523365SDimitry Andric     Result.UnwindToken = ExceptionalToken;
1499ff0cc061SDimitry Andric 
15007d523365SDimitry Andric     const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
15017d523365SDimitry Andric     CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
15027d523365SDimitry Andric                       Builder);
1503ff0cc061SDimitry Andric 
1504ff0cc061SDimitry Andric     // Generate gc relocates and returns for normal block
15057d523365SDimitry Andric     BasicBlock *NormalDest = ToReplace->getNormalDest();
15067d523365SDimitry Andric     assert(!isa<PHINode>(NormalDest->begin()) &&
15077d523365SDimitry Andric            NormalDest->getUniquePredecessor() &&
1508ff0cc061SDimitry Andric            "can't safely insert in this block!");
1509ff0cc061SDimitry Andric 
15107d523365SDimitry Andric     Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
1511ff0cc061SDimitry Andric 
1512ff0cc061SDimitry Andric     // gc relocates will be generated later as if it were regular call
1513ff0cc061SDimitry Andric     // statepoint
1514ff0cc061SDimitry Andric   }
15157d523365SDimitry Andric   assert(Token && "Should be set in one of the above branches!");
1516ff0cc061SDimitry Andric 
15177d523365SDimitry Andric   if (UseDeoptBundles) {
15187d523365SDimitry Andric     Token->setName("statepoint_token");
15197d523365SDimitry Andric     if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
15207d523365SDimitry Andric       StringRef Name =
15217d523365SDimitry Andric           CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
15227d523365SDimitry Andric       CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
15237d523365SDimitry Andric       GCResult->setAttributes(CS.getAttributes().getRetAttributes());
1524ff0cc061SDimitry Andric 
15257d523365SDimitry Andric       // We cannot RAUW or delete CS.getInstruction() because it could be in the
15267d523365SDimitry Andric       // live set of some other safepoint, in which case that safepoint's
15277d523365SDimitry Andric       // PartiallyConstructedSafepointRecord will hold a raw pointer to this
15287d523365SDimitry Andric       // llvm::Instruction.  Instead, we defer the replacement and deletion to
15297d523365SDimitry Andric       // after the live sets have been made explicit in the IR, and we no longer
15307d523365SDimitry Andric       // have raw pointers to worry about.
15317d523365SDimitry Andric       Replacements.emplace_back(CS.getInstruction(), GCResult);
15327d523365SDimitry Andric     } else {
15337d523365SDimitry Andric       Replacements.emplace_back(CS.getInstruction(), nullptr);
15347d523365SDimitry Andric     }
15357d523365SDimitry Andric   } else {
15367d523365SDimitry Andric     assert(!CS.getInstruction()->hasNUsesOrMore(2) &&
1537ff0cc061SDimitry Andric            "only valid use before rewrite is gc.result");
15387d523365SDimitry Andric     assert(!CS.getInstruction()->hasOneUse() ||
15397d523365SDimitry Andric            isGCResult(cast<Instruction>(*CS.getInstruction()->user_begin())));
15407d523365SDimitry Andric 
15417d523365SDimitry Andric     // Take the name of the original statepoint token if there was one.
15427d523365SDimitry Andric     Token->takeName(CS.getInstruction());
1543ff0cc061SDimitry Andric 
1544ff0cc061SDimitry Andric     // Update the gc.result of the original statepoint (if any) to use the newly
1545ff0cc061SDimitry Andric     // inserted statepoint.  This is safe to do here since the token can't be
1546ff0cc061SDimitry Andric     // considered a live reference.
15477d523365SDimitry Andric     CS.getInstruction()->replaceAllUsesWith(Token);
15487d523365SDimitry Andric     CS.getInstruction()->eraseFromParent();
15497d523365SDimitry Andric   }
1550ff0cc061SDimitry Andric 
15517d523365SDimitry Andric   Result.StatepointToken = Token;
1552ff0cc061SDimitry Andric 
1553ff0cc061SDimitry Andric   // Second, create a gc.relocate for every live variable
15547d523365SDimitry Andric   const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
15557d523365SDimitry Andric   CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
1556ff0cc061SDimitry Andric }
1557ff0cc061SDimitry Andric 
1558ff0cc061SDimitry Andric namespace {
15597d523365SDimitry Andric struct NameOrdering {
15607d523365SDimitry Andric   Value *Base;
15617d523365SDimitry Andric   Value *Derived;
15627d523365SDimitry Andric 
15637d523365SDimitry Andric   bool operator()(NameOrdering const &a, NameOrdering const &b) {
15647d523365SDimitry Andric     return -1 == a.Derived->getName().compare(b.Derived->getName());
1565ff0cc061SDimitry Andric   }
1566ff0cc061SDimitry Andric };
1567ff0cc061SDimitry Andric }
1568ff0cc061SDimitry Andric 
15697d523365SDimitry Andric static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
15707d523365SDimitry Andric                            SmallVectorImpl<Value *> &LiveVec) {
15717d523365SDimitry Andric   assert(BaseVec.size() == LiveVec.size());
15727d523365SDimitry Andric 
15737d523365SDimitry Andric   SmallVector<NameOrdering, 64> Temp;
15747d523365SDimitry Andric   for (size_t i = 0; i < BaseVec.size(); i++) {
15757d523365SDimitry Andric     NameOrdering v;
15767d523365SDimitry Andric     v.Base = BaseVec[i];
15777d523365SDimitry Andric     v.Derived = LiveVec[i];
15787d523365SDimitry Andric     Temp.push_back(v);
1579ff0cc061SDimitry Andric   }
15807d523365SDimitry Andric 
15817d523365SDimitry Andric   std::sort(Temp.begin(), Temp.end(), NameOrdering());
15827d523365SDimitry Andric   for (size_t i = 0; i < BaseVec.size(); i++) {
15837d523365SDimitry Andric     BaseVec[i] = Temp[i].Base;
15847d523365SDimitry Andric     LiveVec[i] = Temp[i].Derived;
1585ff0cc061SDimitry Andric   }
1586ff0cc061SDimitry Andric }
1587ff0cc061SDimitry Andric 
1588ff0cc061SDimitry Andric // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1589ff0cc061SDimitry Andric // which make the relocations happening at this safepoint explicit.
1590ff0cc061SDimitry Andric //
1591ff0cc061SDimitry Andric // WARNING: Does not do any fixup to adjust users of the original live
1592ff0cc061SDimitry Andric // values.  That's the callers responsibility.
1593ff0cc061SDimitry Andric static void
15947d523365SDimitry Andric makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
15957d523365SDimitry Andric                        PartiallyConstructedSafepointRecord &Result,
15967d523365SDimitry Andric                        std::vector<DeferredReplacement> &Replacements) {
15977d523365SDimitry Andric   const auto &LiveSet = Result.LiveSet;
15987d523365SDimitry Andric   const auto &PointerToBase = Result.PointerToBase;
1599ff0cc061SDimitry Andric 
1600ff0cc061SDimitry Andric   // Convert to vector for efficient cross referencing.
16017d523365SDimitry Andric   SmallVector<Value *, 64> BaseVec, LiveVec;
16027d523365SDimitry Andric   LiveVec.reserve(LiveSet.size());
16037d523365SDimitry Andric   BaseVec.reserve(LiveSet.size());
16047d523365SDimitry Andric   for (Value *L : LiveSet) {
16057d523365SDimitry Andric     LiveVec.push_back(L);
16067d523365SDimitry Andric     assert(PointerToBase.count(L));
16077d523365SDimitry Andric     Value *Base = PointerToBase.find(L)->second;
16087d523365SDimitry Andric     BaseVec.push_back(Base);
1609ff0cc061SDimitry Andric   }
16107d523365SDimitry Andric   assert(LiveVec.size() == BaseVec.size());
1611ff0cc061SDimitry Andric 
1612ff0cc061SDimitry Andric   // To make the output IR slightly more stable (for use in diffs), ensure a
1613ff0cc061SDimitry Andric   // fixed order of the values in the safepoint (by sorting the value name).
1614ff0cc061SDimitry Andric   // The order is otherwise meaningless.
16157d523365SDimitry Andric   StabilizeOrder(BaseVec, LiveVec);
1616ff0cc061SDimitry Andric 
1617ff0cc061SDimitry Andric   // Do the actual rewriting and delete the old statepoint
16187d523365SDimitry Andric   makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
1619ff0cc061SDimitry Andric }
1620ff0cc061SDimitry Andric 
1621ff0cc061SDimitry Andric // Helper function for the relocationViaAlloca.
16227d523365SDimitry Andric //
16237d523365SDimitry Andric // It receives iterator to the statepoint gc relocates and emits a store to the
16247d523365SDimitry Andric // assigned location (via allocaMap) for the each one of them.  It adds the
16257d523365SDimitry Andric // visited values into the visitedLiveValues set, which we will later use them
16267d523365SDimitry Andric // for sanity checking.
1627ff0cc061SDimitry Andric static void
1628ff0cc061SDimitry Andric insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1629ff0cc061SDimitry Andric                        DenseMap<Value *, Value *> &AllocaMap,
1630ff0cc061SDimitry Andric                        DenseSet<Value *> &VisitedLiveValues) {
1631ff0cc061SDimitry Andric 
1632ff0cc061SDimitry Andric   for (User *U : GCRelocs) {
16334d0b32cdSDimitry Andric     GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
16344d0b32cdSDimitry Andric     if (!Relocate)
1635ff0cc061SDimitry Andric       continue;
1636ff0cc061SDimitry Andric 
16374d0b32cdSDimitry Andric     Value *OriginalValue = const_cast<Value *>(Relocate->getDerivedPtr());
1638ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue));
1639ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1640ff0cc061SDimitry Andric 
1641ff0cc061SDimitry Andric     // Emit store into the related alloca
16427d523365SDimitry Andric     // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
1643ff0cc061SDimitry Andric     // the correct type according to alloca.
16444d0b32cdSDimitry Andric     assert(Relocate->getNextNode() &&
16457d523365SDimitry Andric            "Should always have one since it's not a terminator");
16464d0b32cdSDimitry Andric     IRBuilder<> Builder(Relocate->getNextNode());
1647ff0cc061SDimitry Andric     Value *CastedRelocatedValue =
16484d0b32cdSDimitry Andric       Builder.CreateBitCast(Relocate,
16497d523365SDimitry Andric                             cast<AllocaInst>(Alloca)->getAllocatedType(),
16504d0b32cdSDimitry Andric                             suffixed_name_or(Relocate, ".casted", ""));
1651ff0cc061SDimitry Andric 
1652ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1653ff0cc061SDimitry Andric     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1654ff0cc061SDimitry Andric 
1655ff0cc061SDimitry Andric #ifndef NDEBUG
1656ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1657ff0cc061SDimitry Andric #endif
1658ff0cc061SDimitry Andric   }
1659ff0cc061SDimitry Andric }
1660ff0cc061SDimitry Andric 
1661ff0cc061SDimitry Andric // Helper function for the "relocationViaAlloca". Similar to the
1662ff0cc061SDimitry Andric // "insertRelocationStores" but works for rematerialized values.
1663ff0cc061SDimitry Andric static void
1664ff0cc061SDimitry Andric insertRematerializationStores(
1665ff0cc061SDimitry Andric   RematerializedValueMapTy RematerializedValues,
1666ff0cc061SDimitry Andric   DenseMap<Value *, Value *> &AllocaMap,
1667ff0cc061SDimitry Andric   DenseSet<Value *> &VisitedLiveValues) {
1668ff0cc061SDimitry Andric 
1669ff0cc061SDimitry Andric   for (auto RematerializedValuePair: RematerializedValues) {
1670ff0cc061SDimitry Andric     Instruction *RematerializedValue = RematerializedValuePair.first;
1671ff0cc061SDimitry Andric     Value *OriginalValue = RematerializedValuePair.second;
1672ff0cc061SDimitry Andric 
1673ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue) &&
1674ff0cc061SDimitry Andric            "Can not find alloca for rematerialized value");
1675ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1676ff0cc061SDimitry Andric 
1677ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1678ff0cc061SDimitry Andric     Store->insertAfter(RematerializedValue);
1679ff0cc061SDimitry Andric 
1680ff0cc061SDimitry Andric #ifndef NDEBUG
1681ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1682ff0cc061SDimitry Andric #endif
1683ff0cc061SDimitry Andric   }
1684ff0cc061SDimitry Andric }
1685ff0cc061SDimitry Andric 
16867d523365SDimitry Andric /// Do all the relocation update via allocas and mem2reg
1687ff0cc061SDimitry Andric static void relocationViaAlloca(
1688ff0cc061SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
16897d523365SDimitry Andric     ArrayRef<PartiallyConstructedSafepointRecord> Records) {
1690ff0cc061SDimitry Andric #ifndef NDEBUG
1691ff0cc061SDimitry Andric   // record initial number of (static) allocas; we'll check we have the same
1692ff0cc061SDimitry Andric   // number when we get done.
1693ff0cc061SDimitry Andric   int InitialAllocaNum = 0;
1694ff0cc061SDimitry Andric   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1695ff0cc061SDimitry Andric        I++)
1696ff0cc061SDimitry Andric     if (isa<AllocaInst>(*I))
1697ff0cc061SDimitry Andric       InitialAllocaNum++;
1698ff0cc061SDimitry Andric #endif
1699ff0cc061SDimitry Andric 
1700ff0cc061SDimitry Andric   // TODO-PERF: change data structures, reserve
1701ff0cc061SDimitry Andric   DenseMap<Value *, Value *> AllocaMap;
1702ff0cc061SDimitry Andric   SmallVector<AllocaInst *, 200> PromotableAllocas;
1703ff0cc061SDimitry Andric   // Used later to chack that we have enough allocas to store all values
1704ff0cc061SDimitry Andric   std::size_t NumRematerializedValues = 0;
1705ff0cc061SDimitry Andric   PromotableAllocas.reserve(Live.size());
1706ff0cc061SDimitry Andric 
1707ff0cc061SDimitry Andric   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1708ff0cc061SDimitry Andric   // "PromotableAllocas"
1709ff0cc061SDimitry Andric   auto emitAllocaFor = [&](Value *LiveValue) {
1710ff0cc061SDimitry Andric     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1711ff0cc061SDimitry Andric                                         F.getEntryBlock().getFirstNonPHI());
1712ff0cc061SDimitry Andric     AllocaMap[LiveValue] = Alloca;
1713ff0cc061SDimitry Andric     PromotableAllocas.push_back(Alloca);
1714ff0cc061SDimitry Andric   };
1715ff0cc061SDimitry Andric 
17167d523365SDimitry Andric   // Emit alloca for each live gc pointer
17177d523365SDimitry Andric   for (Value *V : Live)
17187d523365SDimitry Andric     emitAllocaFor(V);
1719ff0cc061SDimitry Andric 
17207d523365SDimitry Andric   // Emit allocas for rematerialized values
17217d523365SDimitry Andric   for (const auto &Info : Records)
1722ff0cc061SDimitry Andric     for (auto RematerializedValuePair : Info.RematerializedValues) {
1723ff0cc061SDimitry Andric       Value *OriginalValue = RematerializedValuePair.second;
1724ff0cc061SDimitry Andric       if (AllocaMap.count(OriginalValue) != 0)
1725ff0cc061SDimitry Andric         continue;
1726ff0cc061SDimitry Andric 
1727ff0cc061SDimitry Andric       emitAllocaFor(OriginalValue);
1728ff0cc061SDimitry Andric       ++NumRematerializedValues;
1729ff0cc061SDimitry Andric     }
1730ff0cc061SDimitry Andric 
1731ff0cc061SDimitry Andric   // The next two loops are part of the same conceptual operation.  We need to
1732ff0cc061SDimitry Andric   // insert a store to the alloca after the original def and at each
1733ff0cc061SDimitry Andric   // redefinition.  We need to insert a load before each use.  These are split
1734ff0cc061SDimitry Andric   // into distinct loops for performance reasons.
1735ff0cc061SDimitry Andric 
17367d523365SDimitry Andric   // Update gc pointer after each statepoint: either store a relocated value or
17377d523365SDimitry Andric   // null (if no relocated value was found for this gc pointer and it is not a
17387d523365SDimitry Andric   // gc_result).  This must happen before we update the statepoint with load of
17397d523365SDimitry Andric   // alloca otherwise we lose the link between statepoint and old def.
17407d523365SDimitry Andric   for (const auto &Info : Records) {
1741ff0cc061SDimitry Andric     Value *Statepoint = Info.StatepointToken;
1742ff0cc061SDimitry Andric 
1743ff0cc061SDimitry Andric     // This will be used for consistency check
1744ff0cc061SDimitry Andric     DenseSet<Value *> VisitedLiveValues;
1745ff0cc061SDimitry Andric 
1746ff0cc061SDimitry Andric     // Insert stores for normal statepoint gc relocates
1747ff0cc061SDimitry Andric     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1748ff0cc061SDimitry Andric 
1749ff0cc061SDimitry Andric     // In case if it was invoke statepoint
1750ff0cc061SDimitry Andric     // we will insert stores for exceptional path gc relocates.
1751ff0cc061SDimitry Andric     if (isa<InvokeInst>(Statepoint)) {
1752ff0cc061SDimitry Andric       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1753ff0cc061SDimitry Andric                              VisitedLiveValues);
1754ff0cc061SDimitry Andric     }
1755ff0cc061SDimitry Andric 
1756ff0cc061SDimitry Andric     // Do similar thing with rematerialized values
1757ff0cc061SDimitry Andric     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1758ff0cc061SDimitry Andric                                   VisitedLiveValues);
1759ff0cc061SDimitry Andric 
1760ff0cc061SDimitry Andric     if (ClobberNonLive) {
17617d523365SDimitry Andric       // As a debugging aid, pretend that an unrelocated pointer becomes null at
1762ff0cc061SDimitry Andric       // the gc.statepoint.  This will turn some subtle GC problems into
1763ff0cc061SDimitry Andric       // slightly easier to debug SEGVs.  Note that on large IR files with
1764ff0cc061SDimitry Andric       // lots of gc.statepoints this is extremely costly both memory and time
1765ff0cc061SDimitry Andric       // wise.
1766ff0cc061SDimitry Andric       SmallVector<AllocaInst *, 64> ToClobber;
1767ff0cc061SDimitry Andric       for (auto Pair : AllocaMap) {
1768ff0cc061SDimitry Andric         Value *Def = Pair.first;
1769ff0cc061SDimitry Andric         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1770ff0cc061SDimitry Andric 
1771ff0cc061SDimitry Andric         // This value was relocated
1772ff0cc061SDimitry Andric         if (VisitedLiveValues.count(Def)) {
1773ff0cc061SDimitry Andric           continue;
1774ff0cc061SDimitry Andric         }
1775ff0cc061SDimitry Andric         ToClobber.push_back(Alloca);
1776ff0cc061SDimitry Andric       }
1777ff0cc061SDimitry Andric 
1778ff0cc061SDimitry Andric       auto InsertClobbersAt = [&](Instruction *IP) {
1779ff0cc061SDimitry Andric         for (auto *AI : ToClobber) {
1780ff0cc061SDimitry Andric           auto AIType = cast<PointerType>(AI->getType());
1781ff0cc061SDimitry Andric           auto PT = cast<PointerType>(AIType->getElementType());
1782ff0cc061SDimitry Andric           Constant *CPN = ConstantPointerNull::get(PT);
1783ff0cc061SDimitry Andric           StoreInst *Store = new StoreInst(CPN, AI);
1784ff0cc061SDimitry Andric           Store->insertBefore(IP);
1785ff0cc061SDimitry Andric         }
1786ff0cc061SDimitry Andric       };
1787ff0cc061SDimitry Andric 
1788ff0cc061SDimitry Andric       // Insert the clobbering stores.  These may get intermixed with the
1789ff0cc061SDimitry Andric       // gc.results and gc.relocates, but that's fine.
1790ff0cc061SDimitry Andric       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
17917d523365SDimitry Andric         InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
17927d523365SDimitry Andric         InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1793ff0cc061SDimitry Andric       } else {
17947d523365SDimitry Andric         InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1795ff0cc061SDimitry Andric       }
1796ff0cc061SDimitry Andric     }
1797ff0cc061SDimitry Andric   }
17987d523365SDimitry Andric 
17997d523365SDimitry Andric   // Update use with load allocas and add store for gc_relocated.
1800ff0cc061SDimitry Andric   for (auto Pair : AllocaMap) {
1801ff0cc061SDimitry Andric     Value *Def = Pair.first;
1802ff0cc061SDimitry Andric     Value *Alloca = Pair.second;
1803ff0cc061SDimitry Andric 
18047d523365SDimitry Andric     // We pre-record the uses of allocas so that we dont have to worry about
18057d523365SDimitry Andric     // later update that changes the user information..
18067d523365SDimitry Andric 
1807ff0cc061SDimitry Andric     SmallVector<Instruction *, 20> Uses;
1808ff0cc061SDimitry Andric     // PERF: trade a linear scan for repeated reallocation
1809ff0cc061SDimitry Andric     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1810ff0cc061SDimitry Andric     for (User *U : Def->users()) {
1811ff0cc061SDimitry Andric       if (!isa<ConstantExpr>(U)) {
1812ff0cc061SDimitry Andric         // If the def has a ConstantExpr use, then the def is either a
1813ff0cc061SDimitry Andric         // ConstantExpr use itself or null.  In either case
1814ff0cc061SDimitry Andric         // (recursively in the first, directly in the second), the oop
1815ff0cc061SDimitry Andric         // it is ultimately dependent on is null and this particular
1816ff0cc061SDimitry Andric         // use does not need to be fixed up.
1817ff0cc061SDimitry Andric         Uses.push_back(cast<Instruction>(U));
1818ff0cc061SDimitry Andric       }
1819ff0cc061SDimitry Andric     }
1820ff0cc061SDimitry Andric 
1821ff0cc061SDimitry Andric     std::sort(Uses.begin(), Uses.end());
1822ff0cc061SDimitry Andric     auto Last = std::unique(Uses.begin(), Uses.end());
1823ff0cc061SDimitry Andric     Uses.erase(Last, Uses.end());
1824ff0cc061SDimitry Andric 
1825ff0cc061SDimitry Andric     for (Instruction *Use : Uses) {
1826ff0cc061SDimitry Andric       if (isa<PHINode>(Use)) {
1827ff0cc061SDimitry Andric         PHINode *Phi = cast<PHINode>(Use);
1828ff0cc061SDimitry Andric         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1829ff0cc061SDimitry Andric           if (Def == Phi->getIncomingValue(i)) {
1830ff0cc061SDimitry Andric             LoadInst *Load = new LoadInst(
1831ff0cc061SDimitry Andric                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1832ff0cc061SDimitry Andric             Phi->setIncomingValue(i, Load);
1833ff0cc061SDimitry Andric           }
1834ff0cc061SDimitry Andric         }
1835ff0cc061SDimitry Andric       } else {
1836ff0cc061SDimitry Andric         LoadInst *Load = new LoadInst(Alloca, "", Use);
1837ff0cc061SDimitry Andric         Use->replaceUsesOfWith(Def, Load);
1838ff0cc061SDimitry Andric       }
1839ff0cc061SDimitry Andric     }
1840ff0cc061SDimitry Andric 
18417d523365SDimitry Andric     // Emit store for the initial gc value.  Store must be inserted after load,
18427d523365SDimitry Andric     // otherwise store will be in alloca's use list and an extra load will be
18437d523365SDimitry Andric     // inserted before it.
1844ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(Def, Alloca);
1845ff0cc061SDimitry Andric     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1846ff0cc061SDimitry Andric       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1847ff0cc061SDimitry Andric         // InvokeInst is a TerminatorInst so the store need to be inserted
1848ff0cc061SDimitry Andric         // into its normal destination block.
1849ff0cc061SDimitry Andric         BasicBlock *NormalDest = Invoke->getNormalDest();
1850ff0cc061SDimitry Andric         Store->insertBefore(NormalDest->getFirstNonPHI());
1851ff0cc061SDimitry Andric       } else {
1852ff0cc061SDimitry Andric         assert(!Inst->isTerminator() &&
1853ff0cc061SDimitry Andric                "The only TerminatorInst that can produce a value is "
1854ff0cc061SDimitry Andric                "InvokeInst which is handled above.");
1855ff0cc061SDimitry Andric         Store->insertAfter(Inst);
1856ff0cc061SDimitry Andric       }
1857ff0cc061SDimitry Andric     } else {
1858ff0cc061SDimitry Andric       assert(isa<Argument>(Def));
1859ff0cc061SDimitry Andric       Store->insertAfter(cast<Instruction>(Alloca));
1860ff0cc061SDimitry Andric     }
1861ff0cc061SDimitry Andric   }
1862ff0cc061SDimitry Andric 
1863ff0cc061SDimitry Andric   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1864ff0cc061SDimitry Andric          "we must have the same allocas with lives");
1865ff0cc061SDimitry Andric   if (!PromotableAllocas.empty()) {
18667d523365SDimitry Andric     // Apply mem2reg to promote alloca to SSA
1867ff0cc061SDimitry Andric     PromoteMemToReg(PromotableAllocas, DT);
1868ff0cc061SDimitry Andric   }
1869ff0cc061SDimitry Andric 
1870ff0cc061SDimitry Andric #ifndef NDEBUG
18717d523365SDimitry Andric   for (auto &I : F.getEntryBlock())
18727d523365SDimitry Andric     if (isa<AllocaInst>(I))
1873ff0cc061SDimitry Andric       InitialAllocaNum--;
1874ff0cc061SDimitry Andric   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1875ff0cc061SDimitry Andric #endif
1876ff0cc061SDimitry Andric }
1877ff0cc061SDimitry Andric 
1878ff0cc061SDimitry Andric /// Implement a unique function which doesn't require we sort the input
1879ff0cc061SDimitry Andric /// vector.  Doing so has the effect of changing the output of a couple of
1880ff0cc061SDimitry Andric /// tests in ways which make them less useful in testing fused safepoints.
1881ff0cc061SDimitry Andric template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
18828f0fd8f6SDimitry Andric   SmallSet<T, 8> Seen;
18838f0fd8f6SDimitry Andric   Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
18848f0fd8f6SDimitry Andric               return !Seen.insert(V).second;
18858f0fd8f6SDimitry Andric             }), Vec.end());
1886ff0cc061SDimitry Andric }
1887ff0cc061SDimitry Andric 
1888ff0cc061SDimitry Andric /// Insert holders so that each Value is obviously live through the entire
1889ff0cc061SDimitry Andric /// lifetime of the call.
1890ff0cc061SDimitry Andric static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1891ff0cc061SDimitry Andric                                  SmallVectorImpl<CallInst *> &Holders) {
1892ff0cc061SDimitry Andric   if (Values.empty())
1893ff0cc061SDimitry Andric     // No values to hold live, might as well not insert the empty holder
1894ff0cc061SDimitry Andric     return;
1895ff0cc061SDimitry Andric 
18967d523365SDimitry Andric   Module *M = CS.getInstruction()->getModule();
1897ff0cc061SDimitry Andric   // Use a dummy vararg function to actually hold the values live
1898ff0cc061SDimitry Andric   Function *Func = cast<Function>(M->getOrInsertFunction(
1899ff0cc061SDimitry Andric       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1900ff0cc061SDimitry Andric   if (CS.isCall()) {
1901ff0cc061SDimitry Andric     // For call safepoints insert dummy calls right after safepoint
19027d523365SDimitry Andric     Holders.push_back(CallInst::Create(Func, Values, "",
19037d523365SDimitry Andric                                        &*++CS.getInstruction()->getIterator()));
1904ff0cc061SDimitry Andric     return;
1905ff0cc061SDimitry Andric   }
1906ff0cc061SDimitry Andric   // For invoke safepooints insert dummy calls both in normal and
1907ff0cc061SDimitry Andric   // exceptional destination blocks
1908ff0cc061SDimitry Andric   auto *II = cast<InvokeInst>(CS.getInstruction());
1909ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
19107d523365SDimitry Andric       Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
1911ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
19127d523365SDimitry Andric       Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
1913ff0cc061SDimitry Andric }
1914ff0cc061SDimitry Andric 
1915ff0cc061SDimitry Andric static void findLiveReferences(
19167d523365SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
1917ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1918ff0cc061SDimitry Andric   GCPtrLivenessData OriginalLivenessData;
1919ff0cc061SDimitry Andric   computeLiveInValues(DT, F, OriginalLivenessData);
1920ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1921ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
1922ff0cc061SDimitry Andric     const CallSite &CS = toUpdate[i];
1923ff0cc061SDimitry Andric     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1924ff0cc061SDimitry Andric   }
1925ff0cc061SDimitry Andric }
1926ff0cc061SDimitry Andric 
1927ff0cc061SDimitry Andric /// Remove any vector of pointers from the live set by scalarizing them over the
1928ff0cc061SDimitry Andric /// statepoint instruction.  Adds the scalarized pieces to the live set.  It
19297d523365SDimitry Andric /// would be preferable to include the vector in the statepoint itself, but
1930ff0cc061SDimitry Andric /// the lowering code currently does not handle that.  Extending it would be
1931ff0cc061SDimitry Andric /// slightly non-trivial since it requires a format change.  Given how rare
19327d523365SDimitry Andric /// such cases are (for the moment?) scalarizing is an acceptable compromise.
1933ff0cc061SDimitry Andric static void splitVectorValues(Instruction *StatepointInst,
19343dac3a9bSDimitry Andric                               StatepointLiveSetTy &LiveSet,
19353dac3a9bSDimitry Andric                               DenseMap<Value *, Value *>& PointerToBase,
19363dac3a9bSDimitry Andric                               DominatorTree &DT) {
1937ff0cc061SDimitry Andric   SmallVector<Value *, 16> ToSplit;
1938ff0cc061SDimitry Andric   for (Value *V : LiveSet)
1939ff0cc061SDimitry Andric     if (isa<VectorType>(V->getType()))
1940ff0cc061SDimitry Andric       ToSplit.push_back(V);
1941ff0cc061SDimitry Andric 
1942ff0cc061SDimitry Andric   if (ToSplit.empty())
1943ff0cc061SDimitry Andric     return;
1944ff0cc061SDimitry Andric 
19453dac3a9bSDimitry Andric   DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
19463dac3a9bSDimitry Andric 
1947ff0cc061SDimitry Andric   Function &F = *(StatepointInst->getParent()->getParent());
1948ff0cc061SDimitry Andric 
1949ff0cc061SDimitry Andric   DenseMap<Value *, AllocaInst *> AllocaMap;
1950ff0cc061SDimitry Andric   // First is normal return, second is exceptional return (invoke only)
1951ff0cc061SDimitry Andric   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1952ff0cc061SDimitry Andric   for (Value *V : ToSplit) {
1953ff0cc061SDimitry Andric     AllocaInst *Alloca =
1954ff0cc061SDimitry Andric         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1955ff0cc061SDimitry Andric     AllocaMap[V] = Alloca;
1956ff0cc061SDimitry Andric 
1957ff0cc061SDimitry Andric     VectorType *VT = cast<VectorType>(V->getType());
1958ff0cc061SDimitry Andric     IRBuilder<> Builder(StatepointInst);
1959ff0cc061SDimitry Andric     SmallVector<Value *, 16> Elements;
1960ff0cc061SDimitry Andric     for (unsigned i = 0; i < VT->getNumElements(); i++)
1961ff0cc061SDimitry Andric       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
19623dac3a9bSDimitry Andric     ElementMapping[V] = Elements;
1963ff0cc061SDimitry Andric 
1964ff0cc061SDimitry Andric     auto InsertVectorReform = [&](Instruction *IP) {
1965ff0cc061SDimitry Andric       Builder.SetInsertPoint(IP);
1966ff0cc061SDimitry Andric       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1967ff0cc061SDimitry Andric       Value *ResultVec = UndefValue::get(VT);
1968ff0cc061SDimitry Andric       for (unsigned i = 0; i < VT->getNumElements(); i++)
1969ff0cc061SDimitry Andric         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1970ff0cc061SDimitry Andric                                                 Builder.getInt32(i));
1971ff0cc061SDimitry Andric       return ResultVec;
1972ff0cc061SDimitry Andric     };
1973ff0cc061SDimitry Andric 
1974ff0cc061SDimitry Andric     if (isa<CallInst>(StatepointInst)) {
1975ff0cc061SDimitry Andric       BasicBlock::iterator Next(StatepointInst);
1976ff0cc061SDimitry Andric       Next++;
1977ff0cc061SDimitry Andric       Instruction *IP = &*(Next);
1978ff0cc061SDimitry Andric       Replacements[V].first = InsertVectorReform(IP);
1979ff0cc061SDimitry Andric       Replacements[V].second = nullptr;
1980ff0cc061SDimitry Andric     } else {
1981ff0cc061SDimitry Andric       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1982ff0cc061SDimitry Andric       // We've already normalized - check that we don't have shared destination
1983ff0cc061SDimitry Andric       // blocks
1984ff0cc061SDimitry Andric       BasicBlock *NormalDest = Invoke->getNormalDest();
1985ff0cc061SDimitry Andric       assert(!isa<PHINode>(NormalDest->begin()));
1986ff0cc061SDimitry Andric       BasicBlock *UnwindDest = Invoke->getUnwindDest();
1987ff0cc061SDimitry Andric       assert(!isa<PHINode>(UnwindDest->begin()));
1988ff0cc061SDimitry Andric       // Insert insert element sequences in both successors
1989ff0cc061SDimitry Andric       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1990ff0cc061SDimitry Andric       Replacements[V].first = InsertVectorReform(IP);
1991ff0cc061SDimitry Andric       IP = &*(UnwindDest->getFirstInsertionPt());
1992ff0cc061SDimitry Andric       Replacements[V].second = InsertVectorReform(IP);
1993ff0cc061SDimitry Andric     }
1994ff0cc061SDimitry Andric   }
19953dac3a9bSDimitry Andric 
1996ff0cc061SDimitry Andric   for (Value *V : ToSplit) {
1997ff0cc061SDimitry Andric     AllocaInst *Alloca = AllocaMap[V];
1998ff0cc061SDimitry Andric 
1999ff0cc061SDimitry Andric     // Capture all users before we start mutating use lists
2000ff0cc061SDimitry Andric     SmallVector<Instruction *, 16> Users;
2001ff0cc061SDimitry Andric     for (User *U : V->users())
2002ff0cc061SDimitry Andric       Users.push_back(cast<Instruction>(U));
2003ff0cc061SDimitry Andric 
2004ff0cc061SDimitry Andric     for (Instruction *I : Users) {
2005ff0cc061SDimitry Andric       if (auto Phi = dyn_cast<PHINode>(I)) {
2006ff0cc061SDimitry Andric         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
2007ff0cc061SDimitry Andric           if (V == Phi->getIncomingValue(i)) {
2008ff0cc061SDimitry Andric             LoadInst *Load = new LoadInst(
2009ff0cc061SDimitry Andric                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
2010ff0cc061SDimitry Andric             Phi->setIncomingValue(i, Load);
2011ff0cc061SDimitry Andric           }
2012ff0cc061SDimitry Andric       } else {
2013ff0cc061SDimitry Andric         LoadInst *Load = new LoadInst(Alloca, "", I);
2014ff0cc061SDimitry Andric         I->replaceUsesOfWith(V, Load);
2015ff0cc061SDimitry Andric       }
2016ff0cc061SDimitry Andric     }
2017ff0cc061SDimitry Andric 
2018ff0cc061SDimitry Andric     // Store the original value and the replacement value into the alloca
2019ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(V, Alloca);
2020ff0cc061SDimitry Andric     if (auto I = dyn_cast<Instruction>(V))
2021ff0cc061SDimitry Andric       Store->insertAfter(I);
2022ff0cc061SDimitry Andric     else
2023ff0cc061SDimitry Andric       Store->insertAfter(Alloca);
2024ff0cc061SDimitry Andric 
2025ff0cc061SDimitry Andric     // Normal return for invoke, or call return
2026ff0cc061SDimitry Andric     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
2027ff0cc061SDimitry Andric     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2028ff0cc061SDimitry Andric     // Unwind return for invoke only
2029ff0cc061SDimitry Andric     Replacement = cast_or_null<Instruction>(Replacements[V].second);
2030ff0cc061SDimitry Andric     if (Replacement)
2031ff0cc061SDimitry Andric       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2032ff0cc061SDimitry Andric   }
2033ff0cc061SDimitry Andric 
2034ff0cc061SDimitry Andric   // apply mem2reg to promote alloca to SSA
2035ff0cc061SDimitry Andric   SmallVector<AllocaInst *, 16> Allocas;
2036ff0cc061SDimitry Andric   for (Value *V : ToSplit)
2037ff0cc061SDimitry Andric     Allocas.push_back(AllocaMap[V]);
2038ff0cc061SDimitry Andric   PromoteMemToReg(Allocas, DT);
20393dac3a9bSDimitry Andric 
20403dac3a9bSDimitry Andric   // Update our tracking of live pointers and base mappings to account for the
20413dac3a9bSDimitry Andric   // changes we just made.
20423dac3a9bSDimitry Andric   for (Value *V : ToSplit) {
20433dac3a9bSDimitry Andric     auto &Elements = ElementMapping[V];
20443dac3a9bSDimitry Andric 
20453dac3a9bSDimitry Andric     LiveSet.erase(V);
20463dac3a9bSDimitry Andric     LiveSet.insert(Elements.begin(), Elements.end());
20473dac3a9bSDimitry Andric     // We need to update the base mapping as well.
20483dac3a9bSDimitry Andric     assert(PointerToBase.count(V));
20493dac3a9bSDimitry Andric     Value *OldBase = PointerToBase[V];
20503dac3a9bSDimitry Andric     auto &BaseElements = ElementMapping[OldBase];
20513dac3a9bSDimitry Andric     PointerToBase.erase(V);
20523dac3a9bSDimitry Andric     assert(Elements.size() == BaseElements.size());
20533dac3a9bSDimitry Andric     for (unsigned i = 0; i < Elements.size(); i++) {
20543dac3a9bSDimitry Andric       Value *Elem = Elements[i];
20553dac3a9bSDimitry Andric       PointerToBase[Elem] = BaseElements[i];
20563dac3a9bSDimitry Andric     }
20573dac3a9bSDimitry Andric   }
2058ff0cc061SDimitry Andric }
2059ff0cc061SDimitry Andric 
2060ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". It walks use chain
2061ff0cc061SDimitry Andric // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2062ff0cc061SDimitry Andric // values are visited (currently it is GEP's and casts). Returns true if it
20637d523365SDimitry Andric // successfully reached "BaseValue" and false otherwise.
2064ff0cc061SDimitry Andric // Fills "ChainToBase" array with all visited values. "BaseValue" is not
2065ff0cc061SDimitry Andric // recorded.
2066ff0cc061SDimitry Andric static bool findRematerializableChainToBasePointer(
2067ff0cc061SDimitry Andric   SmallVectorImpl<Instruction*> &ChainToBase,
2068ff0cc061SDimitry Andric   Value *CurrentValue, Value *BaseValue) {
2069ff0cc061SDimitry Andric 
2070ff0cc061SDimitry Andric   // We have found a base value
2071ff0cc061SDimitry Andric   if (CurrentValue == BaseValue) {
2072ff0cc061SDimitry Andric     return true;
2073ff0cc061SDimitry Andric   }
2074ff0cc061SDimitry Andric 
2075ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2076ff0cc061SDimitry Andric     ChainToBase.push_back(GEP);
2077ff0cc061SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
2078ff0cc061SDimitry Andric                                                   GEP->getPointerOperand(),
2079ff0cc061SDimitry Andric                                                   BaseValue);
2080ff0cc061SDimitry Andric   }
2081ff0cc061SDimitry Andric 
2082ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2083ff0cc061SDimitry Andric     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2084ff0cc061SDimitry Andric       return false;
2085ff0cc061SDimitry Andric 
2086ff0cc061SDimitry Andric     ChainToBase.push_back(CI);
20877d523365SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
20887d523365SDimitry Andric                                                   CI->getOperand(0), BaseValue);
2089ff0cc061SDimitry Andric   }
2090ff0cc061SDimitry Andric 
2091ff0cc061SDimitry Andric   // Not supported instruction in the chain
2092ff0cc061SDimitry Andric   return false;
2093ff0cc061SDimitry Andric }
2094ff0cc061SDimitry Andric 
2095ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". Compute cost of the use
2096ff0cc061SDimitry Andric // chain we are going to rematerialize.
2097ff0cc061SDimitry Andric static unsigned
2098ff0cc061SDimitry Andric chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2099ff0cc061SDimitry Andric                        TargetTransformInfo &TTI) {
2100ff0cc061SDimitry Andric   unsigned Cost = 0;
2101ff0cc061SDimitry Andric 
2102ff0cc061SDimitry Andric   for (Instruction *Instr : Chain) {
2103ff0cc061SDimitry Andric     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2104ff0cc061SDimitry Andric       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2105ff0cc061SDimitry Andric              "non noop cast is found during rematerialization");
2106ff0cc061SDimitry Andric 
2107ff0cc061SDimitry Andric       Type *SrcTy = CI->getOperand(0)->getType();
2108ff0cc061SDimitry Andric       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2109ff0cc061SDimitry Andric 
2110ff0cc061SDimitry Andric     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2111ff0cc061SDimitry Andric       // Cost of the address calculation
2112ff0cc061SDimitry Andric       Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2113ff0cc061SDimitry Andric       Cost += TTI.getAddressComputationCost(ValTy);
2114ff0cc061SDimitry Andric 
2115ff0cc061SDimitry Andric       // And cost of the GEP itself
2116ff0cc061SDimitry Andric       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2117ff0cc061SDimitry Andric       //       allowed for the external usage)
2118ff0cc061SDimitry Andric       if (!GEP->hasAllConstantIndices())
2119ff0cc061SDimitry Andric         Cost += 2;
2120ff0cc061SDimitry Andric 
2121ff0cc061SDimitry Andric     } else {
2122ff0cc061SDimitry Andric       llvm_unreachable("unsupported instruciton type during rematerialization");
2123ff0cc061SDimitry Andric     }
2124ff0cc061SDimitry Andric   }
2125ff0cc061SDimitry Andric 
2126ff0cc061SDimitry Andric   return Cost;
2127ff0cc061SDimitry Andric }
2128ff0cc061SDimitry Andric 
21297d523365SDimitry Andric // From the statepoint live set pick values that are cheaper to recompute then
21307d523365SDimitry Andric // to relocate. Remove this values from the live set, rematerialize them after
2131ff0cc061SDimitry Andric // statepoint and record them in "Info" structure. Note that similar to
2132ff0cc061SDimitry Andric // relocated values we don't do any user adjustments here.
2133ff0cc061SDimitry Andric static void rematerializeLiveValues(CallSite CS,
2134ff0cc061SDimitry Andric                                     PartiallyConstructedSafepointRecord &Info,
2135ff0cc061SDimitry Andric                                     TargetTransformInfo &TTI) {
2136ff0cc061SDimitry Andric   const unsigned int ChainLengthThreshold = 10;
2137ff0cc061SDimitry Andric 
2138ff0cc061SDimitry Andric   // Record values we are going to delete from this statepoint live set.
2139ff0cc061SDimitry Andric   // We can not di this in following loop due to iterator invalidation.
2140ff0cc061SDimitry Andric   SmallVector<Value *, 32> LiveValuesToBeDeleted;
2141ff0cc061SDimitry Andric 
21427d523365SDimitry Andric   for (Value *LiveValue: Info.LiveSet) {
2143ff0cc061SDimitry Andric     // For each live pointer find it's defining chain
2144ff0cc061SDimitry Andric     SmallVector<Instruction *, 3> ChainToBase;
21457d523365SDimitry Andric     assert(Info.PointerToBase.count(LiveValue));
2146ff0cc061SDimitry Andric     bool FoundChain =
2147ff0cc061SDimitry Andric       findRematerializableChainToBasePointer(ChainToBase,
2148ff0cc061SDimitry Andric                                              LiveValue,
2149ff0cc061SDimitry Andric                                              Info.PointerToBase[LiveValue]);
2150ff0cc061SDimitry Andric     // Nothing to do, or chain is too long
2151ff0cc061SDimitry Andric     if (!FoundChain ||
2152ff0cc061SDimitry Andric         ChainToBase.size() == 0 ||
2153ff0cc061SDimitry Andric         ChainToBase.size() > ChainLengthThreshold)
2154ff0cc061SDimitry Andric       continue;
2155ff0cc061SDimitry Andric 
2156ff0cc061SDimitry Andric     // Compute cost of this chain
2157ff0cc061SDimitry Andric     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2158ff0cc061SDimitry Andric     // TODO: We can also account for cases when we will be able to remove some
2159ff0cc061SDimitry Andric     //       of the rematerialized values by later optimization passes. I.e if
2160ff0cc061SDimitry Andric     //       we rematerialized several intersecting chains. Or if original values
2161ff0cc061SDimitry Andric     //       don't have any uses besides this statepoint.
2162ff0cc061SDimitry Andric 
2163ff0cc061SDimitry Andric     // For invokes we need to rematerialize each chain twice - for normal and
2164ff0cc061SDimitry Andric     // for unwind basic blocks. Model this by multiplying cost by two.
2165ff0cc061SDimitry Andric     if (CS.isInvoke()) {
2166ff0cc061SDimitry Andric       Cost *= 2;
2167ff0cc061SDimitry Andric     }
2168ff0cc061SDimitry Andric     // If it's too expensive - skip it
2169ff0cc061SDimitry Andric     if (Cost >= RematerializationThreshold)
2170ff0cc061SDimitry Andric       continue;
2171ff0cc061SDimitry Andric 
2172ff0cc061SDimitry Andric     // Remove value from the live set
2173ff0cc061SDimitry Andric     LiveValuesToBeDeleted.push_back(LiveValue);
2174ff0cc061SDimitry Andric 
2175ff0cc061SDimitry Andric     // Clone instructions and record them inside "Info" structure
2176ff0cc061SDimitry Andric 
2177ff0cc061SDimitry Andric     // Walk backwards to visit top-most instructions first
2178ff0cc061SDimitry Andric     std::reverse(ChainToBase.begin(), ChainToBase.end());
2179ff0cc061SDimitry Andric 
2180ff0cc061SDimitry Andric     // Utility function which clones all instructions from "ChainToBase"
2181ff0cc061SDimitry Andric     // and inserts them before "InsertBefore". Returns rematerialized value
2182ff0cc061SDimitry Andric     // which should be used after statepoint.
2183ff0cc061SDimitry Andric     auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2184ff0cc061SDimitry Andric       Instruction *LastClonedValue = nullptr;
2185ff0cc061SDimitry Andric       Instruction *LastValue = nullptr;
2186ff0cc061SDimitry Andric       for (Instruction *Instr: ChainToBase) {
2187ff0cc061SDimitry Andric         // Only GEP's and casts are suported as we need to be careful to not
2188ff0cc061SDimitry Andric         // introduce any new uses of pointers not in the liveset.
2189ff0cc061SDimitry Andric         // Note that it's fine to introduce new uses of pointers which were
2190ff0cc061SDimitry Andric         // otherwise not used after this statepoint.
2191ff0cc061SDimitry Andric         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2192ff0cc061SDimitry Andric 
2193ff0cc061SDimitry Andric         Instruction *ClonedValue = Instr->clone();
2194ff0cc061SDimitry Andric         ClonedValue->insertBefore(InsertBefore);
2195ff0cc061SDimitry Andric         ClonedValue->setName(Instr->getName() + ".remat");
2196ff0cc061SDimitry Andric 
2197ff0cc061SDimitry Andric         // If it is not first instruction in the chain then it uses previously
2198ff0cc061SDimitry Andric         // cloned value. We should update it to use cloned value.
2199ff0cc061SDimitry Andric         if (LastClonedValue) {
2200ff0cc061SDimitry Andric           assert(LastValue);
2201ff0cc061SDimitry Andric           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2202ff0cc061SDimitry Andric #ifndef NDEBUG
2203ff0cc061SDimitry Andric           // Assert that cloned instruction does not use any instructions from
2204ff0cc061SDimitry Andric           // this chain other than LastClonedValue
2205ff0cc061SDimitry Andric           for (auto OpValue : ClonedValue->operand_values()) {
2206ff0cc061SDimitry Andric             assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2207ff0cc061SDimitry Andric                        ChainToBase.end() &&
2208ff0cc061SDimitry Andric                    "incorrect use in rematerialization chain");
2209ff0cc061SDimitry Andric           }
2210ff0cc061SDimitry Andric #endif
2211ff0cc061SDimitry Andric         }
2212ff0cc061SDimitry Andric 
2213ff0cc061SDimitry Andric         LastClonedValue = ClonedValue;
2214ff0cc061SDimitry Andric         LastValue = Instr;
2215ff0cc061SDimitry Andric       }
2216ff0cc061SDimitry Andric       assert(LastClonedValue);
2217ff0cc061SDimitry Andric       return LastClonedValue;
2218ff0cc061SDimitry Andric     };
2219ff0cc061SDimitry Andric 
2220ff0cc061SDimitry Andric     // Different cases for calls and invokes. For invokes we need to clone
2221ff0cc061SDimitry Andric     // instructions both on normal and unwind path.
2222ff0cc061SDimitry Andric     if (CS.isCall()) {
2223ff0cc061SDimitry Andric       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2224ff0cc061SDimitry Andric       assert(InsertBefore);
2225ff0cc061SDimitry Andric       Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2226ff0cc061SDimitry Andric       Info.RematerializedValues[RematerializedValue] = LiveValue;
2227ff0cc061SDimitry Andric     } else {
2228ff0cc061SDimitry Andric       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2229ff0cc061SDimitry Andric 
2230ff0cc061SDimitry Andric       Instruction *NormalInsertBefore =
22317d523365SDimitry Andric           &*Invoke->getNormalDest()->getFirstInsertionPt();
2232ff0cc061SDimitry Andric       Instruction *UnwindInsertBefore =
22337d523365SDimitry Andric           &*Invoke->getUnwindDest()->getFirstInsertionPt();
2234ff0cc061SDimitry Andric 
2235ff0cc061SDimitry Andric       Instruction *NormalRematerializedValue =
2236ff0cc061SDimitry Andric           rematerializeChain(NormalInsertBefore);
2237ff0cc061SDimitry Andric       Instruction *UnwindRematerializedValue =
2238ff0cc061SDimitry Andric           rematerializeChain(UnwindInsertBefore);
2239ff0cc061SDimitry Andric 
2240ff0cc061SDimitry Andric       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2241ff0cc061SDimitry Andric       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2242ff0cc061SDimitry Andric     }
2243ff0cc061SDimitry Andric   }
2244ff0cc061SDimitry Andric 
2245ff0cc061SDimitry Andric   // Remove rematerializaed values from the live set
2246ff0cc061SDimitry Andric   for (auto LiveValue: LiveValuesToBeDeleted) {
22477d523365SDimitry Andric     Info.LiveSet.erase(LiveValue);
2248ff0cc061SDimitry Andric   }
2249ff0cc061SDimitry Andric }
2250ff0cc061SDimitry Andric 
22517d523365SDimitry Andric static bool insertParsePoints(Function &F, DominatorTree &DT,
22527d523365SDimitry Andric                               TargetTransformInfo &TTI,
22537d523365SDimitry Andric                               SmallVectorImpl<CallSite> &ToUpdate) {
2254ff0cc061SDimitry Andric #ifndef NDEBUG
2255ff0cc061SDimitry Andric   // sanity check the input
22567d523365SDimitry Andric   std::set<CallSite> Uniqued;
22577d523365SDimitry Andric   Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
22587d523365SDimitry Andric   assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
2259ff0cc061SDimitry Andric 
22607d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2261ff0cc061SDimitry Andric     assert(CS.getInstruction()->getParent()->getParent() == &F);
22627d523365SDimitry Andric     assert((UseDeoptBundles || isStatepoint(CS)) &&
22637d523365SDimitry Andric            "expected to already be a deopt statepoint");
2264ff0cc061SDimitry Andric   }
2265ff0cc061SDimitry Andric #endif
2266ff0cc061SDimitry Andric 
2267ff0cc061SDimitry Andric   // When inserting gc.relocates for invokes, we need to be able to insert at
2268ff0cc061SDimitry Andric   // the top of the successor blocks.  See the comment on
2269ff0cc061SDimitry Andric   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2270ff0cc061SDimitry Andric   // may restructure the CFG.
22717d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2272ff0cc061SDimitry Andric     if (!CS.isInvoke())
2273ff0cc061SDimitry Andric       continue;
22747d523365SDimitry Andric     auto *II = cast<InvokeInst>(CS.getInstruction());
22757d523365SDimitry Andric     normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
22767d523365SDimitry Andric     normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
2277ff0cc061SDimitry Andric   }
2278ff0cc061SDimitry Andric 
2279ff0cc061SDimitry Andric   // A list of dummy calls added to the IR to keep various values obviously
2280ff0cc061SDimitry Andric   // live in the IR.  We'll remove all of these when done.
22817d523365SDimitry Andric   SmallVector<CallInst *, 64> Holders;
2282ff0cc061SDimitry Andric 
2283ff0cc061SDimitry Andric   // Insert a dummy call with all of the arguments to the vm_state we'll need
2284ff0cc061SDimitry Andric   // for the actual safepoint insertion.  This ensures reference arguments in
2285ff0cc061SDimitry Andric   // the deopt argument list are considered live through the safepoint (and
2286ff0cc061SDimitry Andric   // thus makes sure they get relocated.)
22877d523365SDimitry Andric   for (CallSite CS : ToUpdate) {
2288ff0cc061SDimitry Andric     SmallVector<Value *, 64> DeoptValues;
22897d523365SDimitry Andric 
22907d523365SDimitry Andric     iterator_range<const Use *> DeoptStateRange =
22917d523365SDimitry Andric         UseDeoptBundles
22927d523365SDimitry Andric             ? iterator_range<const Use *>(GetDeoptBundleOperands(CS))
22937d523365SDimitry Andric             : iterator_range<const Use *>(Statepoint(CS).vm_state_args());
22947d523365SDimitry Andric 
22957d523365SDimitry Andric     for (Value *Arg : DeoptStateRange) {
2296ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2297ff0cc061SDimitry Andric              "support for FCA unimplemented");
2298ff0cc061SDimitry Andric       if (isHandledGCPointerType(Arg->getType()))
2299ff0cc061SDimitry Andric         DeoptValues.push_back(Arg);
2300ff0cc061SDimitry Andric     }
23017d523365SDimitry Andric 
23027d523365SDimitry Andric     insertUseHolderAfter(CS, DeoptValues, Holders);
2303ff0cc061SDimitry Andric   }
2304ff0cc061SDimitry Andric 
23057d523365SDimitry Andric   SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
2306ff0cc061SDimitry Andric 
23077d523365SDimitry Andric   // A) Identify all gc pointers which are statically live at the given call
2308ff0cc061SDimitry Andric   // site.
23097d523365SDimitry Andric   findLiveReferences(F, DT, ToUpdate, Records);
2310ff0cc061SDimitry Andric 
2311ff0cc061SDimitry Andric   // B) Find the base pointers for each live pointer
2312ff0cc061SDimitry Andric   /* scope for caching */ {
2313ff0cc061SDimitry Andric     // Cache the 'defining value' relation used in the computation and
2314ff0cc061SDimitry Andric     // insertion of base phis and selects.  This ensures that we don't insert
2315ff0cc061SDimitry Andric     // large numbers of duplicate base_phis.
2316ff0cc061SDimitry Andric     DefiningValueMapTy DVCache;
2317ff0cc061SDimitry Andric 
23187d523365SDimitry Andric     for (size_t i = 0; i < Records.size(); i++) {
23197d523365SDimitry Andric       PartiallyConstructedSafepointRecord &info = Records[i];
23207d523365SDimitry Andric       findBasePointers(DT, DVCache, ToUpdate[i], info);
2321ff0cc061SDimitry Andric     }
2322ff0cc061SDimitry Andric   } // end of cache scope
2323ff0cc061SDimitry Andric 
2324ff0cc061SDimitry Andric   // The base phi insertion logic (for any safepoint) may have inserted new
2325ff0cc061SDimitry Andric   // instructions which are now live at some safepoint.  The simplest such
2326ff0cc061SDimitry Andric   // example is:
2327ff0cc061SDimitry Andric   // loop:
2328ff0cc061SDimitry Andric   //   phi a  <-- will be a new base_phi here
2329ff0cc061SDimitry Andric   //   safepoint 1 <-- that needs to be live here
2330ff0cc061SDimitry Andric   //   gep a + 1
2331ff0cc061SDimitry Andric   //   safepoint 2
2332ff0cc061SDimitry Andric   //   br loop
2333ff0cc061SDimitry Andric   // We insert some dummy calls after each safepoint to definitely hold live
2334ff0cc061SDimitry Andric   // the base pointers which were identified for that safepoint.  We'll then
2335ff0cc061SDimitry Andric   // ask liveness for _every_ base inserted to see what is now live.  Then we
2336ff0cc061SDimitry Andric   // remove the dummy calls.
23377d523365SDimitry Andric   Holders.reserve(Holders.size() + Records.size());
23387d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
23397d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
2340ff0cc061SDimitry Andric 
2341ff0cc061SDimitry Andric     SmallVector<Value *, 128> Bases;
23427d523365SDimitry Andric     for (auto Pair : Info.PointerToBase)
2343ff0cc061SDimitry Andric       Bases.push_back(Pair.second);
23447d523365SDimitry Andric 
23457d523365SDimitry Andric     insertUseHolderAfter(ToUpdate[i], Bases, Holders);
2346ff0cc061SDimitry Andric   }
2347ff0cc061SDimitry Andric 
2348ff0cc061SDimitry Andric   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2349ff0cc061SDimitry Andric   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2350ff0cc061SDimitry Andric   // not the key issue.
23517d523365SDimitry Andric   recomputeLiveInValues(F, DT, ToUpdate, Records);
2352ff0cc061SDimitry Andric 
2353ff0cc061SDimitry Andric   if (PrintBasePointers) {
23547d523365SDimitry Andric     for (auto &Info : Records) {
2355ff0cc061SDimitry Andric       errs() << "Base Pairs: (w/Relocation)\n";
23567d523365SDimitry Andric       for (auto Pair : Info.PointerToBase) {
23577d523365SDimitry Andric         errs() << " derived ";
23587d523365SDimitry Andric         Pair.first->printAsOperand(errs(), false);
23597d523365SDimitry Andric         errs() << " base ";
23607d523365SDimitry Andric         Pair.second->printAsOperand(errs(), false);
23617d523365SDimitry Andric         errs() << "\n";
2362ff0cc061SDimitry Andric       }
2363ff0cc061SDimitry Andric     }
2364ff0cc061SDimitry Andric   }
23657d523365SDimitry Andric 
23667d523365SDimitry Andric   // It is possible that non-constant live variables have a constant base.  For
23677d523365SDimitry Andric   // example, a GEP with a variable offset from a global.  In this case we can
23687d523365SDimitry Andric   // remove it from the liveset.  We already don't add constants to the liveset
23697d523365SDimitry Andric   // because we assume they won't move at runtime and the GC doesn't need to be
23707d523365SDimitry Andric   // informed about them.  The same reasoning applies if the base is constant.
23717d523365SDimitry Andric   // Note that the relocation placement code relies on this filtering for
23727d523365SDimitry Andric   // correctness as it expects the base to be in the liveset, which isn't true
23737d523365SDimitry Andric   // if the base is constant.
23747d523365SDimitry Andric   for (auto &Info : Records)
23757d523365SDimitry Andric     for (auto &BasePair : Info.PointerToBase)
23767d523365SDimitry Andric       if (isa<Constant>(BasePair.second))
23777d523365SDimitry Andric         Info.LiveSet.erase(BasePair.first);
23787d523365SDimitry Andric 
23797d523365SDimitry Andric   for (CallInst *CI : Holders)
23807d523365SDimitry Andric     CI->eraseFromParent();
23817d523365SDimitry Andric 
23827d523365SDimitry Andric   Holders.clear();
2383ff0cc061SDimitry Andric 
23843dac3a9bSDimitry Andric   // Do a limited scalarization of any live at safepoint vector values which
23853dac3a9bSDimitry Andric   // contain pointers.  This enables this pass to run after vectorization at
2386444ed5c5SDimitry Andric   // the cost of some possible performance loss.  Note: This is known to not
2387444ed5c5SDimitry Andric   // handle updating of the side tables correctly which can lead to relocation
2388444ed5c5SDimitry Andric   // bugs when the same vector is live at multiple statepoints.  We're in the
2389444ed5c5SDimitry Andric   // process of implementing the alternate lowering - relocating the
2390444ed5c5SDimitry Andric   // vector-of-pointers as first class item and updating the backend to
2391444ed5c5SDimitry Andric   // understand that - but that's not yet complete.
2392444ed5c5SDimitry Andric   if (UseVectorSplit)
23937d523365SDimitry Andric     for (size_t i = 0; i < Records.size(); i++) {
23947d523365SDimitry Andric       PartiallyConstructedSafepointRecord &Info = Records[i];
23957d523365SDimitry Andric       Instruction *Statepoint = ToUpdate[i].getInstruction();
23967d523365SDimitry Andric       splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
23977d523365SDimitry Andric                         Info.PointerToBase, DT);
23983dac3a9bSDimitry Andric     }
23993dac3a9bSDimitry Andric 
2400ff0cc061SDimitry Andric   // In order to reduce live set of statepoint we might choose to rematerialize
24017d523365SDimitry Andric   // some values instead of relocating them. This is purely an optimization and
2402ff0cc061SDimitry Andric   // does not influence correctness.
24037d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++)
24047d523365SDimitry Andric     rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
2405ff0cc061SDimitry Andric 
24067d523365SDimitry Andric   // We need this to safely RAUW and delete call or invoke return values that
24077d523365SDimitry Andric   // may themselves be live over a statepoint.  For details, please see usage in
24087d523365SDimitry Andric   // makeStatepointExplicitImpl.
24097d523365SDimitry Andric   std::vector<DeferredReplacement> Replacements;
2410ff0cc061SDimitry Andric 
2411ff0cc061SDimitry Andric   // Now run through and replace the existing statepoints with new ones with
2412ff0cc061SDimitry Andric   // the live variables listed.  We do not yet update uses of the values being
2413ff0cc061SDimitry Andric   // relocated. We have references to live variables that need to
2414ff0cc061SDimitry Andric   // survive to the last iteration of this loop.  (By construction, the
2415ff0cc061SDimitry Andric   // previous statepoint can not be a live variable, thus we can and remove
2416ff0cc061SDimitry Andric   // the old statepoint calls as we go.)
24177d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++)
24187d523365SDimitry Andric     makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
24197d523365SDimitry Andric 
24207d523365SDimitry Andric   ToUpdate.clear(); // prevent accident use of invalid CallSites
24217d523365SDimitry Andric 
24227d523365SDimitry Andric   for (auto &PR : Replacements)
24237d523365SDimitry Andric     PR.doReplacement();
24247d523365SDimitry Andric 
24257d523365SDimitry Andric   Replacements.clear();
24267d523365SDimitry Andric 
24277d523365SDimitry Andric   for (auto &Info : Records) {
24287d523365SDimitry Andric     // These live sets may contain state Value pointers, since we replaced calls
24297d523365SDimitry Andric     // with operand bundles with calls wrapped in gc.statepoint, and some of
24307d523365SDimitry Andric     // those calls may have been def'ing live gc pointers.  Clear these out to
24317d523365SDimitry Andric     // avoid accidentally using them.
24327d523365SDimitry Andric     //
24337d523365SDimitry Andric     // TODO: We should create a separate data structure that does not contain
24347d523365SDimitry Andric     // these live sets, and migrate to using that data structure from this point
24357d523365SDimitry Andric     // onward.
24367d523365SDimitry Andric     Info.LiveSet.clear();
24377d523365SDimitry Andric     Info.PointerToBase.clear();
2438ff0cc061SDimitry Andric   }
2439ff0cc061SDimitry Andric 
2440ff0cc061SDimitry Andric   // Do all the fixups of the original live variables to their relocated selves
24417d523365SDimitry Andric   SmallVector<Value *, 128> Live;
24427d523365SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
24437d523365SDimitry Andric     PartiallyConstructedSafepointRecord &Info = Records[i];
24447d523365SDimitry Andric 
2445ff0cc061SDimitry Andric     // We can't simply save the live set from the original insertion.  One of
2446ff0cc061SDimitry Andric     // the live values might be the result of a call which needs a safepoint.
2447ff0cc061SDimitry Andric     // That Value* no longer exists and we need to use the new gc_result.
2448ff0cc061SDimitry Andric     // Thankfully, the live set is embedded in the statepoint (and updated), so
2449ff0cc061SDimitry Andric     // we just grab that.
24507d523365SDimitry Andric     Statepoint Statepoint(Info.StatepointToken);
24517d523365SDimitry Andric     Live.insert(Live.end(), Statepoint.gc_args_begin(),
24527d523365SDimitry Andric                 Statepoint.gc_args_end());
2453ff0cc061SDimitry Andric #ifndef NDEBUG
2454ff0cc061SDimitry Andric     // Do some basic sanity checks on our liveness results before performing
2455ff0cc061SDimitry Andric     // relocation.  Relocation can and will turn mistakes in liveness results
2456ff0cc061SDimitry Andric     // into non-sensical code which is must harder to debug.
2457ff0cc061SDimitry Andric     // TODO: It would be nice to test consistency as well
24587d523365SDimitry Andric     assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
2459ff0cc061SDimitry Andric            "statepoint must be reachable or liveness is meaningless");
24607d523365SDimitry Andric     for (Value *V : Statepoint.gc_args()) {
2461ff0cc061SDimitry Andric       if (!isa<Instruction>(V))
2462ff0cc061SDimitry Andric         // Non-instruction values trivial dominate all possible uses
2463ff0cc061SDimitry Andric         continue;
24647d523365SDimitry Andric       auto *LiveInst = cast<Instruction>(V);
2465ff0cc061SDimitry Andric       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2466ff0cc061SDimitry Andric              "unreachable values should never be live");
24677d523365SDimitry Andric       assert(DT.dominates(LiveInst, Info.StatepointToken) &&
2468ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2469ff0cc061SDimitry Andric     }
2470ff0cc061SDimitry Andric #endif
2471ff0cc061SDimitry Andric   }
24727d523365SDimitry Andric   unique_unsorted(Live);
2473ff0cc061SDimitry Andric 
2474ff0cc061SDimitry Andric #ifndef NDEBUG
2475ff0cc061SDimitry Andric   // sanity check
24767d523365SDimitry Andric   for (auto *Ptr : Live)
2477444ed5c5SDimitry Andric     assert(isHandledGCPointerType(Ptr->getType()) &&
2478444ed5c5SDimitry Andric            "must be a gc pointer type");
2479ff0cc061SDimitry Andric #endif
2480ff0cc061SDimitry Andric 
24817d523365SDimitry Andric   relocationViaAlloca(F, DT, Live, Records);
24827d523365SDimitry Andric   return !Records.empty();
2483ff0cc061SDimitry Andric }
2484ff0cc061SDimitry Andric 
248597bc6c73SDimitry Andric // Handles both return values and arguments for Functions and CallSites.
248697bc6c73SDimitry Andric template <typename AttrHolder>
24877d523365SDimitry Andric static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
248897bc6c73SDimitry Andric                                       unsigned Index) {
248997bc6c73SDimitry Andric   AttrBuilder R;
249097bc6c73SDimitry Andric   if (AH.getDereferenceableBytes(Index))
249197bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
249297bc6c73SDimitry Andric                                   AH.getDereferenceableBytes(Index)));
249397bc6c73SDimitry Andric   if (AH.getDereferenceableOrNullBytes(Index))
249497bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
249597bc6c73SDimitry Andric                                   AH.getDereferenceableOrNullBytes(Index)));
24967d523365SDimitry Andric   if (AH.doesNotAlias(Index))
24977d523365SDimitry Andric     R.addAttribute(Attribute::NoAlias);
249897bc6c73SDimitry Andric 
249997bc6c73SDimitry Andric   if (!R.empty())
250097bc6c73SDimitry Andric     AH.setAttributes(AH.getAttributes().removeAttributes(
250197bc6c73SDimitry Andric         Ctx, Index, AttributeSet::get(Ctx, Index, R)));
250297bc6c73SDimitry Andric }
250397bc6c73SDimitry Andric 
250497bc6c73SDimitry Andric void
25057d523365SDimitry Andric RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
250697bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
250797bc6c73SDimitry Andric 
250897bc6c73SDimitry Andric   for (Argument &A : F.args())
250997bc6c73SDimitry Andric     if (isa<PointerType>(A.getType()))
25107d523365SDimitry Andric       RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
251197bc6c73SDimitry Andric 
251297bc6c73SDimitry Andric   if (isa<PointerType>(F.getReturnType()))
25137d523365SDimitry Andric     RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
251497bc6c73SDimitry Andric }
251597bc6c73SDimitry Andric 
25167d523365SDimitry Andric void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
251797bc6c73SDimitry Andric   if (F.empty())
251897bc6c73SDimitry Andric     return;
251997bc6c73SDimitry Andric 
252097bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
252197bc6c73SDimitry Andric   MDBuilder Builder(Ctx);
252297bc6c73SDimitry Andric 
25237d523365SDimitry Andric   for (Instruction &I : instructions(F)) {
252497bc6c73SDimitry Andric     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
252597bc6c73SDimitry Andric       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
252697bc6c73SDimitry Andric       bool IsImmutableTBAA =
252797bc6c73SDimitry Andric           MD->getNumOperands() == 4 &&
252897bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
252997bc6c73SDimitry Andric 
253097bc6c73SDimitry Andric       if (!IsImmutableTBAA)
253197bc6c73SDimitry Andric         continue; // no work to do, MD_tbaa is already marked mutable
253297bc6c73SDimitry Andric 
253397bc6c73SDimitry Andric       MDNode *Base = cast<MDNode>(MD->getOperand(0));
253497bc6c73SDimitry Andric       MDNode *Access = cast<MDNode>(MD->getOperand(1));
253597bc6c73SDimitry Andric       uint64_t Offset =
253697bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
253797bc6c73SDimitry Andric 
253897bc6c73SDimitry Andric       MDNode *MutableTBAA =
253997bc6c73SDimitry Andric           Builder.createTBAAStructTagNode(Base, Access, Offset);
254097bc6c73SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
254197bc6c73SDimitry Andric     }
254297bc6c73SDimitry Andric 
254397bc6c73SDimitry Andric     if (CallSite CS = CallSite(&I)) {
254497bc6c73SDimitry Andric       for (int i = 0, e = CS.arg_size(); i != e; i++)
254597bc6c73SDimitry Andric         if (isa<PointerType>(CS.getArgument(i)->getType()))
25467d523365SDimitry Andric           RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
254797bc6c73SDimitry Andric       if (isa<PointerType>(CS.getType()))
25487d523365SDimitry Andric         RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
254997bc6c73SDimitry Andric     }
255097bc6c73SDimitry Andric   }
255197bc6c73SDimitry Andric }
255297bc6c73SDimitry Andric 
2553ff0cc061SDimitry Andric /// Returns true if this function should be rewritten by this pass.  The main
2554ff0cc061SDimitry Andric /// point of this function is as an extension point for custom logic.
2555ff0cc061SDimitry Andric static bool shouldRewriteStatepointsIn(Function &F) {
2556ff0cc061SDimitry Andric   // TODO: This should check the GCStrategy
2557ff0cc061SDimitry Andric   if (F.hasGC()) {
2558444ed5c5SDimitry Andric     const auto &FunctionGCName = F.getGC();
2559ff0cc061SDimitry Andric     const StringRef StatepointExampleName("statepoint-example");
2560ff0cc061SDimitry Andric     const StringRef CoreCLRName("coreclr");
2561ff0cc061SDimitry Andric     return (StatepointExampleName == FunctionGCName) ||
2562ff0cc061SDimitry Andric            (CoreCLRName == FunctionGCName);
2563ff0cc061SDimitry Andric   } else
2564ff0cc061SDimitry Andric     return false;
2565ff0cc061SDimitry Andric }
2566ff0cc061SDimitry Andric 
25677d523365SDimitry Andric void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
256897bc6c73SDimitry Andric #ifndef NDEBUG
256997bc6c73SDimitry Andric   assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
257097bc6c73SDimitry Andric          "precondition!");
257197bc6c73SDimitry Andric #endif
257297bc6c73SDimitry Andric 
257397bc6c73SDimitry Andric   for (Function &F : M)
25747d523365SDimitry Andric     stripNonValidAttributesFromPrototype(F);
257597bc6c73SDimitry Andric 
257697bc6c73SDimitry Andric   for (Function &F : M)
25777d523365SDimitry Andric     stripNonValidAttributesFromBody(F);
257897bc6c73SDimitry Andric }
257997bc6c73SDimitry Andric 
2580ff0cc061SDimitry Andric bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2581ff0cc061SDimitry Andric   // Nothing to do for declarations.
2582ff0cc061SDimitry Andric   if (F.isDeclaration() || F.empty())
2583ff0cc061SDimitry Andric     return false;
2584ff0cc061SDimitry Andric 
2585ff0cc061SDimitry Andric   // Policy choice says not to rewrite - the most common reason is that we're
2586ff0cc061SDimitry Andric   // compiling code without a GCStrategy.
2587ff0cc061SDimitry Andric   if (!shouldRewriteStatepointsIn(F))
2588ff0cc061SDimitry Andric     return false;
2589ff0cc061SDimitry Andric 
259097bc6c73SDimitry Andric   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
25917d523365SDimitry Andric   TargetTransformInfo &TTI =
25927d523365SDimitry Andric       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
25937d523365SDimitry Andric 
25947d523365SDimitry Andric   auto NeedsRewrite = [](Instruction &I) {
25957d523365SDimitry Andric     if (UseDeoptBundles) {
25967d523365SDimitry Andric       if (ImmutableCallSite CS = ImmutableCallSite(&I))
25977d523365SDimitry Andric         return !callsGCLeafFunction(CS);
25987d523365SDimitry Andric       return false;
25997d523365SDimitry Andric     }
26007d523365SDimitry Andric 
26017d523365SDimitry Andric     return isStatepoint(I);
26027d523365SDimitry Andric   };
2603ff0cc061SDimitry Andric 
2604ff0cc061SDimitry Andric   // Gather all the statepoints which need rewritten.  Be careful to only
2605ff0cc061SDimitry Andric   // consider those in reachable code since we need to ask dominance queries
2606ff0cc061SDimitry Andric   // when rewriting.  We'll delete the unreachable ones in a moment.
2607ff0cc061SDimitry Andric   SmallVector<CallSite, 64> ParsePointNeeded;
2608ff0cc061SDimitry Andric   bool HasUnreachableStatepoint = false;
26097d523365SDimitry Andric   for (Instruction &I : instructions(F)) {
2610ff0cc061SDimitry Andric     // TODO: only the ones with the flag set!
26117d523365SDimitry Andric     if (NeedsRewrite(I)) {
2612ff0cc061SDimitry Andric       if (DT.isReachableFromEntry(I.getParent()))
2613ff0cc061SDimitry Andric         ParsePointNeeded.push_back(CallSite(&I));
2614ff0cc061SDimitry Andric       else
2615ff0cc061SDimitry Andric         HasUnreachableStatepoint = true;
2616ff0cc061SDimitry Andric     }
2617ff0cc061SDimitry Andric   }
2618ff0cc061SDimitry Andric 
2619ff0cc061SDimitry Andric   bool MadeChange = false;
2620ff0cc061SDimitry Andric 
2621ff0cc061SDimitry Andric   // Delete any unreachable statepoints so that we don't have unrewritten
2622ff0cc061SDimitry Andric   // statepoints surviving this pass.  This makes testing easier and the
2623ff0cc061SDimitry Andric   // resulting IR less confusing to human readers.  Rather than be fancy, we
2624ff0cc061SDimitry Andric   // just reuse a utility function which removes the unreachable blocks.
2625ff0cc061SDimitry Andric   if (HasUnreachableStatepoint)
2626ff0cc061SDimitry Andric     MadeChange |= removeUnreachableBlocks(F);
2627ff0cc061SDimitry Andric 
2628ff0cc061SDimitry Andric   // Return early if no work to do.
2629ff0cc061SDimitry Andric   if (ParsePointNeeded.empty())
2630ff0cc061SDimitry Andric     return MadeChange;
2631ff0cc061SDimitry Andric 
2632ff0cc061SDimitry Andric   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2633ff0cc061SDimitry Andric   // These are created by LCSSA.  They have the effect of increasing the size
2634ff0cc061SDimitry Andric   // of liveness sets for no good reason.  It may be harder to do this post
2635ff0cc061SDimitry Andric   // insertion since relocations and base phis can confuse things.
2636ff0cc061SDimitry Andric   for (BasicBlock &BB : F)
2637ff0cc061SDimitry Andric     if (BB.getUniquePredecessor()) {
2638ff0cc061SDimitry Andric       MadeChange = true;
2639ff0cc061SDimitry Andric       FoldSingleEntryPHINodes(&BB);
2640ff0cc061SDimitry Andric     }
2641ff0cc061SDimitry Andric 
26427d523365SDimitry Andric   // Before we start introducing relocations, we want to tweak the IR a bit to
26437d523365SDimitry Andric   // avoid unfortunate code generation effects.  The main example is that we
26447d523365SDimitry Andric   // want to try to make sure the comparison feeding a branch is after any
26457d523365SDimitry Andric   // safepoints.  Otherwise, we end up with a comparison of pre-relocation
26467d523365SDimitry Andric   // values feeding a branch after relocation.  This is semantically correct,
26477d523365SDimitry Andric   // but results in extra register pressure since both the pre-relocation and
26487d523365SDimitry Andric   // post-relocation copies must be available in registers.  For code without
26497d523365SDimitry Andric   // relocations this is handled elsewhere, but teaching the scheduler to
26507d523365SDimitry Andric   // reverse the transform we're about to do would be slightly complex.
26517d523365SDimitry Andric   // Note: This may extend the live range of the inputs to the icmp and thus
26527d523365SDimitry Andric   // increase the liveset of any statepoint we move over.  This is profitable
26537d523365SDimitry Andric   // as long as all statepoints are in rare blocks.  If we had in-register
26547d523365SDimitry Andric   // lowering for live values this would be a much safer transform.
26557d523365SDimitry Andric   auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
26567d523365SDimitry Andric     if (auto *BI = dyn_cast<BranchInst>(TI))
26577d523365SDimitry Andric       if (BI->isConditional())
26587d523365SDimitry Andric         return dyn_cast<Instruction>(BI->getCondition());
26597d523365SDimitry Andric     // TODO: Extend this to handle switches
26607d523365SDimitry Andric     return nullptr;
26617d523365SDimitry Andric   };
26627d523365SDimitry Andric   for (BasicBlock &BB : F) {
26637d523365SDimitry Andric     TerminatorInst *TI = BB.getTerminator();
26647d523365SDimitry Andric     if (auto *Cond = getConditionInst(TI))
26657d523365SDimitry Andric       // TODO: Handle more than just ICmps here.  We should be able to move
26667d523365SDimitry Andric       // most instructions without side effects or memory access.
26677d523365SDimitry Andric       if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
26687d523365SDimitry Andric         MadeChange = true;
26697d523365SDimitry Andric         Cond->moveBefore(TI);
26707d523365SDimitry Andric       }
26717d523365SDimitry Andric   }
26727d523365SDimitry Andric 
26737d523365SDimitry Andric   MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
2674ff0cc061SDimitry Andric   return MadeChange;
2675ff0cc061SDimitry Andric }
2676ff0cc061SDimitry Andric 
2677ff0cc061SDimitry Andric // liveness computation via standard dataflow
2678ff0cc061SDimitry Andric // -------------------------------------------------------------------
2679ff0cc061SDimitry Andric 
2680ff0cc061SDimitry Andric // TODO: Consider using bitvectors for liveness, the set of potentially
2681ff0cc061SDimitry Andric // interesting values should be small and easy to pre-compute.
2682ff0cc061SDimitry Andric 
2683ff0cc061SDimitry Andric /// Compute the live-in set for the location rbegin starting from
2684ff0cc061SDimitry Andric /// the live-out set of the basic block
2685ff0cc061SDimitry Andric static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2686ff0cc061SDimitry Andric                                 BasicBlock::reverse_iterator rend,
2687ff0cc061SDimitry Andric                                 DenseSet<Value *> &LiveTmp) {
2688ff0cc061SDimitry Andric 
2689ff0cc061SDimitry Andric   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2690ff0cc061SDimitry Andric     Instruction *I = &*ritr;
2691ff0cc061SDimitry Andric 
2692ff0cc061SDimitry Andric     // KILL/Def - Remove this definition from LiveIn
2693ff0cc061SDimitry Andric     LiveTmp.erase(I);
2694ff0cc061SDimitry Andric 
2695ff0cc061SDimitry Andric     // Don't consider *uses* in PHI nodes, we handle their contribution to
2696ff0cc061SDimitry Andric     // predecessor blocks when we seed the LiveOut sets
2697ff0cc061SDimitry Andric     if (isa<PHINode>(I))
2698ff0cc061SDimitry Andric       continue;
2699ff0cc061SDimitry Andric 
2700ff0cc061SDimitry Andric     // USE - Add to the LiveIn set for this instruction
2701ff0cc061SDimitry Andric     for (Value *V : I->operands()) {
2702ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2703ff0cc061SDimitry Andric              "support for FCA unimplemented");
2704ff0cc061SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2705ff0cc061SDimitry Andric         // The choice to exclude all things constant here is slightly subtle.
27067d523365SDimitry Andric         // There are two independent reasons:
2707ff0cc061SDimitry Andric         // - We assume that things which are constant (from LLVM's definition)
2708ff0cc061SDimitry Andric         // do not move at runtime.  For example, the address of a global
2709ff0cc061SDimitry Andric         // variable is fixed, even though it's contents may not be.
2710ff0cc061SDimitry Andric         // - Second, we can't disallow arbitrary inttoptr constants even
2711ff0cc061SDimitry Andric         // if the language frontend does.  Optimization passes are free to
2712ff0cc061SDimitry Andric         // locally exploit facts without respect to global reachability.  This
2713ff0cc061SDimitry Andric         // can create sections of code which are dynamically unreachable and
2714ff0cc061SDimitry Andric         // contain just about anything.  (see constants.ll in tests)
2715ff0cc061SDimitry Andric         LiveTmp.insert(V);
2716ff0cc061SDimitry Andric       }
2717ff0cc061SDimitry Andric     }
2718ff0cc061SDimitry Andric   }
2719ff0cc061SDimitry Andric }
2720ff0cc061SDimitry Andric 
2721ff0cc061SDimitry Andric static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2722ff0cc061SDimitry Andric 
2723ff0cc061SDimitry Andric   for (BasicBlock *Succ : successors(BB)) {
2724ff0cc061SDimitry Andric     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2725ff0cc061SDimitry Andric     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2726ff0cc061SDimitry Andric       PHINode *Phi = cast<PHINode>(&*I);
2727ff0cc061SDimitry Andric       Value *V = Phi->getIncomingValueForBlock(BB);
2728ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2729ff0cc061SDimitry Andric              "support for FCA unimplemented");
2730ff0cc061SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2731ff0cc061SDimitry Andric         LiveTmp.insert(V);
2732ff0cc061SDimitry Andric       }
2733ff0cc061SDimitry Andric     }
2734ff0cc061SDimitry Andric   }
2735ff0cc061SDimitry Andric }
2736ff0cc061SDimitry Andric 
2737ff0cc061SDimitry Andric static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2738ff0cc061SDimitry Andric   DenseSet<Value *> KillSet;
2739ff0cc061SDimitry Andric   for (Instruction &I : *BB)
2740ff0cc061SDimitry Andric     if (isHandledGCPointerType(I.getType()))
2741ff0cc061SDimitry Andric       KillSet.insert(&I);
2742ff0cc061SDimitry Andric   return KillSet;
2743ff0cc061SDimitry Andric }
2744ff0cc061SDimitry Andric 
2745ff0cc061SDimitry Andric #ifndef NDEBUG
2746ff0cc061SDimitry Andric /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2747ff0cc061SDimitry Andric /// sanity check for the liveness computation.
2748ff0cc061SDimitry Andric static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2749ff0cc061SDimitry Andric                           TerminatorInst *TI, bool TermOkay = false) {
2750ff0cc061SDimitry Andric   for (Value *V : Live) {
2751ff0cc061SDimitry Andric     if (auto *I = dyn_cast<Instruction>(V)) {
2752ff0cc061SDimitry Andric       // The terminator can be a member of the LiveOut set.  LLVM's definition
2753ff0cc061SDimitry Andric       // of instruction dominance states that V does not dominate itself.  As
2754ff0cc061SDimitry Andric       // such, we need to special case this to allow it.
2755ff0cc061SDimitry Andric       if (TermOkay && TI == I)
2756ff0cc061SDimitry Andric         continue;
2757ff0cc061SDimitry Andric       assert(DT.dominates(I, TI) &&
2758ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2759ff0cc061SDimitry Andric     }
2760ff0cc061SDimitry Andric   }
2761ff0cc061SDimitry Andric }
2762ff0cc061SDimitry Andric 
2763ff0cc061SDimitry Andric /// Check that all the liveness sets used during the computation of liveness
2764ff0cc061SDimitry Andric /// obey basic SSA properties.  This is useful for finding cases where we miss
2765ff0cc061SDimitry Andric /// a def.
2766ff0cc061SDimitry Andric static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2767ff0cc061SDimitry Andric                           BasicBlock &BB) {
2768ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2769ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2770ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2771ff0cc061SDimitry Andric }
2772ff0cc061SDimitry Andric #endif
2773ff0cc061SDimitry Andric 
2774ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
2775ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data) {
2776ff0cc061SDimitry Andric 
2777ff0cc061SDimitry Andric   SmallSetVector<BasicBlock *, 200> Worklist;
2778ff0cc061SDimitry Andric   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2779ff0cc061SDimitry Andric     // We use a SetVector so that we don't have duplicates in the worklist.
2780ff0cc061SDimitry Andric     Worklist.insert(pred_begin(BB), pred_end(BB));
2781ff0cc061SDimitry Andric   };
2782ff0cc061SDimitry Andric   auto NextItem = [&]() {
2783ff0cc061SDimitry Andric     BasicBlock *BB = Worklist.back();
2784ff0cc061SDimitry Andric     Worklist.pop_back();
2785ff0cc061SDimitry Andric     return BB;
2786ff0cc061SDimitry Andric   };
2787ff0cc061SDimitry Andric 
2788ff0cc061SDimitry Andric   // Seed the liveness for each individual block
2789ff0cc061SDimitry Andric   for (BasicBlock &BB : F) {
2790ff0cc061SDimitry Andric     Data.KillSet[&BB] = computeKillSet(&BB);
2791ff0cc061SDimitry Andric     Data.LiveSet[&BB].clear();
2792ff0cc061SDimitry Andric     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2793ff0cc061SDimitry Andric 
2794ff0cc061SDimitry Andric #ifndef NDEBUG
2795ff0cc061SDimitry Andric     for (Value *Kill : Data.KillSet[&BB])
2796ff0cc061SDimitry Andric       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2797ff0cc061SDimitry Andric #endif
2798ff0cc061SDimitry Andric 
2799ff0cc061SDimitry Andric     Data.LiveOut[&BB] = DenseSet<Value *>();
2800ff0cc061SDimitry Andric     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2801ff0cc061SDimitry Andric     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2802ff0cc061SDimitry Andric     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2803ff0cc061SDimitry Andric     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2804ff0cc061SDimitry Andric     if (!Data.LiveIn[&BB].empty())
2805ff0cc061SDimitry Andric       AddPredsToWorklist(&BB);
2806ff0cc061SDimitry Andric   }
2807ff0cc061SDimitry Andric 
2808ff0cc061SDimitry Andric   // Propagate that liveness until stable
2809ff0cc061SDimitry Andric   while (!Worklist.empty()) {
2810ff0cc061SDimitry Andric     BasicBlock *BB = NextItem();
2811ff0cc061SDimitry Andric 
2812ff0cc061SDimitry Andric     // Compute our new liveout set, then exit early if it hasn't changed
2813ff0cc061SDimitry Andric     // despite the contribution of our successor.
2814ff0cc061SDimitry Andric     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2815ff0cc061SDimitry Andric     const auto OldLiveOutSize = LiveOut.size();
2816ff0cc061SDimitry Andric     for (BasicBlock *Succ : successors(BB)) {
2817ff0cc061SDimitry Andric       assert(Data.LiveIn.count(Succ));
2818ff0cc061SDimitry Andric       set_union(LiveOut, Data.LiveIn[Succ]);
2819ff0cc061SDimitry Andric     }
2820ff0cc061SDimitry Andric     // assert OutLiveOut is a subset of LiveOut
2821ff0cc061SDimitry Andric     if (OldLiveOutSize == LiveOut.size()) {
2822ff0cc061SDimitry Andric       // If the sets are the same size, then we didn't actually add anything
2823ff0cc061SDimitry Andric       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2824ff0cc061SDimitry Andric       // hasn't changed.
2825ff0cc061SDimitry Andric       continue;
2826ff0cc061SDimitry Andric     }
2827ff0cc061SDimitry Andric     Data.LiveOut[BB] = LiveOut;
2828ff0cc061SDimitry Andric 
2829ff0cc061SDimitry Andric     // Apply the effects of this basic block
2830ff0cc061SDimitry Andric     DenseSet<Value *> LiveTmp = LiveOut;
2831ff0cc061SDimitry Andric     set_union(LiveTmp, Data.LiveSet[BB]);
2832ff0cc061SDimitry Andric     set_subtract(LiveTmp, Data.KillSet[BB]);
2833ff0cc061SDimitry Andric 
2834ff0cc061SDimitry Andric     assert(Data.LiveIn.count(BB));
2835ff0cc061SDimitry Andric     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2836ff0cc061SDimitry Andric     // assert: OldLiveIn is a subset of LiveTmp
2837ff0cc061SDimitry Andric     if (OldLiveIn.size() != LiveTmp.size()) {
2838ff0cc061SDimitry Andric       Data.LiveIn[BB] = LiveTmp;
2839ff0cc061SDimitry Andric       AddPredsToWorklist(BB);
2840ff0cc061SDimitry Andric     }
2841ff0cc061SDimitry Andric   } // while( !worklist.empty() )
2842ff0cc061SDimitry Andric 
2843ff0cc061SDimitry Andric #ifndef NDEBUG
28447d523365SDimitry Andric   // Sanity check our output against SSA properties.  This helps catch any
2845ff0cc061SDimitry Andric   // missing kills during the above iteration.
2846ff0cc061SDimitry Andric   for (BasicBlock &BB : F) {
2847ff0cc061SDimitry Andric     checkBasicSSA(DT, Data, BB);
2848ff0cc061SDimitry Andric   }
2849ff0cc061SDimitry Andric #endif
2850ff0cc061SDimitry Andric }
2851ff0cc061SDimitry Andric 
2852ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2853ff0cc061SDimitry Andric                               StatepointLiveSetTy &Out) {
2854ff0cc061SDimitry Andric 
2855ff0cc061SDimitry Andric   BasicBlock *BB = Inst->getParent();
2856ff0cc061SDimitry Andric 
2857ff0cc061SDimitry Andric   // Note: The copy is intentional and required
2858ff0cc061SDimitry Andric   assert(Data.LiveOut.count(BB));
2859ff0cc061SDimitry Andric   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2860ff0cc061SDimitry Andric 
2861ff0cc061SDimitry Andric   // We want to handle the statepoint itself oddly.  It's
2862ff0cc061SDimitry Andric   // call result is not live (normal), nor are it's arguments
2863ff0cc061SDimitry Andric   // (unless they're used again later).  This adjustment is
2864ff0cc061SDimitry Andric   // specifically what we need to relocate
28657d523365SDimitry Andric   BasicBlock::reverse_iterator rend(Inst->getIterator());
2866ff0cc061SDimitry Andric   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2867ff0cc061SDimitry Andric   LiveOut.erase(Inst);
2868ff0cc061SDimitry Andric   Out.insert(LiveOut.begin(), LiveOut.end());
2869ff0cc061SDimitry Andric }
2870ff0cc061SDimitry Andric 
2871ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2872ff0cc061SDimitry Andric                                   const CallSite &CS,
2873ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &Info) {
2874ff0cc061SDimitry Andric   Instruction *Inst = CS.getInstruction();
2875ff0cc061SDimitry Andric   StatepointLiveSetTy Updated;
2876ff0cc061SDimitry Andric   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2877ff0cc061SDimitry Andric 
2878ff0cc061SDimitry Andric #ifndef NDEBUG
2879ff0cc061SDimitry Andric   DenseSet<Value *> Bases;
2880ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase) {
2881ff0cc061SDimitry Andric     Bases.insert(KVPair.second);
2882ff0cc061SDimitry Andric   }
2883ff0cc061SDimitry Andric #endif
2884ff0cc061SDimitry Andric   // We may have base pointers which are now live that weren't before.  We need
2885ff0cc061SDimitry Andric   // to update the PointerToBase structure to reflect this.
2886ff0cc061SDimitry Andric   for (auto V : Updated)
2887ff0cc061SDimitry Andric     if (!Info.PointerToBase.count(V)) {
2888ff0cc061SDimitry Andric       assert(Bases.count(V) && "can't find base for unexpected live value");
2889ff0cc061SDimitry Andric       Info.PointerToBase[V] = V;
2890ff0cc061SDimitry Andric       continue;
2891ff0cc061SDimitry Andric     }
2892ff0cc061SDimitry Andric 
2893ff0cc061SDimitry Andric #ifndef NDEBUG
2894ff0cc061SDimitry Andric   for (auto V : Updated) {
2895ff0cc061SDimitry Andric     assert(Info.PointerToBase.count(V) &&
2896ff0cc061SDimitry Andric            "must be able to find base for live value");
2897ff0cc061SDimitry Andric   }
2898ff0cc061SDimitry Andric #endif
2899ff0cc061SDimitry Andric 
2900ff0cc061SDimitry Andric   // Remove any stale base mappings - this can happen since our liveness is
2901ff0cc061SDimitry Andric   // more precise then the one inherent in the base pointer analysis
2902ff0cc061SDimitry Andric   DenseSet<Value *> ToErase;
2903ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2904ff0cc061SDimitry Andric     if (!Updated.count(KVPair.first))
2905ff0cc061SDimitry Andric       ToErase.insert(KVPair.first);
2906ff0cc061SDimitry Andric   for (auto V : ToErase)
2907ff0cc061SDimitry Andric     Info.PointerToBase.erase(V);
2908ff0cc061SDimitry Andric 
2909ff0cc061SDimitry Andric #ifndef NDEBUG
2910ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2911ff0cc061SDimitry Andric     assert(Updated.count(KVPair.first) && "record for non-live value");
2912ff0cc061SDimitry Andric #endif
2913ff0cc061SDimitry Andric 
29147d523365SDimitry Andric   Info.LiveSet = Updated;
2915ff0cc061SDimitry Andric }
2916