1ff0cc061SDimitry Andric //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2ff0cc061SDimitry Andric //
3ff0cc061SDimitry Andric //                     The LLVM Compiler Infrastructure
4ff0cc061SDimitry Andric //
5ff0cc061SDimitry Andric // This file is distributed under the University of Illinois Open Source
6ff0cc061SDimitry Andric // License. See LICENSE.TXT for details.
7ff0cc061SDimitry Andric //
8ff0cc061SDimitry Andric //===----------------------------------------------------------------------===//
9ff0cc061SDimitry Andric //
10ff0cc061SDimitry Andric // Rewrite an existing set of gc.statepoints such that they make potential
11ff0cc061SDimitry Andric // relocations performed by the garbage collector explicit in the IR.
12ff0cc061SDimitry Andric //
13ff0cc061SDimitry Andric //===----------------------------------------------------------------------===//
14ff0cc061SDimitry Andric 
15ff0cc061SDimitry Andric #include "llvm/Pass.h"
16ff0cc061SDimitry Andric #include "llvm/Analysis/CFG.h"
17ff0cc061SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
18ff0cc061SDimitry Andric #include "llvm/ADT/SetOperations.h"
19ff0cc061SDimitry Andric #include "llvm/ADT/Statistic.h"
20ff0cc061SDimitry Andric #include "llvm/ADT/DenseSet.h"
21ff0cc061SDimitry Andric #include "llvm/ADT/SetVector.h"
22ff0cc061SDimitry Andric #include "llvm/ADT/StringRef.h"
23ff0cc061SDimitry Andric #include "llvm/IR/BasicBlock.h"
24ff0cc061SDimitry Andric #include "llvm/IR/CallSite.h"
25ff0cc061SDimitry Andric #include "llvm/IR/Dominators.h"
26ff0cc061SDimitry Andric #include "llvm/IR/Function.h"
27ff0cc061SDimitry Andric #include "llvm/IR/IRBuilder.h"
28ff0cc061SDimitry Andric #include "llvm/IR/InstIterator.h"
29ff0cc061SDimitry Andric #include "llvm/IR/Instructions.h"
30ff0cc061SDimitry Andric #include "llvm/IR/Intrinsics.h"
31ff0cc061SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
32ff0cc061SDimitry Andric #include "llvm/IR/Module.h"
3397bc6c73SDimitry Andric #include "llvm/IR/MDBuilder.h"
34ff0cc061SDimitry Andric #include "llvm/IR/Statepoint.h"
35ff0cc061SDimitry Andric #include "llvm/IR/Value.h"
36ff0cc061SDimitry Andric #include "llvm/IR/Verifier.h"
37ff0cc061SDimitry Andric #include "llvm/Support/Debug.h"
38ff0cc061SDimitry Andric #include "llvm/Support/CommandLine.h"
39ff0cc061SDimitry Andric #include "llvm/Transforms/Scalar.h"
40ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
42ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
43ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h"
44ff0cc061SDimitry Andric 
45ff0cc061SDimitry Andric #define DEBUG_TYPE "rewrite-statepoints-for-gc"
46ff0cc061SDimitry Andric 
47ff0cc061SDimitry Andric using namespace llvm;
48ff0cc061SDimitry Andric 
49ff0cc061SDimitry Andric // Print tracing output
50ff0cc061SDimitry Andric static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
51ff0cc061SDimitry Andric                               cl::init(false));
52ff0cc061SDimitry Andric 
53ff0cc061SDimitry Andric // Print the liveset found at the insert location
54ff0cc061SDimitry Andric static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
55ff0cc061SDimitry Andric                                   cl::init(false));
56ff0cc061SDimitry Andric static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
57ff0cc061SDimitry Andric                                       cl::init(false));
58ff0cc061SDimitry Andric // Print out the base pointers for debugging
59ff0cc061SDimitry Andric static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
60ff0cc061SDimitry Andric                                        cl::init(false));
61ff0cc061SDimitry Andric 
62ff0cc061SDimitry Andric // Cost threshold measuring when it is profitable to rematerialize value instead
63ff0cc061SDimitry Andric // of relocating it
64ff0cc061SDimitry Andric static cl::opt<unsigned>
65ff0cc061SDimitry Andric RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
66ff0cc061SDimitry Andric                            cl::init(6));
67ff0cc061SDimitry Andric 
68ff0cc061SDimitry Andric #ifdef XDEBUG
69ff0cc061SDimitry Andric static bool ClobberNonLive = true;
70ff0cc061SDimitry Andric #else
71ff0cc061SDimitry Andric static bool ClobberNonLive = false;
72ff0cc061SDimitry Andric #endif
73ff0cc061SDimitry Andric static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
74ff0cc061SDimitry Andric                                                   cl::location(ClobberNonLive),
75ff0cc061SDimitry Andric                                                   cl::Hidden);
76ff0cc061SDimitry Andric 
77ff0cc061SDimitry Andric namespace {
7897bc6c73SDimitry Andric struct RewriteStatepointsForGC : public ModulePass {
79ff0cc061SDimitry Andric   static char ID; // Pass identification, replacement for typeid
80ff0cc061SDimitry Andric 
8197bc6c73SDimitry Andric   RewriteStatepointsForGC() : ModulePass(ID) {
82ff0cc061SDimitry Andric     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
83ff0cc061SDimitry Andric   }
8497bc6c73SDimitry Andric   bool runOnFunction(Function &F);
8597bc6c73SDimitry Andric   bool runOnModule(Module &M) override {
8697bc6c73SDimitry Andric     bool Changed = false;
8797bc6c73SDimitry Andric     for (Function &F : M)
8897bc6c73SDimitry Andric       Changed |= runOnFunction(F);
8997bc6c73SDimitry Andric 
9097bc6c73SDimitry Andric     if (Changed) {
9197bc6c73SDimitry Andric       // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
9297bc6c73SDimitry Andric       // returns true for at least one function in the module.  Since at least
9397bc6c73SDimitry Andric       // one function changed, we know that the precondition is satisfied.
9497bc6c73SDimitry Andric       stripDereferenceabilityInfo(M);
9597bc6c73SDimitry Andric     }
9697bc6c73SDimitry Andric 
9797bc6c73SDimitry Andric     return Changed;
9897bc6c73SDimitry Andric   }
99ff0cc061SDimitry Andric 
100ff0cc061SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
101ff0cc061SDimitry Andric     // We add and rewrite a bunch of instructions, but don't really do much
102ff0cc061SDimitry Andric     // else.  We could in theory preserve a lot more analyses here.
103ff0cc061SDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
104ff0cc061SDimitry Andric     AU.addRequired<TargetTransformInfoWrapperPass>();
105ff0cc061SDimitry Andric   }
10697bc6c73SDimitry Andric 
10797bc6c73SDimitry Andric   /// The IR fed into RewriteStatepointsForGC may have had attributes implying
10897bc6c73SDimitry Andric   /// dereferenceability that are no longer valid/correct after
10997bc6c73SDimitry Andric   /// RewriteStatepointsForGC has run.  This is because semantically, after
11097bc6c73SDimitry Andric   /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
11197bc6c73SDimitry Andric   /// heap.  stripDereferenceabilityInfo (conservatively) restores correctness
11297bc6c73SDimitry Andric   /// by erasing all attributes in the module that externally imply
11397bc6c73SDimitry Andric   /// dereferenceability.
11497bc6c73SDimitry Andric   ///
11597bc6c73SDimitry Andric   void stripDereferenceabilityInfo(Module &M);
11697bc6c73SDimitry Andric 
11797bc6c73SDimitry Andric   // Helpers for stripDereferenceabilityInfo
11897bc6c73SDimitry Andric   void stripDereferenceabilityInfoFromBody(Function &F);
11997bc6c73SDimitry Andric   void stripDereferenceabilityInfoFromPrototype(Function &F);
120ff0cc061SDimitry Andric };
121ff0cc061SDimitry Andric } // namespace
122ff0cc061SDimitry Andric 
123ff0cc061SDimitry Andric char RewriteStatepointsForGC::ID = 0;
124ff0cc061SDimitry Andric 
12597bc6c73SDimitry Andric ModulePass *llvm::createRewriteStatepointsForGCPass() {
126ff0cc061SDimitry Andric   return new RewriteStatepointsForGC();
127ff0cc061SDimitry Andric }
128ff0cc061SDimitry Andric 
129ff0cc061SDimitry Andric INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
130ff0cc061SDimitry Andric                       "Make relocations explicit at statepoints", false, false)
131ff0cc061SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
132ff0cc061SDimitry Andric INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
133ff0cc061SDimitry Andric                     "Make relocations explicit at statepoints", false, false)
134ff0cc061SDimitry Andric 
135ff0cc061SDimitry Andric namespace {
136ff0cc061SDimitry Andric struct GCPtrLivenessData {
137ff0cc061SDimitry Andric   /// Values defined in this block.
138ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
139ff0cc061SDimitry Andric   /// Values used in this block (and thus live); does not included values
140ff0cc061SDimitry Andric   /// killed within this block.
141ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
142ff0cc061SDimitry Andric 
143ff0cc061SDimitry Andric   /// Values live into this basic block (i.e. used by any
144ff0cc061SDimitry Andric   /// instruction in this basic block or ones reachable from here)
145ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
146ff0cc061SDimitry Andric 
147ff0cc061SDimitry Andric   /// Values live out of this basic block (i.e. live into
148ff0cc061SDimitry Andric   /// any successor block)
149ff0cc061SDimitry Andric   DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
150ff0cc061SDimitry Andric };
151ff0cc061SDimitry Andric 
152ff0cc061SDimitry Andric // The type of the internal cache used inside the findBasePointers family
153ff0cc061SDimitry Andric // of functions.  From the callers perspective, this is an opaque type and
154ff0cc061SDimitry Andric // should not be inspected.
155ff0cc061SDimitry Andric //
156ff0cc061SDimitry Andric // In the actual implementation this caches two relations:
157ff0cc061SDimitry Andric // - The base relation itself (i.e. this pointer is based on that one)
158ff0cc061SDimitry Andric // - The base defining value relation (i.e. before base_phi insertion)
159ff0cc061SDimitry Andric // Generally, after the execution of a full findBasePointer call, only the
160ff0cc061SDimitry Andric // base relation will remain.  Internally, we add a mixture of the two
161ff0cc061SDimitry Andric // types, then update all the second type to the first type
162ff0cc061SDimitry Andric typedef DenseMap<Value *, Value *> DefiningValueMapTy;
163ff0cc061SDimitry Andric typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
164ff0cc061SDimitry Andric typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
165ff0cc061SDimitry Andric 
166ff0cc061SDimitry Andric struct PartiallyConstructedSafepointRecord {
167ff0cc061SDimitry Andric   /// The set of values known to be live accross this safepoint
168ff0cc061SDimitry Andric   StatepointLiveSetTy liveset;
169ff0cc061SDimitry Andric 
170ff0cc061SDimitry Andric   /// Mapping from live pointers to a base-defining-value
171ff0cc061SDimitry Andric   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
172ff0cc061SDimitry Andric 
173ff0cc061SDimitry Andric   /// The *new* gc.statepoint instruction itself.  This produces the token
174ff0cc061SDimitry Andric   /// that normal path gc.relocates and the gc.result are tied to.
175ff0cc061SDimitry Andric   Instruction *StatepointToken;
176ff0cc061SDimitry Andric 
177ff0cc061SDimitry Andric   /// Instruction to which exceptional gc relocates are attached
178ff0cc061SDimitry Andric   /// Makes it easier to iterate through them during relocationViaAlloca.
179ff0cc061SDimitry Andric   Instruction *UnwindToken;
180ff0cc061SDimitry Andric 
181ff0cc061SDimitry Andric   /// Record live values we are rematerialized instead of relocating.
182ff0cc061SDimitry Andric   /// They are not included into 'liveset' field.
183ff0cc061SDimitry Andric   /// Maps rematerialized copy to it's original value.
184ff0cc061SDimitry Andric   RematerializedValueMapTy RematerializedValues;
185ff0cc061SDimitry Andric };
1868f0fd8f6SDimitry Andric } // namespace
187ff0cc061SDimitry Andric 
188ff0cc061SDimitry Andric /// Compute the live-in set for every basic block in the function
189ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
190ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data);
191ff0cc061SDimitry Andric 
192ff0cc061SDimitry Andric /// Given results from the dataflow liveness computation, find the set of live
193ff0cc061SDimitry Andric /// Values at a particular instruction.
194ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
195ff0cc061SDimitry Andric                               StatepointLiveSetTy &out);
196ff0cc061SDimitry Andric 
197ff0cc061SDimitry Andric // TODO: Once we can get to the GCStrategy, this becomes
198ff0cc061SDimitry Andric // Optional<bool> isGCManagedPointer(const Value *V) const override {
199ff0cc061SDimitry Andric 
200ff0cc061SDimitry Andric static bool isGCPointerType(const Type *T) {
201ff0cc061SDimitry Andric   if (const PointerType *PT = dyn_cast<PointerType>(T))
202ff0cc061SDimitry Andric     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
203ff0cc061SDimitry Andric     // GC managed heap.  We know that a pointer into this heap needs to be
204ff0cc061SDimitry Andric     // updated and that no other pointer does.
205ff0cc061SDimitry Andric     return (1 == PT->getAddressSpace());
206ff0cc061SDimitry Andric   return false;
207ff0cc061SDimitry Andric }
208ff0cc061SDimitry Andric 
209ff0cc061SDimitry Andric // Return true if this type is one which a) is a gc pointer or contains a GC
210ff0cc061SDimitry Andric // pointer and b) is of a type this code expects to encounter as a live value.
211ff0cc061SDimitry Andric // (The insertion code will assert that a type which matches (a) and not (b)
212ff0cc061SDimitry Andric // is not encountered.)
213ff0cc061SDimitry Andric static bool isHandledGCPointerType(Type *T) {
214ff0cc061SDimitry Andric   // We fully support gc pointers
215ff0cc061SDimitry Andric   if (isGCPointerType(T))
216ff0cc061SDimitry Andric     return true;
217ff0cc061SDimitry Andric   // We partially support vectors of gc pointers. The code will assert if it
218ff0cc061SDimitry Andric   // can't handle something.
219ff0cc061SDimitry Andric   if (auto VT = dyn_cast<VectorType>(T))
220ff0cc061SDimitry Andric     if (isGCPointerType(VT->getElementType()))
221ff0cc061SDimitry Andric       return true;
222ff0cc061SDimitry Andric   return false;
223ff0cc061SDimitry Andric }
224ff0cc061SDimitry Andric 
225ff0cc061SDimitry Andric #ifndef NDEBUG
226ff0cc061SDimitry Andric /// Returns true if this type contains a gc pointer whether we know how to
227ff0cc061SDimitry Andric /// handle that type or not.
228ff0cc061SDimitry Andric static bool containsGCPtrType(Type *Ty) {
229ff0cc061SDimitry Andric   if (isGCPointerType(Ty))
230ff0cc061SDimitry Andric     return true;
231ff0cc061SDimitry Andric   if (VectorType *VT = dyn_cast<VectorType>(Ty))
232ff0cc061SDimitry Andric     return isGCPointerType(VT->getScalarType());
233ff0cc061SDimitry Andric   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
234ff0cc061SDimitry Andric     return containsGCPtrType(AT->getElementType());
235ff0cc061SDimitry Andric   if (StructType *ST = dyn_cast<StructType>(Ty))
236ff0cc061SDimitry Andric     return std::any_of(
237ff0cc061SDimitry Andric         ST->subtypes().begin(), ST->subtypes().end(),
238ff0cc061SDimitry Andric         [](Type *SubType) { return containsGCPtrType(SubType); });
239ff0cc061SDimitry Andric   return false;
240ff0cc061SDimitry Andric }
241ff0cc061SDimitry Andric 
242ff0cc061SDimitry Andric // Returns true if this is a type which a) is a gc pointer or contains a GC
243ff0cc061SDimitry Andric // pointer and b) is of a type which the code doesn't expect (i.e. first class
244ff0cc061SDimitry Andric // aggregates).  Used to trip assertions.
245ff0cc061SDimitry Andric static bool isUnhandledGCPointerType(Type *Ty) {
246ff0cc061SDimitry Andric   return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
247ff0cc061SDimitry Andric }
248ff0cc061SDimitry Andric #endif
249ff0cc061SDimitry Andric 
250ff0cc061SDimitry Andric static bool order_by_name(llvm::Value *a, llvm::Value *b) {
251ff0cc061SDimitry Andric   if (a->hasName() && b->hasName()) {
252ff0cc061SDimitry Andric     return -1 == a->getName().compare(b->getName());
253ff0cc061SDimitry Andric   } else if (a->hasName() && !b->hasName()) {
254ff0cc061SDimitry Andric     return true;
255ff0cc061SDimitry Andric   } else if (!a->hasName() && b->hasName()) {
256ff0cc061SDimitry Andric     return false;
257ff0cc061SDimitry Andric   } else {
258ff0cc061SDimitry Andric     // Better than nothing, but not stable
259ff0cc061SDimitry Andric     return a < b;
260ff0cc061SDimitry Andric   }
261ff0cc061SDimitry Andric }
262ff0cc061SDimitry Andric 
263ff0cc061SDimitry Andric // Conservatively identifies any definitions which might be live at the
264ff0cc061SDimitry Andric // given instruction. The  analysis is performed immediately before the
265ff0cc061SDimitry Andric // given instruction. Values defined by that instruction are not considered
266ff0cc061SDimitry Andric // live.  Values used by that instruction are considered live.
267ff0cc061SDimitry Andric static void analyzeParsePointLiveness(
268ff0cc061SDimitry Andric     DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
269ff0cc061SDimitry Andric     const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
270ff0cc061SDimitry Andric   Instruction *inst = CS.getInstruction();
271ff0cc061SDimitry Andric 
272ff0cc061SDimitry Andric   StatepointLiveSetTy liveset;
273ff0cc061SDimitry Andric   findLiveSetAtInst(inst, OriginalLivenessData, liveset);
274ff0cc061SDimitry Andric 
275ff0cc061SDimitry Andric   if (PrintLiveSet) {
276ff0cc061SDimitry Andric     // Note: This output is used by several of the test cases
277ff0cc061SDimitry Andric     // The order of elemtns in a set is not stable, put them in a vec and sort
278ff0cc061SDimitry Andric     // by name
279ff0cc061SDimitry Andric     SmallVector<Value *, 64> temp;
280ff0cc061SDimitry Andric     temp.insert(temp.end(), liveset.begin(), liveset.end());
281ff0cc061SDimitry Andric     std::sort(temp.begin(), temp.end(), order_by_name);
282ff0cc061SDimitry Andric     errs() << "Live Variables:\n";
283ff0cc061SDimitry Andric     for (Value *V : temp) {
284ff0cc061SDimitry Andric       errs() << " " << V->getName(); // no newline
285ff0cc061SDimitry Andric       V->dump();
286ff0cc061SDimitry Andric     }
287ff0cc061SDimitry Andric   }
288ff0cc061SDimitry Andric   if (PrintLiveSetSize) {
289ff0cc061SDimitry Andric     errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
290ff0cc061SDimitry Andric     errs() << "Number live values: " << liveset.size() << "\n";
291ff0cc061SDimitry Andric   }
292ff0cc061SDimitry Andric   result.liveset = liveset;
293ff0cc061SDimitry Andric }
294ff0cc061SDimitry Andric 
295ff0cc061SDimitry Andric static Value *findBaseDefiningValue(Value *I);
296ff0cc061SDimitry Andric 
297ff0cc061SDimitry Andric /// If we can trivially determine that the index specified in the given vector
298ff0cc061SDimitry Andric /// is a base pointer, return it.  In cases where the entire vector is known to
299ff0cc061SDimitry Andric /// consist of base pointers, the entire vector will be returned.  This
300ff0cc061SDimitry Andric /// indicates that the relevant extractelement is a valid base pointer and
301ff0cc061SDimitry Andric /// should be used directly.
302ff0cc061SDimitry Andric static Value *findBaseOfVector(Value *I, Value *Index) {
303ff0cc061SDimitry Andric   assert(I->getType()->isVectorTy() &&
304ff0cc061SDimitry Andric          cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
305ff0cc061SDimitry Andric          "Illegal to ask for the base pointer of a non-pointer type");
306ff0cc061SDimitry Andric 
307ff0cc061SDimitry Andric   // Each case parallels findBaseDefiningValue below, see that code for
308ff0cc061SDimitry Andric   // detailed motivation.
309ff0cc061SDimitry Andric 
310ff0cc061SDimitry Andric   if (isa<Argument>(I))
311ff0cc061SDimitry Andric     // An incoming argument to the function is a base pointer
312ff0cc061SDimitry Andric     return I;
313ff0cc061SDimitry Andric 
314ff0cc061SDimitry Andric   // We shouldn't see the address of a global as a vector value?
315ff0cc061SDimitry Andric   assert(!isa<GlobalVariable>(I) &&
316ff0cc061SDimitry Andric          "unexpected global variable found in base of vector");
317ff0cc061SDimitry Andric 
318ff0cc061SDimitry Andric   // inlining could possibly introduce phi node that contains
319ff0cc061SDimitry Andric   // undef if callee has multiple returns
320ff0cc061SDimitry Andric   if (isa<UndefValue>(I))
321ff0cc061SDimitry Andric     // utterly meaningless, but useful for dealing with partially optimized
322ff0cc061SDimitry Andric     // code.
323ff0cc061SDimitry Andric     return I;
324ff0cc061SDimitry Andric 
325ff0cc061SDimitry Andric   // Due to inheritance, this must be _after_ the global variable and undef
326ff0cc061SDimitry Andric   // checks
327ff0cc061SDimitry Andric   if (Constant *Con = dyn_cast<Constant>(I)) {
328ff0cc061SDimitry Andric     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
329ff0cc061SDimitry Andric            "order of checks wrong!");
330ff0cc061SDimitry Andric     assert(Con->isNullValue() && "null is the only case which makes sense");
331ff0cc061SDimitry Andric     return Con;
332ff0cc061SDimitry Andric   }
333ff0cc061SDimitry Andric 
334ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
335ff0cc061SDimitry Andric     return I;
336ff0cc061SDimitry Andric 
337ff0cc061SDimitry Andric   // For an insert element, we might be able to look through it if we know
338ff0cc061SDimitry Andric   // something about the indexes, but if the indices are arbitrary values, we
339ff0cc061SDimitry Andric   // can't without much more extensive scalarization.
340ff0cc061SDimitry Andric   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
341ff0cc061SDimitry Andric     Value *InsertIndex = IEI->getOperand(2);
342ff0cc061SDimitry Andric     // This index is inserting the value, look for it's base
343ff0cc061SDimitry Andric     if (InsertIndex == Index)
344ff0cc061SDimitry Andric       return findBaseDefiningValue(IEI->getOperand(1));
345ff0cc061SDimitry Andric     // Both constant, and can't be equal per above. This insert is definitely
346ff0cc061SDimitry Andric     // not relevant, look back at the rest of the vector and keep trying.
347ff0cc061SDimitry Andric     if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
348ff0cc061SDimitry Andric       return findBaseOfVector(IEI->getOperand(0), Index);
349ff0cc061SDimitry Andric   }
350ff0cc061SDimitry Andric 
351ff0cc061SDimitry Andric   // Note: This code is currently rather incomplete.  We are essentially only
352ff0cc061SDimitry Andric   // handling cases where the vector element is trivially a base pointer.  We
353ff0cc061SDimitry Andric   // need to update the entire base pointer construction algorithm to know how
354ff0cc061SDimitry Andric   // to track vector elements and potentially scalarize, but the case which
355ff0cc061SDimitry Andric   // would motivate the work hasn't shown up in real workloads yet.
356ff0cc061SDimitry Andric   llvm_unreachable("no base found for vector element");
357ff0cc061SDimitry Andric }
358ff0cc061SDimitry Andric 
359ff0cc061SDimitry Andric /// Helper function for findBasePointer - Will return a value which either a)
360ff0cc061SDimitry Andric /// defines the base pointer for the input or b) blocks the simple search
361ff0cc061SDimitry Andric /// (i.e. a PHI or Select of two derived pointers)
362ff0cc061SDimitry Andric static Value *findBaseDefiningValue(Value *I) {
363ff0cc061SDimitry Andric   assert(I->getType()->isPointerTy() &&
364ff0cc061SDimitry Andric          "Illegal to ask for the base pointer of a non-pointer type");
365ff0cc061SDimitry Andric 
366ff0cc061SDimitry Andric   // This case is a bit of a hack - it only handles extracts from vectors which
367ff0cc061SDimitry Andric   // trivially contain only base pointers or cases where we can directly match
368ff0cc061SDimitry Andric   // the index of the original extract element to an insertion into the vector.
369ff0cc061SDimitry Andric   // See note inside the function for how to improve this.
370ff0cc061SDimitry Andric   if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
371ff0cc061SDimitry Andric     Value *VectorOperand = EEI->getVectorOperand();
372ff0cc061SDimitry Andric     Value *Index = EEI->getIndexOperand();
373ff0cc061SDimitry Andric     Value *VectorBase = findBaseOfVector(VectorOperand, Index);
374ff0cc061SDimitry Andric     // If the result returned is a vector, we know the entire vector must
375ff0cc061SDimitry Andric     // contain base pointers.  In that case, the extractelement is a valid base
376ff0cc061SDimitry Andric     // for this value.
377ff0cc061SDimitry Andric     if (VectorBase->getType()->isVectorTy())
378ff0cc061SDimitry Andric       return EEI;
379ff0cc061SDimitry Andric     // Otherwise, we needed to look through the vector to find the base for
380ff0cc061SDimitry Andric     // this particular element.
381ff0cc061SDimitry Andric     assert(VectorBase->getType()->isPointerTy());
382ff0cc061SDimitry Andric     return VectorBase;
383ff0cc061SDimitry Andric   }
384ff0cc061SDimitry Andric 
385ff0cc061SDimitry Andric   if (isa<Argument>(I))
386ff0cc061SDimitry Andric     // An incoming argument to the function is a base pointer
387ff0cc061SDimitry Andric     // We should have never reached here if this argument isn't an gc value
388ff0cc061SDimitry Andric     return I;
389ff0cc061SDimitry Andric 
390ff0cc061SDimitry Andric   if (isa<GlobalVariable>(I))
391ff0cc061SDimitry Andric     // base case
392ff0cc061SDimitry Andric     return I;
393ff0cc061SDimitry Andric 
394ff0cc061SDimitry Andric   // inlining could possibly introduce phi node that contains
395ff0cc061SDimitry Andric   // undef if callee has multiple returns
396ff0cc061SDimitry Andric   if (isa<UndefValue>(I))
397ff0cc061SDimitry Andric     // utterly meaningless, but useful for dealing with
398ff0cc061SDimitry Andric     // partially optimized code.
399ff0cc061SDimitry Andric     return I;
400ff0cc061SDimitry Andric 
401ff0cc061SDimitry Andric   // Due to inheritance, this must be _after_ the global variable and undef
402ff0cc061SDimitry Andric   // checks
403ff0cc061SDimitry Andric   if (Constant *Con = dyn_cast<Constant>(I)) {
404ff0cc061SDimitry Andric     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
405ff0cc061SDimitry Andric            "order of checks wrong!");
406ff0cc061SDimitry Andric     // Note: Finding a constant base for something marked for relocation
407ff0cc061SDimitry Andric     // doesn't really make sense.  The most likely case is either a) some
408ff0cc061SDimitry Andric     // screwed up the address space usage or b) your validating against
409ff0cc061SDimitry Andric     // compiled C++ code w/o the proper separation.  The only real exception
410ff0cc061SDimitry Andric     // is a null pointer.  You could have generic code written to index of
411ff0cc061SDimitry Andric     // off a potentially null value and have proven it null.  We also use
412ff0cc061SDimitry Andric     // null pointers in dead paths of relocation phis (which we might later
413ff0cc061SDimitry Andric     // want to find a base pointer for).
414ff0cc061SDimitry Andric     assert(isa<ConstantPointerNull>(Con) &&
415ff0cc061SDimitry Andric            "null is the only case which makes sense");
416ff0cc061SDimitry Andric     return Con;
417ff0cc061SDimitry Andric   }
418ff0cc061SDimitry Andric 
419ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(I)) {
420ff0cc061SDimitry Andric     Value *Def = CI->stripPointerCasts();
421ff0cc061SDimitry Andric     // If we find a cast instruction here, it means we've found a cast which is
422ff0cc061SDimitry Andric     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
423ff0cc061SDimitry Andric     // handle int->ptr conversion.
424ff0cc061SDimitry Andric     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
425ff0cc061SDimitry Andric     return findBaseDefiningValue(Def);
426ff0cc061SDimitry Andric   }
427ff0cc061SDimitry Andric 
428ff0cc061SDimitry Andric   if (isa<LoadInst>(I))
429ff0cc061SDimitry Andric     return I; // The value loaded is an gc base itself
430ff0cc061SDimitry Andric 
431ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
432ff0cc061SDimitry Andric     // The base of this GEP is the base
433ff0cc061SDimitry Andric     return findBaseDefiningValue(GEP->getPointerOperand());
434ff0cc061SDimitry Andric 
435ff0cc061SDimitry Andric   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
436ff0cc061SDimitry Andric     switch (II->getIntrinsicID()) {
437ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_result_ptr:
438ff0cc061SDimitry Andric     default:
439ff0cc061SDimitry Andric       // fall through to general call handling
440ff0cc061SDimitry Andric       break;
441ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_statepoint:
442ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_result_float:
443ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_result_int:
444ff0cc061SDimitry Andric       llvm_unreachable("these don't produce pointers");
445ff0cc061SDimitry Andric     case Intrinsic::experimental_gc_relocate: {
446ff0cc061SDimitry Andric       // Rerunning safepoint insertion after safepoints are already
447ff0cc061SDimitry Andric       // inserted is not supported.  It could probably be made to work,
448ff0cc061SDimitry Andric       // but why are you doing this?  There's no good reason.
449ff0cc061SDimitry Andric       llvm_unreachable("repeat safepoint insertion is not supported");
450ff0cc061SDimitry Andric     }
451ff0cc061SDimitry Andric     case Intrinsic::gcroot:
452ff0cc061SDimitry Andric       // Currently, this mechanism hasn't been extended to work with gcroot.
453ff0cc061SDimitry Andric       // There's no reason it couldn't be, but I haven't thought about the
454ff0cc061SDimitry Andric       // implications much.
455ff0cc061SDimitry Andric       llvm_unreachable(
456ff0cc061SDimitry Andric           "interaction with the gcroot mechanism is not supported");
457ff0cc061SDimitry Andric     }
458ff0cc061SDimitry Andric   }
459ff0cc061SDimitry Andric   // We assume that functions in the source language only return base
460ff0cc061SDimitry Andric   // pointers.  This should probably be generalized via attributes to support
461ff0cc061SDimitry Andric   // both source language and internal functions.
462ff0cc061SDimitry Andric   if (isa<CallInst>(I) || isa<InvokeInst>(I))
463ff0cc061SDimitry Andric     return I;
464ff0cc061SDimitry Andric 
465ff0cc061SDimitry Andric   // I have absolutely no idea how to implement this part yet.  It's not
466ff0cc061SDimitry Andric   // neccessarily hard, I just haven't really looked at it yet.
467ff0cc061SDimitry Andric   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
468ff0cc061SDimitry Andric 
469ff0cc061SDimitry Andric   if (isa<AtomicCmpXchgInst>(I))
470ff0cc061SDimitry Andric     // A CAS is effectively a atomic store and load combined under a
471ff0cc061SDimitry Andric     // predicate.  From the perspective of base pointers, we just treat it
472ff0cc061SDimitry Andric     // like a load.
473ff0cc061SDimitry Andric     return I;
474ff0cc061SDimitry Andric 
475ff0cc061SDimitry Andric   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
476ff0cc061SDimitry Andric                                    "binary ops which don't apply to pointers");
477ff0cc061SDimitry Andric 
478ff0cc061SDimitry Andric   // The aggregate ops.  Aggregates can either be in the heap or on the
479ff0cc061SDimitry Andric   // stack, but in either case, this is simply a field load.  As a result,
480ff0cc061SDimitry Andric   // this is a defining definition of the base just like a load is.
481ff0cc061SDimitry Andric   if (isa<ExtractValueInst>(I))
482ff0cc061SDimitry Andric     return I;
483ff0cc061SDimitry Andric 
484ff0cc061SDimitry Andric   // We should never see an insert vector since that would require we be
485ff0cc061SDimitry Andric   // tracing back a struct value not a pointer value.
486ff0cc061SDimitry Andric   assert(!isa<InsertValueInst>(I) &&
487ff0cc061SDimitry Andric          "Base pointer for a struct is meaningless");
488ff0cc061SDimitry Andric 
489ff0cc061SDimitry Andric   // The last two cases here don't return a base pointer.  Instead, they
490ff0cc061SDimitry Andric   // return a value which dynamically selects from amoung several base
491ff0cc061SDimitry Andric   // derived pointers (each with it's own base potentially).  It's the job of
492ff0cc061SDimitry Andric   // the caller to resolve these.
493ff0cc061SDimitry Andric   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
494ff0cc061SDimitry Andric          "missing instruction case in findBaseDefiningValing");
495ff0cc061SDimitry Andric   return I;
496ff0cc061SDimitry Andric }
497ff0cc061SDimitry Andric 
498ff0cc061SDimitry Andric /// Returns the base defining value for this value.
499ff0cc061SDimitry Andric static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
500ff0cc061SDimitry Andric   Value *&Cached = Cache[I];
501ff0cc061SDimitry Andric   if (!Cached) {
502ff0cc061SDimitry Andric     Cached = findBaseDefiningValue(I);
503ff0cc061SDimitry Andric   }
504ff0cc061SDimitry Andric   assert(Cache[I] != nullptr);
505ff0cc061SDimitry Andric 
506ff0cc061SDimitry Andric   if (TraceLSP) {
507ff0cc061SDimitry Andric     dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
508ff0cc061SDimitry Andric            << "\n";
509ff0cc061SDimitry Andric   }
510ff0cc061SDimitry Andric   return Cached;
511ff0cc061SDimitry Andric }
512ff0cc061SDimitry Andric 
513ff0cc061SDimitry Andric /// Return a base pointer for this value if known.  Otherwise, return it's
514ff0cc061SDimitry Andric /// base defining value.
515ff0cc061SDimitry Andric static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
516ff0cc061SDimitry Andric   Value *Def = findBaseDefiningValueCached(I, Cache);
517ff0cc061SDimitry Andric   auto Found = Cache.find(Def);
518ff0cc061SDimitry Andric   if (Found != Cache.end()) {
519ff0cc061SDimitry Andric     // Either a base-of relation, or a self reference.  Caller must check.
520ff0cc061SDimitry Andric     return Found->second;
521ff0cc061SDimitry Andric   }
522ff0cc061SDimitry Andric   // Only a BDV available
523ff0cc061SDimitry Andric   return Def;
524ff0cc061SDimitry Andric }
525ff0cc061SDimitry Andric 
526ff0cc061SDimitry Andric /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
527ff0cc061SDimitry Andric /// is it known to be a base pointer?  Or do we need to continue searching.
528ff0cc061SDimitry Andric static bool isKnownBaseResult(Value *V) {
529ff0cc061SDimitry Andric   if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
530ff0cc061SDimitry Andric     // no recursion possible
531ff0cc061SDimitry Andric     return true;
532ff0cc061SDimitry Andric   }
533ff0cc061SDimitry Andric   if (isa<Instruction>(V) &&
534ff0cc061SDimitry Andric       cast<Instruction>(V)->getMetadata("is_base_value")) {
535ff0cc061SDimitry Andric     // This is a previously inserted base phi or select.  We know
536ff0cc061SDimitry Andric     // that this is a base value.
537ff0cc061SDimitry Andric     return true;
538ff0cc061SDimitry Andric   }
539ff0cc061SDimitry Andric 
540ff0cc061SDimitry Andric   // We need to keep searching
541ff0cc061SDimitry Andric   return false;
542ff0cc061SDimitry Andric }
543ff0cc061SDimitry Andric 
544ff0cc061SDimitry Andric // TODO: find a better name for this
545ff0cc061SDimitry Andric namespace {
546ff0cc061SDimitry Andric class PhiState {
547ff0cc061SDimitry Andric public:
548ff0cc061SDimitry Andric   enum Status { Unknown, Base, Conflict };
549ff0cc061SDimitry Andric 
550ff0cc061SDimitry Andric   PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
551ff0cc061SDimitry Andric     assert(status != Base || b);
552ff0cc061SDimitry Andric   }
553ff0cc061SDimitry Andric   PhiState(Value *b) : status(Base), base(b) {}
554ff0cc061SDimitry Andric   PhiState() : status(Unknown), base(nullptr) {}
555ff0cc061SDimitry Andric 
556ff0cc061SDimitry Andric   Status getStatus() const { return status; }
557ff0cc061SDimitry Andric   Value *getBase() const { return base; }
558ff0cc061SDimitry Andric 
559ff0cc061SDimitry Andric   bool isBase() const { return getStatus() == Base; }
560ff0cc061SDimitry Andric   bool isUnknown() const { return getStatus() == Unknown; }
561ff0cc061SDimitry Andric   bool isConflict() const { return getStatus() == Conflict; }
562ff0cc061SDimitry Andric 
563ff0cc061SDimitry Andric   bool operator==(const PhiState &other) const {
564ff0cc061SDimitry Andric     return base == other.base && status == other.status;
565ff0cc061SDimitry Andric   }
566ff0cc061SDimitry Andric 
567ff0cc061SDimitry Andric   bool operator!=(const PhiState &other) const { return !(*this == other); }
568ff0cc061SDimitry Andric 
569ff0cc061SDimitry Andric   void dump() {
570ff0cc061SDimitry Andric     errs() << status << " (" << base << " - "
571ff0cc061SDimitry Andric            << (base ? base->getName() : "nullptr") << "): ";
572ff0cc061SDimitry Andric   }
573ff0cc061SDimitry Andric 
574ff0cc061SDimitry Andric private:
575ff0cc061SDimitry Andric   Status status;
576ff0cc061SDimitry Andric   Value *base; // non null only if status == base
577ff0cc061SDimitry Andric };
578ff0cc061SDimitry Andric 
579ff0cc061SDimitry Andric typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
580ff0cc061SDimitry Andric // Values of type PhiState form a lattice, and this is a helper
581ff0cc061SDimitry Andric // class that implementes the meet operation.  The meat of the meet
582ff0cc061SDimitry Andric // operation is implemented in MeetPhiStates::pureMeet
583ff0cc061SDimitry Andric class MeetPhiStates {
584ff0cc061SDimitry Andric public:
585ff0cc061SDimitry Andric   // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
586ff0cc061SDimitry Andric   explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
587ff0cc061SDimitry Andric       : phiStates(phiStates) {}
588ff0cc061SDimitry Andric 
589ff0cc061SDimitry Andric   // Destructively meet the current result with the base V.  V can
590ff0cc061SDimitry Andric   // either be a merge instruction (SelectInst / PHINode), in which
591ff0cc061SDimitry Andric   // case its status is looked up in the phiStates map; or a regular
592ff0cc061SDimitry Andric   // SSA value, in which case it is assumed to be a base.
593ff0cc061SDimitry Andric   void meetWith(Value *V) {
594ff0cc061SDimitry Andric     PhiState otherState = getStateForBDV(V);
595ff0cc061SDimitry Andric     assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
596ff0cc061SDimitry Andric             MeetPhiStates::pureMeet(currentResult, otherState)) &&
597ff0cc061SDimitry Andric            "math is wrong: meet does not commute!");
598ff0cc061SDimitry Andric     currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
599ff0cc061SDimitry Andric   }
600ff0cc061SDimitry Andric 
601ff0cc061SDimitry Andric   PhiState getResult() const { return currentResult; }
602ff0cc061SDimitry Andric 
603ff0cc061SDimitry Andric private:
604ff0cc061SDimitry Andric   const ConflictStateMapTy &phiStates;
605ff0cc061SDimitry Andric   PhiState currentResult;
606ff0cc061SDimitry Andric 
607ff0cc061SDimitry Andric   /// Return a phi state for a base defining value.  We'll generate a new
608ff0cc061SDimitry Andric   /// base state for known bases and expect to find a cached state otherwise
609ff0cc061SDimitry Andric   PhiState getStateForBDV(Value *baseValue) {
610ff0cc061SDimitry Andric     if (isKnownBaseResult(baseValue)) {
611ff0cc061SDimitry Andric       return PhiState(baseValue);
612ff0cc061SDimitry Andric     } else {
613ff0cc061SDimitry Andric       return lookupFromMap(baseValue);
614ff0cc061SDimitry Andric     }
615ff0cc061SDimitry Andric   }
616ff0cc061SDimitry Andric 
617ff0cc061SDimitry Andric   PhiState lookupFromMap(Value *V) {
618ff0cc061SDimitry Andric     auto I = phiStates.find(V);
619ff0cc061SDimitry Andric     assert(I != phiStates.end() && "lookup failed!");
620ff0cc061SDimitry Andric     return I->second;
621ff0cc061SDimitry Andric   }
622ff0cc061SDimitry Andric 
623ff0cc061SDimitry Andric   static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
624ff0cc061SDimitry Andric     switch (stateA.getStatus()) {
625ff0cc061SDimitry Andric     case PhiState::Unknown:
626ff0cc061SDimitry Andric       return stateB;
627ff0cc061SDimitry Andric 
628ff0cc061SDimitry Andric     case PhiState::Base:
629ff0cc061SDimitry Andric       assert(stateA.getBase() && "can't be null");
630ff0cc061SDimitry Andric       if (stateB.isUnknown())
631ff0cc061SDimitry Andric         return stateA;
632ff0cc061SDimitry Andric 
633ff0cc061SDimitry Andric       if (stateB.isBase()) {
634ff0cc061SDimitry Andric         if (stateA.getBase() == stateB.getBase()) {
635ff0cc061SDimitry Andric           assert(stateA == stateB && "equality broken!");
636ff0cc061SDimitry Andric           return stateA;
637ff0cc061SDimitry Andric         }
638ff0cc061SDimitry Andric         return PhiState(PhiState::Conflict);
639ff0cc061SDimitry Andric       }
640ff0cc061SDimitry Andric       assert(stateB.isConflict() && "only three states!");
641ff0cc061SDimitry Andric       return PhiState(PhiState::Conflict);
642ff0cc061SDimitry Andric 
643ff0cc061SDimitry Andric     case PhiState::Conflict:
644ff0cc061SDimitry Andric       return stateA;
645ff0cc061SDimitry Andric     }
646ff0cc061SDimitry Andric     llvm_unreachable("only three states!");
647ff0cc061SDimitry Andric   }
648ff0cc061SDimitry Andric };
6498f0fd8f6SDimitry Andric } // namespace
650ff0cc061SDimitry Andric /// For a given value or instruction, figure out what base ptr it's derived
651ff0cc061SDimitry Andric /// from.  For gc objects, this is simply itself.  On success, returns a value
652ff0cc061SDimitry Andric /// which is the base pointer.  (This is reliable and can be used for
653ff0cc061SDimitry Andric /// relocation.)  On failure, returns nullptr.
654ff0cc061SDimitry Andric static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
655ff0cc061SDimitry Andric   Value *def = findBaseOrBDV(I, cache);
656ff0cc061SDimitry Andric 
657ff0cc061SDimitry Andric   if (isKnownBaseResult(def)) {
658ff0cc061SDimitry Andric     return def;
659ff0cc061SDimitry Andric   }
660ff0cc061SDimitry Andric 
661ff0cc061SDimitry Andric   // Here's the rough algorithm:
662ff0cc061SDimitry Andric   // - For every SSA value, construct a mapping to either an actual base
663ff0cc061SDimitry Andric   //   pointer or a PHI which obscures the base pointer.
664ff0cc061SDimitry Andric   // - Construct a mapping from PHI to unknown TOP state.  Use an
665ff0cc061SDimitry Andric   //   optimistic algorithm to propagate base pointer information.  Lattice
666ff0cc061SDimitry Andric   //   looks like:
667ff0cc061SDimitry Andric   //   UNKNOWN
668ff0cc061SDimitry Andric   //   b1 b2 b3 b4
669ff0cc061SDimitry Andric   //   CONFLICT
670ff0cc061SDimitry Andric   //   When algorithm terminates, all PHIs will either have a single concrete
671ff0cc061SDimitry Andric   //   base or be in a conflict state.
672ff0cc061SDimitry Andric   // - For every conflict, insert a dummy PHI node without arguments.  Add
673ff0cc061SDimitry Andric   //   these to the base[Instruction] = BasePtr mapping.  For every
674ff0cc061SDimitry Andric   //   non-conflict, add the actual base.
675ff0cc061SDimitry Andric   //  - For every conflict, add arguments for the base[a] of each input
676ff0cc061SDimitry Andric   //   arguments.
677ff0cc061SDimitry Andric   //
678ff0cc061SDimitry Andric   // Note: A simpler form of this would be to add the conflict form of all
679ff0cc061SDimitry Andric   // PHIs without running the optimistic algorithm.  This would be
680ff0cc061SDimitry Andric   // analougous to pessimistic data flow and would likely lead to an
681ff0cc061SDimitry Andric   // overall worse solution.
682ff0cc061SDimitry Andric 
683ff0cc061SDimitry Andric   ConflictStateMapTy states;
684ff0cc061SDimitry Andric   states[def] = PhiState();
685ff0cc061SDimitry Andric   // Recursively fill in all phis & selects reachable from the initial one
686ff0cc061SDimitry Andric   // for which we don't already know a definite base value for
687ff0cc061SDimitry Andric   // TODO: This should be rewritten with a worklist
688ff0cc061SDimitry Andric   bool done = false;
689ff0cc061SDimitry Andric   while (!done) {
690ff0cc061SDimitry Andric     done = true;
691ff0cc061SDimitry Andric     // Since we're adding elements to 'states' as we run, we can't keep
692ff0cc061SDimitry Andric     // iterators into the set.
693ff0cc061SDimitry Andric     SmallVector<Value *, 16> Keys;
694ff0cc061SDimitry Andric     Keys.reserve(states.size());
695ff0cc061SDimitry Andric     for (auto Pair : states) {
696ff0cc061SDimitry Andric       Value *V = Pair.first;
697ff0cc061SDimitry Andric       Keys.push_back(V);
698ff0cc061SDimitry Andric     }
699ff0cc061SDimitry Andric     for (Value *v : Keys) {
700ff0cc061SDimitry Andric       assert(!isKnownBaseResult(v) && "why did it get added?");
701ff0cc061SDimitry Andric       if (PHINode *phi = dyn_cast<PHINode>(v)) {
702ff0cc061SDimitry Andric         assert(phi->getNumIncomingValues() > 0 &&
703ff0cc061SDimitry Andric                "zero input phis are illegal");
704ff0cc061SDimitry Andric         for (Value *InVal : phi->incoming_values()) {
705ff0cc061SDimitry Andric           Value *local = findBaseOrBDV(InVal, cache);
706ff0cc061SDimitry Andric           if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
707ff0cc061SDimitry Andric             states[local] = PhiState();
708ff0cc061SDimitry Andric             done = false;
709ff0cc061SDimitry Andric           }
710ff0cc061SDimitry Andric         }
711ff0cc061SDimitry Andric       } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
712ff0cc061SDimitry Andric         Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
713ff0cc061SDimitry Andric         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
714ff0cc061SDimitry Andric           states[local] = PhiState();
715ff0cc061SDimitry Andric           done = false;
716ff0cc061SDimitry Andric         }
717ff0cc061SDimitry Andric         local = findBaseOrBDV(sel->getFalseValue(), cache);
718ff0cc061SDimitry Andric         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
719ff0cc061SDimitry Andric           states[local] = PhiState();
720ff0cc061SDimitry Andric           done = false;
721ff0cc061SDimitry Andric         }
722ff0cc061SDimitry Andric       }
723ff0cc061SDimitry Andric     }
724ff0cc061SDimitry Andric   }
725ff0cc061SDimitry Andric 
726ff0cc061SDimitry Andric   if (TraceLSP) {
727ff0cc061SDimitry Andric     errs() << "States after initialization:\n";
728ff0cc061SDimitry Andric     for (auto Pair : states) {
729ff0cc061SDimitry Andric       Instruction *v = cast<Instruction>(Pair.first);
730ff0cc061SDimitry Andric       PhiState state = Pair.second;
731ff0cc061SDimitry Andric       state.dump();
732ff0cc061SDimitry Andric       v->dump();
733ff0cc061SDimitry Andric     }
734ff0cc061SDimitry Andric   }
735ff0cc061SDimitry Andric 
736ff0cc061SDimitry Andric   // TODO: come back and revisit the state transitions around inputs which
737ff0cc061SDimitry Andric   // have reached conflict state.  The current version seems too conservative.
738ff0cc061SDimitry Andric 
739ff0cc061SDimitry Andric   bool progress = true;
740ff0cc061SDimitry Andric   while (progress) {
741ff0cc061SDimitry Andric #ifndef NDEBUG
742ff0cc061SDimitry Andric     size_t oldSize = states.size();
743ff0cc061SDimitry Andric #endif
744ff0cc061SDimitry Andric     progress = false;
745ff0cc061SDimitry Andric     // We're only changing keys in this loop, thus safe to keep iterators
746ff0cc061SDimitry Andric     for (auto Pair : states) {
747ff0cc061SDimitry Andric       MeetPhiStates calculateMeet(states);
748ff0cc061SDimitry Andric       Value *v = Pair.first;
749ff0cc061SDimitry Andric       assert(!isKnownBaseResult(v) && "why did it get added?");
750ff0cc061SDimitry Andric       if (SelectInst *select = dyn_cast<SelectInst>(v)) {
751ff0cc061SDimitry Andric         calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
752ff0cc061SDimitry Andric         calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
753ff0cc061SDimitry Andric       } else
754ff0cc061SDimitry Andric         for (Value *Val : cast<PHINode>(v)->incoming_values())
755ff0cc061SDimitry Andric           calculateMeet.meetWith(findBaseOrBDV(Val, cache));
756ff0cc061SDimitry Andric 
757ff0cc061SDimitry Andric       PhiState oldState = states[v];
758ff0cc061SDimitry Andric       PhiState newState = calculateMeet.getResult();
759ff0cc061SDimitry Andric       if (oldState != newState) {
760ff0cc061SDimitry Andric         progress = true;
761ff0cc061SDimitry Andric         states[v] = newState;
762ff0cc061SDimitry Andric       }
763ff0cc061SDimitry Andric     }
764ff0cc061SDimitry Andric 
765ff0cc061SDimitry Andric     assert(oldSize <= states.size());
766ff0cc061SDimitry Andric     assert(oldSize == states.size() || progress);
767ff0cc061SDimitry Andric   }
768ff0cc061SDimitry Andric 
769ff0cc061SDimitry Andric   if (TraceLSP) {
770ff0cc061SDimitry Andric     errs() << "States after meet iteration:\n";
771ff0cc061SDimitry Andric     for (auto Pair : states) {
772ff0cc061SDimitry Andric       Instruction *v = cast<Instruction>(Pair.first);
773ff0cc061SDimitry Andric       PhiState state = Pair.second;
774ff0cc061SDimitry Andric       state.dump();
775ff0cc061SDimitry Andric       v->dump();
776ff0cc061SDimitry Andric     }
777ff0cc061SDimitry Andric   }
778ff0cc061SDimitry Andric 
779ff0cc061SDimitry Andric   // Insert Phis for all conflicts
780ff0cc061SDimitry Andric   // We want to keep naming deterministic in the loop that follows, so
781ff0cc061SDimitry Andric   // sort the keys before iteration.  This is useful in allowing us to
782ff0cc061SDimitry Andric   // write stable tests. Note that there is no invalidation issue here.
783ff0cc061SDimitry Andric   SmallVector<Value *, 16> Keys;
784ff0cc061SDimitry Andric   Keys.reserve(states.size());
785ff0cc061SDimitry Andric   for (auto Pair : states) {
786ff0cc061SDimitry Andric     Value *V = Pair.first;
787ff0cc061SDimitry Andric     Keys.push_back(V);
788ff0cc061SDimitry Andric   }
789ff0cc061SDimitry Andric   std::sort(Keys.begin(), Keys.end(), order_by_name);
790ff0cc061SDimitry Andric   // TODO: adjust naming patterns to avoid this order of iteration dependency
791ff0cc061SDimitry Andric   for (Value *V : Keys) {
792ff0cc061SDimitry Andric     Instruction *v = cast<Instruction>(V);
793ff0cc061SDimitry Andric     PhiState state = states[V];
794ff0cc061SDimitry Andric     assert(!isKnownBaseResult(v) && "why did it get added?");
795ff0cc061SDimitry Andric     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
796ff0cc061SDimitry Andric     if (!state.isConflict())
797ff0cc061SDimitry Andric       continue;
798ff0cc061SDimitry Andric 
799ff0cc061SDimitry Andric     if (isa<PHINode>(v)) {
800ff0cc061SDimitry Andric       int num_preds =
801ff0cc061SDimitry Andric           std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
802ff0cc061SDimitry Andric       assert(num_preds > 0 && "how did we reach here");
803ff0cc061SDimitry Andric       PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
804ff0cc061SDimitry Andric       // Add metadata marking this as a base value
805ff0cc061SDimitry Andric       auto *const_1 = ConstantInt::get(
806ff0cc061SDimitry Andric           Type::getInt32Ty(
807ff0cc061SDimitry Andric               v->getParent()->getParent()->getParent()->getContext()),
808ff0cc061SDimitry Andric           1);
809ff0cc061SDimitry Andric       auto MDConst = ConstantAsMetadata::get(const_1);
810ff0cc061SDimitry Andric       MDNode *md = MDNode::get(
811ff0cc061SDimitry Andric           v->getParent()->getParent()->getParent()->getContext(), MDConst);
812ff0cc061SDimitry Andric       phi->setMetadata("is_base_value", md);
813ff0cc061SDimitry Andric       states[v] = PhiState(PhiState::Conflict, phi);
814ff0cc061SDimitry Andric     } else {
815ff0cc061SDimitry Andric       SelectInst *sel = cast<SelectInst>(v);
816ff0cc061SDimitry Andric       // The undef will be replaced later
817ff0cc061SDimitry Andric       UndefValue *undef = UndefValue::get(sel->getType());
818ff0cc061SDimitry Andric       SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
819ff0cc061SDimitry Andric                                                undef, "base_select", sel);
820ff0cc061SDimitry Andric       // Add metadata marking this as a base value
821ff0cc061SDimitry Andric       auto *const_1 = ConstantInt::get(
822ff0cc061SDimitry Andric           Type::getInt32Ty(
823ff0cc061SDimitry Andric               v->getParent()->getParent()->getParent()->getContext()),
824ff0cc061SDimitry Andric           1);
825ff0cc061SDimitry Andric       auto MDConst = ConstantAsMetadata::get(const_1);
826ff0cc061SDimitry Andric       MDNode *md = MDNode::get(
827ff0cc061SDimitry Andric           v->getParent()->getParent()->getParent()->getContext(), MDConst);
828ff0cc061SDimitry Andric       basesel->setMetadata("is_base_value", md);
829ff0cc061SDimitry Andric       states[v] = PhiState(PhiState::Conflict, basesel);
830ff0cc061SDimitry Andric     }
831ff0cc061SDimitry Andric   }
832ff0cc061SDimitry Andric 
833ff0cc061SDimitry Andric   // Fixup all the inputs of the new PHIs
834ff0cc061SDimitry Andric   for (auto Pair : states) {
835ff0cc061SDimitry Andric     Instruction *v = cast<Instruction>(Pair.first);
836ff0cc061SDimitry Andric     PhiState state = Pair.second;
837ff0cc061SDimitry Andric 
838ff0cc061SDimitry Andric     assert(!isKnownBaseResult(v) && "why did it get added?");
839ff0cc061SDimitry Andric     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
840ff0cc061SDimitry Andric     if (!state.isConflict())
841ff0cc061SDimitry Andric       continue;
842ff0cc061SDimitry Andric 
843ff0cc061SDimitry Andric     if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
844ff0cc061SDimitry Andric       PHINode *phi = cast<PHINode>(v);
845ff0cc061SDimitry Andric       unsigned NumPHIValues = phi->getNumIncomingValues();
846ff0cc061SDimitry Andric       for (unsigned i = 0; i < NumPHIValues; i++) {
847ff0cc061SDimitry Andric         Value *InVal = phi->getIncomingValue(i);
848ff0cc061SDimitry Andric         BasicBlock *InBB = phi->getIncomingBlock(i);
849ff0cc061SDimitry Andric 
850ff0cc061SDimitry Andric         // If we've already seen InBB, add the same incoming value
851ff0cc061SDimitry Andric         // we added for it earlier.  The IR verifier requires phi
852ff0cc061SDimitry Andric         // nodes with multiple entries from the same basic block
853ff0cc061SDimitry Andric         // to have the same incoming value for each of those
854ff0cc061SDimitry Andric         // entries.  If we don't do this check here and basephi
855ff0cc061SDimitry Andric         // has a different type than base, we'll end up adding two
856ff0cc061SDimitry Andric         // bitcasts (and hence two distinct values) as incoming
857ff0cc061SDimitry Andric         // values for the same basic block.
858ff0cc061SDimitry Andric 
859ff0cc061SDimitry Andric         int blockIndex = basephi->getBasicBlockIndex(InBB);
860ff0cc061SDimitry Andric         if (blockIndex != -1) {
861ff0cc061SDimitry Andric           Value *oldBase = basephi->getIncomingValue(blockIndex);
862ff0cc061SDimitry Andric           basephi->addIncoming(oldBase, InBB);
863ff0cc061SDimitry Andric #ifndef NDEBUG
864ff0cc061SDimitry Andric           Value *base = findBaseOrBDV(InVal, cache);
865ff0cc061SDimitry Andric           if (!isKnownBaseResult(base)) {
866ff0cc061SDimitry Andric             // Either conflict or base.
867ff0cc061SDimitry Andric             assert(states.count(base));
868ff0cc061SDimitry Andric             base = states[base].getBase();
869ff0cc061SDimitry Andric             assert(base != nullptr && "unknown PhiState!");
870ff0cc061SDimitry Andric           }
871ff0cc061SDimitry Andric 
872ff0cc061SDimitry Andric           // In essense this assert states: the only way two
873ff0cc061SDimitry Andric           // values incoming from the same basic block may be
874ff0cc061SDimitry Andric           // different is by being different bitcasts of the same
875ff0cc061SDimitry Andric           // value.  A cleanup that remains TODO is changing
876ff0cc061SDimitry Andric           // findBaseOrBDV to return an llvm::Value of the correct
877ff0cc061SDimitry Andric           // type (and still remain pure).  This will remove the
878ff0cc061SDimitry Andric           // need to add bitcasts.
879ff0cc061SDimitry Andric           assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
880ff0cc061SDimitry Andric                  "sanity -- findBaseOrBDV should be pure!");
881ff0cc061SDimitry Andric #endif
882ff0cc061SDimitry Andric           continue;
883ff0cc061SDimitry Andric         }
884ff0cc061SDimitry Andric 
885ff0cc061SDimitry Andric         // Find either the defining value for the PHI or the normal base for
886ff0cc061SDimitry Andric         // a non-phi node
887ff0cc061SDimitry Andric         Value *base = findBaseOrBDV(InVal, cache);
888ff0cc061SDimitry Andric         if (!isKnownBaseResult(base)) {
889ff0cc061SDimitry Andric           // Either conflict or base.
890ff0cc061SDimitry Andric           assert(states.count(base));
891ff0cc061SDimitry Andric           base = states[base].getBase();
892ff0cc061SDimitry Andric           assert(base != nullptr && "unknown PhiState!");
893ff0cc061SDimitry Andric         }
894ff0cc061SDimitry Andric         assert(base && "can't be null");
895ff0cc061SDimitry Andric         // Must use original input BB since base may not be Instruction
896ff0cc061SDimitry Andric         // The cast is needed since base traversal may strip away bitcasts
897ff0cc061SDimitry Andric         if (base->getType() != basephi->getType()) {
898ff0cc061SDimitry Andric           base = new BitCastInst(base, basephi->getType(), "cast",
899ff0cc061SDimitry Andric                                  InBB->getTerminator());
900ff0cc061SDimitry Andric         }
901ff0cc061SDimitry Andric         basephi->addIncoming(base, InBB);
902ff0cc061SDimitry Andric       }
903ff0cc061SDimitry Andric       assert(basephi->getNumIncomingValues() == NumPHIValues);
904ff0cc061SDimitry Andric     } else {
905ff0cc061SDimitry Andric       SelectInst *basesel = cast<SelectInst>(state.getBase());
906ff0cc061SDimitry Andric       SelectInst *sel = cast<SelectInst>(v);
907ff0cc061SDimitry Andric       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
908ff0cc061SDimitry Andric       // something more safe and less hacky.
909ff0cc061SDimitry Andric       for (int i = 1; i <= 2; i++) {
910ff0cc061SDimitry Andric         Value *InVal = sel->getOperand(i);
911ff0cc061SDimitry Andric         // Find either the defining value for the PHI or the normal base for
912ff0cc061SDimitry Andric         // a non-phi node
913ff0cc061SDimitry Andric         Value *base = findBaseOrBDV(InVal, cache);
914ff0cc061SDimitry Andric         if (!isKnownBaseResult(base)) {
915ff0cc061SDimitry Andric           // Either conflict or base.
916ff0cc061SDimitry Andric           assert(states.count(base));
917ff0cc061SDimitry Andric           base = states[base].getBase();
918ff0cc061SDimitry Andric           assert(base != nullptr && "unknown PhiState!");
919ff0cc061SDimitry Andric         }
920ff0cc061SDimitry Andric         assert(base && "can't be null");
921ff0cc061SDimitry Andric         // Must use original input BB since base may not be Instruction
922ff0cc061SDimitry Andric         // The cast is needed since base traversal may strip away bitcasts
923ff0cc061SDimitry Andric         if (base->getType() != basesel->getType()) {
924ff0cc061SDimitry Andric           base = new BitCastInst(base, basesel->getType(), "cast", basesel);
925ff0cc061SDimitry Andric         }
926ff0cc061SDimitry Andric         basesel->setOperand(i, base);
927ff0cc061SDimitry Andric       }
928ff0cc061SDimitry Andric     }
929ff0cc061SDimitry Andric   }
930ff0cc061SDimitry Andric 
931ff0cc061SDimitry Andric   // Cache all of our results so we can cheaply reuse them
932ff0cc061SDimitry Andric   // NOTE: This is actually two caches: one of the base defining value
933ff0cc061SDimitry Andric   // relation and one of the base pointer relation!  FIXME
934ff0cc061SDimitry Andric   for (auto item : states) {
935ff0cc061SDimitry Andric     Value *v = item.first;
936ff0cc061SDimitry Andric     Value *base = item.second.getBase();
937ff0cc061SDimitry Andric     assert(v && base);
938ff0cc061SDimitry Andric     assert(!isKnownBaseResult(v) && "why did it get added?");
939ff0cc061SDimitry Andric 
940ff0cc061SDimitry Andric     if (TraceLSP) {
941ff0cc061SDimitry Andric       std::string fromstr =
942ff0cc061SDimitry Andric           cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
943ff0cc061SDimitry Andric                          : "none";
944ff0cc061SDimitry Andric       errs() << "Updating base value cache"
945ff0cc061SDimitry Andric              << " for: " << (v->hasName() ? v->getName() : "")
946ff0cc061SDimitry Andric              << " from: " << fromstr
947ff0cc061SDimitry Andric              << " to: " << (base->hasName() ? base->getName() : "") << "\n";
948ff0cc061SDimitry Andric     }
949ff0cc061SDimitry Andric 
950ff0cc061SDimitry Andric     assert(isKnownBaseResult(base) &&
951ff0cc061SDimitry Andric            "must be something we 'know' is a base pointer");
952ff0cc061SDimitry Andric     if (cache.count(v)) {
953ff0cc061SDimitry Andric       // Once we transition from the BDV relation being store in the cache to
954ff0cc061SDimitry Andric       // the base relation being stored, it must be stable
955ff0cc061SDimitry Andric       assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
956ff0cc061SDimitry Andric              "base relation should be stable");
957ff0cc061SDimitry Andric     }
958ff0cc061SDimitry Andric     cache[v] = base;
959ff0cc061SDimitry Andric   }
960ff0cc061SDimitry Andric   assert(cache.find(def) != cache.end());
961ff0cc061SDimitry Andric   return cache[def];
962ff0cc061SDimitry Andric }
963ff0cc061SDimitry Andric 
964ff0cc061SDimitry Andric // For a set of live pointers (base and/or derived), identify the base
965ff0cc061SDimitry Andric // pointer of the object which they are derived from.  This routine will
966ff0cc061SDimitry Andric // mutate the IR graph as needed to make the 'base' pointer live at the
967ff0cc061SDimitry Andric // definition site of 'derived'.  This ensures that any use of 'derived' can
968ff0cc061SDimitry Andric // also use 'base'.  This may involve the insertion of a number of
969ff0cc061SDimitry Andric // additional PHI nodes.
970ff0cc061SDimitry Andric //
971ff0cc061SDimitry Andric // preconditions: live is a set of pointer type Values
972ff0cc061SDimitry Andric //
973ff0cc061SDimitry Andric // side effects: may insert PHI nodes into the existing CFG, will preserve
974ff0cc061SDimitry Andric // CFG, will not remove or mutate any existing nodes
975ff0cc061SDimitry Andric //
976ff0cc061SDimitry Andric // post condition: PointerToBase contains one (derived, base) pair for every
977ff0cc061SDimitry Andric // pointer in live.  Note that derived can be equal to base if the original
978ff0cc061SDimitry Andric // pointer was a base pointer.
979ff0cc061SDimitry Andric static void
980ff0cc061SDimitry Andric findBasePointers(const StatepointLiveSetTy &live,
981ff0cc061SDimitry Andric                  DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
982ff0cc061SDimitry Andric                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
983ff0cc061SDimitry Andric   // For the naming of values inserted to be deterministic - which makes for
984ff0cc061SDimitry Andric   // much cleaner and more stable tests - we need to assign an order to the
985ff0cc061SDimitry Andric   // live values.  DenseSets do not provide a deterministic order across runs.
986ff0cc061SDimitry Andric   SmallVector<Value *, 64> Temp;
987ff0cc061SDimitry Andric   Temp.insert(Temp.end(), live.begin(), live.end());
988ff0cc061SDimitry Andric   std::sort(Temp.begin(), Temp.end(), order_by_name);
989ff0cc061SDimitry Andric   for (Value *ptr : Temp) {
990ff0cc061SDimitry Andric     Value *base = findBasePointer(ptr, DVCache);
991ff0cc061SDimitry Andric     assert(base && "failed to find base pointer");
992ff0cc061SDimitry Andric     PointerToBase[ptr] = base;
993ff0cc061SDimitry Andric     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
994ff0cc061SDimitry Andric             DT->dominates(cast<Instruction>(base)->getParent(),
995ff0cc061SDimitry Andric                           cast<Instruction>(ptr)->getParent())) &&
996ff0cc061SDimitry Andric            "The base we found better dominate the derived pointer");
997ff0cc061SDimitry Andric 
998ff0cc061SDimitry Andric     // If you see this trip and like to live really dangerously, the code should
999ff0cc061SDimitry Andric     // be correct, just with idioms the verifier can't handle.  You can try
1000ff0cc061SDimitry Andric     // disabling the verifier at your own substaintial risk.
1001ff0cc061SDimitry Andric     assert(!isa<ConstantPointerNull>(base) &&
1002ff0cc061SDimitry Andric            "the relocation code needs adjustment to handle the relocation of "
1003ff0cc061SDimitry Andric            "a null pointer constant without causing false positives in the "
1004ff0cc061SDimitry Andric            "safepoint ir verifier.");
1005ff0cc061SDimitry Andric   }
1006ff0cc061SDimitry Andric }
1007ff0cc061SDimitry Andric 
1008ff0cc061SDimitry Andric /// Find the required based pointers (and adjust the live set) for the given
1009ff0cc061SDimitry Andric /// parse point.
1010ff0cc061SDimitry Andric static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1011ff0cc061SDimitry Andric                              const CallSite &CS,
1012ff0cc061SDimitry Andric                              PartiallyConstructedSafepointRecord &result) {
1013ff0cc061SDimitry Andric   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1014ff0cc061SDimitry Andric   findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
1015ff0cc061SDimitry Andric 
1016ff0cc061SDimitry Andric   if (PrintBasePointers) {
1017ff0cc061SDimitry Andric     // Note: Need to print these in a stable order since this is checked in
1018ff0cc061SDimitry Andric     // some tests.
1019ff0cc061SDimitry Andric     errs() << "Base Pairs (w/o Relocation):\n";
1020ff0cc061SDimitry Andric     SmallVector<Value *, 64> Temp;
1021ff0cc061SDimitry Andric     Temp.reserve(PointerToBase.size());
1022ff0cc061SDimitry Andric     for (auto Pair : PointerToBase) {
1023ff0cc061SDimitry Andric       Temp.push_back(Pair.first);
1024ff0cc061SDimitry Andric     }
1025ff0cc061SDimitry Andric     std::sort(Temp.begin(), Temp.end(), order_by_name);
1026ff0cc061SDimitry Andric     for (Value *Ptr : Temp) {
1027ff0cc061SDimitry Andric       Value *Base = PointerToBase[Ptr];
1028ff0cc061SDimitry Andric       errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1029ff0cc061SDimitry Andric              << "\n";
1030ff0cc061SDimitry Andric     }
1031ff0cc061SDimitry Andric   }
1032ff0cc061SDimitry Andric 
1033ff0cc061SDimitry Andric   result.PointerToBase = PointerToBase;
1034ff0cc061SDimitry Andric }
1035ff0cc061SDimitry Andric 
1036ff0cc061SDimitry Andric /// Given an updated version of the dataflow liveness results, update the
1037ff0cc061SDimitry Andric /// liveset and base pointer maps for the call site CS.
1038ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1039ff0cc061SDimitry Andric                                   const CallSite &CS,
1040ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &result);
1041ff0cc061SDimitry Andric 
1042ff0cc061SDimitry Andric static void recomputeLiveInValues(
1043ff0cc061SDimitry Andric     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1044ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1045ff0cc061SDimitry Andric   // TODO-PERF: reuse the original liveness, then simply run the dataflow
1046ff0cc061SDimitry Andric   // again.  The old values are still live and will help it stablize quickly.
1047ff0cc061SDimitry Andric   GCPtrLivenessData RevisedLivenessData;
1048ff0cc061SDimitry Andric   computeLiveInValues(DT, F, RevisedLivenessData);
1049ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1050ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
1051ff0cc061SDimitry Andric     const CallSite &CS = toUpdate[i];
1052ff0cc061SDimitry Andric     recomputeLiveInValues(RevisedLivenessData, CS, info);
1053ff0cc061SDimitry Andric   }
1054ff0cc061SDimitry Andric }
1055ff0cc061SDimitry Andric 
1056ff0cc061SDimitry Andric // When inserting gc.relocate calls, we need to ensure there are no uses
1057ff0cc061SDimitry Andric // of the original value between the gc.statepoint and the gc.relocate call.
1058ff0cc061SDimitry Andric // One case which can arise is a phi node starting one of the successor blocks.
1059ff0cc061SDimitry Andric // We also need to be able to insert the gc.relocates only on the path which
1060ff0cc061SDimitry Andric // goes through the statepoint.  We might need to split an edge to make this
1061ff0cc061SDimitry Andric // possible.
1062ff0cc061SDimitry Andric static BasicBlock *
106397bc6c73SDimitry Andric normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
106497bc6c73SDimitry Andric                             DominatorTree &DT) {
1065ff0cc061SDimitry Andric   BasicBlock *Ret = BB;
1066ff0cc061SDimitry Andric   if (!BB->getUniquePredecessor()) {
106797bc6c73SDimitry Andric     Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, &DT);
1068ff0cc061SDimitry Andric   }
1069ff0cc061SDimitry Andric 
1070ff0cc061SDimitry Andric   // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1071ff0cc061SDimitry Andric   // from it
1072ff0cc061SDimitry Andric   FoldSingleEntryPHINodes(Ret);
1073ff0cc061SDimitry Andric   assert(!isa<PHINode>(Ret->begin()));
1074ff0cc061SDimitry Andric 
1075ff0cc061SDimitry Andric   // At this point, we can safely insert a gc.relocate as the first instruction
1076ff0cc061SDimitry Andric   // in Ret if needed.
1077ff0cc061SDimitry Andric   return Ret;
1078ff0cc061SDimitry Andric }
1079ff0cc061SDimitry Andric 
1080ff0cc061SDimitry Andric static int find_index(ArrayRef<Value *> livevec, Value *val) {
1081ff0cc061SDimitry Andric   auto itr = std::find(livevec.begin(), livevec.end(), val);
1082ff0cc061SDimitry Andric   assert(livevec.end() != itr);
1083ff0cc061SDimitry Andric   size_t index = std::distance(livevec.begin(), itr);
1084ff0cc061SDimitry Andric   assert(index < livevec.size());
1085ff0cc061SDimitry Andric   return index;
1086ff0cc061SDimitry Andric }
1087ff0cc061SDimitry Andric 
1088ff0cc061SDimitry Andric // Create new attribute set containing only attributes which can be transfered
1089ff0cc061SDimitry Andric // from original call to the safepoint.
1090ff0cc061SDimitry Andric static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1091ff0cc061SDimitry Andric   AttributeSet ret;
1092ff0cc061SDimitry Andric 
1093ff0cc061SDimitry Andric   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1094ff0cc061SDimitry Andric     unsigned index = AS.getSlotIndex(Slot);
1095ff0cc061SDimitry Andric 
1096ff0cc061SDimitry Andric     if (index == AttributeSet::ReturnIndex ||
1097ff0cc061SDimitry Andric         index == AttributeSet::FunctionIndex) {
1098ff0cc061SDimitry Andric 
1099ff0cc061SDimitry Andric       for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1100ff0cc061SDimitry Andric            ++it) {
1101ff0cc061SDimitry Andric         Attribute attr = *it;
1102ff0cc061SDimitry Andric 
1103ff0cc061SDimitry Andric         // Do not allow certain attributes - just skip them
1104ff0cc061SDimitry Andric         // Safepoint can not be read only or read none.
1105ff0cc061SDimitry Andric         if (attr.hasAttribute(Attribute::ReadNone) ||
1106ff0cc061SDimitry Andric             attr.hasAttribute(Attribute::ReadOnly))
1107ff0cc061SDimitry Andric           continue;
1108ff0cc061SDimitry Andric 
1109ff0cc061SDimitry Andric         ret = ret.addAttributes(
1110ff0cc061SDimitry Andric             AS.getContext(), index,
1111ff0cc061SDimitry Andric             AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1112ff0cc061SDimitry Andric       }
1113ff0cc061SDimitry Andric     }
1114ff0cc061SDimitry Andric 
1115ff0cc061SDimitry Andric     // Just skip parameter attributes for now
1116ff0cc061SDimitry Andric   }
1117ff0cc061SDimitry Andric 
1118ff0cc061SDimitry Andric   return ret;
1119ff0cc061SDimitry Andric }
1120ff0cc061SDimitry Andric 
1121ff0cc061SDimitry Andric /// Helper function to place all gc relocates necessary for the given
1122ff0cc061SDimitry Andric /// statepoint.
1123ff0cc061SDimitry Andric /// Inputs:
1124ff0cc061SDimitry Andric ///   liveVariables - list of variables to be relocated.
1125ff0cc061SDimitry Andric ///   liveStart - index of the first live variable.
1126ff0cc061SDimitry Andric ///   basePtrs - base pointers.
1127ff0cc061SDimitry Andric ///   statepointToken - statepoint instruction to which relocates should be
1128ff0cc061SDimitry Andric ///   bound.
1129ff0cc061SDimitry Andric ///   Builder - Llvm IR builder to be used to construct new calls.
1130ff0cc061SDimitry Andric static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1131ff0cc061SDimitry Andric                               const int LiveStart,
1132ff0cc061SDimitry Andric                               ArrayRef<llvm::Value *> BasePtrs,
1133ff0cc061SDimitry Andric                               Instruction *StatepointToken,
1134ff0cc061SDimitry Andric                               IRBuilder<> Builder) {
1135ff0cc061SDimitry Andric   SmallVector<Instruction *, 64> NewDefs;
1136ff0cc061SDimitry Andric   NewDefs.reserve(LiveVariables.size());
1137ff0cc061SDimitry Andric 
1138ff0cc061SDimitry Andric   Module *M = StatepointToken->getParent()->getParent()->getParent();
1139ff0cc061SDimitry Andric 
1140ff0cc061SDimitry Andric   for (unsigned i = 0; i < LiveVariables.size(); i++) {
1141ff0cc061SDimitry Andric     // We generate a (potentially) unique declaration for every pointer type
1142ff0cc061SDimitry Andric     // combination.  This results is some blow up the function declarations in
1143ff0cc061SDimitry Andric     // the IR, but removes the need for argument bitcasts which shrinks the IR
1144ff0cc061SDimitry Andric     // greatly and makes it much more readable.
1145ff0cc061SDimitry Andric     SmallVector<Type *, 1> Types;                 // one per 'any' type
1146ff0cc061SDimitry Andric     // All gc_relocate are set to i8 addrspace(1)* type. This could help avoid
1147ff0cc061SDimitry Andric     // cases where the actual value's type mangling is not supported by llvm. A
1148ff0cc061SDimitry Andric     // bitcast is added later to convert gc_relocate to the actual value's type.
1149ff0cc061SDimitry Andric     Types.push_back(Type::getInt8PtrTy(M->getContext(), 1));
1150ff0cc061SDimitry Andric     Value *GCRelocateDecl = Intrinsic::getDeclaration(
1151ff0cc061SDimitry Andric         M, Intrinsic::experimental_gc_relocate, Types);
1152ff0cc061SDimitry Andric 
1153ff0cc061SDimitry Andric     // Generate the gc.relocate call and save the result
1154ff0cc061SDimitry Andric     Value *BaseIdx =
1155ff0cc061SDimitry Andric         ConstantInt::get(Type::getInt32Ty(M->getContext()),
1156ff0cc061SDimitry Andric                          LiveStart + find_index(LiveVariables, BasePtrs[i]));
1157ff0cc061SDimitry Andric     Value *LiveIdx = ConstantInt::get(
1158ff0cc061SDimitry Andric         Type::getInt32Ty(M->getContext()),
1159ff0cc061SDimitry Andric         LiveStart + find_index(LiveVariables, LiveVariables[i]));
1160ff0cc061SDimitry Andric 
1161ff0cc061SDimitry Andric     // only specify a debug name if we can give a useful one
1162ff0cc061SDimitry Andric     Value *Reloc = Builder.CreateCall(
1163ff0cc061SDimitry Andric         GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1164ff0cc061SDimitry Andric         LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
1165ff0cc061SDimitry Andric                                     : "");
1166ff0cc061SDimitry Andric     // Trick CodeGen into thinking there are lots of free registers at this
1167ff0cc061SDimitry Andric     // fake call.
1168ff0cc061SDimitry Andric     cast<CallInst>(Reloc)->setCallingConv(CallingConv::Cold);
1169ff0cc061SDimitry Andric 
1170ff0cc061SDimitry Andric     NewDefs.push_back(cast<Instruction>(Reloc));
1171ff0cc061SDimitry Andric   }
1172ff0cc061SDimitry Andric   assert(NewDefs.size() == LiveVariables.size() &&
1173ff0cc061SDimitry Andric          "missing or extra redefinition at safepoint");
1174ff0cc061SDimitry Andric }
1175ff0cc061SDimitry Andric 
1176ff0cc061SDimitry Andric static void
1177ff0cc061SDimitry Andric makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1178ff0cc061SDimitry Andric                            const SmallVectorImpl<llvm::Value *> &basePtrs,
1179ff0cc061SDimitry Andric                            const SmallVectorImpl<llvm::Value *> &liveVariables,
1180ff0cc061SDimitry Andric                            Pass *P,
1181ff0cc061SDimitry Andric                            PartiallyConstructedSafepointRecord &result) {
1182ff0cc061SDimitry Andric   assert(basePtrs.size() == liveVariables.size());
1183ff0cc061SDimitry Andric   assert(isStatepoint(CS) &&
1184ff0cc061SDimitry Andric          "This method expects to be rewriting a statepoint");
1185ff0cc061SDimitry Andric 
1186ff0cc061SDimitry Andric   BasicBlock *BB = CS.getInstruction()->getParent();
1187ff0cc061SDimitry Andric   assert(BB);
1188ff0cc061SDimitry Andric   Function *F = BB->getParent();
1189ff0cc061SDimitry Andric   assert(F && "must be set");
1190ff0cc061SDimitry Andric   Module *M = F->getParent();
1191ff0cc061SDimitry Andric   (void)M;
1192ff0cc061SDimitry Andric   assert(M && "must be set");
1193ff0cc061SDimitry Andric 
1194ff0cc061SDimitry Andric   // We're not changing the function signature of the statepoint since the gc
1195ff0cc061SDimitry Andric   // arguments go into the var args section.
1196ff0cc061SDimitry Andric   Function *gc_statepoint_decl = CS.getCalledFunction();
1197ff0cc061SDimitry Andric 
1198ff0cc061SDimitry Andric   // Then go ahead and use the builder do actually do the inserts.  We insert
1199ff0cc061SDimitry Andric   // immediately before the previous instruction under the assumption that all
1200ff0cc061SDimitry Andric   // arguments will be available here.  We can't insert afterwards since we may
1201ff0cc061SDimitry Andric   // be replacing a terminator.
1202ff0cc061SDimitry Andric   Instruction *insertBefore = CS.getInstruction();
1203ff0cc061SDimitry Andric   IRBuilder<> Builder(insertBefore);
1204ff0cc061SDimitry Andric   // Copy all of the arguments from the original statepoint - this includes the
1205ff0cc061SDimitry Andric   // target, call args, and deopt args
1206ff0cc061SDimitry Andric   SmallVector<llvm::Value *, 64> args;
1207ff0cc061SDimitry Andric   args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1208ff0cc061SDimitry Andric   // TODO: Clear the 'needs rewrite' flag
1209ff0cc061SDimitry Andric 
1210ff0cc061SDimitry Andric   // add all the pointers to be relocated (gc arguments)
1211ff0cc061SDimitry Andric   // Capture the start of the live variable list for use in the gc_relocates
1212ff0cc061SDimitry Andric   const int live_start = args.size();
1213ff0cc061SDimitry Andric   args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1214ff0cc061SDimitry Andric 
1215ff0cc061SDimitry Andric   // Create the statepoint given all the arguments
1216ff0cc061SDimitry Andric   Instruction *token = nullptr;
1217ff0cc061SDimitry Andric   AttributeSet return_attributes;
1218ff0cc061SDimitry Andric   if (CS.isCall()) {
1219ff0cc061SDimitry Andric     CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1220ff0cc061SDimitry Andric     CallInst *call =
1221ff0cc061SDimitry Andric         Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1222ff0cc061SDimitry Andric     call->setTailCall(toReplace->isTailCall());
1223ff0cc061SDimitry Andric     call->setCallingConv(toReplace->getCallingConv());
1224ff0cc061SDimitry Andric 
1225ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1226ff0cc061SDimitry Andric     // function attributes.
1227ff0cc061SDimitry Andric     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1228ff0cc061SDimitry Andric     // In case if we can handle this set of sttributes - set up function attrs
1229ff0cc061SDimitry Andric     // directly on statepoint and return attrs later for gc_result intrinsic.
1230ff0cc061SDimitry Andric     call->setAttributes(new_attrs.getFnAttributes());
1231ff0cc061SDimitry Andric     return_attributes = new_attrs.getRetAttributes();
1232ff0cc061SDimitry Andric 
1233ff0cc061SDimitry Andric     token = call;
1234ff0cc061SDimitry Andric 
1235ff0cc061SDimitry Andric     // Put the following gc_result and gc_relocate calls immediately after the
1236ff0cc061SDimitry Andric     // the old call (which we're about to delete)
1237ff0cc061SDimitry Andric     BasicBlock::iterator next(toReplace);
1238ff0cc061SDimitry Andric     assert(BB->end() != next && "not a terminator, must have next");
1239ff0cc061SDimitry Andric     next++;
1240ff0cc061SDimitry Andric     Instruction *IP = &*(next);
1241ff0cc061SDimitry Andric     Builder.SetInsertPoint(IP);
1242ff0cc061SDimitry Andric     Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1243ff0cc061SDimitry Andric 
1244ff0cc061SDimitry Andric   } else {
1245ff0cc061SDimitry Andric     InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1246ff0cc061SDimitry Andric 
1247ff0cc061SDimitry Andric     // Insert the new invoke into the old block.  We'll remove the old one in a
1248ff0cc061SDimitry Andric     // moment at which point this will become the new terminator for the
1249ff0cc061SDimitry Andric     // original block.
1250ff0cc061SDimitry Andric     InvokeInst *invoke = InvokeInst::Create(
1251ff0cc061SDimitry Andric         gc_statepoint_decl, toReplace->getNormalDest(),
1252ff0cc061SDimitry Andric         toReplace->getUnwindDest(), args, "", toReplace->getParent());
1253ff0cc061SDimitry Andric     invoke->setCallingConv(toReplace->getCallingConv());
1254ff0cc061SDimitry Andric 
1255ff0cc061SDimitry Andric     // Currently we will fail on parameter attributes and on certain
1256ff0cc061SDimitry Andric     // function attributes.
1257ff0cc061SDimitry Andric     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1258ff0cc061SDimitry Andric     // In case if we can handle this set of sttributes - set up function attrs
1259ff0cc061SDimitry Andric     // directly on statepoint and return attrs later for gc_result intrinsic.
1260ff0cc061SDimitry Andric     invoke->setAttributes(new_attrs.getFnAttributes());
1261ff0cc061SDimitry Andric     return_attributes = new_attrs.getRetAttributes();
1262ff0cc061SDimitry Andric 
1263ff0cc061SDimitry Andric     token = invoke;
1264ff0cc061SDimitry Andric 
1265ff0cc061SDimitry Andric     // Generate gc relocates in exceptional path
1266ff0cc061SDimitry Andric     BasicBlock *unwindBlock = toReplace->getUnwindDest();
1267ff0cc061SDimitry Andric     assert(!isa<PHINode>(unwindBlock->begin()) &&
1268ff0cc061SDimitry Andric            unwindBlock->getUniquePredecessor() &&
1269ff0cc061SDimitry Andric            "can't safely insert in this block!");
1270ff0cc061SDimitry Andric 
1271ff0cc061SDimitry Andric     Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1272ff0cc061SDimitry Andric     Builder.SetInsertPoint(IP);
1273ff0cc061SDimitry Andric     Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1274ff0cc061SDimitry Andric 
1275ff0cc061SDimitry Andric     // Extract second element from landingpad return value. We will attach
1276ff0cc061SDimitry Andric     // exceptional gc relocates to it.
1277ff0cc061SDimitry Andric     const unsigned idx = 1;
1278ff0cc061SDimitry Andric     Instruction *exceptional_token =
1279ff0cc061SDimitry Andric         cast<Instruction>(Builder.CreateExtractValue(
1280ff0cc061SDimitry Andric             unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1281ff0cc061SDimitry Andric     result.UnwindToken = exceptional_token;
1282ff0cc061SDimitry Andric 
1283ff0cc061SDimitry Andric     // Just throw away return value. We will use the one we got for normal
1284ff0cc061SDimitry Andric     // block.
1285ff0cc061SDimitry Andric     (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1286ff0cc061SDimitry Andric                             exceptional_token, Builder);
1287ff0cc061SDimitry Andric 
1288ff0cc061SDimitry Andric     // Generate gc relocates and returns for normal block
1289ff0cc061SDimitry Andric     BasicBlock *normalDest = toReplace->getNormalDest();
1290ff0cc061SDimitry Andric     assert(!isa<PHINode>(normalDest->begin()) &&
1291ff0cc061SDimitry Andric            normalDest->getUniquePredecessor() &&
1292ff0cc061SDimitry Andric            "can't safely insert in this block!");
1293ff0cc061SDimitry Andric 
1294ff0cc061SDimitry Andric     IP = &*(normalDest->getFirstInsertionPt());
1295ff0cc061SDimitry Andric     Builder.SetInsertPoint(IP);
1296ff0cc061SDimitry Andric 
1297ff0cc061SDimitry Andric     // gc relocates will be generated later as if it were regular call
1298ff0cc061SDimitry Andric     // statepoint
1299ff0cc061SDimitry Andric   }
1300ff0cc061SDimitry Andric   assert(token);
1301ff0cc061SDimitry Andric 
1302ff0cc061SDimitry Andric   // Take the name of the original value call if it had one.
1303ff0cc061SDimitry Andric   token->takeName(CS.getInstruction());
1304ff0cc061SDimitry Andric 
1305ff0cc061SDimitry Andric // The GCResult is already inserted, we just need to find it
1306ff0cc061SDimitry Andric #ifndef NDEBUG
1307ff0cc061SDimitry Andric   Instruction *toReplace = CS.getInstruction();
1308ff0cc061SDimitry Andric   assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1309ff0cc061SDimitry Andric          "only valid use before rewrite is gc.result");
1310ff0cc061SDimitry Andric   assert(!toReplace->hasOneUse() ||
1311ff0cc061SDimitry Andric          isGCResult(cast<Instruction>(*toReplace->user_begin())));
1312ff0cc061SDimitry Andric #endif
1313ff0cc061SDimitry Andric 
1314ff0cc061SDimitry Andric   // Update the gc.result of the original statepoint (if any) to use the newly
1315ff0cc061SDimitry Andric   // inserted statepoint.  This is safe to do here since the token can't be
1316ff0cc061SDimitry Andric   // considered a live reference.
1317ff0cc061SDimitry Andric   CS.getInstruction()->replaceAllUsesWith(token);
1318ff0cc061SDimitry Andric 
1319ff0cc061SDimitry Andric   result.StatepointToken = token;
1320ff0cc061SDimitry Andric 
1321ff0cc061SDimitry Andric   // Second, create a gc.relocate for every live variable
1322ff0cc061SDimitry Andric   CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1323ff0cc061SDimitry Andric }
1324ff0cc061SDimitry Andric 
1325ff0cc061SDimitry Andric namespace {
1326ff0cc061SDimitry Andric struct name_ordering {
1327ff0cc061SDimitry Andric   Value *base;
1328ff0cc061SDimitry Andric   Value *derived;
1329ff0cc061SDimitry Andric   bool operator()(name_ordering const &a, name_ordering const &b) {
1330ff0cc061SDimitry Andric     return -1 == a.derived->getName().compare(b.derived->getName());
1331ff0cc061SDimitry Andric   }
1332ff0cc061SDimitry Andric };
1333ff0cc061SDimitry Andric }
1334ff0cc061SDimitry Andric static void stablize_order(SmallVectorImpl<Value *> &basevec,
1335ff0cc061SDimitry Andric                            SmallVectorImpl<Value *> &livevec) {
1336ff0cc061SDimitry Andric   assert(basevec.size() == livevec.size());
1337ff0cc061SDimitry Andric 
1338ff0cc061SDimitry Andric   SmallVector<name_ordering, 64> temp;
1339ff0cc061SDimitry Andric   for (size_t i = 0; i < basevec.size(); i++) {
1340ff0cc061SDimitry Andric     name_ordering v;
1341ff0cc061SDimitry Andric     v.base = basevec[i];
1342ff0cc061SDimitry Andric     v.derived = livevec[i];
1343ff0cc061SDimitry Andric     temp.push_back(v);
1344ff0cc061SDimitry Andric   }
1345ff0cc061SDimitry Andric   std::sort(temp.begin(), temp.end(), name_ordering());
1346ff0cc061SDimitry Andric   for (size_t i = 0; i < basevec.size(); i++) {
1347ff0cc061SDimitry Andric     basevec[i] = temp[i].base;
1348ff0cc061SDimitry Andric     livevec[i] = temp[i].derived;
1349ff0cc061SDimitry Andric   }
1350ff0cc061SDimitry Andric }
1351ff0cc061SDimitry Andric 
1352ff0cc061SDimitry Andric // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1353ff0cc061SDimitry Andric // which make the relocations happening at this safepoint explicit.
1354ff0cc061SDimitry Andric //
1355ff0cc061SDimitry Andric // WARNING: Does not do any fixup to adjust users of the original live
1356ff0cc061SDimitry Andric // values.  That's the callers responsibility.
1357ff0cc061SDimitry Andric static void
1358ff0cc061SDimitry Andric makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1359ff0cc061SDimitry Andric                        PartiallyConstructedSafepointRecord &result) {
1360ff0cc061SDimitry Andric   auto liveset = result.liveset;
1361ff0cc061SDimitry Andric   auto PointerToBase = result.PointerToBase;
1362ff0cc061SDimitry Andric 
1363ff0cc061SDimitry Andric   // Convert to vector for efficient cross referencing.
1364ff0cc061SDimitry Andric   SmallVector<Value *, 64> basevec, livevec;
1365ff0cc061SDimitry Andric   livevec.reserve(liveset.size());
1366ff0cc061SDimitry Andric   basevec.reserve(liveset.size());
1367ff0cc061SDimitry Andric   for (Value *L : liveset) {
1368ff0cc061SDimitry Andric     livevec.push_back(L);
1369ff0cc061SDimitry Andric 
1370ff0cc061SDimitry Andric     assert(PointerToBase.find(L) != PointerToBase.end());
1371ff0cc061SDimitry Andric     Value *base = PointerToBase[L];
1372ff0cc061SDimitry Andric     basevec.push_back(base);
1373ff0cc061SDimitry Andric   }
1374ff0cc061SDimitry Andric   assert(livevec.size() == basevec.size());
1375ff0cc061SDimitry Andric 
1376ff0cc061SDimitry Andric   // To make the output IR slightly more stable (for use in diffs), ensure a
1377ff0cc061SDimitry Andric   // fixed order of the values in the safepoint (by sorting the value name).
1378ff0cc061SDimitry Andric   // The order is otherwise meaningless.
1379ff0cc061SDimitry Andric   stablize_order(basevec, livevec);
1380ff0cc061SDimitry Andric 
1381ff0cc061SDimitry Andric   // Do the actual rewriting and delete the old statepoint
1382ff0cc061SDimitry Andric   makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1383ff0cc061SDimitry Andric   CS.getInstruction()->eraseFromParent();
1384ff0cc061SDimitry Andric }
1385ff0cc061SDimitry Andric 
1386ff0cc061SDimitry Andric // Helper function for the relocationViaAlloca.
1387ff0cc061SDimitry Andric // It receives iterator to the statepoint gc relocates and emits store to the
1388ff0cc061SDimitry Andric // assigned
1389ff0cc061SDimitry Andric // location (via allocaMap) for the each one of them.
1390ff0cc061SDimitry Andric // Add visited values into the visitedLiveValues set we will later use them
1391ff0cc061SDimitry Andric // for sanity check.
1392ff0cc061SDimitry Andric static void
1393ff0cc061SDimitry Andric insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1394ff0cc061SDimitry Andric                        DenseMap<Value *, Value *> &AllocaMap,
1395ff0cc061SDimitry Andric                        DenseSet<Value *> &VisitedLiveValues) {
1396ff0cc061SDimitry Andric 
1397ff0cc061SDimitry Andric   for (User *U : GCRelocs) {
1398ff0cc061SDimitry Andric     if (!isa<IntrinsicInst>(U))
1399ff0cc061SDimitry Andric       continue;
1400ff0cc061SDimitry Andric 
1401ff0cc061SDimitry Andric     IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
1402ff0cc061SDimitry Andric 
1403ff0cc061SDimitry Andric     // We only care about relocates
1404ff0cc061SDimitry Andric     if (RelocatedValue->getIntrinsicID() !=
1405ff0cc061SDimitry Andric         Intrinsic::experimental_gc_relocate) {
1406ff0cc061SDimitry Andric       continue;
1407ff0cc061SDimitry Andric     }
1408ff0cc061SDimitry Andric 
1409ff0cc061SDimitry Andric     GCRelocateOperands RelocateOperands(RelocatedValue);
1410ff0cc061SDimitry Andric     Value *OriginalValue =
1411ff0cc061SDimitry Andric         const_cast<Value *>(RelocateOperands.getDerivedPtr());
1412ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue));
1413ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1414ff0cc061SDimitry Andric 
1415ff0cc061SDimitry Andric     // Emit store into the related alloca
1416ff0cc061SDimitry Andric     // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1417ff0cc061SDimitry Andric     // the correct type according to alloca.
1418ff0cc061SDimitry Andric     assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1419ff0cc061SDimitry Andric     IRBuilder<> Builder(RelocatedValue->getNextNode());
1420ff0cc061SDimitry Andric     Value *CastedRelocatedValue =
1421ff0cc061SDimitry Andric         Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1422ff0cc061SDimitry Andric         RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
1423ff0cc061SDimitry Andric 
1424ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1425ff0cc061SDimitry Andric     Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1426ff0cc061SDimitry Andric 
1427ff0cc061SDimitry Andric #ifndef NDEBUG
1428ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1429ff0cc061SDimitry Andric #endif
1430ff0cc061SDimitry Andric   }
1431ff0cc061SDimitry Andric }
1432ff0cc061SDimitry Andric 
1433ff0cc061SDimitry Andric // Helper function for the "relocationViaAlloca". Similar to the
1434ff0cc061SDimitry Andric // "insertRelocationStores" but works for rematerialized values.
1435ff0cc061SDimitry Andric static void
1436ff0cc061SDimitry Andric insertRematerializationStores(
1437ff0cc061SDimitry Andric   RematerializedValueMapTy RematerializedValues,
1438ff0cc061SDimitry Andric   DenseMap<Value *, Value *> &AllocaMap,
1439ff0cc061SDimitry Andric   DenseSet<Value *> &VisitedLiveValues) {
1440ff0cc061SDimitry Andric 
1441ff0cc061SDimitry Andric   for (auto RematerializedValuePair: RematerializedValues) {
1442ff0cc061SDimitry Andric     Instruction *RematerializedValue = RematerializedValuePair.first;
1443ff0cc061SDimitry Andric     Value *OriginalValue = RematerializedValuePair.second;
1444ff0cc061SDimitry Andric 
1445ff0cc061SDimitry Andric     assert(AllocaMap.count(OriginalValue) &&
1446ff0cc061SDimitry Andric            "Can not find alloca for rematerialized value");
1447ff0cc061SDimitry Andric     Value *Alloca = AllocaMap[OriginalValue];
1448ff0cc061SDimitry Andric 
1449ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1450ff0cc061SDimitry Andric     Store->insertAfter(RematerializedValue);
1451ff0cc061SDimitry Andric 
1452ff0cc061SDimitry Andric #ifndef NDEBUG
1453ff0cc061SDimitry Andric     VisitedLiveValues.insert(OriginalValue);
1454ff0cc061SDimitry Andric #endif
1455ff0cc061SDimitry Andric   }
1456ff0cc061SDimitry Andric }
1457ff0cc061SDimitry Andric 
1458ff0cc061SDimitry Andric /// do all the relocation update via allocas and mem2reg
1459ff0cc061SDimitry Andric static void relocationViaAlloca(
1460ff0cc061SDimitry Andric     Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1461ff0cc061SDimitry Andric     ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
1462ff0cc061SDimitry Andric #ifndef NDEBUG
1463ff0cc061SDimitry Andric   // record initial number of (static) allocas; we'll check we have the same
1464ff0cc061SDimitry Andric   // number when we get done.
1465ff0cc061SDimitry Andric   int InitialAllocaNum = 0;
1466ff0cc061SDimitry Andric   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1467ff0cc061SDimitry Andric        I++)
1468ff0cc061SDimitry Andric     if (isa<AllocaInst>(*I))
1469ff0cc061SDimitry Andric       InitialAllocaNum++;
1470ff0cc061SDimitry Andric #endif
1471ff0cc061SDimitry Andric 
1472ff0cc061SDimitry Andric   // TODO-PERF: change data structures, reserve
1473ff0cc061SDimitry Andric   DenseMap<Value *, Value *> AllocaMap;
1474ff0cc061SDimitry Andric   SmallVector<AllocaInst *, 200> PromotableAllocas;
1475ff0cc061SDimitry Andric   // Used later to chack that we have enough allocas to store all values
1476ff0cc061SDimitry Andric   std::size_t NumRematerializedValues = 0;
1477ff0cc061SDimitry Andric   PromotableAllocas.reserve(Live.size());
1478ff0cc061SDimitry Andric 
1479ff0cc061SDimitry Andric   // Emit alloca for "LiveValue" and record it in "allocaMap" and
1480ff0cc061SDimitry Andric   // "PromotableAllocas"
1481ff0cc061SDimitry Andric   auto emitAllocaFor = [&](Value *LiveValue) {
1482ff0cc061SDimitry Andric     AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1483ff0cc061SDimitry Andric                                         F.getEntryBlock().getFirstNonPHI());
1484ff0cc061SDimitry Andric     AllocaMap[LiveValue] = Alloca;
1485ff0cc061SDimitry Andric     PromotableAllocas.push_back(Alloca);
1486ff0cc061SDimitry Andric   };
1487ff0cc061SDimitry Andric 
1488ff0cc061SDimitry Andric   // emit alloca for each live gc pointer
1489ff0cc061SDimitry Andric   for (unsigned i = 0; i < Live.size(); i++) {
1490ff0cc061SDimitry Andric     emitAllocaFor(Live[i]);
1491ff0cc061SDimitry Andric   }
1492ff0cc061SDimitry Andric 
1493ff0cc061SDimitry Andric   // emit allocas for rematerialized values
1494ff0cc061SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
1495ff0cc061SDimitry Andric     const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1496ff0cc061SDimitry Andric 
1497ff0cc061SDimitry Andric     for (auto RematerializedValuePair : Info.RematerializedValues) {
1498ff0cc061SDimitry Andric       Value *OriginalValue = RematerializedValuePair.second;
1499ff0cc061SDimitry Andric       if (AllocaMap.count(OriginalValue) != 0)
1500ff0cc061SDimitry Andric         continue;
1501ff0cc061SDimitry Andric 
1502ff0cc061SDimitry Andric       emitAllocaFor(OriginalValue);
1503ff0cc061SDimitry Andric       ++NumRematerializedValues;
1504ff0cc061SDimitry Andric     }
1505ff0cc061SDimitry Andric   }
1506ff0cc061SDimitry Andric 
1507ff0cc061SDimitry Andric   // The next two loops are part of the same conceptual operation.  We need to
1508ff0cc061SDimitry Andric   // insert a store to the alloca after the original def and at each
1509ff0cc061SDimitry Andric   // redefinition.  We need to insert a load before each use.  These are split
1510ff0cc061SDimitry Andric   // into distinct loops for performance reasons.
1511ff0cc061SDimitry Andric 
1512ff0cc061SDimitry Andric   // update gc pointer after each statepoint
1513ff0cc061SDimitry Andric   // either store a relocated value or null (if no relocated value found for
1514ff0cc061SDimitry Andric   // this gc pointer and it is not a gc_result)
1515ff0cc061SDimitry Andric   // this must happen before we update the statepoint with load of alloca
1516ff0cc061SDimitry Andric   // otherwise we lose the link between statepoint and old def
1517ff0cc061SDimitry Andric   for (size_t i = 0; i < Records.size(); i++) {
1518ff0cc061SDimitry Andric     const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1519ff0cc061SDimitry Andric     Value *Statepoint = Info.StatepointToken;
1520ff0cc061SDimitry Andric 
1521ff0cc061SDimitry Andric     // This will be used for consistency check
1522ff0cc061SDimitry Andric     DenseSet<Value *> VisitedLiveValues;
1523ff0cc061SDimitry Andric 
1524ff0cc061SDimitry Andric     // Insert stores for normal statepoint gc relocates
1525ff0cc061SDimitry Andric     insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1526ff0cc061SDimitry Andric 
1527ff0cc061SDimitry Andric     // In case if it was invoke statepoint
1528ff0cc061SDimitry Andric     // we will insert stores for exceptional path gc relocates.
1529ff0cc061SDimitry Andric     if (isa<InvokeInst>(Statepoint)) {
1530ff0cc061SDimitry Andric       insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1531ff0cc061SDimitry Andric                              VisitedLiveValues);
1532ff0cc061SDimitry Andric     }
1533ff0cc061SDimitry Andric 
1534ff0cc061SDimitry Andric     // Do similar thing with rematerialized values
1535ff0cc061SDimitry Andric     insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1536ff0cc061SDimitry Andric                                   VisitedLiveValues);
1537ff0cc061SDimitry Andric 
1538ff0cc061SDimitry Andric     if (ClobberNonLive) {
1539ff0cc061SDimitry Andric       // As a debuging aid, pretend that an unrelocated pointer becomes null at
1540ff0cc061SDimitry Andric       // the gc.statepoint.  This will turn some subtle GC problems into
1541ff0cc061SDimitry Andric       // slightly easier to debug SEGVs.  Note that on large IR files with
1542ff0cc061SDimitry Andric       // lots of gc.statepoints this is extremely costly both memory and time
1543ff0cc061SDimitry Andric       // wise.
1544ff0cc061SDimitry Andric       SmallVector<AllocaInst *, 64> ToClobber;
1545ff0cc061SDimitry Andric       for (auto Pair : AllocaMap) {
1546ff0cc061SDimitry Andric         Value *Def = Pair.first;
1547ff0cc061SDimitry Andric         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1548ff0cc061SDimitry Andric 
1549ff0cc061SDimitry Andric         // This value was relocated
1550ff0cc061SDimitry Andric         if (VisitedLiveValues.count(Def)) {
1551ff0cc061SDimitry Andric           continue;
1552ff0cc061SDimitry Andric         }
1553ff0cc061SDimitry Andric         ToClobber.push_back(Alloca);
1554ff0cc061SDimitry Andric       }
1555ff0cc061SDimitry Andric 
1556ff0cc061SDimitry Andric       auto InsertClobbersAt = [&](Instruction *IP) {
1557ff0cc061SDimitry Andric         for (auto *AI : ToClobber) {
1558ff0cc061SDimitry Andric           auto AIType = cast<PointerType>(AI->getType());
1559ff0cc061SDimitry Andric           auto PT = cast<PointerType>(AIType->getElementType());
1560ff0cc061SDimitry Andric           Constant *CPN = ConstantPointerNull::get(PT);
1561ff0cc061SDimitry Andric           StoreInst *Store = new StoreInst(CPN, AI);
1562ff0cc061SDimitry Andric           Store->insertBefore(IP);
1563ff0cc061SDimitry Andric         }
1564ff0cc061SDimitry Andric       };
1565ff0cc061SDimitry Andric 
1566ff0cc061SDimitry Andric       // Insert the clobbering stores.  These may get intermixed with the
1567ff0cc061SDimitry Andric       // gc.results and gc.relocates, but that's fine.
1568ff0cc061SDimitry Andric       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1569ff0cc061SDimitry Andric         InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1570ff0cc061SDimitry Andric         InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1571ff0cc061SDimitry Andric       } else {
1572ff0cc061SDimitry Andric         BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1573ff0cc061SDimitry Andric         Next++;
1574ff0cc061SDimitry Andric         InsertClobbersAt(Next);
1575ff0cc061SDimitry Andric       }
1576ff0cc061SDimitry Andric     }
1577ff0cc061SDimitry Andric   }
1578ff0cc061SDimitry Andric   // update use with load allocas and add store for gc_relocated
1579ff0cc061SDimitry Andric   for (auto Pair : AllocaMap) {
1580ff0cc061SDimitry Andric     Value *Def = Pair.first;
1581ff0cc061SDimitry Andric     Value *Alloca = Pair.second;
1582ff0cc061SDimitry Andric 
1583ff0cc061SDimitry Andric     // we pre-record the uses of allocas so that we dont have to worry about
1584ff0cc061SDimitry Andric     // later update
1585ff0cc061SDimitry Andric     // that change the user information.
1586ff0cc061SDimitry Andric     SmallVector<Instruction *, 20> Uses;
1587ff0cc061SDimitry Andric     // PERF: trade a linear scan for repeated reallocation
1588ff0cc061SDimitry Andric     Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1589ff0cc061SDimitry Andric     for (User *U : Def->users()) {
1590ff0cc061SDimitry Andric       if (!isa<ConstantExpr>(U)) {
1591ff0cc061SDimitry Andric         // If the def has a ConstantExpr use, then the def is either a
1592ff0cc061SDimitry Andric         // ConstantExpr use itself or null.  In either case
1593ff0cc061SDimitry Andric         // (recursively in the first, directly in the second), the oop
1594ff0cc061SDimitry Andric         // it is ultimately dependent on is null and this particular
1595ff0cc061SDimitry Andric         // use does not need to be fixed up.
1596ff0cc061SDimitry Andric         Uses.push_back(cast<Instruction>(U));
1597ff0cc061SDimitry Andric       }
1598ff0cc061SDimitry Andric     }
1599ff0cc061SDimitry Andric 
1600ff0cc061SDimitry Andric     std::sort(Uses.begin(), Uses.end());
1601ff0cc061SDimitry Andric     auto Last = std::unique(Uses.begin(), Uses.end());
1602ff0cc061SDimitry Andric     Uses.erase(Last, Uses.end());
1603ff0cc061SDimitry Andric 
1604ff0cc061SDimitry Andric     for (Instruction *Use : Uses) {
1605ff0cc061SDimitry Andric       if (isa<PHINode>(Use)) {
1606ff0cc061SDimitry Andric         PHINode *Phi = cast<PHINode>(Use);
1607ff0cc061SDimitry Andric         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1608ff0cc061SDimitry Andric           if (Def == Phi->getIncomingValue(i)) {
1609ff0cc061SDimitry Andric             LoadInst *Load = new LoadInst(
1610ff0cc061SDimitry Andric                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1611ff0cc061SDimitry Andric             Phi->setIncomingValue(i, Load);
1612ff0cc061SDimitry Andric           }
1613ff0cc061SDimitry Andric         }
1614ff0cc061SDimitry Andric       } else {
1615ff0cc061SDimitry Andric         LoadInst *Load = new LoadInst(Alloca, "", Use);
1616ff0cc061SDimitry Andric         Use->replaceUsesOfWith(Def, Load);
1617ff0cc061SDimitry Andric       }
1618ff0cc061SDimitry Andric     }
1619ff0cc061SDimitry Andric 
1620ff0cc061SDimitry Andric     // emit store for the initial gc value
1621ff0cc061SDimitry Andric     // store must be inserted after load, otherwise store will be in alloca's
1622ff0cc061SDimitry Andric     // use list and an extra load will be inserted before it
1623ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(Def, Alloca);
1624ff0cc061SDimitry Andric     if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1625ff0cc061SDimitry Andric       if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1626ff0cc061SDimitry Andric         // InvokeInst is a TerminatorInst so the store need to be inserted
1627ff0cc061SDimitry Andric         // into its normal destination block.
1628ff0cc061SDimitry Andric         BasicBlock *NormalDest = Invoke->getNormalDest();
1629ff0cc061SDimitry Andric         Store->insertBefore(NormalDest->getFirstNonPHI());
1630ff0cc061SDimitry Andric       } else {
1631ff0cc061SDimitry Andric         assert(!Inst->isTerminator() &&
1632ff0cc061SDimitry Andric                "The only TerminatorInst that can produce a value is "
1633ff0cc061SDimitry Andric                "InvokeInst which is handled above.");
1634ff0cc061SDimitry Andric         Store->insertAfter(Inst);
1635ff0cc061SDimitry Andric       }
1636ff0cc061SDimitry Andric     } else {
1637ff0cc061SDimitry Andric       assert(isa<Argument>(Def));
1638ff0cc061SDimitry Andric       Store->insertAfter(cast<Instruction>(Alloca));
1639ff0cc061SDimitry Andric     }
1640ff0cc061SDimitry Andric   }
1641ff0cc061SDimitry Andric 
1642ff0cc061SDimitry Andric   assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1643ff0cc061SDimitry Andric          "we must have the same allocas with lives");
1644ff0cc061SDimitry Andric   if (!PromotableAllocas.empty()) {
1645ff0cc061SDimitry Andric     // apply mem2reg to promote alloca to SSA
1646ff0cc061SDimitry Andric     PromoteMemToReg(PromotableAllocas, DT);
1647ff0cc061SDimitry Andric   }
1648ff0cc061SDimitry Andric 
1649ff0cc061SDimitry Andric #ifndef NDEBUG
1650ff0cc061SDimitry Andric   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1651ff0cc061SDimitry Andric        I++)
1652ff0cc061SDimitry Andric     if (isa<AllocaInst>(*I))
1653ff0cc061SDimitry Andric       InitialAllocaNum--;
1654ff0cc061SDimitry Andric   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1655ff0cc061SDimitry Andric #endif
1656ff0cc061SDimitry Andric }
1657ff0cc061SDimitry Andric 
1658ff0cc061SDimitry Andric /// Implement a unique function which doesn't require we sort the input
1659ff0cc061SDimitry Andric /// vector.  Doing so has the effect of changing the output of a couple of
1660ff0cc061SDimitry Andric /// tests in ways which make them less useful in testing fused safepoints.
1661ff0cc061SDimitry Andric template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
16628f0fd8f6SDimitry Andric   SmallSet<T, 8> Seen;
16638f0fd8f6SDimitry Andric   Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
16648f0fd8f6SDimitry Andric               return !Seen.insert(V).second;
16658f0fd8f6SDimitry Andric             }), Vec.end());
1666ff0cc061SDimitry Andric }
1667ff0cc061SDimitry Andric 
1668ff0cc061SDimitry Andric /// Insert holders so that each Value is obviously live through the entire
1669ff0cc061SDimitry Andric /// lifetime of the call.
1670ff0cc061SDimitry Andric static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1671ff0cc061SDimitry Andric                                  SmallVectorImpl<CallInst *> &Holders) {
1672ff0cc061SDimitry Andric   if (Values.empty())
1673ff0cc061SDimitry Andric     // No values to hold live, might as well not insert the empty holder
1674ff0cc061SDimitry Andric     return;
1675ff0cc061SDimitry Andric 
1676ff0cc061SDimitry Andric   Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1677ff0cc061SDimitry Andric   // Use a dummy vararg function to actually hold the values live
1678ff0cc061SDimitry Andric   Function *Func = cast<Function>(M->getOrInsertFunction(
1679ff0cc061SDimitry Andric       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1680ff0cc061SDimitry Andric   if (CS.isCall()) {
1681ff0cc061SDimitry Andric     // For call safepoints insert dummy calls right after safepoint
1682ff0cc061SDimitry Andric     BasicBlock::iterator Next(CS.getInstruction());
1683ff0cc061SDimitry Andric     Next++;
1684ff0cc061SDimitry Andric     Holders.push_back(CallInst::Create(Func, Values, "", Next));
1685ff0cc061SDimitry Andric     return;
1686ff0cc061SDimitry Andric   }
1687ff0cc061SDimitry Andric   // For invoke safepooints insert dummy calls both in normal and
1688ff0cc061SDimitry Andric   // exceptional destination blocks
1689ff0cc061SDimitry Andric   auto *II = cast<InvokeInst>(CS.getInstruction());
1690ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
1691ff0cc061SDimitry Andric       Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1692ff0cc061SDimitry Andric   Holders.push_back(CallInst::Create(
1693ff0cc061SDimitry Andric       Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
1694ff0cc061SDimitry Andric }
1695ff0cc061SDimitry Andric 
1696ff0cc061SDimitry Andric static void findLiveReferences(
1697ff0cc061SDimitry Andric     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1698ff0cc061SDimitry Andric     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1699ff0cc061SDimitry Andric   GCPtrLivenessData OriginalLivenessData;
1700ff0cc061SDimitry Andric   computeLiveInValues(DT, F, OriginalLivenessData);
1701ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
1702ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
1703ff0cc061SDimitry Andric     const CallSite &CS = toUpdate[i];
1704ff0cc061SDimitry Andric     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1705ff0cc061SDimitry Andric   }
1706ff0cc061SDimitry Andric }
1707ff0cc061SDimitry Andric 
1708ff0cc061SDimitry Andric /// Remove any vector of pointers from the liveset by scalarizing them over the
1709ff0cc061SDimitry Andric /// statepoint instruction.  Adds the scalarized pieces to the liveset.  It
1710ff0cc061SDimitry Andric /// would be preferrable to include the vector in the statepoint itself, but
1711ff0cc061SDimitry Andric /// the lowering code currently does not handle that.  Extending it would be
1712ff0cc061SDimitry Andric /// slightly non-trivial since it requires a format change.  Given how rare
1713ff0cc061SDimitry Andric /// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1714ff0cc061SDimitry Andric static void splitVectorValues(Instruction *StatepointInst,
1715ff0cc061SDimitry Andric                               StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
1716ff0cc061SDimitry Andric   SmallVector<Value *, 16> ToSplit;
1717ff0cc061SDimitry Andric   for (Value *V : LiveSet)
1718ff0cc061SDimitry Andric     if (isa<VectorType>(V->getType()))
1719ff0cc061SDimitry Andric       ToSplit.push_back(V);
1720ff0cc061SDimitry Andric 
1721ff0cc061SDimitry Andric   if (ToSplit.empty())
1722ff0cc061SDimitry Andric     return;
1723ff0cc061SDimitry Andric 
1724ff0cc061SDimitry Andric   Function &F = *(StatepointInst->getParent()->getParent());
1725ff0cc061SDimitry Andric 
1726ff0cc061SDimitry Andric   DenseMap<Value *, AllocaInst *> AllocaMap;
1727ff0cc061SDimitry Andric   // First is normal return, second is exceptional return (invoke only)
1728ff0cc061SDimitry Andric   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1729ff0cc061SDimitry Andric   for (Value *V : ToSplit) {
1730ff0cc061SDimitry Andric     LiveSet.erase(V);
1731ff0cc061SDimitry Andric 
1732ff0cc061SDimitry Andric     AllocaInst *Alloca =
1733ff0cc061SDimitry Andric         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1734ff0cc061SDimitry Andric     AllocaMap[V] = Alloca;
1735ff0cc061SDimitry Andric 
1736ff0cc061SDimitry Andric     VectorType *VT = cast<VectorType>(V->getType());
1737ff0cc061SDimitry Andric     IRBuilder<> Builder(StatepointInst);
1738ff0cc061SDimitry Andric     SmallVector<Value *, 16> Elements;
1739ff0cc061SDimitry Andric     for (unsigned i = 0; i < VT->getNumElements(); i++)
1740ff0cc061SDimitry Andric       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1741ff0cc061SDimitry Andric     LiveSet.insert(Elements.begin(), Elements.end());
1742ff0cc061SDimitry Andric 
1743ff0cc061SDimitry Andric     auto InsertVectorReform = [&](Instruction *IP) {
1744ff0cc061SDimitry Andric       Builder.SetInsertPoint(IP);
1745ff0cc061SDimitry Andric       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1746ff0cc061SDimitry Andric       Value *ResultVec = UndefValue::get(VT);
1747ff0cc061SDimitry Andric       for (unsigned i = 0; i < VT->getNumElements(); i++)
1748ff0cc061SDimitry Andric         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1749ff0cc061SDimitry Andric                                                 Builder.getInt32(i));
1750ff0cc061SDimitry Andric       return ResultVec;
1751ff0cc061SDimitry Andric     };
1752ff0cc061SDimitry Andric 
1753ff0cc061SDimitry Andric     if (isa<CallInst>(StatepointInst)) {
1754ff0cc061SDimitry Andric       BasicBlock::iterator Next(StatepointInst);
1755ff0cc061SDimitry Andric       Next++;
1756ff0cc061SDimitry Andric       Instruction *IP = &*(Next);
1757ff0cc061SDimitry Andric       Replacements[V].first = InsertVectorReform(IP);
1758ff0cc061SDimitry Andric       Replacements[V].second = nullptr;
1759ff0cc061SDimitry Andric     } else {
1760ff0cc061SDimitry Andric       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1761ff0cc061SDimitry Andric       // We've already normalized - check that we don't have shared destination
1762ff0cc061SDimitry Andric       // blocks
1763ff0cc061SDimitry Andric       BasicBlock *NormalDest = Invoke->getNormalDest();
1764ff0cc061SDimitry Andric       assert(!isa<PHINode>(NormalDest->begin()));
1765ff0cc061SDimitry Andric       BasicBlock *UnwindDest = Invoke->getUnwindDest();
1766ff0cc061SDimitry Andric       assert(!isa<PHINode>(UnwindDest->begin()));
1767ff0cc061SDimitry Andric       // Insert insert element sequences in both successors
1768ff0cc061SDimitry Andric       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1769ff0cc061SDimitry Andric       Replacements[V].first = InsertVectorReform(IP);
1770ff0cc061SDimitry Andric       IP = &*(UnwindDest->getFirstInsertionPt());
1771ff0cc061SDimitry Andric       Replacements[V].second = InsertVectorReform(IP);
1772ff0cc061SDimitry Andric     }
1773ff0cc061SDimitry Andric   }
1774ff0cc061SDimitry Andric   for (Value *V : ToSplit) {
1775ff0cc061SDimitry Andric     AllocaInst *Alloca = AllocaMap[V];
1776ff0cc061SDimitry Andric 
1777ff0cc061SDimitry Andric     // Capture all users before we start mutating use lists
1778ff0cc061SDimitry Andric     SmallVector<Instruction *, 16> Users;
1779ff0cc061SDimitry Andric     for (User *U : V->users())
1780ff0cc061SDimitry Andric       Users.push_back(cast<Instruction>(U));
1781ff0cc061SDimitry Andric 
1782ff0cc061SDimitry Andric     for (Instruction *I : Users) {
1783ff0cc061SDimitry Andric       if (auto Phi = dyn_cast<PHINode>(I)) {
1784ff0cc061SDimitry Andric         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1785ff0cc061SDimitry Andric           if (V == Phi->getIncomingValue(i)) {
1786ff0cc061SDimitry Andric             LoadInst *Load = new LoadInst(
1787ff0cc061SDimitry Andric                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1788ff0cc061SDimitry Andric             Phi->setIncomingValue(i, Load);
1789ff0cc061SDimitry Andric           }
1790ff0cc061SDimitry Andric       } else {
1791ff0cc061SDimitry Andric         LoadInst *Load = new LoadInst(Alloca, "", I);
1792ff0cc061SDimitry Andric         I->replaceUsesOfWith(V, Load);
1793ff0cc061SDimitry Andric       }
1794ff0cc061SDimitry Andric     }
1795ff0cc061SDimitry Andric 
1796ff0cc061SDimitry Andric     // Store the original value and the replacement value into the alloca
1797ff0cc061SDimitry Andric     StoreInst *Store = new StoreInst(V, Alloca);
1798ff0cc061SDimitry Andric     if (auto I = dyn_cast<Instruction>(V))
1799ff0cc061SDimitry Andric       Store->insertAfter(I);
1800ff0cc061SDimitry Andric     else
1801ff0cc061SDimitry Andric       Store->insertAfter(Alloca);
1802ff0cc061SDimitry Andric 
1803ff0cc061SDimitry Andric     // Normal return for invoke, or call return
1804ff0cc061SDimitry Andric     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1805ff0cc061SDimitry Andric     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1806ff0cc061SDimitry Andric     // Unwind return for invoke only
1807ff0cc061SDimitry Andric     Replacement = cast_or_null<Instruction>(Replacements[V].second);
1808ff0cc061SDimitry Andric     if (Replacement)
1809ff0cc061SDimitry Andric       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1810ff0cc061SDimitry Andric   }
1811ff0cc061SDimitry Andric 
1812ff0cc061SDimitry Andric   // apply mem2reg to promote alloca to SSA
1813ff0cc061SDimitry Andric   SmallVector<AllocaInst *, 16> Allocas;
1814ff0cc061SDimitry Andric   for (Value *V : ToSplit)
1815ff0cc061SDimitry Andric     Allocas.push_back(AllocaMap[V]);
1816ff0cc061SDimitry Andric   PromoteMemToReg(Allocas, DT);
1817ff0cc061SDimitry Andric }
1818ff0cc061SDimitry Andric 
1819ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". It walks use chain
1820ff0cc061SDimitry Andric // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1821ff0cc061SDimitry Andric // values are visited (currently it is GEP's and casts). Returns true if it
1822ff0cc061SDimitry Andric // sucessfully reached "BaseValue" and false otherwise.
1823ff0cc061SDimitry Andric // Fills "ChainToBase" array with all visited values. "BaseValue" is not
1824ff0cc061SDimitry Andric // recorded.
1825ff0cc061SDimitry Andric static bool findRematerializableChainToBasePointer(
1826ff0cc061SDimitry Andric   SmallVectorImpl<Instruction*> &ChainToBase,
1827ff0cc061SDimitry Andric   Value *CurrentValue, Value *BaseValue) {
1828ff0cc061SDimitry Andric 
1829ff0cc061SDimitry Andric   // We have found a base value
1830ff0cc061SDimitry Andric   if (CurrentValue == BaseValue) {
1831ff0cc061SDimitry Andric     return true;
1832ff0cc061SDimitry Andric   }
1833ff0cc061SDimitry Andric 
1834ff0cc061SDimitry Andric   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1835ff0cc061SDimitry Andric     ChainToBase.push_back(GEP);
1836ff0cc061SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase,
1837ff0cc061SDimitry Andric                                                   GEP->getPointerOperand(),
1838ff0cc061SDimitry Andric                                                   BaseValue);
1839ff0cc061SDimitry Andric   }
1840ff0cc061SDimitry Andric 
1841ff0cc061SDimitry Andric   if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1842ff0cc061SDimitry Andric     Value *Def = CI->stripPointerCasts();
1843ff0cc061SDimitry Andric 
1844ff0cc061SDimitry Andric     // This two checks are basically similar. First one is here for the
1845ff0cc061SDimitry Andric     // consistency with findBasePointers logic.
1846ff0cc061SDimitry Andric     assert(!isa<CastInst>(Def) && "not a pointer cast found");
1847ff0cc061SDimitry Andric     if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1848ff0cc061SDimitry Andric       return false;
1849ff0cc061SDimitry Andric 
1850ff0cc061SDimitry Andric     ChainToBase.push_back(CI);
1851ff0cc061SDimitry Andric     return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1852ff0cc061SDimitry Andric   }
1853ff0cc061SDimitry Andric 
1854ff0cc061SDimitry Andric   // Not supported instruction in the chain
1855ff0cc061SDimitry Andric   return false;
1856ff0cc061SDimitry Andric }
1857ff0cc061SDimitry Andric 
1858ff0cc061SDimitry Andric // Helper function for the "rematerializeLiveValues". Compute cost of the use
1859ff0cc061SDimitry Andric // chain we are going to rematerialize.
1860ff0cc061SDimitry Andric static unsigned
1861ff0cc061SDimitry Andric chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1862ff0cc061SDimitry Andric                        TargetTransformInfo &TTI) {
1863ff0cc061SDimitry Andric   unsigned Cost = 0;
1864ff0cc061SDimitry Andric 
1865ff0cc061SDimitry Andric   for (Instruction *Instr : Chain) {
1866ff0cc061SDimitry Andric     if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1867ff0cc061SDimitry Andric       assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1868ff0cc061SDimitry Andric              "non noop cast is found during rematerialization");
1869ff0cc061SDimitry Andric 
1870ff0cc061SDimitry Andric       Type *SrcTy = CI->getOperand(0)->getType();
1871ff0cc061SDimitry Andric       Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1872ff0cc061SDimitry Andric 
1873ff0cc061SDimitry Andric     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1874ff0cc061SDimitry Andric       // Cost of the address calculation
1875ff0cc061SDimitry Andric       Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
1876ff0cc061SDimitry Andric       Cost += TTI.getAddressComputationCost(ValTy);
1877ff0cc061SDimitry Andric 
1878ff0cc061SDimitry Andric       // And cost of the GEP itself
1879ff0cc061SDimitry Andric       // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1880ff0cc061SDimitry Andric       //       allowed for the external usage)
1881ff0cc061SDimitry Andric       if (!GEP->hasAllConstantIndices())
1882ff0cc061SDimitry Andric         Cost += 2;
1883ff0cc061SDimitry Andric 
1884ff0cc061SDimitry Andric     } else {
1885ff0cc061SDimitry Andric       llvm_unreachable("unsupported instruciton type during rematerialization");
1886ff0cc061SDimitry Andric     }
1887ff0cc061SDimitry Andric   }
1888ff0cc061SDimitry Andric 
1889ff0cc061SDimitry Andric   return Cost;
1890ff0cc061SDimitry Andric }
1891ff0cc061SDimitry Andric 
1892ff0cc061SDimitry Andric // From the statepoint liveset pick values that are cheaper to recompute then to
1893ff0cc061SDimitry Andric // relocate. Remove this values from the liveset, rematerialize them after
1894ff0cc061SDimitry Andric // statepoint and record them in "Info" structure. Note that similar to
1895ff0cc061SDimitry Andric // relocated values we don't do any user adjustments here.
1896ff0cc061SDimitry Andric static void rematerializeLiveValues(CallSite CS,
1897ff0cc061SDimitry Andric                                     PartiallyConstructedSafepointRecord &Info,
1898ff0cc061SDimitry Andric                                     TargetTransformInfo &TTI) {
1899ff0cc061SDimitry Andric   const unsigned int ChainLengthThreshold = 10;
1900ff0cc061SDimitry Andric 
1901ff0cc061SDimitry Andric   // Record values we are going to delete from this statepoint live set.
1902ff0cc061SDimitry Andric   // We can not di this in following loop due to iterator invalidation.
1903ff0cc061SDimitry Andric   SmallVector<Value *, 32> LiveValuesToBeDeleted;
1904ff0cc061SDimitry Andric 
1905ff0cc061SDimitry Andric   for (Value *LiveValue: Info.liveset) {
1906ff0cc061SDimitry Andric     // For each live pointer find it's defining chain
1907ff0cc061SDimitry Andric     SmallVector<Instruction *, 3> ChainToBase;
1908ff0cc061SDimitry Andric     assert(Info.PointerToBase.find(LiveValue) != Info.PointerToBase.end());
1909ff0cc061SDimitry Andric     bool FoundChain =
1910ff0cc061SDimitry Andric       findRematerializableChainToBasePointer(ChainToBase,
1911ff0cc061SDimitry Andric                                              LiveValue,
1912ff0cc061SDimitry Andric                                              Info.PointerToBase[LiveValue]);
1913ff0cc061SDimitry Andric     // Nothing to do, or chain is too long
1914ff0cc061SDimitry Andric     if (!FoundChain ||
1915ff0cc061SDimitry Andric         ChainToBase.size() == 0 ||
1916ff0cc061SDimitry Andric         ChainToBase.size() > ChainLengthThreshold)
1917ff0cc061SDimitry Andric       continue;
1918ff0cc061SDimitry Andric 
1919ff0cc061SDimitry Andric     // Compute cost of this chain
1920ff0cc061SDimitry Andric     unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1921ff0cc061SDimitry Andric     // TODO: We can also account for cases when we will be able to remove some
1922ff0cc061SDimitry Andric     //       of the rematerialized values by later optimization passes. I.e if
1923ff0cc061SDimitry Andric     //       we rematerialized several intersecting chains. Or if original values
1924ff0cc061SDimitry Andric     //       don't have any uses besides this statepoint.
1925ff0cc061SDimitry Andric 
1926ff0cc061SDimitry Andric     // For invokes we need to rematerialize each chain twice - for normal and
1927ff0cc061SDimitry Andric     // for unwind basic blocks. Model this by multiplying cost by two.
1928ff0cc061SDimitry Andric     if (CS.isInvoke()) {
1929ff0cc061SDimitry Andric       Cost *= 2;
1930ff0cc061SDimitry Andric     }
1931ff0cc061SDimitry Andric     // If it's too expensive - skip it
1932ff0cc061SDimitry Andric     if (Cost >= RematerializationThreshold)
1933ff0cc061SDimitry Andric       continue;
1934ff0cc061SDimitry Andric 
1935ff0cc061SDimitry Andric     // Remove value from the live set
1936ff0cc061SDimitry Andric     LiveValuesToBeDeleted.push_back(LiveValue);
1937ff0cc061SDimitry Andric 
1938ff0cc061SDimitry Andric     // Clone instructions and record them inside "Info" structure
1939ff0cc061SDimitry Andric 
1940ff0cc061SDimitry Andric     // Walk backwards to visit top-most instructions first
1941ff0cc061SDimitry Andric     std::reverse(ChainToBase.begin(), ChainToBase.end());
1942ff0cc061SDimitry Andric 
1943ff0cc061SDimitry Andric     // Utility function which clones all instructions from "ChainToBase"
1944ff0cc061SDimitry Andric     // and inserts them before "InsertBefore". Returns rematerialized value
1945ff0cc061SDimitry Andric     // which should be used after statepoint.
1946ff0cc061SDimitry Andric     auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
1947ff0cc061SDimitry Andric       Instruction *LastClonedValue = nullptr;
1948ff0cc061SDimitry Andric       Instruction *LastValue = nullptr;
1949ff0cc061SDimitry Andric       for (Instruction *Instr: ChainToBase) {
1950ff0cc061SDimitry Andric         // Only GEP's and casts are suported as we need to be careful to not
1951ff0cc061SDimitry Andric         // introduce any new uses of pointers not in the liveset.
1952ff0cc061SDimitry Andric         // Note that it's fine to introduce new uses of pointers which were
1953ff0cc061SDimitry Andric         // otherwise not used after this statepoint.
1954ff0cc061SDimitry Andric         assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
1955ff0cc061SDimitry Andric 
1956ff0cc061SDimitry Andric         Instruction *ClonedValue = Instr->clone();
1957ff0cc061SDimitry Andric         ClonedValue->insertBefore(InsertBefore);
1958ff0cc061SDimitry Andric         ClonedValue->setName(Instr->getName() + ".remat");
1959ff0cc061SDimitry Andric 
1960ff0cc061SDimitry Andric         // If it is not first instruction in the chain then it uses previously
1961ff0cc061SDimitry Andric         // cloned value. We should update it to use cloned value.
1962ff0cc061SDimitry Andric         if (LastClonedValue) {
1963ff0cc061SDimitry Andric           assert(LastValue);
1964ff0cc061SDimitry Andric           ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
1965ff0cc061SDimitry Andric #ifndef NDEBUG
1966ff0cc061SDimitry Andric           // Assert that cloned instruction does not use any instructions from
1967ff0cc061SDimitry Andric           // this chain other than LastClonedValue
1968ff0cc061SDimitry Andric           for (auto OpValue : ClonedValue->operand_values()) {
1969ff0cc061SDimitry Andric             assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
1970ff0cc061SDimitry Andric                        ChainToBase.end() &&
1971ff0cc061SDimitry Andric                    "incorrect use in rematerialization chain");
1972ff0cc061SDimitry Andric           }
1973ff0cc061SDimitry Andric #endif
1974ff0cc061SDimitry Andric         }
1975ff0cc061SDimitry Andric 
1976ff0cc061SDimitry Andric         LastClonedValue = ClonedValue;
1977ff0cc061SDimitry Andric         LastValue = Instr;
1978ff0cc061SDimitry Andric       }
1979ff0cc061SDimitry Andric       assert(LastClonedValue);
1980ff0cc061SDimitry Andric       return LastClonedValue;
1981ff0cc061SDimitry Andric     };
1982ff0cc061SDimitry Andric 
1983ff0cc061SDimitry Andric     // Different cases for calls and invokes. For invokes we need to clone
1984ff0cc061SDimitry Andric     // instructions both on normal and unwind path.
1985ff0cc061SDimitry Andric     if (CS.isCall()) {
1986ff0cc061SDimitry Andric       Instruction *InsertBefore = CS.getInstruction()->getNextNode();
1987ff0cc061SDimitry Andric       assert(InsertBefore);
1988ff0cc061SDimitry Andric       Instruction *RematerializedValue = rematerializeChain(InsertBefore);
1989ff0cc061SDimitry Andric       Info.RematerializedValues[RematerializedValue] = LiveValue;
1990ff0cc061SDimitry Andric     } else {
1991ff0cc061SDimitry Andric       InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
1992ff0cc061SDimitry Andric 
1993ff0cc061SDimitry Andric       Instruction *NormalInsertBefore =
1994ff0cc061SDimitry Andric           Invoke->getNormalDest()->getFirstInsertionPt();
1995ff0cc061SDimitry Andric       Instruction *UnwindInsertBefore =
1996ff0cc061SDimitry Andric           Invoke->getUnwindDest()->getFirstInsertionPt();
1997ff0cc061SDimitry Andric 
1998ff0cc061SDimitry Andric       Instruction *NormalRematerializedValue =
1999ff0cc061SDimitry Andric           rematerializeChain(NormalInsertBefore);
2000ff0cc061SDimitry Andric       Instruction *UnwindRematerializedValue =
2001ff0cc061SDimitry Andric           rematerializeChain(UnwindInsertBefore);
2002ff0cc061SDimitry Andric 
2003ff0cc061SDimitry Andric       Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2004ff0cc061SDimitry Andric       Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2005ff0cc061SDimitry Andric     }
2006ff0cc061SDimitry Andric   }
2007ff0cc061SDimitry Andric 
2008ff0cc061SDimitry Andric   // Remove rematerializaed values from the live set
2009ff0cc061SDimitry Andric   for (auto LiveValue: LiveValuesToBeDeleted) {
2010ff0cc061SDimitry Andric     Info.liveset.erase(LiveValue);
2011ff0cc061SDimitry Andric   }
2012ff0cc061SDimitry Andric }
2013ff0cc061SDimitry Andric 
2014ff0cc061SDimitry Andric static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
2015ff0cc061SDimitry Andric                               SmallVectorImpl<CallSite> &toUpdate) {
2016ff0cc061SDimitry Andric #ifndef NDEBUG
2017ff0cc061SDimitry Andric   // sanity check the input
2018ff0cc061SDimitry Andric   std::set<CallSite> uniqued;
2019ff0cc061SDimitry Andric   uniqued.insert(toUpdate.begin(), toUpdate.end());
2020ff0cc061SDimitry Andric   assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2021ff0cc061SDimitry Andric 
2022ff0cc061SDimitry Andric   for (size_t i = 0; i < toUpdate.size(); i++) {
2023ff0cc061SDimitry Andric     CallSite &CS = toUpdate[i];
2024ff0cc061SDimitry Andric     assert(CS.getInstruction()->getParent()->getParent() == &F);
2025ff0cc061SDimitry Andric     assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2026ff0cc061SDimitry Andric   }
2027ff0cc061SDimitry Andric #endif
2028ff0cc061SDimitry Andric 
2029ff0cc061SDimitry Andric   // When inserting gc.relocates for invokes, we need to be able to insert at
2030ff0cc061SDimitry Andric   // the top of the successor blocks.  See the comment on
2031ff0cc061SDimitry Andric   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
2032ff0cc061SDimitry Andric   // may restructure the CFG.
2033ff0cc061SDimitry Andric   for (CallSite CS : toUpdate) {
2034ff0cc061SDimitry Andric     if (!CS.isInvoke())
2035ff0cc061SDimitry Andric       continue;
2036ff0cc061SDimitry Andric     InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2037ff0cc061SDimitry Andric     normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
203897bc6c73SDimitry Andric                                 DT);
2039ff0cc061SDimitry Andric     normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
204097bc6c73SDimitry Andric                                 DT);
2041ff0cc061SDimitry Andric   }
2042ff0cc061SDimitry Andric 
2043ff0cc061SDimitry Andric   // A list of dummy calls added to the IR to keep various values obviously
2044ff0cc061SDimitry Andric   // live in the IR.  We'll remove all of these when done.
2045ff0cc061SDimitry Andric   SmallVector<CallInst *, 64> holders;
2046ff0cc061SDimitry Andric 
2047ff0cc061SDimitry Andric   // Insert a dummy call with all of the arguments to the vm_state we'll need
2048ff0cc061SDimitry Andric   // for the actual safepoint insertion.  This ensures reference arguments in
2049ff0cc061SDimitry Andric   // the deopt argument list are considered live through the safepoint (and
2050ff0cc061SDimitry Andric   // thus makes sure they get relocated.)
2051ff0cc061SDimitry Andric   for (size_t i = 0; i < toUpdate.size(); i++) {
2052ff0cc061SDimitry Andric     CallSite &CS = toUpdate[i];
2053ff0cc061SDimitry Andric     Statepoint StatepointCS(CS);
2054ff0cc061SDimitry Andric 
2055ff0cc061SDimitry Andric     SmallVector<Value *, 64> DeoptValues;
2056ff0cc061SDimitry Andric     for (Use &U : StatepointCS.vm_state_args()) {
2057ff0cc061SDimitry Andric       Value *Arg = cast<Value>(&U);
2058ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(Arg->getType()) &&
2059ff0cc061SDimitry Andric              "support for FCA unimplemented");
2060ff0cc061SDimitry Andric       if (isHandledGCPointerType(Arg->getType()))
2061ff0cc061SDimitry Andric         DeoptValues.push_back(Arg);
2062ff0cc061SDimitry Andric     }
2063ff0cc061SDimitry Andric     insertUseHolderAfter(CS, DeoptValues, holders);
2064ff0cc061SDimitry Andric   }
2065ff0cc061SDimitry Andric 
2066ff0cc061SDimitry Andric   SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
2067ff0cc061SDimitry Andric   records.reserve(toUpdate.size());
2068ff0cc061SDimitry Andric   for (size_t i = 0; i < toUpdate.size(); i++) {
2069ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord info;
2070ff0cc061SDimitry Andric     records.push_back(info);
2071ff0cc061SDimitry Andric   }
2072ff0cc061SDimitry Andric   assert(records.size() == toUpdate.size());
2073ff0cc061SDimitry Andric 
2074ff0cc061SDimitry Andric   // A) Identify all gc pointers which are staticly live at the given call
2075ff0cc061SDimitry Andric   // site.
2076ff0cc061SDimitry Andric   findLiveReferences(F, DT, P, toUpdate, records);
2077ff0cc061SDimitry Andric 
2078ff0cc061SDimitry Andric   // Do a limited scalarization of any live at safepoint vector values which
2079ff0cc061SDimitry Andric   // contain pointers.  This enables this pass to run after vectorization at
2080ff0cc061SDimitry Andric   // the cost of some possible performance loss.  TODO: it would be nice to
2081ff0cc061SDimitry Andric   // natively support vectors all the way through the backend so we don't need
2082ff0cc061SDimitry Andric   // to scalarize here.
2083ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
2084ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
2085ff0cc061SDimitry Andric     Instruction *statepoint = toUpdate[i].getInstruction();
2086ff0cc061SDimitry Andric     splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
2087ff0cc061SDimitry Andric   }
2088ff0cc061SDimitry Andric 
2089ff0cc061SDimitry Andric   // B) Find the base pointers for each live pointer
2090ff0cc061SDimitry Andric   /* scope for caching */ {
2091ff0cc061SDimitry Andric     // Cache the 'defining value' relation used in the computation and
2092ff0cc061SDimitry Andric     // insertion of base phis and selects.  This ensures that we don't insert
2093ff0cc061SDimitry Andric     // large numbers of duplicate base_phis.
2094ff0cc061SDimitry Andric     DefiningValueMapTy DVCache;
2095ff0cc061SDimitry Andric 
2096ff0cc061SDimitry Andric     for (size_t i = 0; i < records.size(); i++) {
2097ff0cc061SDimitry Andric       struct PartiallyConstructedSafepointRecord &info = records[i];
2098ff0cc061SDimitry Andric       CallSite &CS = toUpdate[i];
2099ff0cc061SDimitry Andric       findBasePointers(DT, DVCache, CS, info);
2100ff0cc061SDimitry Andric     }
2101ff0cc061SDimitry Andric   } // end of cache scope
2102ff0cc061SDimitry Andric 
2103ff0cc061SDimitry Andric   // The base phi insertion logic (for any safepoint) may have inserted new
2104ff0cc061SDimitry Andric   // instructions which are now live at some safepoint.  The simplest such
2105ff0cc061SDimitry Andric   // example is:
2106ff0cc061SDimitry Andric   // loop:
2107ff0cc061SDimitry Andric   //   phi a  <-- will be a new base_phi here
2108ff0cc061SDimitry Andric   //   safepoint 1 <-- that needs to be live here
2109ff0cc061SDimitry Andric   //   gep a + 1
2110ff0cc061SDimitry Andric   //   safepoint 2
2111ff0cc061SDimitry Andric   //   br loop
2112ff0cc061SDimitry Andric   // We insert some dummy calls after each safepoint to definitely hold live
2113ff0cc061SDimitry Andric   // the base pointers which were identified for that safepoint.  We'll then
2114ff0cc061SDimitry Andric   // ask liveness for _every_ base inserted to see what is now live.  Then we
2115ff0cc061SDimitry Andric   // remove the dummy calls.
2116ff0cc061SDimitry Andric   holders.reserve(holders.size() + records.size());
2117ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
2118ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
2119ff0cc061SDimitry Andric     CallSite &CS = toUpdate[i];
2120ff0cc061SDimitry Andric 
2121ff0cc061SDimitry Andric     SmallVector<Value *, 128> Bases;
2122ff0cc061SDimitry Andric     for (auto Pair : info.PointerToBase) {
2123ff0cc061SDimitry Andric       Bases.push_back(Pair.second);
2124ff0cc061SDimitry Andric     }
2125ff0cc061SDimitry Andric     insertUseHolderAfter(CS, Bases, holders);
2126ff0cc061SDimitry Andric   }
2127ff0cc061SDimitry Andric 
2128ff0cc061SDimitry Andric   // By selecting base pointers, we've effectively inserted new uses. Thus, we
2129ff0cc061SDimitry Andric   // need to rerun liveness.  We may *also* have inserted new defs, but that's
2130ff0cc061SDimitry Andric   // not the key issue.
2131ff0cc061SDimitry Andric   recomputeLiveInValues(F, DT, P, toUpdate, records);
2132ff0cc061SDimitry Andric 
2133ff0cc061SDimitry Andric   if (PrintBasePointers) {
2134ff0cc061SDimitry Andric     for (size_t i = 0; i < records.size(); i++) {
2135ff0cc061SDimitry Andric       struct PartiallyConstructedSafepointRecord &info = records[i];
2136ff0cc061SDimitry Andric       errs() << "Base Pairs: (w/Relocation)\n";
2137ff0cc061SDimitry Andric       for (auto Pair : info.PointerToBase) {
2138ff0cc061SDimitry Andric         errs() << " derived %" << Pair.first->getName() << " base %"
2139ff0cc061SDimitry Andric                << Pair.second->getName() << "\n";
2140ff0cc061SDimitry Andric       }
2141ff0cc061SDimitry Andric     }
2142ff0cc061SDimitry Andric   }
2143ff0cc061SDimitry Andric   for (size_t i = 0; i < holders.size(); i++) {
2144ff0cc061SDimitry Andric     holders[i]->eraseFromParent();
2145ff0cc061SDimitry Andric     holders[i] = nullptr;
2146ff0cc061SDimitry Andric   }
2147ff0cc061SDimitry Andric   holders.clear();
2148ff0cc061SDimitry Andric 
2149ff0cc061SDimitry Andric   // In order to reduce live set of statepoint we might choose to rematerialize
2150ff0cc061SDimitry Andric   // some values instead of relocating them. This is purelly an optimization and
2151ff0cc061SDimitry Andric   // does not influence correctness.
2152ff0cc061SDimitry Andric   TargetTransformInfo &TTI =
2153ff0cc061SDimitry Andric     P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2154ff0cc061SDimitry Andric 
2155ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
2156ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
2157ff0cc061SDimitry Andric     CallSite &CS = toUpdate[i];
2158ff0cc061SDimitry Andric 
2159ff0cc061SDimitry Andric     rematerializeLiveValues(CS, info, TTI);
2160ff0cc061SDimitry Andric   }
2161ff0cc061SDimitry Andric 
2162ff0cc061SDimitry Andric   // Now run through and replace the existing statepoints with new ones with
2163ff0cc061SDimitry Andric   // the live variables listed.  We do not yet update uses of the values being
2164ff0cc061SDimitry Andric   // relocated. We have references to live variables that need to
2165ff0cc061SDimitry Andric   // survive to the last iteration of this loop.  (By construction, the
2166ff0cc061SDimitry Andric   // previous statepoint can not be a live variable, thus we can and remove
2167ff0cc061SDimitry Andric   // the old statepoint calls as we go.)
2168ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
2169ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
2170ff0cc061SDimitry Andric     CallSite &CS = toUpdate[i];
2171ff0cc061SDimitry Andric     makeStatepointExplicit(DT, CS, P, info);
2172ff0cc061SDimitry Andric   }
2173ff0cc061SDimitry Andric   toUpdate.clear(); // prevent accident use of invalid CallSites
2174ff0cc061SDimitry Andric 
2175ff0cc061SDimitry Andric   // Do all the fixups of the original live variables to their relocated selves
2176ff0cc061SDimitry Andric   SmallVector<Value *, 128> live;
2177ff0cc061SDimitry Andric   for (size_t i = 0; i < records.size(); i++) {
2178ff0cc061SDimitry Andric     struct PartiallyConstructedSafepointRecord &info = records[i];
2179ff0cc061SDimitry Andric     // We can't simply save the live set from the original insertion.  One of
2180ff0cc061SDimitry Andric     // the live values might be the result of a call which needs a safepoint.
2181ff0cc061SDimitry Andric     // That Value* no longer exists and we need to use the new gc_result.
2182ff0cc061SDimitry Andric     // Thankfully, the liveset is embedded in the statepoint (and updated), so
2183ff0cc061SDimitry Andric     // we just grab that.
2184ff0cc061SDimitry Andric     Statepoint statepoint(info.StatepointToken);
2185ff0cc061SDimitry Andric     live.insert(live.end(), statepoint.gc_args_begin(),
2186ff0cc061SDimitry Andric                 statepoint.gc_args_end());
2187ff0cc061SDimitry Andric #ifndef NDEBUG
2188ff0cc061SDimitry Andric     // Do some basic sanity checks on our liveness results before performing
2189ff0cc061SDimitry Andric     // relocation.  Relocation can and will turn mistakes in liveness results
2190ff0cc061SDimitry Andric     // into non-sensical code which is must harder to debug.
2191ff0cc061SDimitry Andric     // TODO: It would be nice to test consistency as well
2192ff0cc061SDimitry Andric     assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2193ff0cc061SDimitry Andric            "statepoint must be reachable or liveness is meaningless");
2194ff0cc061SDimitry Andric     for (Value *V : statepoint.gc_args()) {
2195ff0cc061SDimitry Andric       if (!isa<Instruction>(V))
2196ff0cc061SDimitry Andric         // Non-instruction values trivial dominate all possible uses
2197ff0cc061SDimitry Andric         continue;
2198ff0cc061SDimitry Andric       auto LiveInst = cast<Instruction>(V);
2199ff0cc061SDimitry Andric       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2200ff0cc061SDimitry Andric              "unreachable values should never be live");
2201ff0cc061SDimitry Andric       assert(DT.dominates(LiveInst, info.StatepointToken) &&
2202ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2203ff0cc061SDimitry Andric     }
2204ff0cc061SDimitry Andric #endif
2205ff0cc061SDimitry Andric   }
2206ff0cc061SDimitry Andric   unique_unsorted(live);
2207ff0cc061SDimitry Andric 
2208ff0cc061SDimitry Andric #ifndef NDEBUG
2209ff0cc061SDimitry Andric   // sanity check
2210ff0cc061SDimitry Andric   for (auto ptr : live) {
2211ff0cc061SDimitry Andric     assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2212ff0cc061SDimitry Andric   }
2213ff0cc061SDimitry Andric #endif
2214ff0cc061SDimitry Andric 
2215ff0cc061SDimitry Andric   relocationViaAlloca(F, DT, live, records);
2216ff0cc061SDimitry Andric   return !records.empty();
2217ff0cc061SDimitry Andric }
2218ff0cc061SDimitry Andric 
221997bc6c73SDimitry Andric // Handles both return values and arguments for Functions and CallSites.
222097bc6c73SDimitry Andric template <typename AttrHolder>
222197bc6c73SDimitry Andric static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
222297bc6c73SDimitry Andric                                    unsigned Index) {
222397bc6c73SDimitry Andric   AttrBuilder R;
222497bc6c73SDimitry Andric   if (AH.getDereferenceableBytes(Index))
222597bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
222697bc6c73SDimitry Andric                                   AH.getDereferenceableBytes(Index)));
222797bc6c73SDimitry Andric   if (AH.getDereferenceableOrNullBytes(Index))
222897bc6c73SDimitry Andric     R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
222997bc6c73SDimitry Andric                                   AH.getDereferenceableOrNullBytes(Index)));
223097bc6c73SDimitry Andric 
223197bc6c73SDimitry Andric   if (!R.empty())
223297bc6c73SDimitry Andric     AH.setAttributes(AH.getAttributes().removeAttributes(
223397bc6c73SDimitry Andric         Ctx, Index, AttributeSet::get(Ctx, Index, R)));
223497bc6c73SDimitry Andric }
223597bc6c73SDimitry Andric 
223697bc6c73SDimitry Andric void
223797bc6c73SDimitry Andric RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
223897bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
223997bc6c73SDimitry Andric 
224097bc6c73SDimitry Andric   for (Argument &A : F.args())
224197bc6c73SDimitry Andric     if (isa<PointerType>(A.getType()))
224297bc6c73SDimitry Andric       RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
224397bc6c73SDimitry Andric 
224497bc6c73SDimitry Andric   if (isa<PointerType>(F.getReturnType()))
224597bc6c73SDimitry Andric     RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
224697bc6c73SDimitry Andric }
224797bc6c73SDimitry Andric 
224897bc6c73SDimitry Andric void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
224997bc6c73SDimitry Andric   if (F.empty())
225097bc6c73SDimitry Andric     return;
225197bc6c73SDimitry Andric 
225297bc6c73SDimitry Andric   LLVMContext &Ctx = F.getContext();
225397bc6c73SDimitry Andric   MDBuilder Builder(Ctx);
225497bc6c73SDimitry Andric 
225597bc6c73SDimitry Andric   for (Instruction &I : inst_range(F)) {
225697bc6c73SDimitry Andric     if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
225797bc6c73SDimitry Andric       assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
225897bc6c73SDimitry Andric       bool IsImmutableTBAA =
225997bc6c73SDimitry Andric           MD->getNumOperands() == 4 &&
226097bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
226197bc6c73SDimitry Andric 
226297bc6c73SDimitry Andric       if (!IsImmutableTBAA)
226397bc6c73SDimitry Andric         continue; // no work to do, MD_tbaa is already marked mutable
226497bc6c73SDimitry Andric 
226597bc6c73SDimitry Andric       MDNode *Base = cast<MDNode>(MD->getOperand(0));
226697bc6c73SDimitry Andric       MDNode *Access = cast<MDNode>(MD->getOperand(1));
226797bc6c73SDimitry Andric       uint64_t Offset =
226897bc6c73SDimitry Andric           mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
226997bc6c73SDimitry Andric 
227097bc6c73SDimitry Andric       MDNode *MutableTBAA =
227197bc6c73SDimitry Andric           Builder.createTBAAStructTagNode(Base, Access, Offset);
227297bc6c73SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
227397bc6c73SDimitry Andric     }
227497bc6c73SDimitry Andric 
227597bc6c73SDimitry Andric     if (CallSite CS = CallSite(&I)) {
227697bc6c73SDimitry Andric       for (int i = 0, e = CS.arg_size(); i != e; i++)
227797bc6c73SDimitry Andric         if (isa<PointerType>(CS.getArgument(i)->getType()))
227897bc6c73SDimitry Andric           RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
227997bc6c73SDimitry Andric       if (isa<PointerType>(CS.getType()))
228097bc6c73SDimitry Andric         RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
228197bc6c73SDimitry Andric     }
228297bc6c73SDimitry Andric   }
228397bc6c73SDimitry Andric }
228497bc6c73SDimitry Andric 
2285ff0cc061SDimitry Andric /// Returns true if this function should be rewritten by this pass.  The main
2286ff0cc061SDimitry Andric /// point of this function is as an extension point for custom logic.
2287ff0cc061SDimitry Andric static bool shouldRewriteStatepointsIn(Function &F) {
2288ff0cc061SDimitry Andric   // TODO: This should check the GCStrategy
2289ff0cc061SDimitry Andric   if (F.hasGC()) {
2290ff0cc061SDimitry Andric     const char *FunctionGCName = F.getGC();
2291ff0cc061SDimitry Andric     const StringRef StatepointExampleName("statepoint-example");
2292ff0cc061SDimitry Andric     const StringRef CoreCLRName("coreclr");
2293ff0cc061SDimitry Andric     return (StatepointExampleName == FunctionGCName) ||
2294ff0cc061SDimitry Andric            (CoreCLRName == FunctionGCName);
2295ff0cc061SDimitry Andric   } else
2296ff0cc061SDimitry Andric     return false;
2297ff0cc061SDimitry Andric }
2298ff0cc061SDimitry Andric 
229997bc6c73SDimitry Andric void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
230097bc6c73SDimitry Andric #ifndef NDEBUG
230197bc6c73SDimitry Andric   assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
230297bc6c73SDimitry Andric          "precondition!");
230397bc6c73SDimitry Andric #endif
230497bc6c73SDimitry Andric 
230597bc6c73SDimitry Andric   for (Function &F : M)
230697bc6c73SDimitry Andric     stripDereferenceabilityInfoFromPrototype(F);
230797bc6c73SDimitry Andric 
230897bc6c73SDimitry Andric   for (Function &F : M)
230997bc6c73SDimitry Andric     stripDereferenceabilityInfoFromBody(F);
231097bc6c73SDimitry Andric }
231197bc6c73SDimitry Andric 
2312ff0cc061SDimitry Andric bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2313ff0cc061SDimitry Andric   // Nothing to do for declarations.
2314ff0cc061SDimitry Andric   if (F.isDeclaration() || F.empty())
2315ff0cc061SDimitry Andric     return false;
2316ff0cc061SDimitry Andric 
2317ff0cc061SDimitry Andric   // Policy choice says not to rewrite - the most common reason is that we're
2318ff0cc061SDimitry Andric   // compiling code without a GCStrategy.
2319ff0cc061SDimitry Andric   if (!shouldRewriteStatepointsIn(F))
2320ff0cc061SDimitry Andric     return false;
2321ff0cc061SDimitry Andric 
232297bc6c73SDimitry Andric   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2323ff0cc061SDimitry Andric 
2324ff0cc061SDimitry Andric   // Gather all the statepoints which need rewritten.  Be careful to only
2325ff0cc061SDimitry Andric   // consider those in reachable code since we need to ask dominance queries
2326ff0cc061SDimitry Andric   // when rewriting.  We'll delete the unreachable ones in a moment.
2327ff0cc061SDimitry Andric   SmallVector<CallSite, 64> ParsePointNeeded;
2328ff0cc061SDimitry Andric   bool HasUnreachableStatepoint = false;
2329ff0cc061SDimitry Andric   for (Instruction &I : inst_range(F)) {
2330ff0cc061SDimitry Andric     // TODO: only the ones with the flag set!
2331ff0cc061SDimitry Andric     if (isStatepoint(I)) {
2332ff0cc061SDimitry Andric       if (DT.isReachableFromEntry(I.getParent()))
2333ff0cc061SDimitry Andric         ParsePointNeeded.push_back(CallSite(&I));
2334ff0cc061SDimitry Andric       else
2335ff0cc061SDimitry Andric         HasUnreachableStatepoint = true;
2336ff0cc061SDimitry Andric     }
2337ff0cc061SDimitry Andric   }
2338ff0cc061SDimitry Andric 
2339ff0cc061SDimitry Andric   bool MadeChange = false;
2340ff0cc061SDimitry Andric 
2341ff0cc061SDimitry Andric   // Delete any unreachable statepoints so that we don't have unrewritten
2342ff0cc061SDimitry Andric   // statepoints surviving this pass.  This makes testing easier and the
2343ff0cc061SDimitry Andric   // resulting IR less confusing to human readers.  Rather than be fancy, we
2344ff0cc061SDimitry Andric   // just reuse a utility function which removes the unreachable blocks.
2345ff0cc061SDimitry Andric   if (HasUnreachableStatepoint)
2346ff0cc061SDimitry Andric     MadeChange |= removeUnreachableBlocks(F);
2347ff0cc061SDimitry Andric 
2348ff0cc061SDimitry Andric   // Return early if no work to do.
2349ff0cc061SDimitry Andric   if (ParsePointNeeded.empty())
2350ff0cc061SDimitry Andric     return MadeChange;
2351ff0cc061SDimitry Andric 
2352ff0cc061SDimitry Andric   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2353ff0cc061SDimitry Andric   // These are created by LCSSA.  They have the effect of increasing the size
2354ff0cc061SDimitry Andric   // of liveness sets for no good reason.  It may be harder to do this post
2355ff0cc061SDimitry Andric   // insertion since relocations and base phis can confuse things.
2356ff0cc061SDimitry Andric   for (BasicBlock &BB : F)
2357ff0cc061SDimitry Andric     if (BB.getUniquePredecessor()) {
2358ff0cc061SDimitry Andric       MadeChange = true;
2359ff0cc061SDimitry Andric       FoldSingleEntryPHINodes(&BB);
2360ff0cc061SDimitry Andric     }
2361ff0cc061SDimitry Andric 
2362ff0cc061SDimitry Andric   MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2363ff0cc061SDimitry Andric   return MadeChange;
2364ff0cc061SDimitry Andric }
2365ff0cc061SDimitry Andric 
2366ff0cc061SDimitry Andric // liveness computation via standard dataflow
2367ff0cc061SDimitry Andric // -------------------------------------------------------------------
2368ff0cc061SDimitry Andric 
2369ff0cc061SDimitry Andric // TODO: Consider using bitvectors for liveness, the set of potentially
2370ff0cc061SDimitry Andric // interesting values should be small and easy to pre-compute.
2371ff0cc061SDimitry Andric 
2372ff0cc061SDimitry Andric /// Compute the live-in set for the location rbegin starting from
2373ff0cc061SDimitry Andric /// the live-out set of the basic block
2374ff0cc061SDimitry Andric static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2375ff0cc061SDimitry Andric                                 BasicBlock::reverse_iterator rend,
2376ff0cc061SDimitry Andric                                 DenseSet<Value *> &LiveTmp) {
2377ff0cc061SDimitry Andric 
2378ff0cc061SDimitry Andric   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2379ff0cc061SDimitry Andric     Instruction *I = &*ritr;
2380ff0cc061SDimitry Andric 
2381ff0cc061SDimitry Andric     // KILL/Def - Remove this definition from LiveIn
2382ff0cc061SDimitry Andric     LiveTmp.erase(I);
2383ff0cc061SDimitry Andric 
2384ff0cc061SDimitry Andric     // Don't consider *uses* in PHI nodes, we handle their contribution to
2385ff0cc061SDimitry Andric     // predecessor blocks when we seed the LiveOut sets
2386ff0cc061SDimitry Andric     if (isa<PHINode>(I))
2387ff0cc061SDimitry Andric       continue;
2388ff0cc061SDimitry Andric 
2389ff0cc061SDimitry Andric     // USE - Add to the LiveIn set for this instruction
2390ff0cc061SDimitry Andric     for (Value *V : I->operands()) {
2391ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2392ff0cc061SDimitry Andric              "support for FCA unimplemented");
2393ff0cc061SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2394ff0cc061SDimitry Andric         // The choice to exclude all things constant here is slightly subtle.
2395ff0cc061SDimitry Andric         // There are two idependent reasons:
2396ff0cc061SDimitry Andric         // - We assume that things which are constant (from LLVM's definition)
2397ff0cc061SDimitry Andric         // do not move at runtime.  For example, the address of a global
2398ff0cc061SDimitry Andric         // variable is fixed, even though it's contents may not be.
2399ff0cc061SDimitry Andric         // - Second, we can't disallow arbitrary inttoptr constants even
2400ff0cc061SDimitry Andric         // if the language frontend does.  Optimization passes are free to
2401ff0cc061SDimitry Andric         // locally exploit facts without respect to global reachability.  This
2402ff0cc061SDimitry Andric         // can create sections of code which are dynamically unreachable and
2403ff0cc061SDimitry Andric         // contain just about anything.  (see constants.ll in tests)
2404ff0cc061SDimitry Andric         LiveTmp.insert(V);
2405ff0cc061SDimitry Andric       }
2406ff0cc061SDimitry Andric     }
2407ff0cc061SDimitry Andric   }
2408ff0cc061SDimitry Andric }
2409ff0cc061SDimitry Andric 
2410ff0cc061SDimitry Andric static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2411ff0cc061SDimitry Andric 
2412ff0cc061SDimitry Andric   for (BasicBlock *Succ : successors(BB)) {
2413ff0cc061SDimitry Andric     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2414ff0cc061SDimitry Andric     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2415ff0cc061SDimitry Andric       PHINode *Phi = cast<PHINode>(&*I);
2416ff0cc061SDimitry Andric       Value *V = Phi->getIncomingValueForBlock(BB);
2417ff0cc061SDimitry Andric       assert(!isUnhandledGCPointerType(V->getType()) &&
2418ff0cc061SDimitry Andric              "support for FCA unimplemented");
2419ff0cc061SDimitry Andric       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2420ff0cc061SDimitry Andric         LiveTmp.insert(V);
2421ff0cc061SDimitry Andric       }
2422ff0cc061SDimitry Andric     }
2423ff0cc061SDimitry Andric   }
2424ff0cc061SDimitry Andric }
2425ff0cc061SDimitry Andric 
2426ff0cc061SDimitry Andric static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2427ff0cc061SDimitry Andric   DenseSet<Value *> KillSet;
2428ff0cc061SDimitry Andric   for (Instruction &I : *BB)
2429ff0cc061SDimitry Andric     if (isHandledGCPointerType(I.getType()))
2430ff0cc061SDimitry Andric       KillSet.insert(&I);
2431ff0cc061SDimitry Andric   return KillSet;
2432ff0cc061SDimitry Andric }
2433ff0cc061SDimitry Andric 
2434ff0cc061SDimitry Andric #ifndef NDEBUG
2435ff0cc061SDimitry Andric /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2436ff0cc061SDimitry Andric /// sanity check for the liveness computation.
2437ff0cc061SDimitry Andric static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2438ff0cc061SDimitry Andric                           TerminatorInst *TI, bool TermOkay = false) {
2439ff0cc061SDimitry Andric   for (Value *V : Live) {
2440ff0cc061SDimitry Andric     if (auto *I = dyn_cast<Instruction>(V)) {
2441ff0cc061SDimitry Andric       // The terminator can be a member of the LiveOut set.  LLVM's definition
2442ff0cc061SDimitry Andric       // of instruction dominance states that V does not dominate itself.  As
2443ff0cc061SDimitry Andric       // such, we need to special case this to allow it.
2444ff0cc061SDimitry Andric       if (TermOkay && TI == I)
2445ff0cc061SDimitry Andric         continue;
2446ff0cc061SDimitry Andric       assert(DT.dominates(I, TI) &&
2447ff0cc061SDimitry Andric              "basic SSA liveness expectation violated by liveness analysis");
2448ff0cc061SDimitry Andric     }
2449ff0cc061SDimitry Andric   }
2450ff0cc061SDimitry Andric }
2451ff0cc061SDimitry Andric 
2452ff0cc061SDimitry Andric /// Check that all the liveness sets used during the computation of liveness
2453ff0cc061SDimitry Andric /// obey basic SSA properties.  This is useful for finding cases where we miss
2454ff0cc061SDimitry Andric /// a def.
2455ff0cc061SDimitry Andric static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2456ff0cc061SDimitry Andric                           BasicBlock &BB) {
2457ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2458ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2459ff0cc061SDimitry Andric   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2460ff0cc061SDimitry Andric }
2461ff0cc061SDimitry Andric #endif
2462ff0cc061SDimitry Andric 
2463ff0cc061SDimitry Andric static void computeLiveInValues(DominatorTree &DT, Function &F,
2464ff0cc061SDimitry Andric                                 GCPtrLivenessData &Data) {
2465ff0cc061SDimitry Andric 
2466ff0cc061SDimitry Andric   SmallSetVector<BasicBlock *, 200> Worklist;
2467ff0cc061SDimitry Andric   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2468ff0cc061SDimitry Andric     // We use a SetVector so that we don't have duplicates in the worklist.
2469ff0cc061SDimitry Andric     Worklist.insert(pred_begin(BB), pred_end(BB));
2470ff0cc061SDimitry Andric   };
2471ff0cc061SDimitry Andric   auto NextItem = [&]() {
2472ff0cc061SDimitry Andric     BasicBlock *BB = Worklist.back();
2473ff0cc061SDimitry Andric     Worklist.pop_back();
2474ff0cc061SDimitry Andric     return BB;
2475ff0cc061SDimitry Andric   };
2476ff0cc061SDimitry Andric 
2477ff0cc061SDimitry Andric   // Seed the liveness for each individual block
2478ff0cc061SDimitry Andric   for (BasicBlock &BB : F) {
2479ff0cc061SDimitry Andric     Data.KillSet[&BB] = computeKillSet(&BB);
2480ff0cc061SDimitry Andric     Data.LiveSet[&BB].clear();
2481ff0cc061SDimitry Andric     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2482ff0cc061SDimitry Andric 
2483ff0cc061SDimitry Andric #ifndef NDEBUG
2484ff0cc061SDimitry Andric     for (Value *Kill : Data.KillSet[&BB])
2485ff0cc061SDimitry Andric       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2486ff0cc061SDimitry Andric #endif
2487ff0cc061SDimitry Andric 
2488ff0cc061SDimitry Andric     Data.LiveOut[&BB] = DenseSet<Value *>();
2489ff0cc061SDimitry Andric     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2490ff0cc061SDimitry Andric     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2491ff0cc061SDimitry Andric     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2492ff0cc061SDimitry Andric     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2493ff0cc061SDimitry Andric     if (!Data.LiveIn[&BB].empty())
2494ff0cc061SDimitry Andric       AddPredsToWorklist(&BB);
2495ff0cc061SDimitry Andric   }
2496ff0cc061SDimitry Andric 
2497ff0cc061SDimitry Andric   // Propagate that liveness until stable
2498ff0cc061SDimitry Andric   while (!Worklist.empty()) {
2499ff0cc061SDimitry Andric     BasicBlock *BB = NextItem();
2500ff0cc061SDimitry Andric 
2501ff0cc061SDimitry Andric     // Compute our new liveout set, then exit early if it hasn't changed
2502ff0cc061SDimitry Andric     // despite the contribution of our successor.
2503ff0cc061SDimitry Andric     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2504ff0cc061SDimitry Andric     const auto OldLiveOutSize = LiveOut.size();
2505ff0cc061SDimitry Andric     for (BasicBlock *Succ : successors(BB)) {
2506ff0cc061SDimitry Andric       assert(Data.LiveIn.count(Succ));
2507ff0cc061SDimitry Andric       set_union(LiveOut, Data.LiveIn[Succ]);
2508ff0cc061SDimitry Andric     }
2509ff0cc061SDimitry Andric     // assert OutLiveOut is a subset of LiveOut
2510ff0cc061SDimitry Andric     if (OldLiveOutSize == LiveOut.size()) {
2511ff0cc061SDimitry Andric       // If the sets are the same size, then we didn't actually add anything
2512ff0cc061SDimitry Andric       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2513ff0cc061SDimitry Andric       // hasn't changed.
2514ff0cc061SDimitry Andric       continue;
2515ff0cc061SDimitry Andric     }
2516ff0cc061SDimitry Andric     Data.LiveOut[BB] = LiveOut;
2517ff0cc061SDimitry Andric 
2518ff0cc061SDimitry Andric     // Apply the effects of this basic block
2519ff0cc061SDimitry Andric     DenseSet<Value *> LiveTmp = LiveOut;
2520ff0cc061SDimitry Andric     set_union(LiveTmp, Data.LiveSet[BB]);
2521ff0cc061SDimitry Andric     set_subtract(LiveTmp, Data.KillSet[BB]);
2522ff0cc061SDimitry Andric 
2523ff0cc061SDimitry Andric     assert(Data.LiveIn.count(BB));
2524ff0cc061SDimitry Andric     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2525ff0cc061SDimitry Andric     // assert: OldLiveIn is a subset of LiveTmp
2526ff0cc061SDimitry Andric     if (OldLiveIn.size() != LiveTmp.size()) {
2527ff0cc061SDimitry Andric       Data.LiveIn[BB] = LiveTmp;
2528ff0cc061SDimitry Andric       AddPredsToWorklist(BB);
2529ff0cc061SDimitry Andric     }
2530ff0cc061SDimitry Andric   } // while( !worklist.empty() )
2531ff0cc061SDimitry Andric 
2532ff0cc061SDimitry Andric #ifndef NDEBUG
2533ff0cc061SDimitry Andric   // Sanity check our ouput against SSA properties.  This helps catch any
2534ff0cc061SDimitry Andric   // missing kills during the above iteration.
2535ff0cc061SDimitry Andric   for (BasicBlock &BB : F) {
2536ff0cc061SDimitry Andric     checkBasicSSA(DT, Data, BB);
2537ff0cc061SDimitry Andric   }
2538ff0cc061SDimitry Andric #endif
2539ff0cc061SDimitry Andric }
2540ff0cc061SDimitry Andric 
2541ff0cc061SDimitry Andric static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2542ff0cc061SDimitry Andric                               StatepointLiveSetTy &Out) {
2543ff0cc061SDimitry Andric 
2544ff0cc061SDimitry Andric   BasicBlock *BB = Inst->getParent();
2545ff0cc061SDimitry Andric 
2546ff0cc061SDimitry Andric   // Note: The copy is intentional and required
2547ff0cc061SDimitry Andric   assert(Data.LiveOut.count(BB));
2548ff0cc061SDimitry Andric   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2549ff0cc061SDimitry Andric 
2550ff0cc061SDimitry Andric   // We want to handle the statepoint itself oddly.  It's
2551ff0cc061SDimitry Andric   // call result is not live (normal), nor are it's arguments
2552ff0cc061SDimitry Andric   // (unless they're used again later).  This adjustment is
2553ff0cc061SDimitry Andric   // specifically what we need to relocate
2554ff0cc061SDimitry Andric   BasicBlock::reverse_iterator rend(Inst);
2555ff0cc061SDimitry Andric   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2556ff0cc061SDimitry Andric   LiveOut.erase(Inst);
2557ff0cc061SDimitry Andric   Out.insert(LiveOut.begin(), LiveOut.end());
2558ff0cc061SDimitry Andric }
2559ff0cc061SDimitry Andric 
2560ff0cc061SDimitry Andric static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2561ff0cc061SDimitry Andric                                   const CallSite &CS,
2562ff0cc061SDimitry Andric                                   PartiallyConstructedSafepointRecord &Info) {
2563ff0cc061SDimitry Andric   Instruction *Inst = CS.getInstruction();
2564ff0cc061SDimitry Andric   StatepointLiveSetTy Updated;
2565ff0cc061SDimitry Andric   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2566ff0cc061SDimitry Andric 
2567ff0cc061SDimitry Andric #ifndef NDEBUG
2568ff0cc061SDimitry Andric   DenseSet<Value *> Bases;
2569ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase) {
2570ff0cc061SDimitry Andric     Bases.insert(KVPair.second);
2571ff0cc061SDimitry Andric   }
2572ff0cc061SDimitry Andric #endif
2573ff0cc061SDimitry Andric   // We may have base pointers which are now live that weren't before.  We need
2574ff0cc061SDimitry Andric   // to update the PointerToBase structure to reflect this.
2575ff0cc061SDimitry Andric   for (auto V : Updated)
2576ff0cc061SDimitry Andric     if (!Info.PointerToBase.count(V)) {
2577ff0cc061SDimitry Andric       assert(Bases.count(V) && "can't find base for unexpected live value");
2578ff0cc061SDimitry Andric       Info.PointerToBase[V] = V;
2579ff0cc061SDimitry Andric       continue;
2580ff0cc061SDimitry Andric     }
2581ff0cc061SDimitry Andric 
2582ff0cc061SDimitry Andric #ifndef NDEBUG
2583ff0cc061SDimitry Andric   for (auto V : Updated) {
2584ff0cc061SDimitry Andric     assert(Info.PointerToBase.count(V) &&
2585ff0cc061SDimitry Andric            "must be able to find base for live value");
2586ff0cc061SDimitry Andric   }
2587ff0cc061SDimitry Andric #endif
2588ff0cc061SDimitry Andric 
2589ff0cc061SDimitry Andric   // Remove any stale base mappings - this can happen since our liveness is
2590ff0cc061SDimitry Andric   // more precise then the one inherent in the base pointer analysis
2591ff0cc061SDimitry Andric   DenseSet<Value *> ToErase;
2592ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2593ff0cc061SDimitry Andric     if (!Updated.count(KVPair.first))
2594ff0cc061SDimitry Andric       ToErase.insert(KVPair.first);
2595ff0cc061SDimitry Andric   for (auto V : ToErase)
2596ff0cc061SDimitry Andric     Info.PointerToBase.erase(V);
2597ff0cc061SDimitry Andric 
2598ff0cc061SDimitry Andric #ifndef NDEBUG
2599ff0cc061SDimitry Andric   for (auto KVPair : Info.PointerToBase)
2600ff0cc061SDimitry Andric     assert(Updated.count(KVPair.first) && "record for non-live value");
2601ff0cc061SDimitry Andric #endif
2602ff0cc061SDimitry Andric 
2603ff0cc061SDimitry Andric   Info.liveset = Updated;
2604ff0cc061SDimitry Andric }
2605