blob: 5a1fac0c456d4dffd4d13be0ed1c1f2f1dda89a6 [file] [log] [blame]
Philip Reamesd16a9b12015-02-20 01:06:44 +00001//===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Rewrite an existing set of gc.statepoints such that they make potential
11// relocations performed by the garbage collector explicit in the IR.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Pass.h"
16#include "llvm/Analysis/CFG.h"
Igor Laevskye0317182015-05-19 15:59:05 +000017#include "llvm/Analysis/TargetTransformInfo.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000018#include "llvm/ADT/SetOperations.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/DenseSet.h"
Philip Reames4d80ede2015-04-10 23:11:26 +000021#include "llvm/ADT/SetVector.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000022#include "llvm/ADT/StringRef.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CallSite.h"
25#include "llvm/IR/Dominators.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/InstIterator.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Module.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000033#include "llvm/IR/MDBuilder.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000034#include "llvm/IR/Statepoint.h"
35#include "llvm/IR/Value.h"
36#include "llvm/IR/Verifier.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Transforms/Scalar.h"
40#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41#include "llvm/Transforms/Utils/Cloning.h"
42#include "llvm/Transforms/Utils/Local.h"
43#include "llvm/Transforms/Utils/PromoteMemToReg.h"
44
45#define DEBUG_TYPE "rewrite-statepoints-for-gc"
46
47using namespace llvm;
48
49// Print tracing output
50static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
51 cl::init(false));
52
53// Print the liveset found at the insert location
54static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
55 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000056static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
57 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000058// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000059static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
60 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000061
Igor Laevskye0317182015-05-19 15:59:05 +000062// Cost threshold measuring when it is profitable to rematerialize value instead
63// of relocating it
64static cl::opt<unsigned>
65RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
66 cl::init(6));
67
Philip Reamese73300b2015-04-13 16:41:32 +000068#ifdef XDEBUG
69static bool ClobberNonLive = true;
70#else
71static bool ClobberNonLive = false;
72#endif
73static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
74 cl::location(ClobberNonLive),
75 cl::Hidden);
76
Benjamin Kramer6f665452015-02-20 14:00:58 +000077namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000078struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000079 static char ID; // Pass identification, replacement for typeid
80
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000081 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000082 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
83 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000084 bool runOnFunction(Function &F);
85 bool runOnModule(Module &M) override {
86 bool Changed = false;
87 for (Function &F : M)
88 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000089
90 if (Changed) {
91 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
92 // returns true for at least one function in the module. Since at least
93 // one function changed, we know that the precondition is satisfied.
94 stripDereferenceabilityInfo(M);
95 }
96
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000097 return Changed;
98 }
Philip Reamesd16a9b12015-02-20 01:06:44 +000099
100 void getAnalysisUsage(AnalysisUsage &AU) const override {
101 // We add and rewrite a bunch of instructions, but don't really do much
102 // else. We could in theory preserve a lot more analyses here.
103 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000104 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000105 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000106
107 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
108 /// dereferenceability that are no longer valid/correct after
109 /// RewriteStatepointsForGC has run. This is because semantically, after
110 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
111 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
112 /// by erasing all attributes in the module that externally imply
113 /// dereferenceability.
114 ///
115 void stripDereferenceabilityInfo(Module &M);
116
117 // Helpers for stripDereferenceabilityInfo
118 void stripDereferenceabilityInfoFromBody(Function &F);
119 void stripDereferenceabilityInfoFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000120};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000121} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000122
123char RewriteStatepointsForGC::ID = 0;
124
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000125ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000126 return new RewriteStatepointsForGC();
127}
128
129INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
130 "Make relocations explicit at statepoints", false, false)
131INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
132INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
133 "Make relocations explicit at statepoints", false, false)
134
135namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000136struct GCPtrLivenessData {
137 /// Values defined in this block.
138 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
139 /// Values used in this block (and thus live); does not included values
140 /// killed within this block.
141 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
142
143 /// Values live into this basic block (i.e. used by any
144 /// instruction in this basic block or ones reachable from here)
145 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
146
147 /// Values live out of this basic block (i.e. live into
148 /// any successor block)
149 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
150};
151
Philip Reamesd16a9b12015-02-20 01:06:44 +0000152// The type of the internal cache used inside the findBasePointers family
153// of functions. From the callers perspective, this is an opaque type and
154// should not be inspected.
155//
156// In the actual implementation this caches two relations:
157// - The base relation itself (i.e. this pointer is based on that one)
158// - The base defining value relation (i.e. before base_phi insertion)
159// Generally, after the execution of a full findBasePointer call, only the
160// base relation will remain. Internally, we add a mixture of the two
161// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000162typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Philip Reames1f017542015-02-20 23:16:52 +0000163typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
Igor Laevskye0317182015-05-19 15:59:05 +0000164typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000165
Philip Reamesd16a9b12015-02-20 01:06:44 +0000166struct PartiallyConstructedSafepointRecord {
167 /// The set of values known to be live accross this safepoint
Philip Reames860660e2015-02-20 22:05:18 +0000168 StatepointLiveSetTy liveset;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000169
170 /// Mapping from live pointers to a base-defining-value
Philip Reamesf2041322015-02-20 19:26:04 +0000171 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000172
Philip Reames0a3240f2015-02-20 21:34:11 +0000173 /// The *new* gc.statepoint instruction itself. This produces the token
174 /// that normal path gc.relocates and the gc.result are tied to.
175 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000176
Philip Reamesf2041322015-02-20 19:26:04 +0000177 /// Instruction to which exceptional gc relocates are attached
178 /// Makes it easier to iterate through them during relocationViaAlloca.
179 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000180
181 /// Record live values we are rematerialized instead of relocating.
182 /// They are not included into 'liveset' field.
183 /// Maps rematerialized copy to it's original value.
184 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000185};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000186}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000187
Philip Reamesdf1ef082015-04-10 22:53:14 +0000188/// Compute the live-in set for every basic block in the function
189static void computeLiveInValues(DominatorTree &DT, Function &F,
190 GCPtrLivenessData &Data);
191
192/// Given results from the dataflow liveness computation, find the set of live
193/// Values at a particular instruction.
194static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
195 StatepointLiveSetTy &out);
196
Philip Reamesd16a9b12015-02-20 01:06:44 +0000197// TODO: Once we can get to the GCStrategy, this becomes
198// Optional<bool> isGCManagedPointer(const Value *V) const override {
199
200static bool isGCPointerType(const Type *T) {
201 if (const PointerType *PT = dyn_cast<PointerType>(T))
202 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
203 // GC managed heap. We know that a pointer into this heap needs to be
204 // updated and that no other pointer does.
205 return (1 == PT->getAddressSpace());
206 return false;
207}
208
Philip Reames8531d8c2015-04-10 21:48:25 +0000209// Return true if this type is one which a) is a gc pointer or contains a GC
210// pointer and b) is of a type this code expects to encounter as a live value.
211// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000212// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000213static bool isHandledGCPointerType(Type *T) {
214 // We fully support gc pointers
215 if (isGCPointerType(T))
216 return true;
217 // We partially support vectors of gc pointers. The code will assert if it
218 // can't handle something.
219 if (auto VT = dyn_cast<VectorType>(T))
220 if (isGCPointerType(VT->getElementType()))
221 return true;
222 return false;
223}
224
225#ifndef NDEBUG
226/// Returns true if this type contains a gc pointer whether we know how to
227/// handle that type or not.
228static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000229 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000230 return true;
231 if (VectorType *VT = dyn_cast<VectorType>(Ty))
232 return isGCPointerType(VT->getScalarType());
233 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
234 return containsGCPtrType(AT->getElementType());
235 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000236 return std::any_of(
237 ST->subtypes().begin(), ST->subtypes().end(),
238 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000239 return false;
240}
241
242// Returns true if this is a type which a) is a gc pointer or contains a GC
243// pointer and b) is of a type which the code doesn't expect (i.e. first class
244// aggregates). Used to trip assertions.
245static bool isUnhandledGCPointerType(Type *Ty) {
246 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
247}
248#endif
249
Philip Reamesd16a9b12015-02-20 01:06:44 +0000250static bool order_by_name(llvm::Value *a, llvm::Value *b) {
251 if (a->hasName() && b->hasName()) {
252 return -1 == a->getName().compare(b->getName());
253 } else if (a->hasName() && !b->hasName()) {
254 return true;
255 } else if (!a->hasName() && b->hasName()) {
256 return false;
257 } else {
258 // Better than nothing, but not stable
259 return a < b;
260 }
261}
262
Philip Reamesdf1ef082015-04-10 22:53:14 +0000263// Conservatively identifies any definitions which might be live at the
264// given instruction. The analysis is performed immediately before the
265// given instruction. Values defined by that instruction are not considered
266// live. Values used by that instruction are considered live.
267static void analyzeParsePointLiveness(
268 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
269 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000270 Instruction *inst = CS.getInstruction();
271
Philip Reames1f017542015-02-20 23:16:52 +0000272 StatepointLiveSetTy liveset;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000273 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000274
275 if (PrintLiveSet) {
276 // Note: This output is used by several of the test cases
277 // The order of elemtns in a set is not stable, put them in a vec and sort
278 // by name
Philip Reames860660e2015-02-20 22:05:18 +0000279 SmallVector<Value *, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000280 temp.insert(temp.end(), liveset.begin(), liveset.end());
281 std::sort(temp.begin(), temp.end(), order_by_name);
282 errs() << "Live Variables:\n";
283 for (Value *V : temp) {
284 errs() << " " << V->getName(); // no newline
285 V->dump();
286 }
287 }
288 if (PrintLiveSetSize) {
289 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
290 errs() << "Number live values: " << liveset.size() << "\n";
291 }
292 result.liveset = liveset;
293}
294
Philip Reames311f7102015-05-12 22:19:52 +0000295static Value *findBaseDefiningValue(Value *I);
296
Philip Reames8fe7f132015-06-26 22:47:37 +0000297/// Return a base defining value for the 'Index' element of the given vector
298/// instruction 'I'. If Index is null, returns a BDV for the entire vector
299/// 'I'. As an optimization, this method will try to determine when the
300/// element is known to already be a base pointer. If this can be established,
301/// the second value in the returned pair will be true. Note that either a
302/// vector or a pointer typed value can be returned. For the former, the
303/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
304/// If the later, the return pointer is a BDV (or possibly a base) for the
305/// particular element in 'I'.
306static std::pair<Value *, bool>
307findBaseDefiningValueOfVector(Value *I, Value *Index = nullptr) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000308 assert(I->getType()->isVectorTy() &&
309 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
310 "Illegal to ask for the base pointer of a non-pointer type");
311
312 // Each case parallels findBaseDefiningValue below, see that code for
313 // detailed motivation.
314
315 if (isa<Argument>(I))
316 // An incoming argument to the function is a base pointer
Philip Reames8fe7f132015-06-26 22:47:37 +0000317 return std::make_pair(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000318
319 // We shouldn't see the address of a global as a vector value?
320 assert(!isa<GlobalVariable>(I) &&
321 "unexpected global variable found in base of vector");
322
323 // inlining could possibly introduce phi node that contains
324 // undef if callee has multiple returns
325 if (isa<UndefValue>(I))
326 // utterly meaningless, but useful for dealing with partially optimized
327 // code.
Philip Reames8fe7f132015-06-26 22:47:37 +0000328 return std::make_pair(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000329
330 // Due to inheritance, this must be _after_ the global variable and undef
331 // checks
332 if (Constant *Con = dyn_cast<Constant>(I)) {
333 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
334 "order of checks wrong!");
335 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reames8fe7f132015-06-26 22:47:37 +0000336 return std::make_pair(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000337 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000338
Philip Reames8531d8c2015-04-10 21:48:25 +0000339 if (isa<LoadInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000340 return std::make_pair(I, true);
341
Philip Reames311f7102015-05-12 22:19:52 +0000342 // For an insert element, we might be able to look through it if we know
Philip Reames8fe7f132015-06-26 22:47:37 +0000343 // something about the indexes.
Philip Reames311f7102015-05-12 22:19:52 +0000344 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000345 if (Index) {
346 Value *InsertIndex = IEI->getOperand(2);
347 // This index is inserting the value, look for its BDV
348 if (InsertIndex == Index)
349 return std::make_pair(findBaseDefiningValue(IEI->getOperand(1)), false);
350 // Both constant, and can't be equal per above. This insert is definitely
351 // not relevant, look back at the rest of the vector and keep trying.
352 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
353 return findBaseDefiningValueOfVector(IEI->getOperand(0), Index);
354 }
355
356 // We don't know whether this vector contains entirely base pointers or
357 // not. To be conservatively correct, we treat it as a BDV and will
358 // duplicate code as needed to construct a parallel vector of bases.
359 return std::make_pair(IEI, false);
Philip Reames311f7102015-05-12 22:19:52 +0000360 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000361
Philip Reames8fe7f132015-06-26 22:47:37 +0000362 if (isa<ShuffleVectorInst>(I))
363 // We don't know whether this vector contains entirely base pointers or
364 // not. To be conservatively correct, we treat it as a BDV and will
365 // duplicate code as needed to construct a parallel vector of bases.
366 // TODO: There a number of local optimizations which could be applied here
367 // for particular sufflevector patterns.
368 return std::make_pair(I, false);
369
370 // A PHI or Select is a base defining value. The outer findBasePointer
371 // algorithm is responsible for constructing a base value for this BDV.
372 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
373 "unknown vector instruction - no base found for vector element");
374 return std::make_pair(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000375}
376
Philip Reames8fe7f132015-06-26 22:47:37 +0000377static bool isKnownBaseResult(Value *V);
378
Philip Reamesd16a9b12015-02-20 01:06:44 +0000379/// Helper function for findBasePointer - Will return a value which either a)
380/// defines the base pointer for the input or b) blocks the simple search
381/// (i.e. a PHI or Select of two derived pointers)
382static Value *findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000383 if (I->getType()->isVectorTy())
384 return findBaseDefiningValueOfVector(I).first;
385
Philip Reamesd16a9b12015-02-20 01:06:44 +0000386 assert(I->getType()->isPointerTy() &&
387 "Illegal to ask for the base pointer of a non-pointer type");
388
Philip Reames8531d8c2015-04-10 21:48:25 +0000389 // This case is a bit of a hack - it only handles extracts from vectors which
Philip Reames311f7102015-05-12 22:19:52 +0000390 // trivially contain only base pointers or cases where we can directly match
391 // the index of the original extract element to an insertion into the vector.
392 // See note inside the function for how to improve this.
Philip Reames8531d8c2015-04-10 21:48:25 +0000393 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
394 Value *VectorOperand = EEI->getVectorOperand();
Philip Reames311f7102015-05-12 22:19:52 +0000395 Value *Index = EEI->getIndexOperand();
Philip Reames8fe7f132015-06-26 22:47:37 +0000396 std::pair<Value *, bool> pair =
397 findBaseDefiningValueOfVector(VectorOperand, Index);
398 Value *VectorBase = pair.first;
399 if (VectorBase->getType()->isPointerTy())
400 // We found a BDV for this specific element with the vector. This is an
401 // optimization, but in practice it covers most of the useful cases
402 // created via scalarization.
403 return VectorBase;
404 else {
405 assert(VectorBase->getType()->isVectorTy());
406 if (pair.second)
407 // If the entire vector returned is known to be entirely base pointers,
408 // then the extractelement is valid base for this value.
409 return EEI;
410 else {
411 // Otherwise, we have an instruction which potentially produces a
412 // derived pointer and we need findBasePointers to clone code for us
413 // such that we can create an instruction which produces the
414 // accompanying base pointer.
415 // Note: This code is currently rather incomplete. We don't currently
416 // support the general form of shufflevector of insertelement.
417 // Conceptually, these are just 'base defining values' of the same
418 // variety as phi or select instructions. We need to update the
419 // findBasePointers algorithm to insert new 'base-only' versions of the
420 // original instructions. This is relative straight forward to do, but
421 // the case which would motivate the work hasn't shown up in real
422 // workloads yet.
423 assert((isa<PHINode>(VectorBase) || isa<SelectInst>(VectorBase)) &&
424 "need to extend findBasePointers for generic vector"
425 "instruction cases");
426 return VectorBase;
427 }
428 }
Philip Reames8531d8c2015-04-10 21:48:25 +0000429 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000430
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000431 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000432 // An incoming argument to the function is a base pointer
433 // We should have never reached here if this argument isn't an gc value
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000434 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000435
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000436 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000437 // base case
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000438 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000439
440 // inlining could possibly introduce phi node that contains
441 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000442 if (isa<UndefValue>(I))
443 // utterly meaningless, but useful for dealing with
444 // partially optimized code.
Philip Reames704e78b2015-04-10 22:34:56 +0000445 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000446
447 // Due to inheritance, this must be _after_ the global variable and undef
448 // checks
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000449 if (Constant *Con = dyn_cast<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000450 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
451 "order of checks wrong!");
452 // Note: Finding a constant base for something marked for relocation
453 // doesn't really make sense. The most likely case is either a) some
454 // screwed up the address space usage or b) your validating against
455 // compiled C++ code w/o the proper separation. The only real exception
456 // is a null pointer. You could have generic code written to index of
457 // off a potentially null value and have proven it null. We also use
458 // null pointers in dead paths of relocation phis (which we might later
459 // want to find a base pointer for).
Philip Reames24c6cd52015-03-27 05:47:00 +0000460 assert(isa<ConstantPointerNull>(Con) &&
461 "null is the only case which makes sense");
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000462 return Con;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000463 }
464
465 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000466 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000467 // If we find a cast instruction here, it means we've found a cast which is
468 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
469 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000470 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
471 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000472 }
473
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000474 if (isa<LoadInst>(I))
475 return I; // The value loaded is an gc base itself
Philip Reamesd16a9b12015-02-20 01:06:44 +0000476
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000477 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
478 // The base of this GEP is the base
479 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000480
481 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
482 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000483 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000484 default:
485 // fall through to general call handling
486 break;
487 case Intrinsic::experimental_gc_statepoint:
488 case Intrinsic::experimental_gc_result_float:
489 case Intrinsic::experimental_gc_result_int:
490 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000491 case Intrinsic::experimental_gc_relocate: {
492 // Rerunning safepoint insertion after safepoints are already
493 // inserted is not supported. It could probably be made to work,
494 // but why are you doing this? There's no good reason.
495 llvm_unreachable("repeat safepoint insertion is not supported");
496 }
497 case Intrinsic::gcroot:
498 // Currently, this mechanism hasn't been extended to work with gcroot.
499 // There's no reason it couldn't be, but I haven't thought about the
500 // implications much.
501 llvm_unreachable(
502 "interaction with the gcroot mechanism is not supported");
503 }
504 }
505 // We assume that functions in the source language only return base
506 // pointers. This should probably be generalized via attributes to support
507 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000508 if (isa<CallInst>(I) || isa<InvokeInst>(I))
509 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000510
511 // I have absolutely no idea how to implement this part yet. It's not
512 // neccessarily hard, I just haven't really looked at it yet.
513 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
514
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000515 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000516 // A CAS is effectively a atomic store and load combined under a
517 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000518 // like a load.
519 return I;
Philip Reames704e78b2015-04-10 22:34:56 +0000520
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000521 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000522 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000523
524 // The aggregate ops. Aggregates can either be in the heap or on the
525 // stack, but in either case, this is simply a field load. As a result,
526 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000527 if (isa<ExtractValueInst>(I))
528 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000529
530 // We should never see an insert vector since that would require we be
531 // tracing back a struct value not a pointer value.
532 assert(!isa<InsertValueInst>(I) &&
533 "Base pointer for a struct is meaningless");
534
535 // The last two cases here don't return a base pointer. Instead, they
536 // return a value which dynamically selects from amoung several base
537 // derived pointers (each with it's own base potentially). It's the job of
538 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000539 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000540 "missing instruction case in findBaseDefiningValing");
541 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000542}
543
544/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000545static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
546 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000547 if (!Cached) {
548 Cached = findBaseDefiningValue(I);
Philip Reames2a892a62015-07-23 22:25:26 +0000549 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
550 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000551 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000552 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000553 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000554}
555
556/// Return a base pointer for this value if known. Otherwise, return it's
557/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000558static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
559 Value *Def = findBaseDefiningValueCached(I, Cache);
560 auto Found = Cache.find(Def);
561 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000562 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000563 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000564 }
565 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000566 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000567}
568
569/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
570/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000571static bool isKnownBaseResult(Value *V) {
572 if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000573 // no recursion possible
574 return true;
575 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000576 if (isa<Instruction>(V) &&
577 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000578 // This is a previously inserted base phi or select. We know
579 // that this is a base value.
580 return true;
581 }
582
583 // We need to keep searching
584 return false;
585}
586
Philip Reamesd16a9b12015-02-20 01:06:44 +0000587namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000588/// Models the state of a single base defining value in the findBasePointer
589/// algorithm for determining where a new instruction is needed to propagate
590/// the base of this BDV.
591class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000592public:
593 enum Status { Unknown, Base, Conflict };
594
Philip Reames9b141ed2015-07-23 22:49:14 +0000595 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000596 assert(status != Base || b);
597 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000598 explicit BDVState(Value *b) : status(Base), base(b) {}
599 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000600
601 Status getStatus() const { return status; }
602 Value *getBase() const { return base; }
603
604 bool isBase() const { return getStatus() == Base; }
605 bool isUnknown() const { return getStatus() == Unknown; }
606 bool isConflict() const { return getStatus() == Conflict; }
607
Philip Reames9b141ed2015-07-23 22:49:14 +0000608 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000609 return base == other.base && status == other.status;
610 }
611
Philip Reames9b141ed2015-07-23 22:49:14 +0000612 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000613
Philip Reames2a892a62015-07-23 22:25:26 +0000614 LLVM_DUMP_METHOD
615 void dump() const { print(dbgs()); dbgs() << '\n'; }
616
617 void print(raw_ostream &OS) const {
618 OS << status << " (" << base << " - "
619 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000620 }
621
622private:
623 Status status;
624 Value *base; // non null only if status == base
625};
626
Philip Reames9b141ed2015-07-23 22:49:14 +0000627inline raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000628 State.print(OS);
629 return OS;
630}
631
632
Philip Reames9b141ed2015-07-23 22:49:14 +0000633typedef DenseMap<Value *, BDVState> ConflictStateMapTy;
634// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000635// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000636// operation is implemented in MeetBDVStates::pureMeet
637class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000638public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000639 /// Initializes the currentResult to the TOP state so that if can be met with
640 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000641 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000642
Philip Reames9b141ed2015-07-23 22:49:14 +0000643 // Destructively meet the current result with the given BDVState
644 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000645 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000646 }
647
Philip Reames9b141ed2015-07-23 22:49:14 +0000648 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000649
650private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000651 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000652
Philip Reames9b141ed2015-07-23 22:49:14 +0000653 /// Perform a meet operation on two elements of the BDVState lattice.
654 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000655 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
656 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000657 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000658 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
659 << " produced " << Result << "\n");
660 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000661 }
662
Philip Reames9b141ed2015-07-23 22:49:14 +0000663 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000664 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000665 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000666 return stateB;
667
Philip Reames9b141ed2015-07-23 22:49:14 +0000668 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000669 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000670 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000671 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000672
673 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000674 if (stateA.getBase() == stateB.getBase()) {
675 assert(stateA == stateB && "equality broken!");
676 return stateA;
677 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000678 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000679 }
David Blaikie82ad7872015-02-20 23:44:24 +0000680 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000681 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000682
Philip Reames9b141ed2015-07-23 22:49:14 +0000683 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000684 return stateA;
685 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000686 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000687 }
688};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000689}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000690/// For a given value or instruction, figure out what base ptr it's derived
691/// from. For gc objects, this is simply itself. On success, returns a value
692/// which is the base pointer. (This is reliable and can be used for
693/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000694static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000695 Value *def = findBaseOrBDV(I, cache);
696
697 if (isKnownBaseResult(def)) {
698 return def;
699 }
700
701 // Here's the rough algorithm:
702 // - For every SSA value, construct a mapping to either an actual base
703 // pointer or a PHI which obscures the base pointer.
704 // - Construct a mapping from PHI to unknown TOP state. Use an
705 // optimistic algorithm to propagate base pointer information. Lattice
706 // looks like:
707 // UNKNOWN
708 // b1 b2 b3 b4
709 // CONFLICT
710 // When algorithm terminates, all PHIs will either have a single concrete
711 // base or be in a conflict state.
712 // - For every conflict, insert a dummy PHI node without arguments. Add
713 // these to the base[Instruction] = BasePtr mapping. For every
714 // non-conflict, add the actual base.
715 // - For every conflict, add arguments for the base[a] of each input
716 // arguments.
717 //
718 // Note: A simpler form of this would be to add the conflict form of all
719 // PHIs without running the optimistic algorithm. This would be
720 // analougous to pessimistic data flow and would likely lead to an
721 // overall worse solution.
722
Philip Reames29e9ae72015-07-24 00:42:55 +0000723#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000724 auto isExpectedBDVType = [](Value *BDV) {
725 return isa<PHINode>(BDV) || isa<SelectInst>(BDV);
726 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000727#endif
Philip Reames88958b22015-07-24 00:02:11 +0000728
729 // Once populated, will contain a mapping from each potentially non-base BDV
730 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames860660e2015-02-20 22:05:18 +0000731 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000732 // Recursively fill in all phis & selects reachable from the initial one
733 // for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000734 /* scope */ {
735 DenseSet<Value *> Visited;
736 SmallVector<Value*, 16> Worklist;
737 Worklist.push_back(def);
738 Visited.insert(def);
739 while (!Worklist.empty()) {
740 Value *Current = Worklist.pop_back_val();
741 assert(!isKnownBaseResult(Current) && "why did it get added?");
742
743 auto visitIncomingValue = [&](Value *InVal) {
744 Value *Base = findBaseOrBDV(InVal, cache);
745 if (isKnownBaseResult(Base))
746 // Known bases won't need new instructions introduced and can be
747 // ignored safely
748 return;
749 assert(isExpectedBDVType(Base) && "the only non-base values "
750 "we see should be base defining values");
751 if (Visited.insert(Base).second)
752 Worklist.push_back(Base);
753 };
754 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
755 for (Value *InVal : Phi->incoming_values())
756 visitIncomingValue(InVal);
757 } else {
758 SelectInst *Sel = cast<SelectInst>(Current);
759 visitIncomingValue(Sel->getTrueValue());
760 visitIncomingValue(Sel->getFalseValue());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000761 }
762 }
Philip Reames88958b22015-07-24 00:02:11 +0000763 // The frontier of visited instructions are the ones we might need to
764 // duplicate, so fill in the starting state for the optimistic algorithm
765 // that follows.
766 for (Value *BDV : Visited) {
767 states[BDV] = BDVState();
768 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000769 }
770
771 if (TraceLSP) {
772 errs() << "States after initialization:\n";
Philip Reames2a892a62015-07-23 22:25:26 +0000773 for (auto Pair : states)
774 dbgs() << " " << Pair.second << " for " << Pair.first << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000775 }
776
777 // TODO: come back and revisit the state transitions around inputs which
778 // have reached conflict state. The current version seems too conservative.
779
Philip Reames273e6bb2015-07-23 21:41:27 +0000780 // Return a phi state for a base defining value. We'll generate a new
781 // base state for known bases and expect to find a cached state otherwise.
782 auto getStateForBDV = [&](Value *baseValue) {
783 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000784 return BDVState(baseValue);
Philip Reames273e6bb2015-07-23 21:41:27 +0000785 auto I = states.find(baseValue);
786 assert(I != states.end() && "lookup failed!");
787 return I->second;
788 };
789
Philip Reamesd16a9b12015-02-20 01:06:44 +0000790 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000791 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000792#ifndef NDEBUG
793 size_t oldSize = states.size();
794#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000795 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000796 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000797 for (auto Pair : states) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000798 Value *v = Pair.first;
799 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000800
Philip Reames9b141ed2015-07-23 22:49:14 +0000801 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000802 // instance which represents the BDV of that value.
803 auto getStateForInput = [&](Value *V) mutable {
804 Value *BDV = findBaseOrBDV(V, cache);
805 return getStateForBDV(BDV);
806 };
807
Philip Reames9b141ed2015-07-23 22:49:14 +0000808 MeetBDVStates calculateMeet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000809 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000810 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
811 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
David Blaikie82ad7872015-02-20 23:44:24 +0000812 } else
813 for (Value *Val : cast<PHINode>(v)->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000814 calculateMeet.meetWith(getStateForInput(Val));
Philip Reamesd16a9b12015-02-20 01:06:44 +0000815
Philip Reames9b141ed2015-07-23 22:49:14 +0000816 BDVState oldState = states[v];
817 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000818 if (oldState != newState) {
819 progress = true;
820 states[v] = newState;
821 }
822 }
823
824 assert(oldSize <= states.size());
825 assert(oldSize == states.size() || progress);
826 }
827
828 if (TraceLSP) {
829 errs() << "States after meet iteration:\n";
Philip Reames2a892a62015-07-23 22:25:26 +0000830 for (auto Pair : states)
831 dbgs() << " " << Pair.second << " for " << Pair.first << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000832 }
833
834 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000835 // We want to keep naming deterministic in the loop that follows, so
836 // sort the keys before iteration. This is useful in allowing us to
837 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000838 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000839 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000840 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000841 Value *V = Pair.first;
842 Keys.push_back(V);
843 }
844 std::sort(Keys.begin(), Keys.end(), order_by_name);
845 // TODO: adjust naming patterns to avoid this order of iteration dependency
846 for (Value *V : Keys) {
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000847 Instruction *I = cast<Instruction>(V);
Philip Reames9b141ed2015-07-23 22:49:14 +0000848 BDVState State = states[I];
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000849 assert(!isKnownBaseResult(I) && "why did it get added?");
850 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
851 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000852 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000853
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000854 /// Create and insert a new instruction which will represent the base of
855 /// the given instruction 'I'.
856 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
857 if (isa<PHINode>(I)) {
858 BasicBlock *BB = I->getParent();
859 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
860 assert(NumPreds > 0 && "how did we reach here");
861 return PHINode::Create(I->getType(), NumPreds, "base_phi", I);
862 }
863 SelectInst *Sel = cast<SelectInst>(I);
Philip Reamesf986d682015-02-28 00:54:41 +0000864 // The undef will be replaced later
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000865 UndefValue *Undef = UndefValue::get(Sel->getType());
866 return SelectInst::Create(Sel->getCondition(), Undef,
867 Undef, "base_select", Sel);
868 };
869 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
870 // Add metadata marking this as a base value
871 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames9b141ed2015-07-23 22:49:14 +0000872 states[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000873 }
874
875 // Fixup all the inputs of the new PHIs
876 for (auto Pair : states) {
877 Instruction *v = cast<Instruction>(Pair.first);
Philip Reames9b141ed2015-07-23 22:49:14 +0000878 BDVState state = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000879
880 assert(!isKnownBaseResult(v) && "why did it get added?");
881 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000882 if (!state.isConflict())
883 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000884
Philip Reames28e61ce2015-02-28 01:57:44 +0000885 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
886 PHINode *phi = cast<PHINode>(v);
887 unsigned NumPHIValues = phi->getNumIncomingValues();
888 for (unsigned i = 0; i < NumPHIValues; i++) {
889 Value *InVal = phi->getIncomingValue(i);
890 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000891
Philip Reames28e61ce2015-02-28 01:57:44 +0000892 // If we've already seen InBB, add the same incoming value
893 // we added for it earlier. The IR verifier requires phi
894 // nodes with multiple entries from the same basic block
895 // to have the same incoming value for each of those
896 // entries. If we don't do this check here and basephi
897 // has a different type than base, we'll end up adding two
898 // bitcasts (and hence two distinct values) as incoming
899 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000900
Philip Reames28e61ce2015-02-28 01:57:44 +0000901 int blockIndex = basephi->getBasicBlockIndex(InBB);
902 if (blockIndex != -1) {
903 Value *oldBase = basephi->getIncomingValue(blockIndex);
904 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000905#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000906 Value *base = findBaseOrBDV(InVal, cache);
907 if (!isKnownBaseResult(base)) {
908 // Either conflict or base.
909 assert(states.count(base));
910 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000911 assert(base != nullptr && "unknown BDVState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000912 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000913
Philip Reames28e61ce2015-02-28 01:57:44 +0000914 // In essense this assert states: the only way two
915 // values incoming from the same basic block may be
916 // different is by being different bitcasts of the same
917 // value. A cleanup that remains TODO is changing
918 // findBaseOrBDV to return an llvm::Value of the correct
919 // type (and still remain pure). This will remove the
920 // need to add bitcasts.
921 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
922 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000923#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000924 continue;
925 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000926
Philip Reames28e61ce2015-02-28 01:57:44 +0000927 // Find either the defining value for the PHI or the normal base for
928 // a non-phi node
929 Value *base = findBaseOrBDV(InVal, cache);
930 if (!isKnownBaseResult(base)) {
931 // Either conflict or base.
932 assert(states.count(base));
933 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000934 assert(base != nullptr && "unknown BDVState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000935 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000936 assert(base && "can't be null");
937 // Must use original input BB since base may not be Instruction
938 // The cast is needed since base traversal may strip away bitcasts
939 if (base->getType() != basephi->getType()) {
940 base = new BitCastInst(base, basephi->getType(), "cast",
941 InBB->getTerminator());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000942 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000943 basephi->addIncoming(base, InBB);
944 }
945 assert(basephi->getNumIncomingValues() == NumPHIValues);
946 } else {
947 SelectInst *basesel = cast<SelectInst>(state.getBase());
948 SelectInst *sel = cast<SelectInst>(v);
949 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
950 // something more safe and less hacky.
951 for (int i = 1; i <= 2; i++) {
952 Value *InVal = sel->getOperand(i);
953 // Find either the defining value for the PHI or the normal base for
954 // a non-phi node
955 Value *base = findBaseOrBDV(InVal, cache);
956 if (!isKnownBaseResult(base)) {
957 // Either conflict or base.
958 assert(states.count(base));
959 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000960 assert(base != nullptr && "unknown BDVState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000961 }
962 assert(base && "can't be null");
963 // Must use original input BB since base may not be Instruction
964 // The cast is needed since base traversal may strip away bitcasts
965 if (base->getType() != basesel->getType()) {
966 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
Philip Reames28e61ce2015-02-28 01:57:44 +0000967 }
968 basesel->setOperand(i, base);
969 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000970 }
971 }
972
973 // Cache all of our results so we can cheaply reuse them
974 // NOTE: This is actually two caches: one of the base defining value
975 // relation and one of the base pointer relation! FIXME
976 for (auto item : states) {
977 Value *v = item.first;
978 Value *base = item.second.getBase();
979 assert(v && base);
980 assert(!isKnownBaseResult(v) && "why did it get added?");
981
982 if (TraceLSP) {
983 std::string fromstr =
984 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
985 : "none";
986 errs() << "Updating base value cache"
987 << " for: " << (v->hasName() ? v->getName() : "")
988 << " from: " << fromstr
989 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
990 }
991
992 assert(isKnownBaseResult(base) &&
993 "must be something we 'know' is a base pointer");
994 if (cache.count(v)) {
995 // Once we transition from the BDV relation being store in the cache to
996 // the base relation being stored, it must be stable
997 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
998 "base relation should be stable");
999 }
1000 cache[v] = base;
1001 }
1002 assert(cache.find(def) != cache.end());
1003 return cache[def];
1004}
1005
1006// For a set of live pointers (base and/or derived), identify the base
1007// pointer of the object which they are derived from. This routine will
1008// mutate the IR graph as needed to make the 'base' pointer live at the
1009// definition site of 'derived'. This ensures that any use of 'derived' can
1010// also use 'base'. This may involve the insertion of a number of
1011// additional PHI nodes.
1012//
1013// preconditions: live is a set of pointer type Values
1014//
1015// side effects: may insert PHI nodes into the existing CFG, will preserve
1016// CFG, will not remove or mutate any existing nodes
1017//
Philip Reamesf2041322015-02-20 19:26:04 +00001018// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001019// pointer in live. Note that derived can be equal to base if the original
1020// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001021static void
1022findBasePointers(const StatepointLiveSetTy &live,
1023 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001024 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001025 // For the naming of values inserted to be deterministic - which makes for
1026 // much cleaner and more stable tests - we need to assign an order to the
1027 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001028 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001029 Temp.insert(Temp.end(), live.begin(), live.end());
1030 std::sort(Temp.begin(), Temp.end(), order_by_name);
1031 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001032 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001033 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001034 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001035 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1036 DT->dominates(cast<Instruction>(base)->getParent(),
1037 cast<Instruction>(ptr)->getParent())) &&
1038 "The base we found better dominate the derived pointer");
1039
David Blaikie82ad7872015-02-20 23:44:24 +00001040 // If you see this trip and like to live really dangerously, the code should
1041 // be correct, just with idioms the verifier can't handle. You can try
1042 // disabling the verifier at your own substaintial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001043 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001044 "the relocation code needs adjustment to handle the relocation of "
1045 "a null pointer constant without causing false positives in the "
1046 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001047 }
1048}
1049
1050/// Find the required based pointers (and adjust the live set) for the given
1051/// parse point.
1052static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1053 const CallSite &CS,
1054 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001055 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +00001056 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001057
1058 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001059 // Note: Need to print these in a stable order since this is checked in
1060 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001061 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001062 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001063 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001064 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001065 Temp.push_back(Pair.first);
1066 }
1067 std::sort(Temp.begin(), Temp.end(), order_by_name);
1068 for (Value *Ptr : Temp) {
1069 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001070 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1071 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001072 }
1073 }
1074
Philip Reamesf2041322015-02-20 19:26:04 +00001075 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001076}
1077
Philip Reamesdf1ef082015-04-10 22:53:14 +00001078/// Given an updated version of the dataflow liveness results, update the
1079/// liveset and base pointer maps for the call site CS.
1080static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1081 const CallSite &CS,
1082 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001083
Philip Reamesdf1ef082015-04-10 22:53:14 +00001084static void recomputeLiveInValues(
1085 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001086 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001087 // TODO-PERF: reuse the original liveness, then simply run the dataflow
1088 // again. The old values are still live and will help it stablize quickly.
1089 GCPtrLivenessData RevisedLivenessData;
1090 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001091 for (size_t i = 0; i < records.size(); i++) {
1092 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001093 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001094 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001095 }
1096}
1097
Philip Reames69e51ca2015-04-13 18:07:21 +00001098// When inserting gc.relocate calls, we need to ensure there are no uses
1099// of the original value between the gc.statepoint and the gc.relocate call.
1100// One case which can arise is a phi node starting one of the successor blocks.
1101// We also need to be able to insert the gc.relocates only on the path which
1102// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001103// possible.
1104static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001105normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1106 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001107 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001108 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001109 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001110 }
1111
Philip Reames69e51ca2015-04-13 18:07:21 +00001112 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1113 // from it
1114 FoldSingleEntryPHINodes(Ret);
1115 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001116
Philip Reames69e51ca2015-04-13 18:07:21 +00001117 // At this point, we can safely insert a gc.relocate as the first instruction
1118 // in Ret if needed.
1119 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001120}
1121
Philip Reamesd2b66462015-02-20 22:39:41 +00001122static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001123 auto itr = std::find(livevec.begin(), livevec.end(), val);
1124 assert(livevec.end() != itr);
1125 size_t index = std::distance(livevec.begin(), itr);
1126 assert(index < livevec.size());
1127 return index;
1128}
1129
1130// Create new attribute set containing only attributes which can be transfered
1131// from original call to the safepoint.
1132static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1133 AttributeSet ret;
1134
1135 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1136 unsigned index = AS.getSlotIndex(Slot);
1137
1138 if (index == AttributeSet::ReturnIndex ||
1139 index == AttributeSet::FunctionIndex) {
1140
1141 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1142 ++it) {
1143 Attribute attr = *it;
1144
1145 // Do not allow certain attributes - just skip them
1146 // Safepoint can not be read only or read none.
1147 if (attr.hasAttribute(Attribute::ReadNone) ||
1148 attr.hasAttribute(Attribute::ReadOnly))
1149 continue;
1150
1151 ret = ret.addAttributes(
1152 AS.getContext(), index,
1153 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1154 }
1155 }
1156
1157 // Just skip parameter attributes for now
1158 }
1159
1160 return ret;
1161}
1162
1163/// Helper function to place all gc relocates necessary for the given
1164/// statepoint.
1165/// Inputs:
1166/// liveVariables - list of variables to be relocated.
1167/// liveStart - index of the first live variable.
1168/// basePtrs - base pointers.
1169/// statepointToken - statepoint instruction to which relocates should be
1170/// bound.
1171/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001172static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1173 const int LiveStart,
1174 ArrayRef<llvm::Value *> BasePtrs,
1175 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001176 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001177 if (LiveVariables.empty())
1178 return;
1179
1180 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1181 // unique declarations for each pointer type, but this proved problematic
1182 // because the intrinsic mangling code is incomplete and fragile. Since
1183 // we're moving towards a single unified pointer type anyways, we can just
1184 // cast everything to an i8* of the right address space. A bitcast is added
1185 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001186 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001187 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1188 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1189 Value *GCRelocateDecl =
1190 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001191
Sanjoy Das5665c992015-05-11 23:47:27 +00001192 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001193 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001194 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001195 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1196 Value *LiveIdx =
1197 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001198
1199 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001200 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001201 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001202 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001203 : "");
1204 // Trick CodeGen into thinking there are lots of free registers at this
1205 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001206 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001207 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001208}
1209
1210static void
1211makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1212 const SmallVectorImpl<llvm::Value *> &basePtrs,
1213 const SmallVectorImpl<llvm::Value *> &liveVariables,
1214 Pass *P,
1215 PartiallyConstructedSafepointRecord &result) {
1216 assert(basePtrs.size() == liveVariables.size());
1217 assert(isStatepoint(CS) &&
1218 "This method expects to be rewriting a statepoint");
1219
1220 BasicBlock *BB = CS.getInstruction()->getParent();
1221 assert(BB);
1222 Function *F = BB->getParent();
1223 assert(F && "must be set");
1224 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001225 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001226 assert(M && "must be set");
1227
1228 // We're not changing the function signature of the statepoint since the gc
1229 // arguments go into the var args section.
1230 Function *gc_statepoint_decl = CS.getCalledFunction();
1231
1232 // Then go ahead and use the builder do actually do the inserts. We insert
1233 // immediately before the previous instruction under the assumption that all
1234 // arguments will be available here. We can't insert afterwards since we may
1235 // be replacing a terminator.
1236 Instruction *insertBefore = CS.getInstruction();
1237 IRBuilder<> Builder(insertBefore);
1238 // Copy all of the arguments from the original statepoint - this includes the
1239 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001240 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001241 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1242 // TODO: Clear the 'needs rewrite' flag
1243
1244 // add all the pointers to be relocated (gc arguments)
1245 // Capture the start of the live variable list for use in the gc_relocates
1246 const int live_start = args.size();
1247 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1248
1249 // Create the statepoint given all the arguments
1250 Instruction *token = nullptr;
1251 AttributeSet return_attributes;
1252 if (CS.isCall()) {
1253 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1254 CallInst *call =
1255 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1256 call->setTailCall(toReplace->isTailCall());
1257 call->setCallingConv(toReplace->getCallingConv());
1258
1259 // Currently we will fail on parameter attributes and on certain
1260 // function attributes.
1261 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1262 // In case if we can handle this set of sttributes - set up function attrs
1263 // directly on statepoint and return attrs later for gc_result intrinsic.
1264 call->setAttributes(new_attrs.getFnAttributes());
1265 return_attributes = new_attrs.getRetAttributes();
1266
1267 token = call;
1268
1269 // Put the following gc_result and gc_relocate calls immediately after the
1270 // the old call (which we're about to delete)
1271 BasicBlock::iterator next(toReplace);
1272 assert(BB->end() != next && "not a terminator, must have next");
1273 next++;
1274 Instruction *IP = &*(next);
1275 Builder.SetInsertPoint(IP);
1276 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1277
David Blaikie82ad7872015-02-20 23:44:24 +00001278 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001279 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1280
1281 // Insert the new invoke into the old block. We'll remove the old one in a
1282 // moment at which point this will become the new terminator for the
1283 // original block.
1284 InvokeInst *invoke = InvokeInst::Create(
1285 gc_statepoint_decl, toReplace->getNormalDest(),
1286 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1287 invoke->setCallingConv(toReplace->getCallingConv());
1288
1289 // Currently we will fail on parameter attributes and on certain
1290 // function attributes.
1291 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1292 // In case if we can handle this set of sttributes - set up function attrs
1293 // directly on statepoint and return attrs later for gc_result intrinsic.
1294 invoke->setAttributes(new_attrs.getFnAttributes());
1295 return_attributes = new_attrs.getRetAttributes();
1296
1297 token = invoke;
1298
1299 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001300 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1301 assert(!isa<PHINode>(unwindBlock->begin()) &&
1302 unwindBlock->getUniquePredecessor() &&
1303 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001304
1305 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1306 Builder.SetInsertPoint(IP);
1307 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1308
1309 // Extract second element from landingpad return value. We will attach
1310 // exceptional gc relocates to it.
1311 const unsigned idx = 1;
1312 Instruction *exceptional_token =
1313 cast<Instruction>(Builder.CreateExtractValue(
1314 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001315 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001316
Philip Reames6ff1a1e32015-07-21 19:04:38 +00001317 CreateGCRelocates(liveVariables, live_start, basePtrs,
1318 exceptional_token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001319
1320 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001321 BasicBlock *normalDest = toReplace->getNormalDest();
1322 assert(!isa<PHINode>(normalDest->begin()) &&
1323 normalDest->getUniquePredecessor() &&
1324 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001325
1326 IP = &*(normalDest->getFirstInsertionPt());
1327 Builder.SetInsertPoint(IP);
1328
1329 // gc relocates will be generated later as if it were regular call
1330 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001331 }
1332 assert(token);
1333
1334 // Take the name of the original value call if it had one.
1335 token->takeName(CS.getInstruction());
1336
Philip Reames704e78b2015-04-10 22:34:56 +00001337// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001338#ifndef NDEBUG
1339 Instruction *toReplace = CS.getInstruction();
1340 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1341 "only valid use before rewrite is gc.result");
1342 assert(!toReplace->hasOneUse() ||
1343 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1344#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001345
1346 // Update the gc.result of the original statepoint (if any) to use the newly
1347 // inserted statepoint. This is safe to do here since the token can't be
1348 // considered a live reference.
1349 CS.getInstruction()->replaceAllUsesWith(token);
1350
Philip Reames0a3240f2015-02-20 21:34:11 +00001351 result.StatepointToken = token;
1352
Philip Reamesd16a9b12015-02-20 01:06:44 +00001353 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001354 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001355}
1356
1357namespace {
1358struct name_ordering {
1359 Value *base;
1360 Value *derived;
1361 bool operator()(name_ordering const &a, name_ordering const &b) {
1362 return -1 == a.derived->getName().compare(b.derived->getName());
1363 }
1364};
1365}
1366static void stablize_order(SmallVectorImpl<Value *> &basevec,
1367 SmallVectorImpl<Value *> &livevec) {
1368 assert(basevec.size() == livevec.size());
1369
Philip Reames860660e2015-02-20 22:05:18 +00001370 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001371 for (size_t i = 0; i < basevec.size(); i++) {
1372 name_ordering v;
1373 v.base = basevec[i];
1374 v.derived = livevec[i];
1375 temp.push_back(v);
1376 }
1377 std::sort(temp.begin(), temp.end(), name_ordering());
1378 for (size_t i = 0; i < basevec.size(); i++) {
1379 basevec[i] = temp[i].base;
1380 livevec[i] = temp[i].derived;
1381 }
1382}
1383
1384// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1385// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001386//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001387// WARNING: Does not do any fixup to adjust users of the original live
1388// values. That's the callers responsibility.
1389static void
1390makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1391 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001392 auto liveset = result.liveset;
1393 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001394
1395 // Convert to vector for efficient cross referencing.
1396 SmallVector<Value *, 64> basevec, livevec;
1397 livevec.reserve(liveset.size());
1398 basevec.reserve(liveset.size());
1399 for (Value *L : liveset) {
1400 livevec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001401 assert(PointerToBase.count(L));
Philip Reamesf2041322015-02-20 19:26:04 +00001402 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001403 basevec.push_back(base);
1404 }
1405 assert(livevec.size() == basevec.size());
1406
1407 // To make the output IR slightly more stable (for use in diffs), ensure a
1408 // fixed order of the values in the safepoint (by sorting the value name).
1409 // The order is otherwise meaningless.
1410 stablize_order(basevec, livevec);
1411
1412 // Do the actual rewriting and delete the old statepoint
1413 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1414 CS.getInstruction()->eraseFromParent();
1415}
1416
1417// Helper function for the relocationViaAlloca.
1418// It receives iterator to the statepoint gc relocates and emits store to the
1419// assigned
1420// location (via allocaMap) for the each one of them.
1421// Add visited values into the visitedLiveValues set we will later use them
1422// for sanity check.
1423static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001424insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1425 DenseMap<Value *, Value *> &AllocaMap,
1426 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001427
Sanjoy Das5665c992015-05-11 23:47:27 +00001428 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001429 if (!isa<IntrinsicInst>(U))
1430 continue;
1431
Sanjoy Das5665c992015-05-11 23:47:27 +00001432 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001433
1434 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001435 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001436 Intrinsic::experimental_gc_relocate) {
1437 continue;
1438 }
1439
Sanjoy Das5665c992015-05-11 23:47:27 +00001440 GCRelocateOperands RelocateOperands(RelocatedValue);
1441 Value *OriginalValue =
1442 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1443 assert(AllocaMap.count(OriginalValue));
1444 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001445
1446 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001447 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1448 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001449 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1450 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001451 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001452 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1453 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001454
Sanjoy Das5665c992015-05-11 23:47:27 +00001455 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1456 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001457
1458#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001459 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001460#endif
1461 }
1462}
1463
Igor Laevskye0317182015-05-19 15:59:05 +00001464// Helper function for the "relocationViaAlloca". Similar to the
1465// "insertRelocationStores" but works for rematerialized values.
1466static void
1467insertRematerializationStores(
1468 RematerializedValueMapTy RematerializedValues,
1469 DenseMap<Value *, Value *> &AllocaMap,
1470 DenseSet<Value *> &VisitedLiveValues) {
1471
1472 for (auto RematerializedValuePair: RematerializedValues) {
1473 Instruction *RematerializedValue = RematerializedValuePair.first;
1474 Value *OriginalValue = RematerializedValuePair.second;
1475
1476 assert(AllocaMap.count(OriginalValue) &&
1477 "Can not find alloca for rematerialized value");
1478 Value *Alloca = AllocaMap[OriginalValue];
1479
1480 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1481 Store->insertAfter(RematerializedValue);
1482
1483#ifndef NDEBUG
1484 VisitedLiveValues.insert(OriginalValue);
1485#endif
1486 }
1487}
1488
Philip Reamesd16a9b12015-02-20 01:06:44 +00001489/// do all the relocation update via allocas and mem2reg
1490static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001491 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1492 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001493#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001494 // record initial number of (static) allocas; we'll check we have the same
1495 // number when we get done.
1496 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001497 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1498 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001499 if (isa<AllocaInst>(*I))
1500 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001501#endif
1502
1503 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001504 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001505 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001506 // Used later to chack that we have enough allocas to store all values
1507 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001508 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001509
Igor Laevskye0317182015-05-19 15:59:05 +00001510 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1511 // "PromotableAllocas"
1512 auto emitAllocaFor = [&](Value *LiveValue) {
1513 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1514 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001515 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001516 PromotableAllocas.push_back(Alloca);
1517 };
1518
Philip Reamesd16a9b12015-02-20 01:06:44 +00001519 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001520 for (unsigned i = 0; i < Live.size(); i++) {
1521 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001522 }
1523
Igor Laevskye0317182015-05-19 15:59:05 +00001524 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001525 for (size_t i = 0; i < Records.size(); i++) {
1526 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001527
Igor Laevsky285fe842015-05-19 16:29:43 +00001528 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001529 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001530 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001531 continue;
1532
1533 emitAllocaFor(OriginalValue);
1534 ++NumRematerializedValues;
1535 }
1536 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001537
Philip Reamesd16a9b12015-02-20 01:06:44 +00001538 // The next two loops are part of the same conceptual operation. We need to
1539 // insert a store to the alloca after the original def and at each
1540 // redefinition. We need to insert a load before each use. These are split
1541 // into distinct loops for performance reasons.
1542
1543 // update gc pointer after each statepoint
1544 // either store a relocated value or null (if no relocated value found for
1545 // this gc pointer and it is not a gc_result)
1546 // this must happen before we update the statepoint with load of alloca
1547 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001548 for (size_t i = 0; i < Records.size(); i++) {
1549 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1550 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001551
1552 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001553 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001554
1555 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001556 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001557
1558 // In case if it was invoke statepoint
1559 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001560 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001561 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1562 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001563 }
1564
Igor Laevskye0317182015-05-19 15:59:05 +00001565 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001566 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1567 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001568
Philip Reamese73300b2015-04-13 16:41:32 +00001569 if (ClobberNonLive) {
1570 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1571 // the gc.statepoint. This will turn some subtle GC problems into
1572 // slightly easier to debug SEGVs. Note that on large IR files with
1573 // lots of gc.statepoints this is extremely costly both memory and time
1574 // wise.
1575 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001576 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001577 Value *Def = Pair.first;
1578 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001579
Philip Reamese73300b2015-04-13 16:41:32 +00001580 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001581 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001582 continue;
1583 }
1584 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001585 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001586
Philip Reamese73300b2015-04-13 16:41:32 +00001587 auto InsertClobbersAt = [&](Instruction *IP) {
1588 for (auto *AI : ToClobber) {
1589 auto AIType = cast<PointerType>(AI->getType());
1590 auto PT = cast<PointerType>(AIType->getElementType());
1591 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001592 StoreInst *Store = new StoreInst(CPN, AI);
1593 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001594 }
1595 };
1596
1597 // Insert the clobbering stores. These may get intermixed with the
1598 // gc.results and gc.relocates, but that's fine.
1599 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1600 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1601 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1602 } else {
1603 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1604 Next++;
1605 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001606 }
David Blaikie82ad7872015-02-20 23:44:24 +00001607 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001608 }
1609 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001610 for (auto Pair : AllocaMap) {
1611 Value *Def = Pair.first;
1612 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001613
1614 // we pre-record the uses of allocas so that we dont have to worry about
1615 // later update
1616 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001617 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001618 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001619 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1620 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001621 if (!isa<ConstantExpr>(U)) {
1622 // If the def has a ConstantExpr use, then the def is either a
1623 // ConstantExpr use itself or null. In either case
1624 // (recursively in the first, directly in the second), the oop
1625 // it is ultimately dependent on is null and this particular
1626 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001627 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001628 }
1629 }
1630
Igor Laevsky285fe842015-05-19 16:29:43 +00001631 std::sort(Uses.begin(), Uses.end());
1632 auto Last = std::unique(Uses.begin(), Uses.end());
1633 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001634
Igor Laevsky285fe842015-05-19 16:29:43 +00001635 for (Instruction *Use : Uses) {
1636 if (isa<PHINode>(Use)) {
1637 PHINode *Phi = cast<PHINode>(Use);
1638 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1639 if (Def == Phi->getIncomingValue(i)) {
1640 LoadInst *Load = new LoadInst(
1641 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1642 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001643 }
1644 }
1645 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001646 LoadInst *Load = new LoadInst(Alloca, "", Use);
1647 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001648 }
1649 }
1650
1651 // emit store for the initial gc value
1652 // store must be inserted after load, otherwise store will be in alloca's
1653 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001654 StoreInst *Store = new StoreInst(Def, Alloca);
1655 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1656 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001657 // InvokeInst is a TerminatorInst so the store need to be inserted
1658 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001659 BasicBlock *NormalDest = Invoke->getNormalDest();
1660 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001661 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001662 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001663 "The only TerminatorInst that can produce a value is "
1664 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001665 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001666 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001667 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001668 assert(isa<Argument>(Def));
1669 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001670 }
1671 }
1672
Igor Laevsky285fe842015-05-19 16:29:43 +00001673 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001674 "we must have the same allocas with lives");
1675 if (!PromotableAllocas.empty()) {
1676 // apply mem2reg to promote alloca to SSA
1677 PromoteMemToReg(PromotableAllocas, DT);
1678 }
1679
1680#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001681 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1682 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001683 if (isa<AllocaInst>(*I))
1684 InitialAllocaNum--;
1685 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001686#endif
1687}
1688
1689/// Implement a unique function which doesn't require we sort the input
1690/// vector. Doing so has the effect of changing the output of a couple of
1691/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001692template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001693 SmallSet<T, 8> Seen;
1694 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1695 return !Seen.insert(V).second;
1696 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001697}
1698
Philip Reamesd16a9b12015-02-20 01:06:44 +00001699/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001700/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001701static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001702 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001703 if (Values.empty())
1704 // No values to hold live, might as well not insert the empty holder
1705 return;
1706
Philip Reamesd16a9b12015-02-20 01:06:44 +00001707 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001708 // Use a dummy vararg function to actually hold the values live
1709 Function *Func = cast<Function>(M->getOrInsertFunction(
1710 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001711 if (CS.isCall()) {
1712 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001713 BasicBlock::iterator Next(CS.getInstruction());
1714 Next++;
1715 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1716 return;
1717 }
1718 // For invoke safepooints insert dummy calls both in normal and
1719 // exceptional destination blocks
1720 auto *II = cast<InvokeInst>(CS.getInstruction());
1721 Holders.push_back(CallInst::Create(
1722 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1723 Holders.push_back(CallInst::Create(
1724 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001725}
1726
1727static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001728 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1729 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001730 GCPtrLivenessData OriginalLivenessData;
1731 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001732 for (size_t i = 0; i < records.size(); i++) {
1733 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001734 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001735 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001736 }
1737}
1738
Philip Reames8531d8c2015-04-10 21:48:25 +00001739/// Remove any vector of pointers from the liveset by scalarizing them over the
1740/// statepoint instruction. Adds the scalarized pieces to the liveset. It
1741/// would be preferrable to include the vector in the statepoint itself, but
1742/// the lowering code currently does not handle that. Extending it would be
1743/// slightly non-trivial since it requires a format change. Given how rare
1744/// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1745static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001746 StatepointLiveSetTy &LiveSet,
1747 DenseMap<Value *, Value *>& PointerToBase,
1748 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001749 SmallVector<Value *, 16> ToSplit;
1750 for (Value *V : LiveSet)
1751 if (isa<VectorType>(V->getType()))
1752 ToSplit.push_back(V);
1753
1754 if (ToSplit.empty())
1755 return;
1756
Philip Reames8fe7f132015-06-26 22:47:37 +00001757 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1758
Philip Reames8531d8c2015-04-10 21:48:25 +00001759 Function &F = *(StatepointInst->getParent()->getParent());
1760
Philip Reames704e78b2015-04-10 22:34:56 +00001761 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001762 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001763 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001764 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001765 AllocaInst *Alloca =
1766 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001767 AllocaMap[V] = Alloca;
1768
1769 VectorType *VT = cast<VectorType>(V->getType());
1770 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001771 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001772 for (unsigned i = 0; i < VT->getNumElements(); i++)
1773 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001774 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001775
1776 auto InsertVectorReform = [&](Instruction *IP) {
1777 Builder.SetInsertPoint(IP);
1778 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1779 Value *ResultVec = UndefValue::get(VT);
1780 for (unsigned i = 0; i < VT->getNumElements(); i++)
1781 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1782 Builder.getInt32(i));
1783 return ResultVec;
1784 };
1785
1786 if (isa<CallInst>(StatepointInst)) {
1787 BasicBlock::iterator Next(StatepointInst);
1788 Next++;
1789 Instruction *IP = &*(Next);
1790 Replacements[V].first = InsertVectorReform(IP);
1791 Replacements[V].second = nullptr;
1792 } else {
1793 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1794 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001795 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001796 BasicBlock *NormalDest = Invoke->getNormalDest();
1797 assert(!isa<PHINode>(NormalDest->begin()));
1798 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1799 assert(!isa<PHINode>(UnwindDest->begin()));
1800 // Insert insert element sequences in both successors
1801 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1802 Replacements[V].first = InsertVectorReform(IP);
1803 IP = &*(UnwindDest->getFirstInsertionPt());
1804 Replacements[V].second = InsertVectorReform(IP);
1805 }
1806 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001807
Philip Reames8531d8c2015-04-10 21:48:25 +00001808 for (Value *V : ToSplit) {
1809 AllocaInst *Alloca = AllocaMap[V];
1810
1811 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001812 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001813 for (User *U : V->users())
1814 Users.push_back(cast<Instruction>(U));
1815
1816 for (Instruction *I : Users) {
1817 if (auto Phi = dyn_cast<PHINode>(I)) {
1818 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1819 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001820 LoadInst *Load = new LoadInst(
1821 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001822 Phi->setIncomingValue(i, Load);
1823 }
1824 } else {
1825 LoadInst *Load = new LoadInst(Alloca, "", I);
1826 I->replaceUsesOfWith(V, Load);
1827 }
1828 }
1829
1830 // Store the original value and the replacement value into the alloca
1831 StoreInst *Store = new StoreInst(V, Alloca);
1832 if (auto I = dyn_cast<Instruction>(V))
1833 Store->insertAfter(I);
1834 else
1835 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001836
Philip Reames8531d8c2015-04-10 21:48:25 +00001837 // Normal return for invoke, or call return
1838 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1839 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1840 // Unwind return for invoke only
1841 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1842 if (Replacement)
1843 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1844 }
1845
1846 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001847 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001848 for (Value *V : ToSplit)
1849 Allocas.push_back(AllocaMap[V]);
1850 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001851
1852 // Update our tracking of live pointers and base mappings to account for the
1853 // changes we just made.
1854 for (Value *V : ToSplit) {
1855 auto &Elements = ElementMapping[V];
1856
1857 LiveSet.erase(V);
1858 LiveSet.insert(Elements.begin(), Elements.end());
1859 // We need to update the base mapping as well.
1860 assert(PointerToBase.count(V));
1861 Value *OldBase = PointerToBase[V];
1862 auto &BaseElements = ElementMapping[OldBase];
1863 PointerToBase.erase(V);
1864 assert(Elements.size() == BaseElements.size());
1865 for (unsigned i = 0; i < Elements.size(); i++) {
1866 Value *Elem = Elements[i];
1867 PointerToBase[Elem] = BaseElements[i];
1868 }
1869 }
Philip Reames8531d8c2015-04-10 21:48:25 +00001870}
1871
Igor Laevskye0317182015-05-19 15:59:05 +00001872// Helper function for the "rematerializeLiveValues". It walks use chain
1873// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1874// values are visited (currently it is GEP's and casts). Returns true if it
1875// sucessfully reached "BaseValue" and false otherwise.
1876// Fills "ChainToBase" array with all visited values. "BaseValue" is not
1877// recorded.
1878static bool findRematerializableChainToBasePointer(
1879 SmallVectorImpl<Instruction*> &ChainToBase,
1880 Value *CurrentValue, Value *BaseValue) {
1881
1882 // We have found a base value
1883 if (CurrentValue == BaseValue) {
1884 return true;
1885 }
1886
1887 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1888 ChainToBase.push_back(GEP);
1889 return findRematerializableChainToBasePointer(ChainToBase,
1890 GEP->getPointerOperand(),
1891 BaseValue);
1892 }
1893
1894 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1895 Value *Def = CI->stripPointerCasts();
1896
1897 // This two checks are basically similar. First one is here for the
1898 // consistency with findBasePointers logic.
1899 assert(!isa<CastInst>(Def) && "not a pointer cast found");
1900 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1901 return false;
1902
1903 ChainToBase.push_back(CI);
1904 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1905 }
1906
1907 // Not supported instruction in the chain
1908 return false;
1909}
1910
1911// Helper function for the "rematerializeLiveValues". Compute cost of the use
1912// chain we are going to rematerialize.
1913static unsigned
1914chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1915 TargetTransformInfo &TTI) {
1916 unsigned Cost = 0;
1917
1918 for (Instruction *Instr : Chain) {
1919 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1920 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1921 "non noop cast is found during rematerialization");
1922
1923 Type *SrcTy = CI->getOperand(0)->getType();
1924 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1925
1926 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1927 // Cost of the address calculation
1928 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
1929 Cost += TTI.getAddressComputationCost(ValTy);
1930
1931 // And cost of the GEP itself
1932 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1933 // allowed for the external usage)
1934 if (!GEP->hasAllConstantIndices())
1935 Cost += 2;
1936
1937 } else {
1938 llvm_unreachable("unsupported instruciton type during rematerialization");
1939 }
1940 }
1941
1942 return Cost;
1943}
1944
1945// From the statepoint liveset pick values that are cheaper to recompute then to
1946// relocate. Remove this values from the liveset, rematerialize them after
1947// statepoint and record them in "Info" structure. Note that similar to
1948// relocated values we don't do any user adjustments here.
1949static void rematerializeLiveValues(CallSite CS,
1950 PartiallyConstructedSafepointRecord &Info,
1951 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00001952 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00001953
Igor Laevskye0317182015-05-19 15:59:05 +00001954 // Record values we are going to delete from this statepoint live set.
1955 // We can not di this in following loop due to iterator invalidation.
1956 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1957
1958 for (Value *LiveValue: Info.liveset) {
1959 // For each live pointer find it's defining chain
1960 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00001961 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00001962 bool FoundChain =
1963 findRematerializableChainToBasePointer(ChainToBase,
1964 LiveValue,
1965 Info.PointerToBase[LiveValue]);
1966 // Nothing to do, or chain is too long
1967 if (!FoundChain ||
1968 ChainToBase.size() == 0 ||
1969 ChainToBase.size() > ChainLengthThreshold)
1970 continue;
1971
1972 // Compute cost of this chain
1973 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
1974 // TODO: We can also account for cases when we will be able to remove some
1975 // of the rematerialized values by later optimization passes. I.e if
1976 // we rematerialized several intersecting chains. Or if original values
1977 // don't have any uses besides this statepoint.
1978
1979 // For invokes we need to rematerialize each chain twice - for normal and
1980 // for unwind basic blocks. Model this by multiplying cost by two.
1981 if (CS.isInvoke()) {
1982 Cost *= 2;
1983 }
1984 // If it's too expensive - skip it
1985 if (Cost >= RematerializationThreshold)
1986 continue;
1987
1988 // Remove value from the live set
1989 LiveValuesToBeDeleted.push_back(LiveValue);
1990
1991 // Clone instructions and record them inside "Info" structure
1992
1993 // Walk backwards to visit top-most instructions first
1994 std::reverse(ChainToBase.begin(), ChainToBase.end());
1995
1996 // Utility function which clones all instructions from "ChainToBase"
1997 // and inserts them before "InsertBefore". Returns rematerialized value
1998 // which should be used after statepoint.
1999 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2000 Instruction *LastClonedValue = nullptr;
2001 Instruction *LastValue = nullptr;
2002 for (Instruction *Instr: ChainToBase) {
2003 // Only GEP's and casts are suported as we need to be careful to not
2004 // introduce any new uses of pointers not in the liveset.
2005 // Note that it's fine to introduce new uses of pointers which were
2006 // otherwise not used after this statepoint.
2007 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2008
2009 Instruction *ClonedValue = Instr->clone();
2010 ClonedValue->insertBefore(InsertBefore);
2011 ClonedValue->setName(Instr->getName() + ".remat");
2012
2013 // If it is not first instruction in the chain then it uses previously
2014 // cloned value. We should update it to use cloned value.
2015 if (LastClonedValue) {
2016 assert(LastValue);
2017 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2018#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002019 // Assert that cloned instruction does not use any instructions from
2020 // this chain other than LastClonedValue
2021 for (auto OpValue : ClonedValue->operand_values()) {
2022 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2023 ChainToBase.end() &&
2024 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002025 }
2026#endif
2027 }
2028
2029 LastClonedValue = ClonedValue;
2030 LastValue = Instr;
2031 }
2032 assert(LastClonedValue);
2033 return LastClonedValue;
2034 };
2035
2036 // Different cases for calls and invokes. For invokes we need to clone
2037 // instructions both on normal and unwind path.
2038 if (CS.isCall()) {
2039 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2040 assert(InsertBefore);
2041 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2042 Info.RematerializedValues[RematerializedValue] = LiveValue;
2043 } else {
2044 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2045
2046 Instruction *NormalInsertBefore =
2047 Invoke->getNormalDest()->getFirstInsertionPt();
2048 Instruction *UnwindInsertBefore =
2049 Invoke->getUnwindDest()->getFirstInsertionPt();
2050
2051 Instruction *NormalRematerializedValue =
2052 rematerializeChain(NormalInsertBefore);
2053 Instruction *UnwindRematerializedValue =
2054 rematerializeChain(UnwindInsertBefore);
2055
2056 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2057 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2058 }
2059 }
2060
2061 // Remove rematerializaed values from the live set
2062 for (auto LiveValue: LiveValuesToBeDeleted) {
2063 Info.liveset.erase(LiveValue);
2064 }
2065}
2066
Philip Reamesd16a9b12015-02-20 01:06:44 +00002067static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00002068 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002069#ifndef NDEBUG
2070 // sanity check the input
2071 std::set<CallSite> uniqued;
2072 uniqued.insert(toUpdate.begin(), toUpdate.end());
2073 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2074
2075 for (size_t i = 0; i < toUpdate.size(); i++) {
2076 CallSite &CS = toUpdate[i];
2077 assert(CS.getInstruction()->getParent()->getParent() == &F);
2078 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2079 }
2080#endif
2081
Philip Reames69e51ca2015-04-13 18:07:21 +00002082 // When inserting gc.relocates for invokes, we need to be able to insert at
2083 // the top of the successor blocks. See the comment on
2084 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002085 // may restructure the CFG.
2086 for (CallSite CS : toUpdate) {
2087 if (!CS.isInvoke())
2088 continue;
2089 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2090 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002091 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002092 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002093 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002094 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002095
Philip Reamesd16a9b12015-02-20 01:06:44 +00002096 // A list of dummy calls added to the IR to keep various values obviously
2097 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002098 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002099
2100 // Insert a dummy call with all of the arguments to the vm_state we'll need
2101 // for the actual safepoint insertion. This ensures reference arguments in
2102 // the deopt argument list are considered live through the safepoint (and
2103 // thus makes sure they get relocated.)
2104 for (size_t i = 0; i < toUpdate.size(); i++) {
2105 CallSite &CS = toUpdate[i];
2106 Statepoint StatepointCS(CS);
2107
2108 SmallVector<Value *, 64> DeoptValues;
2109 for (Use &U : StatepointCS.vm_state_args()) {
2110 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002111 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2112 "support for FCA unimplemented");
2113 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002114 DeoptValues.push_back(Arg);
2115 }
2116 insertUseHolderAfter(CS, DeoptValues, holders);
2117 }
2118
Philip Reamesd2b66462015-02-20 22:39:41 +00002119 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002120 records.reserve(toUpdate.size());
2121 for (size_t i = 0; i < toUpdate.size(); i++) {
2122 struct PartiallyConstructedSafepointRecord info;
2123 records.push_back(info);
2124 }
2125 assert(records.size() == toUpdate.size());
2126
2127 // A) Identify all gc pointers which are staticly live at the given call
2128 // site.
2129 findLiveReferences(F, DT, P, toUpdate, records);
2130
2131 // B) Find the base pointers for each live pointer
2132 /* scope for caching */ {
2133 // Cache the 'defining value' relation used in the computation and
2134 // insertion of base phis and selects. This ensures that we don't insert
2135 // large numbers of duplicate base_phis.
2136 DefiningValueMapTy DVCache;
2137
2138 for (size_t i = 0; i < records.size(); i++) {
2139 struct PartiallyConstructedSafepointRecord &info = records[i];
2140 CallSite &CS = toUpdate[i];
2141 findBasePointers(DT, DVCache, CS, info);
2142 }
2143 } // end of cache scope
2144
2145 // The base phi insertion logic (for any safepoint) may have inserted new
2146 // instructions which are now live at some safepoint. The simplest such
2147 // example is:
2148 // loop:
2149 // phi a <-- will be a new base_phi here
2150 // safepoint 1 <-- that needs to be live here
2151 // gep a + 1
2152 // safepoint 2
2153 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002154 // We insert some dummy calls after each safepoint to definitely hold live
2155 // the base pointers which were identified for that safepoint. We'll then
2156 // ask liveness for _every_ base inserted to see what is now live. Then we
2157 // remove the dummy calls.
2158 holders.reserve(holders.size() + records.size());
2159 for (size_t i = 0; i < records.size(); i++) {
2160 struct PartiallyConstructedSafepointRecord &info = records[i];
2161 CallSite &CS = toUpdate[i];
2162
2163 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002164 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002165 Bases.push_back(Pair.second);
2166 }
2167 insertUseHolderAfter(CS, Bases, holders);
2168 }
2169
Philip Reamesdf1ef082015-04-10 22:53:14 +00002170 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2171 // need to rerun liveness. We may *also* have inserted new defs, but that's
2172 // not the key issue.
2173 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002174
Philip Reamesd16a9b12015-02-20 01:06:44 +00002175 if (PrintBasePointers) {
2176 for (size_t i = 0; i < records.size(); i++) {
2177 struct PartiallyConstructedSafepointRecord &info = records[i];
2178 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002179 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002180 errs() << " derived %" << Pair.first->getName() << " base %"
2181 << Pair.second->getName() << "\n";
2182 }
2183 }
2184 }
2185 for (size_t i = 0; i < holders.size(); i++) {
2186 holders[i]->eraseFromParent();
2187 holders[i] = nullptr;
2188 }
2189 holders.clear();
2190
Philip Reames8fe7f132015-06-26 22:47:37 +00002191 // Do a limited scalarization of any live at safepoint vector values which
2192 // contain pointers. This enables this pass to run after vectorization at
2193 // the cost of some possible performance loss. TODO: it would be nice to
2194 // natively support vectors all the way through the backend so we don't need
2195 // to scalarize here.
2196 for (size_t i = 0; i < records.size(); i++) {
2197 struct PartiallyConstructedSafepointRecord &info = records[i];
2198 Instruction *statepoint = toUpdate[i].getInstruction();
2199 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2200 info.PointerToBase, DT);
2201 }
2202
Igor Laevskye0317182015-05-19 15:59:05 +00002203 // In order to reduce live set of statepoint we might choose to rematerialize
2204 // some values instead of relocating them. This is purelly an optimization and
2205 // does not influence correctness.
2206 TargetTransformInfo &TTI =
2207 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2208
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002209 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002210 struct PartiallyConstructedSafepointRecord &info = records[i];
2211 CallSite &CS = toUpdate[i];
2212
2213 rematerializeLiveValues(CS, info, TTI);
2214 }
2215
Philip Reamesd16a9b12015-02-20 01:06:44 +00002216 // Now run through and replace the existing statepoints with new ones with
2217 // the live variables listed. We do not yet update uses of the values being
2218 // relocated. We have references to live variables that need to
2219 // survive to the last iteration of this loop. (By construction, the
2220 // previous statepoint can not be a live variable, thus we can and remove
2221 // the old statepoint calls as we go.)
2222 for (size_t i = 0; i < records.size(); i++) {
2223 struct PartiallyConstructedSafepointRecord &info = records[i];
2224 CallSite &CS = toUpdate[i];
2225 makeStatepointExplicit(DT, CS, P, info);
2226 }
2227 toUpdate.clear(); // prevent accident use of invalid CallSites
2228
Philip Reamesd16a9b12015-02-20 01:06:44 +00002229 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002230 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002231 for (size_t i = 0; i < records.size(); i++) {
2232 struct PartiallyConstructedSafepointRecord &info = records[i];
2233 // We can't simply save the live set from the original insertion. One of
2234 // the live values might be the result of a call which needs a safepoint.
2235 // That Value* no longer exists and we need to use the new gc_result.
2236 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2237 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002238 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002239 live.insert(live.end(), statepoint.gc_args_begin(),
2240 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002241#ifndef NDEBUG
2242 // Do some basic sanity checks on our liveness results before performing
2243 // relocation. Relocation can and will turn mistakes in liveness results
2244 // into non-sensical code which is must harder to debug.
2245 // TODO: It would be nice to test consistency as well
2246 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2247 "statepoint must be reachable or liveness is meaningless");
2248 for (Value *V : statepoint.gc_args()) {
2249 if (!isa<Instruction>(V))
2250 // Non-instruction values trivial dominate all possible uses
2251 continue;
2252 auto LiveInst = cast<Instruction>(V);
2253 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2254 "unreachable values should never be live");
2255 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2256 "basic SSA liveness expectation violated by liveness analysis");
2257 }
2258#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002259 }
2260 unique_unsorted(live);
2261
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002262#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002263 // sanity check
2264 for (auto ptr : live) {
2265 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2266 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002267#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002268
2269 relocationViaAlloca(F, DT, live, records);
2270 return !records.empty();
2271}
2272
Sanjoy Das353a19e2015-06-02 22:33:37 +00002273// Handles both return values and arguments for Functions and CallSites.
2274template <typename AttrHolder>
2275static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2276 unsigned Index) {
2277 AttrBuilder R;
2278 if (AH.getDereferenceableBytes(Index))
2279 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2280 AH.getDereferenceableBytes(Index)));
2281 if (AH.getDereferenceableOrNullBytes(Index))
2282 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2283 AH.getDereferenceableOrNullBytes(Index)));
2284
2285 if (!R.empty())
2286 AH.setAttributes(AH.getAttributes().removeAttributes(
2287 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002288}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002289
2290void
2291RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2292 LLVMContext &Ctx = F.getContext();
2293
2294 for (Argument &A : F.args())
2295 if (isa<PointerType>(A.getType()))
2296 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2297
2298 if (isa<PointerType>(F.getReturnType()))
2299 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2300}
2301
2302void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2303 if (F.empty())
2304 return;
2305
2306 LLVMContext &Ctx = F.getContext();
2307 MDBuilder Builder(Ctx);
2308
2309 for (Instruction &I : inst_range(F)) {
2310 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2311 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2312 bool IsImmutableTBAA =
2313 MD->getNumOperands() == 4 &&
2314 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2315
2316 if (!IsImmutableTBAA)
2317 continue; // no work to do, MD_tbaa is already marked mutable
2318
2319 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2320 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2321 uint64_t Offset =
2322 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2323
2324 MDNode *MutableTBAA =
2325 Builder.createTBAAStructTagNode(Base, Access, Offset);
2326 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2327 }
2328
2329 if (CallSite CS = CallSite(&I)) {
2330 for (int i = 0, e = CS.arg_size(); i != e; i++)
2331 if (isa<PointerType>(CS.getArgument(i)->getType()))
2332 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2333 if (isa<PointerType>(CS.getType()))
2334 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2335 }
2336 }
2337}
2338
Philip Reamesd16a9b12015-02-20 01:06:44 +00002339/// Returns true if this function should be rewritten by this pass. The main
2340/// point of this function is as an extension point for custom logic.
2341static bool shouldRewriteStatepointsIn(Function &F) {
2342 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002343 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002344 const char *FunctionGCName = F.getGC();
2345 const StringRef StatepointExampleName("statepoint-example");
2346 const StringRef CoreCLRName("coreclr");
2347 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002348 (CoreCLRName == FunctionGCName);
2349 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002350 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002351}
2352
Sanjoy Das353a19e2015-06-02 22:33:37 +00002353void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2354#ifndef NDEBUG
2355 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2356 "precondition!");
2357#endif
2358
2359 for (Function &F : M)
2360 stripDereferenceabilityInfoFromPrototype(F);
2361
2362 for (Function &F : M)
2363 stripDereferenceabilityInfoFromBody(F);
2364}
2365
Philip Reamesd16a9b12015-02-20 01:06:44 +00002366bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2367 // Nothing to do for declarations.
2368 if (F.isDeclaration() || F.empty())
2369 return false;
2370
2371 // Policy choice says not to rewrite - the most common reason is that we're
2372 // compiling code without a GCStrategy.
2373 if (!shouldRewriteStatepointsIn(F))
2374 return false;
2375
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002376 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002377
Philip Reames85b36a82015-04-10 22:07:04 +00002378 // Gather all the statepoints which need rewritten. Be careful to only
2379 // consider those in reachable code since we need to ask dominance queries
2380 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002381 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002382 bool HasUnreachableStatepoint = false;
Philip Reamesd2b66462015-02-20 22:39:41 +00002383 for (Instruction &I : inst_range(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002384 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002385 if (isStatepoint(I)) {
2386 if (DT.isReachableFromEntry(I.getParent()))
2387 ParsePointNeeded.push_back(CallSite(&I));
2388 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002389 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002390 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002391 }
2392
Philip Reames85b36a82015-04-10 22:07:04 +00002393 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002394
Philip Reames85b36a82015-04-10 22:07:04 +00002395 // Delete any unreachable statepoints so that we don't have unrewritten
2396 // statepoints surviving this pass. This makes testing easier and the
2397 // resulting IR less confusing to human readers. Rather than be fancy, we
2398 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002399 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002400 MadeChange |= removeUnreachableBlocks(F);
2401
Philip Reamesd16a9b12015-02-20 01:06:44 +00002402 // Return early if no work to do.
2403 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002404 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002405
Philip Reames85b36a82015-04-10 22:07:04 +00002406 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2407 // These are created by LCSSA. They have the effect of increasing the size
2408 // of liveness sets for no good reason. It may be harder to do this post
2409 // insertion since relocations and base phis can confuse things.
2410 for (BasicBlock &BB : F)
2411 if (BB.getUniquePredecessor()) {
2412 MadeChange = true;
2413 FoldSingleEntryPHINodes(&BB);
2414 }
2415
2416 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2417 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002418}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002419
2420// liveness computation via standard dataflow
2421// -------------------------------------------------------------------
2422
2423// TODO: Consider using bitvectors for liveness, the set of potentially
2424// interesting values should be small and easy to pre-compute.
2425
Philip Reamesdf1ef082015-04-10 22:53:14 +00002426/// Compute the live-in set for the location rbegin starting from
2427/// the live-out set of the basic block
2428static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2429 BasicBlock::reverse_iterator rend,
2430 DenseSet<Value *> &LiveTmp) {
2431
2432 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2433 Instruction *I = &*ritr;
2434
2435 // KILL/Def - Remove this definition from LiveIn
2436 LiveTmp.erase(I);
2437
2438 // Don't consider *uses* in PHI nodes, we handle their contribution to
2439 // predecessor blocks when we seed the LiveOut sets
2440 if (isa<PHINode>(I))
2441 continue;
2442
2443 // USE - Add to the LiveIn set for this instruction
2444 for (Value *V : I->operands()) {
2445 assert(!isUnhandledGCPointerType(V->getType()) &&
2446 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002447 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2448 // The choice to exclude all things constant here is slightly subtle.
2449 // There are two idependent reasons:
2450 // - We assume that things which are constant (from LLVM's definition)
2451 // do not move at runtime. For example, the address of a global
2452 // variable is fixed, even though it's contents may not be.
2453 // - Second, we can't disallow arbitrary inttoptr constants even
2454 // if the language frontend does. Optimization passes are free to
2455 // locally exploit facts without respect to global reachability. This
2456 // can create sections of code which are dynamically unreachable and
2457 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002458 LiveTmp.insert(V);
2459 }
2460 }
2461 }
2462}
2463
2464static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2465
2466 for (BasicBlock *Succ : successors(BB)) {
2467 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2468 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2469 PHINode *Phi = cast<PHINode>(&*I);
2470 Value *V = Phi->getIncomingValueForBlock(BB);
2471 assert(!isUnhandledGCPointerType(V->getType()) &&
2472 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002473 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002474 LiveTmp.insert(V);
2475 }
2476 }
2477 }
2478}
2479
2480static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2481 DenseSet<Value *> KillSet;
2482 for (Instruction &I : *BB)
2483 if (isHandledGCPointerType(I.getType()))
2484 KillSet.insert(&I);
2485 return KillSet;
2486}
2487
Philip Reames9638ff92015-04-11 00:06:47 +00002488#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002489/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2490/// sanity check for the liveness computation.
2491static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2492 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002493 for (Value *V : Live) {
2494 if (auto *I = dyn_cast<Instruction>(V)) {
2495 // The terminator can be a member of the LiveOut set. LLVM's definition
2496 // of instruction dominance states that V does not dominate itself. As
2497 // such, we need to special case this to allow it.
2498 if (TermOkay && TI == I)
2499 continue;
2500 assert(DT.dominates(I, TI) &&
2501 "basic SSA liveness expectation violated by liveness analysis");
2502 }
2503 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002504}
2505
2506/// Check that all the liveness sets used during the computation of liveness
2507/// obey basic SSA properties. This is useful for finding cases where we miss
2508/// a def.
2509static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2510 BasicBlock &BB) {
2511 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2512 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2513 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2514}
Philip Reames9638ff92015-04-11 00:06:47 +00002515#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002516
2517static void computeLiveInValues(DominatorTree &DT, Function &F,
2518 GCPtrLivenessData &Data) {
2519
Philip Reames4d80ede2015-04-10 23:11:26 +00002520 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002521 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002522 // We use a SetVector so that we don't have duplicates in the worklist.
2523 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002524 };
2525 auto NextItem = [&]() {
2526 BasicBlock *BB = Worklist.back();
2527 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002528 return BB;
2529 };
2530
2531 // Seed the liveness for each individual block
2532 for (BasicBlock &BB : F) {
2533 Data.KillSet[&BB] = computeKillSet(&BB);
2534 Data.LiveSet[&BB].clear();
2535 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2536
2537#ifndef NDEBUG
2538 for (Value *Kill : Data.KillSet[&BB])
2539 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2540#endif
2541
2542 Data.LiveOut[&BB] = DenseSet<Value *>();
2543 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2544 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2545 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2546 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2547 if (!Data.LiveIn[&BB].empty())
2548 AddPredsToWorklist(&BB);
2549 }
2550
2551 // Propagate that liveness until stable
2552 while (!Worklist.empty()) {
2553 BasicBlock *BB = NextItem();
2554
2555 // Compute our new liveout set, then exit early if it hasn't changed
2556 // despite the contribution of our successor.
2557 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2558 const auto OldLiveOutSize = LiveOut.size();
2559 for (BasicBlock *Succ : successors(BB)) {
2560 assert(Data.LiveIn.count(Succ));
2561 set_union(LiveOut, Data.LiveIn[Succ]);
2562 }
2563 // assert OutLiveOut is a subset of LiveOut
2564 if (OldLiveOutSize == LiveOut.size()) {
2565 // If the sets are the same size, then we didn't actually add anything
2566 // when unioning our successors LiveIn Thus, the LiveIn of this block
2567 // hasn't changed.
2568 continue;
2569 }
2570 Data.LiveOut[BB] = LiveOut;
2571
2572 // Apply the effects of this basic block
2573 DenseSet<Value *> LiveTmp = LiveOut;
2574 set_union(LiveTmp, Data.LiveSet[BB]);
2575 set_subtract(LiveTmp, Data.KillSet[BB]);
2576
2577 assert(Data.LiveIn.count(BB));
2578 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2579 // assert: OldLiveIn is a subset of LiveTmp
2580 if (OldLiveIn.size() != LiveTmp.size()) {
2581 Data.LiveIn[BB] = LiveTmp;
2582 AddPredsToWorklist(BB);
2583 }
2584 } // while( !worklist.empty() )
2585
2586#ifndef NDEBUG
2587 // Sanity check our ouput against SSA properties. This helps catch any
2588 // missing kills during the above iteration.
2589 for (BasicBlock &BB : F) {
2590 checkBasicSSA(DT, Data, BB);
2591 }
2592#endif
2593}
2594
2595static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2596 StatepointLiveSetTy &Out) {
2597
2598 BasicBlock *BB = Inst->getParent();
2599
2600 // Note: The copy is intentional and required
2601 assert(Data.LiveOut.count(BB));
2602 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2603
2604 // We want to handle the statepoint itself oddly. It's
2605 // call result is not live (normal), nor are it's arguments
2606 // (unless they're used again later). This adjustment is
2607 // specifically what we need to relocate
2608 BasicBlock::reverse_iterator rend(Inst);
2609 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2610 LiveOut.erase(Inst);
2611 Out.insert(LiveOut.begin(), LiveOut.end());
2612}
2613
2614static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2615 const CallSite &CS,
2616 PartiallyConstructedSafepointRecord &Info) {
2617 Instruction *Inst = CS.getInstruction();
2618 StatepointLiveSetTy Updated;
2619 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2620
2621#ifndef NDEBUG
2622 DenseSet<Value *> Bases;
2623 for (auto KVPair : Info.PointerToBase) {
2624 Bases.insert(KVPair.second);
2625 }
2626#endif
2627 // We may have base pointers which are now live that weren't before. We need
2628 // to update the PointerToBase structure to reflect this.
2629 for (auto V : Updated)
2630 if (!Info.PointerToBase.count(V)) {
2631 assert(Bases.count(V) && "can't find base for unexpected live value");
2632 Info.PointerToBase[V] = V;
2633 continue;
2634 }
2635
2636#ifndef NDEBUG
2637 for (auto V : Updated) {
2638 assert(Info.PointerToBase.count(V) &&
2639 "must be able to find base for live value");
2640 }
2641#endif
2642
2643 // Remove any stale base mappings - this can happen since our liveness is
2644 // more precise then the one inherent in the base pointer analysis
2645 DenseSet<Value *> ToErase;
2646 for (auto KVPair : Info.PointerToBase)
2647 if (!Updated.count(KVPair.first))
2648 ToErase.insert(KVPair.first);
2649 for (auto V : ToErase)
2650 Info.PointerToBase.erase(V);
2651
2652#ifndef NDEBUG
2653 for (auto KVPair : Info.PointerToBase)
2654 assert(Updated.count(KVPair.first) && "record for non-live value");
2655#endif
2656
2657 Info.liveset = Updated;
2658}