blob: d3a4d353f9a5aaa1ad58921520174b83491917a9 [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 {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000167 /// The set of values known to be live across 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
Craig Toppere3dcce92015-08-01 22:20:21 +0000200static bool isGCPointerType(Type *T) {
201 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000202 // 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
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000277 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000278 // 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)
Philip Reames9ac4e382015-08-12 21:00:20 +0000380/// defines the base pointer for the input, b) blocks the simple search
381/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
382/// from pointer to vector type or back.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000383static Value *findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000384 if (I->getType()->isVectorTy())
385 return findBaseDefiningValueOfVector(I).first;
386
Philip Reamesd16a9b12015-02-20 01:06:44 +0000387 assert(I->getType()->isPointerTy() &&
388 "Illegal to ask for the base pointer of a non-pointer type");
389
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000390 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000391 // An incoming argument to the function is a base pointer
392 // We should have never reached here if this argument isn't an gc value
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000393 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000394
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000395 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000396 // base case
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000397 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000398
399 // inlining could possibly introduce phi node that contains
400 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000401 if (isa<UndefValue>(I))
402 // utterly meaningless, but useful for dealing with
403 // partially optimized code.
Philip Reames704e78b2015-04-10 22:34:56 +0000404 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000405
406 // Due to inheritance, this must be _after_ the global variable and undef
407 // checks
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000408 if (Constant *Con = dyn_cast<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000409 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
410 "order of checks wrong!");
411 // Note: Finding a constant base for something marked for relocation
412 // doesn't really make sense. The most likely case is either a) some
413 // screwed up the address space usage or b) your validating against
414 // compiled C++ code w/o the proper separation. The only real exception
415 // is a null pointer. You could have generic code written to index of
416 // off a potentially null value and have proven it null. We also use
417 // null pointers in dead paths of relocation phis (which we might later
418 // want to find a base pointer for).
Philip Reames24c6cd52015-03-27 05:47:00 +0000419 assert(isa<ConstantPointerNull>(Con) &&
420 "null is the only case which makes sense");
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000421 return Con;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000422 }
423
424 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000425 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000426 // If we find a cast instruction here, it means we've found a cast which is
427 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
428 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000429 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
430 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000431 }
432
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000433 if (isa<LoadInst>(I))
434 return I; // The value loaded is an gc base itself
Philip Reamesd16a9b12015-02-20 01:06:44 +0000435
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000436 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
437 // The base of this GEP is the base
438 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000439
440 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
441 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000442 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000443 default:
444 // fall through to general call handling
445 break;
446 case Intrinsic::experimental_gc_statepoint:
447 case Intrinsic::experimental_gc_result_float:
448 case Intrinsic::experimental_gc_result_int:
449 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000450 case Intrinsic::experimental_gc_relocate: {
451 // Rerunning safepoint insertion after safepoints are already
452 // inserted is not supported. It could probably be made to work,
453 // but why are you doing this? There's no good reason.
454 llvm_unreachable("repeat safepoint insertion is not supported");
455 }
456 case Intrinsic::gcroot:
457 // Currently, this mechanism hasn't been extended to work with gcroot.
458 // There's no reason it couldn't be, but I haven't thought about the
459 // implications much.
460 llvm_unreachable(
461 "interaction with the gcroot mechanism is not supported");
462 }
463 }
464 // We assume that functions in the source language only return base
465 // pointers. This should probably be generalized via attributes to support
466 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000467 if (isa<CallInst>(I) || isa<InvokeInst>(I))
468 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000469
470 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000471 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000472 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
473
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000474 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000475 // A CAS is effectively a atomic store and load combined under a
476 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000477 // like a load.
478 return I;
Philip Reames704e78b2015-04-10 22:34:56 +0000479
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000480 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000481 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000482
483 // The aggregate ops. Aggregates can either be in the heap or on the
484 // stack, but in either case, this is simply a field load. As a result,
485 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000486 if (isa<ExtractValueInst>(I))
487 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000488
489 // We should never see an insert vector since that would require we be
490 // tracing back a struct value not a pointer value.
491 assert(!isa<InsertValueInst>(I) &&
492 "Base pointer for a struct is meaningless");
493
Philip Reames9ac4e382015-08-12 21:00:20 +0000494 // An extractelement produces a base result exactly when it's input does.
495 // We may need to insert a parallel instruction to extract the appropriate
496 // element out of the base vector corresponding to the input. Given this,
497 // it's analogous to the phi and select case even though it's not a merge.
498 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
499 Value *VectorOperand = EEI->getVectorOperand();
500 Value *Index = EEI->getIndexOperand();
501 std::pair<Value *, bool> pair =
502 findBaseDefiningValueOfVector(VectorOperand, Index);
503 Value *VectorBase = pair.first;
504 if (VectorBase->getType()->isPointerTy())
505 // We found a BDV for this specific element with the vector. This is an
506 // optimization, but in practice it covers most of the useful cases
507 // created via scalarization. Note: The peephole optimization here is
508 // currently needed for correctness since the general algorithm doesn't
509 // yet handle insertelements. That will change shortly.
510 return VectorBase;
511 else {
512 assert(VectorBase->getType()->isVectorTy());
513 // Otherwise, we have an instruction which potentially produces a
514 // derived pointer and we need findBasePointers to clone code for us
515 // such that we can create an instruction which produces the
516 // accompanying base pointer.
517 return EEI;
518 }
519 }
520
Philip Reamesd16a9b12015-02-20 01:06:44 +0000521 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000522 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000523 // derived pointers (each with it's own base potentially). It's the job of
524 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000525 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000526 "missing instruction case in findBaseDefiningValing");
527 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000528}
529
530/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000531static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
532 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000533 if (!Cached) {
534 Cached = findBaseDefiningValue(I);
Philip Reames2a892a62015-07-23 22:25:26 +0000535 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
536 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000537 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000538 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000539 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000540}
541
542/// Return a base pointer for this value if known. Otherwise, return it's
543/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000544static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
545 Value *Def = findBaseDefiningValueCached(I, Cache);
546 auto Found = Cache.find(Def);
547 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000548 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000549 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000550 }
551 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000552 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000553}
554
555/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
556/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000557static bool isKnownBaseResult(Value *V) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000558 if (!isa<PHINode>(V) && !isa<SelectInst>(V) && !isa<ExtractElementInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000559 // no recursion possible
560 return true;
561 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000562 if (isa<Instruction>(V) &&
563 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000564 // This is a previously inserted base phi or select. We know
565 // that this is a base value.
566 return true;
567 }
568
569 // We need to keep searching
570 return false;
571}
572
Philip Reamesd16a9b12015-02-20 01:06:44 +0000573namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000574/// Models the state of a single base defining value in the findBasePointer
575/// algorithm for determining where a new instruction is needed to propagate
576/// the base of this BDV.
577class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000578public:
579 enum Status { Unknown, Base, Conflict };
580
Philip Reames9b141ed2015-07-23 22:49:14 +0000581 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000582 assert(status != Base || b);
583 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000584 explicit BDVState(Value *b) : status(Base), base(b) {}
585 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000586
587 Status getStatus() const { return status; }
588 Value *getBase() const { return base; }
589
590 bool isBase() const { return getStatus() == Base; }
591 bool isUnknown() const { return getStatus() == Unknown; }
592 bool isConflict() const { return getStatus() == Conflict; }
593
Philip Reames9b141ed2015-07-23 22:49:14 +0000594 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000595 return base == other.base && status == other.status;
596 }
597
Philip Reames9b141ed2015-07-23 22:49:14 +0000598 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000599
Philip Reames2a892a62015-07-23 22:25:26 +0000600 LLVM_DUMP_METHOD
601 void dump() const { print(dbgs()); dbgs() << '\n'; }
602
603 void print(raw_ostream &OS) const {
604 OS << status << " (" << base << " - "
605 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000606 }
607
608private:
609 Status status;
610 Value *base; // non null only if status == base
611};
612
Philip Reames9b141ed2015-07-23 22:49:14 +0000613inline raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000614 State.print(OS);
615 return OS;
616}
617
618
Philip Reames9b141ed2015-07-23 22:49:14 +0000619typedef DenseMap<Value *, BDVState> ConflictStateMapTy;
620// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000621// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000622// operation is implemented in MeetBDVStates::pureMeet
623class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000624public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000625 /// Initializes the currentResult to the TOP state so that if can be met with
626 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000627 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000628
Philip Reames9b141ed2015-07-23 22:49:14 +0000629 // Destructively meet the current result with the given BDVState
630 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000631 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000632 }
633
Philip Reames9b141ed2015-07-23 22:49:14 +0000634 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000635
636private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000637 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000638
Philip Reames9b141ed2015-07-23 22:49:14 +0000639 /// Perform a meet operation on two elements of the BDVState lattice.
640 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000641 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
642 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000643 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000644 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
645 << " produced " << Result << "\n");
646 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000647 }
648
Philip Reames9b141ed2015-07-23 22:49:14 +0000649 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000650 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000651 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000652 return stateB;
653
Philip Reames9b141ed2015-07-23 22:49:14 +0000654 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000655 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000656 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000657 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000658
659 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000660 if (stateA.getBase() == stateB.getBase()) {
661 assert(stateA == stateB && "equality broken!");
662 return stateA;
663 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000664 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000665 }
David Blaikie82ad7872015-02-20 23:44:24 +0000666 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000667 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000668
Philip Reames9b141ed2015-07-23 22:49:14 +0000669 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000670 return stateA;
671 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000672 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000673 }
674};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000675}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000676/// For a given value or instruction, figure out what base ptr it's derived
677/// from. For gc objects, this is simply itself. On success, returns a value
678/// which is the base pointer. (This is reliable and can be used for
679/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000680static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000681 Value *def = findBaseOrBDV(I, cache);
682
683 if (isKnownBaseResult(def)) {
684 return def;
685 }
686
687 // Here's the rough algorithm:
688 // - For every SSA value, construct a mapping to either an actual base
689 // pointer or a PHI which obscures the base pointer.
690 // - Construct a mapping from PHI to unknown TOP state. Use an
691 // optimistic algorithm to propagate base pointer information. Lattice
692 // looks like:
693 // UNKNOWN
694 // b1 b2 b3 b4
695 // CONFLICT
696 // When algorithm terminates, all PHIs will either have a single concrete
697 // base or be in a conflict state.
698 // - For every conflict, insert a dummy PHI node without arguments. Add
699 // these to the base[Instruction] = BasePtr mapping. For every
700 // non-conflict, add the actual base.
701 // - For every conflict, add arguments for the base[a] of each input
702 // arguments.
703 //
704 // Note: A simpler form of this would be to add the conflict form of all
705 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000706 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000707 // overall worse solution.
708
Philip Reames29e9ae72015-07-24 00:42:55 +0000709#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000710 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000711 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) || isa<ExtractElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000712 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000713#endif
Philip Reames88958b22015-07-24 00:02:11 +0000714
715 // Once populated, will contain a mapping from each potentially non-base BDV
716 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames860660e2015-02-20 22:05:18 +0000717 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000718 // Recursively fill in all phis & selects reachable from the initial one
719 // for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000720 /* scope */ {
721 DenseSet<Value *> Visited;
722 SmallVector<Value*, 16> Worklist;
723 Worklist.push_back(def);
724 Visited.insert(def);
725 while (!Worklist.empty()) {
726 Value *Current = Worklist.pop_back_val();
727 assert(!isKnownBaseResult(Current) && "why did it get added?");
728
729 auto visitIncomingValue = [&](Value *InVal) {
730 Value *Base = findBaseOrBDV(InVal, cache);
731 if (isKnownBaseResult(Base))
732 // Known bases won't need new instructions introduced and can be
733 // ignored safely
734 return;
735 assert(isExpectedBDVType(Base) && "the only non-base values "
736 "we see should be base defining values");
737 if (Visited.insert(Base).second)
738 Worklist.push_back(Base);
739 };
740 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
741 for (Value *InVal : Phi->incoming_values())
742 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000743 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000744 visitIncomingValue(Sel->getTrueValue());
745 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000746 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
747 visitIncomingValue(EE->getVectorOperand());
748 } else {
749 // There are two classes of instructions we know we don't handle.
750 assert(isa<ShuffleVectorInst>(Current) ||
751 isa<InsertElementInst>(Current));
752 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000753 }
754 }
Philip Reames88958b22015-07-24 00:02:11 +0000755 // The frontier of visited instructions are the ones we might need to
756 // duplicate, so fill in the starting state for the optimistic algorithm
757 // that follows.
758 for (Value *BDV : Visited) {
759 states[BDV] = BDVState();
760 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000761 }
762
763 if (TraceLSP) {
764 errs() << "States after initialization:\n";
Philip Reames2a892a62015-07-23 22:25:26 +0000765 for (auto Pair : states)
Philip Reames9ac4e382015-08-12 21:00:20 +0000766 dbgs() << " " << Pair.second << " for " << *Pair.first << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000767 }
768
769 // TODO: come back and revisit the state transitions around inputs which
770 // have reached conflict state. The current version seems too conservative.
771
Philip Reames273e6bb2015-07-23 21:41:27 +0000772 // Return a phi state for a base defining value. We'll generate a new
773 // base state for known bases and expect to find a cached state otherwise.
774 auto getStateForBDV = [&](Value *baseValue) {
775 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000776 return BDVState(baseValue);
Philip Reames273e6bb2015-07-23 21:41:27 +0000777 auto I = states.find(baseValue);
778 assert(I != states.end() && "lookup failed!");
779 return I->second;
780 };
781
Philip Reamesd16a9b12015-02-20 01:06:44 +0000782 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000783 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000784#ifndef NDEBUG
785 size_t oldSize = states.size();
786#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000787 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000788 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000789 for (auto Pair : states) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000790 Value *v = Pair.first;
791 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000792
Philip Reames9b141ed2015-07-23 22:49:14 +0000793 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000794 // instance which represents the BDV of that value.
795 auto getStateForInput = [&](Value *V) mutable {
796 Value *BDV = findBaseOrBDV(V, cache);
797 return getStateForBDV(BDV);
798 };
799
Philip Reames9b141ed2015-07-23 22:49:14 +0000800 MeetBDVStates calculateMeet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000801 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000802 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
803 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reames9ac4e382015-08-12 21:00:20 +0000804 } else if (PHINode *Phi = dyn_cast<PHINode>(v)) {
805 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000806 calculateMeet.meetWith(getStateForInput(Val));
Philip Reames9ac4e382015-08-12 21:00:20 +0000807 } else {
808 // The 'meet' for an extractelement is slightly trivial, but it's still
809 // useful in that it drives us to conflict if our input is.
810 auto *EE = cast<ExtractElementInst>(v);
811 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
812 }
813
Philip Reamesd16a9b12015-02-20 01:06:44 +0000814
Philip Reames9b141ed2015-07-23 22:49:14 +0000815 BDVState oldState = states[v];
816 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000817 if (oldState != newState) {
818 progress = true;
819 states[v] = newState;
820 }
821 }
822
823 assert(oldSize <= states.size());
824 assert(oldSize == states.size() || progress);
825 }
826
827 if (TraceLSP) {
828 errs() << "States after meet iteration:\n";
Philip Reames2a892a62015-07-23 22:25:26 +0000829 for (auto Pair : states)
Philip Reames9ac4e382015-08-12 21:00:20 +0000830 dbgs() << " " << Pair.second << " for " << *Pair.first << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000831 }
832
833 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000834 // We want to keep naming deterministic in the loop that follows, so
835 // sort the keys before iteration. This is useful in allowing us to
836 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000837 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000838 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000839 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000840 Value *V = Pair.first;
841 Keys.push_back(V);
842 }
843 std::sort(Keys.begin(), Keys.end(), order_by_name);
844 // TODO: adjust naming patterns to avoid this order of iteration dependency
845 for (Value *V : Keys) {
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000846 Instruction *I = cast<Instruction>(V);
Philip Reames9b141ed2015-07-23 22:49:14 +0000847 BDVState State = states[I];
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000848 assert(!isKnownBaseResult(I) && "why did it get added?");
849 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000850
851 // extractelement instructions are a bit special in that we may need to
852 // insert an extract even when we know an exact base for the instruction.
853 // The problem is that we need to convert from a vector base to a scalar
854 // base for the particular indice we're interested in.
855 if (State.isBase() && isa<ExtractElementInst>(I) &&
856 isa<VectorType>(State.getBase()->getType())) {
857 auto *EE = cast<ExtractElementInst>(I);
858 // TODO: In many cases, the new instruction is just EE itself. We should
859 // exploit this, but can't do it here since it would break the invariant
860 // about the BDV not being known to be a base.
861 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
862 EE->getIndexOperand(),
863 "base_ee", EE);
864 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
865 states[I] = BDVState(BDVState::Base, BaseInst);
866 }
867
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000868 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000869 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000870
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000871 /// Create and insert a new instruction which will represent the base of
872 /// the given instruction 'I'.
873 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
874 if (isa<PHINode>(I)) {
875 BasicBlock *BB = I->getParent();
876 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
877 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000878 std::string Name = I->hasName() ?
879 (I->getName() + ".base").str() : "base_phi";
880 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000881 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
882 // The undef will be replaced later
883 UndefValue *Undef = UndefValue::get(Sel->getType());
884 std::string Name = I->hasName() ?
885 (I->getName() + ".base").str() : "base_select";
886 return SelectInst::Create(Sel->getCondition(), Undef,
887 Undef, Name, Sel);
888 } else {
889 auto *EE = cast<ExtractElementInst>(I);
890 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
891 std::string Name = I->hasName() ?
892 (I->getName() + ".base").str() : "base_ee";
893 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
894 EE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000895 }
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000896 };
897 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
898 // Add metadata marking this as a base value
899 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames9b141ed2015-07-23 22:49:14 +0000900 states[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000901 }
902
903 // Fixup all the inputs of the new PHIs
904 for (auto Pair : states) {
905 Instruction *v = cast<Instruction>(Pair.first);
Philip Reames9b141ed2015-07-23 22:49:14 +0000906 BDVState state = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000907
908 assert(!isKnownBaseResult(v) && "why did it get added?");
909 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000910 if (!state.isConflict())
911 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000912
Philip Reames28e61ce2015-02-28 01:57:44 +0000913 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
914 PHINode *phi = cast<PHINode>(v);
915 unsigned NumPHIValues = phi->getNumIncomingValues();
916 for (unsigned i = 0; i < NumPHIValues; i++) {
917 Value *InVal = phi->getIncomingValue(i);
918 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000919
Philip Reames28e61ce2015-02-28 01:57:44 +0000920 // If we've already seen InBB, add the same incoming value
921 // we added for it earlier. The IR verifier requires phi
922 // nodes with multiple entries from the same basic block
923 // to have the same incoming value for each of those
924 // entries. If we don't do this check here and basephi
925 // has a different type than base, we'll end up adding two
926 // bitcasts (and hence two distinct values) as incoming
927 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000928
Philip Reames28e61ce2015-02-28 01:57:44 +0000929 int blockIndex = basephi->getBasicBlockIndex(InBB);
930 if (blockIndex != -1) {
931 Value *oldBase = basephi->getIncomingValue(blockIndex);
932 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000933#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000934 Value *base = findBaseOrBDV(InVal, cache);
935 if (!isKnownBaseResult(base)) {
936 // Either conflict or base.
937 assert(states.count(base));
938 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000939 assert(base != nullptr && "unknown BDVState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000940 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000941
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000942 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +0000943 // values incoming from the same basic block may be
944 // different is by being different bitcasts of the same
945 // value. A cleanup that remains TODO is changing
946 // findBaseOrBDV to return an llvm::Value of the correct
947 // type (and still remain pure). This will remove the
948 // need to add bitcasts.
949 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
950 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000951#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000952 continue;
953 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000954
Philip Reames28e61ce2015-02-28 01:57:44 +0000955 // Find either the defining value for the PHI or the normal base for
956 // a non-phi node
957 Value *base = findBaseOrBDV(InVal, cache);
958 if (!isKnownBaseResult(base)) {
959 // Either conflict or base.
960 assert(states.count(base));
961 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000962 assert(base != nullptr && "unknown BDVState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000963 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000964 assert(base && "can't be null");
965 // Must use original input BB since base may not be Instruction
966 // The cast is needed since base traversal may strip away bitcasts
967 if (base->getType() != basephi->getType()) {
968 base = new BitCastInst(base, basephi->getType(), "cast",
969 InBB->getTerminator());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000970 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000971 basephi->addIncoming(base, InBB);
972 }
973 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reames9ac4e382015-08-12 21:00:20 +0000974 } else if (SelectInst *basesel = dyn_cast<SelectInst>(state.getBase())) {
Philip Reames28e61ce2015-02-28 01:57:44 +0000975 SelectInst *sel = cast<SelectInst>(v);
976 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
977 // something more safe and less hacky.
978 for (int i = 1; i <= 2; i++) {
979 Value *InVal = sel->getOperand(i);
980 // Find either the defining value for the PHI or the normal base for
981 // a non-phi node
982 Value *base = findBaseOrBDV(InVal, cache);
983 if (!isKnownBaseResult(base)) {
984 // Either conflict or base.
985 assert(states.count(base));
986 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000987 assert(base != nullptr && "unknown BDVState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000988 }
989 assert(base && "can't be null");
990 // Must use original input BB since base may not be Instruction
991 // The cast is needed since base traversal may strip away bitcasts
992 if (base->getType() != basesel->getType()) {
993 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
Philip Reames28e61ce2015-02-28 01:57:44 +0000994 }
995 basesel->setOperand(i, base);
996 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000997 } else {
998 auto *BaseEE = cast<ExtractElementInst>(state.getBase());
999 Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
1000 Value *Base = findBaseOrBDV(InVal, cache);
1001 if (!isKnownBaseResult(Base)) {
1002 // Either conflict or base.
1003 assert(states.count(Base));
1004 Base = states[Base].getBase();
1005 assert(Base != nullptr && "unknown BDVState!");
1006 }
1007 assert(Base && "can't be null");
1008 BaseEE->setOperand(0, Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001009 }
1010 }
1011
1012 // Cache all of our results so we can cheaply reuse them
1013 // NOTE: This is actually two caches: one of the base defining value
1014 // relation and one of the base pointer relation! FIXME
1015 for (auto item : states) {
1016 Value *v = item.first;
1017 Value *base = item.second.getBase();
1018 assert(v && base);
1019 assert(!isKnownBaseResult(v) && "why did it get added?");
1020
1021 if (TraceLSP) {
1022 std::string fromstr =
1023 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
1024 : "none";
1025 errs() << "Updating base value cache"
1026 << " for: " << (v->hasName() ? v->getName() : "")
1027 << " from: " << fromstr
1028 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
1029 }
1030
1031 assert(isKnownBaseResult(base) &&
1032 "must be something we 'know' is a base pointer");
1033 if (cache.count(v)) {
1034 // Once we transition from the BDV relation being store in the cache to
1035 // the base relation being stored, it must be stable
1036 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
1037 "base relation should be stable");
1038 }
1039 cache[v] = base;
1040 }
1041 assert(cache.find(def) != cache.end());
1042 return cache[def];
1043}
1044
1045// For a set of live pointers (base and/or derived), identify the base
1046// pointer of the object which they are derived from. This routine will
1047// mutate the IR graph as needed to make the 'base' pointer live at the
1048// definition site of 'derived'. This ensures that any use of 'derived' can
1049// also use 'base'. This may involve the insertion of a number of
1050// additional PHI nodes.
1051//
1052// preconditions: live is a set of pointer type Values
1053//
1054// side effects: may insert PHI nodes into the existing CFG, will preserve
1055// CFG, will not remove or mutate any existing nodes
1056//
Philip Reamesf2041322015-02-20 19:26:04 +00001057// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001058// pointer in live. Note that derived can be equal to base if the original
1059// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001060static void
1061findBasePointers(const StatepointLiveSetTy &live,
1062 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001063 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001064 // For the naming of values inserted to be deterministic - which makes for
1065 // much cleaner and more stable tests - we need to assign an order to the
1066 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001067 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001068 Temp.insert(Temp.end(), live.begin(), live.end());
1069 std::sort(Temp.begin(), Temp.end(), order_by_name);
1070 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001071 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001072 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001073 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001074 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1075 DT->dominates(cast<Instruction>(base)->getParent(),
1076 cast<Instruction>(ptr)->getParent())) &&
1077 "The base we found better dominate the derived pointer");
1078
David Blaikie82ad7872015-02-20 23:44:24 +00001079 // If you see this trip and like to live really dangerously, the code should
1080 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001081 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001082 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001083 "the relocation code needs adjustment to handle the relocation of "
1084 "a null pointer constant without causing false positives in the "
1085 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001086 }
1087}
1088
1089/// Find the required based pointers (and adjust the live set) for the given
1090/// parse point.
1091static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1092 const CallSite &CS,
1093 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001094 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +00001095 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001096
1097 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001098 // Note: Need to print these in a stable order since this is checked in
1099 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001100 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001101 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001102 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001103 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001104 Temp.push_back(Pair.first);
1105 }
1106 std::sort(Temp.begin(), Temp.end(), order_by_name);
1107 for (Value *Ptr : Temp) {
1108 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001109 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1110 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001111 }
1112 }
1113
Philip Reamesf2041322015-02-20 19:26:04 +00001114 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001115}
1116
Philip Reamesdf1ef082015-04-10 22:53:14 +00001117/// Given an updated version of the dataflow liveness results, update the
1118/// liveset and base pointer maps for the call site CS.
1119static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1120 const CallSite &CS,
1121 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001122
Philip Reamesdf1ef082015-04-10 22:53:14 +00001123static void recomputeLiveInValues(
1124 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001125 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001126 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001127 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001128 GCPtrLivenessData RevisedLivenessData;
1129 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001130 for (size_t i = 0; i < records.size(); i++) {
1131 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001132 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001133 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001134 }
1135}
1136
Philip Reames69e51ca2015-04-13 18:07:21 +00001137// When inserting gc.relocate calls, we need to ensure there are no uses
1138// of the original value between the gc.statepoint and the gc.relocate call.
1139// One case which can arise is a phi node starting one of the successor blocks.
1140// We also need to be able to insert the gc.relocates only on the path which
1141// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001142// possible.
1143static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001144normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1145 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001146 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001147 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001148 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001149 }
1150
Philip Reames69e51ca2015-04-13 18:07:21 +00001151 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1152 // from it
1153 FoldSingleEntryPHINodes(Ret);
1154 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001155
Philip Reames69e51ca2015-04-13 18:07:21 +00001156 // At this point, we can safely insert a gc.relocate as the first instruction
1157 // in Ret if needed.
1158 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001159}
1160
Philip Reamesd2b66462015-02-20 22:39:41 +00001161static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001162 auto itr = std::find(livevec.begin(), livevec.end(), val);
1163 assert(livevec.end() != itr);
1164 size_t index = std::distance(livevec.begin(), itr);
1165 assert(index < livevec.size());
1166 return index;
1167}
1168
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001169// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001170// from original call to the safepoint.
1171static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1172 AttributeSet ret;
1173
1174 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1175 unsigned index = AS.getSlotIndex(Slot);
1176
1177 if (index == AttributeSet::ReturnIndex ||
1178 index == AttributeSet::FunctionIndex) {
1179
1180 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1181 ++it) {
1182 Attribute attr = *it;
1183
1184 // Do not allow certain attributes - just skip them
1185 // Safepoint can not be read only or read none.
1186 if (attr.hasAttribute(Attribute::ReadNone) ||
1187 attr.hasAttribute(Attribute::ReadOnly))
1188 continue;
1189
1190 ret = ret.addAttributes(
1191 AS.getContext(), index,
1192 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1193 }
1194 }
1195
1196 // Just skip parameter attributes for now
1197 }
1198
1199 return ret;
1200}
1201
1202/// Helper function to place all gc relocates necessary for the given
1203/// statepoint.
1204/// Inputs:
1205/// liveVariables - list of variables to be relocated.
1206/// liveStart - index of the first live variable.
1207/// basePtrs - base pointers.
1208/// statepointToken - statepoint instruction to which relocates should be
1209/// bound.
1210/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001211static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1212 const int LiveStart,
1213 ArrayRef<llvm::Value *> BasePtrs,
1214 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001215 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001216 if (LiveVariables.empty())
1217 return;
1218
1219 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1220 // unique declarations for each pointer type, but this proved problematic
1221 // because the intrinsic mangling code is incomplete and fragile. Since
1222 // we're moving towards a single unified pointer type anyways, we can just
1223 // cast everything to an i8* of the right address space. A bitcast is added
1224 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001225 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001226 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1227 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1228 Value *GCRelocateDecl =
1229 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001230
Sanjoy Das5665c992015-05-11 23:47:27 +00001231 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001232 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001233 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001234 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1235 Value *LiveIdx =
1236 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001237
1238 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001239 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001240 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001241 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001242 : "");
1243 // Trick CodeGen into thinking there are lots of free registers at this
1244 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001245 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001246 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001247}
1248
1249static void
1250makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1251 const SmallVectorImpl<llvm::Value *> &basePtrs,
1252 const SmallVectorImpl<llvm::Value *> &liveVariables,
1253 Pass *P,
1254 PartiallyConstructedSafepointRecord &result) {
1255 assert(basePtrs.size() == liveVariables.size());
1256 assert(isStatepoint(CS) &&
1257 "This method expects to be rewriting a statepoint");
1258
1259 BasicBlock *BB = CS.getInstruction()->getParent();
1260 assert(BB);
1261 Function *F = BB->getParent();
1262 assert(F && "must be set");
1263 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001264 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001265 assert(M && "must be set");
1266
1267 // We're not changing the function signature of the statepoint since the gc
1268 // arguments go into the var args section.
1269 Function *gc_statepoint_decl = CS.getCalledFunction();
1270
1271 // Then go ahead and use the builder do actually do the inserts. We insert
1272 // immediately before the previous instruction under the assumption that all
1273 // arguments will be available here. We can't insert afterwards since we may
1274 // be replacing a terminator.
1275 Instruction *insertBefore = CS.getInstruction();
1276 IRBuilder<> Builder(insertBefore);
1277 // Copy all of the arguments from the original statepoint - this includes the
1278 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001279 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001280 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1281 // TODO: Clear the 'needs rewrite' flag
1282
1283 // add all the pointers to be relocated (gc arguments)
1284 // Capture the start of the live variable list for use in the gc_relocates
1285 const int live_start = args.size();
1286 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1287
1288 // Create the statepoint given all the arguments
1289 Instruction *token = nullptr;
1290 AttributeSet return_attributes;
1291 if (CS.isCall()) {
1292 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1293 CallInst *call =
1294 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1295 call->setTailCall(toReplace->isTailCall());
1296 call->setCallingConv(toReplace->getCallingConv());
1297
1298 // Currently we will fail on parameter attributes and on certain
1299 // function attributes.
1300 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001301 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001302 // directly on statepoint and return attrs later for gc_result intrinsic.
1303 call->setAttributes(new_attrs.getFnAttributes());
1304 return_attributes = new_attrs.getRetAttributes();
1305
1306 token = call;
1307
1308 // Put the following gc_result and gc_relocate calls immediately after the
1309 // the old call (which we're about to delete)
1310 BasicBlock::iterator next(toReplace);
1311 assert(BB->end() != next && "not a terminator, must have next");
1312 next++;
1313 Instruction *IP = &*(next);
1314 Builder.SetInsertPoint(IP);
1315 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1316
David Blaikie82ad7872015-02-20 23:44:24 +00001317 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001318 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1319
1320 // Insert the new invoke into the old block. We'll remove the old one in a
1321 // moment at which point this will become the new terminator for the
1322 // original block.
1323 InvokeInst *invoke = InvokeInst::Create(
1324 gc_statepoint_decl, toReplace->getNormalDest(),
Philip Reamesfa2c6302015-07-24 19:01:39 +00001325 toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001326 invoke->setCallingConv(toReplace->getCallingConv());
1327
1328 // Currently we will fail on parameter attributes and on certain
1329 // function attributes.
1330 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001331 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001332 // directly on statepoint and return attrs later for gc_result intrinsic.
1333 invoke->setAttributes(new_attrs.getFnAttributes());
1334 return_attributes = new_attrs.getRetAttributes();
1335
1336 token = invoke;
1337
1338 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001339 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1340 assert(!isa<PHINode>(unwindBlock->begin()) &&
1341 unwindBlock->getUniquePredecessor() &&
1342 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001343
1344 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1345 Builder.SetInsertPoint(IP);
1346 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1347
1348 // Extract second element from landingpad return value. We will attach
1349 // exceptional gc relocates to it.
1350 const unsigned idx = 1;
1351 Instruction *exceptional_token =
1352 cast<Instruction>(Builder.CreateExtractValue(
1353 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001354 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001355
Philip Reames6ff1a1e32015-07-21 19:04:38 +00001356 CreateGCRelocates(liveVariables, live_start, basePtrs,
1357 exceptional_token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001358
1359 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001360 BasicBlock *normalDest = toReplace->getNormalDest();
1361 assert(!isa<PHINode>(normalDest->begin()) &&
1362 normalDest->getUniquePredecessor() &&
1363 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001364
1365 IP = &*(normalDest->getFirstInsertionPt());
1366 Builder.SetInsertPoint(IP);
1367
1368 // gc relocates will be generated later as if it were regular call
1369 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001370 }
1371 assert(token);
1372
1373 // Take the name of the original value call if it had one.
1374 token->takeName(CS.getInstruction());
1375
Philip Reames704e78b2015-04-10 22:34:56 +00001376// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001377#ifndef NDEBUG
1378 Instruction *toReplace = CS.getInstruction();
1379 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1380 "only valid use before rewrite is gc.result");
1381 assert(!toReplace->hasOneUse() ||
1382 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1383#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001384
1385 // Update the gc.result of the original statepoint (if any) to use the newly
1386 // inserted statepoint. This is safe to do here since the token can't be
1387 // considered a live reference.
1388 CS.getInstruction()->replaceAllUsesWith(token);
1389
Philip Reames0a3240f2015-02-20 21:34:11 +00001390 result.StatepointToken = token;
1391
Philip Reamesd16a9b12015-02-20 01:06:44 +00001392 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001393 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001394}
1395
1396namespace {
1397struct name_ordering {
1398 Value *base;
1399 Value *derived;
1400 bool operator()(name_ordering const &a, name_ordering const &b) {
1401 return -1 == a.derived->getName().compare(b.derived->getName());
1402 }
1403};
1404}
1405static void stablize_order(SmallVectorImpl<Value *> &basevec,
1406 SmallVectorImpl<Value *> &livevec) {
1407 assert(basevec.size() == livevec.size());
1408
Philip Reames860660e2015-02-20 22:05:18 +00001409 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001410 for (size_t i = 0; i < basevec.size(); i++) {
1411 name_ordering v;
1412 v.base = basevec[i];
1413 v.derived = livevec[i];
1414 temp.push_back(v);
1415 }
1416 std::sort(temp.begin(), temp.end(), name_ordering());
1417 for (size_t i = 0; i < basevec.size(); i++) {
1418 basevec[i] = temp[i].base;
1419 livevec[i] = temp[i].derived;
1420 }
1421}
1422
1423// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1424// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001425//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001426// WARNING: Does not do any fixup to adjust users of the original live
1427// values. That's the callers responsibility.
1428static void
1429makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1430 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001431 auto liveset = result.liveset;
1432 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001433
1434 // Convert to vector for efficient cross referencing.
1435 SmallVector<Value *, 64> basevec, livevec;
1436 livevec.reserve(liveset.size());
1437 basevec.reserve(liveset.size());
1438 for (Value *L : liveset) {
1439 livevec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001440 assert(PointerToBase.count(L));
Philip Reamesf2041322015-02-20 19:26:04 +00001441 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001442 basevec.push_back(base);
1443 }
1444 assert(livevec.size() == basevec.size());
1445
1446 // To make the output IR slightly more stable (for use in diffs), ensure a
1447 // fixed order of the values in the safepoint (by sorting the value name).
1448 // The order is otherwise meaningless.
1449 stablize_order(basevec, livevec);
1450
1451 // Do the actual rewriting and delete the old statepoint
1452 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1453 CS.getInstruction()->eraseFromParent();
1454}
1455
1456// Helper function for the relocationViaAlloca.
1457// It receives iterator to the statepoint gc relocates and emits store to the
1458// assigned
1459// location (via allocaMap) for the each one of them.
1460// Add visited values into the visitedLiveValues set we will later use them
1461// for sanity check.
1462static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001463insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1464 DenseMap<Value *, Value *> &AllocaMap,
1465 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001466
Sanjoy Das5665c992015-05-11 23:47:27 +00001467 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001468 if (!isa<IntrinsicInst>(U))
1469 continue;
1470
Sanjoy Das5665c992015-05-11 23:47:27 +00001471 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001472
1473 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001474 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001475 Intrinsic::experimental_gc_relocate) {
1476 continue;
1477 }
1478
Sanjoy Das5665c992015-05-11 23:47:27 +00001479 GCRelocateOperands RelocateOperands(RelocatedValue);
1480 Value *OriginalValue =
1481 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1482 assert(AllocaMap.count(OriginalValue));
1483 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001484
1485 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001486 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1487 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001488 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1489 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001490 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001491 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1492 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001493
Sanjoy Das5665c992015-05-11 23:47:27 +00001494 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1495 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001496
1497#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001498 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001499#endif
1500 }
1501}
1502
Igor Laevskye0317182015-05-19 15:59:05 +00001503// Helper function for the "relocationViaAlloca". Similar to the
1504// "insertRelocationStores" but works for rematerialized values.
1505static void
1506insertRematerializationStores(
1507 RematerializedValueMapTy RematerializedValues,
1508 DenseMap<Value *, Value *> &AllocaMap,
1509 DenseSet<Value *> &VisitedLiveValues) {
1510
1511 for (auto RematerializedValuePair: RematerializedValues) {
1512 Instruction *RematerializedValue = RematerializedValuePair.first;
1513 Value *OriginalValue = RematerializedValuePair.second;
1514
1515 assert(AllocaMap.count(OriginalValue) &&
1516 "Can not find alloca for rematerialized value");
1517 Value *Alloca = AllocaMap[OriginalValue];
1518
1519 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1520 Store->insertAfter(RematerializedValue);
1521
1522#ifndef NDEBUG
1523 VisitedLiveValues.insert(OriginalValue);
1524#endif
1525 }
1526}
1527
Philip Reamesd16a9b12015-02-20 01:06:44 +00001528/// do all the relocation update via allocas and mem2reg
1529static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001530 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1531 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001532#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001533 // record initial number of (static) allocas; we'll check we have the same
1534 // number when we get done.
1535 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001536 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1537 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001538 if (isa<AllocaInst>(*I))
1539 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001540#endif
1541
1542 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001543 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001544 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001545 // Used later to chack that we have enough allocas to store all values
1546 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001547 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001548
Igor Laevskye0317182015-05-19 15:59:05 +00001549 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1550 // "PromotableAllocas"
1551 auto emitAllocaFor = [&](Value *LiveValue) {
1552 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1553 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001554 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001555 PromotableAllocas.push_back(Alloca);
1556 };
1557
Philip Reamesd16a9b12015-02-20 01:06:44 +00001558 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001559 for (unsigned i = 0; i < Live.size(); i++) {
1560 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001561 }
1562
Igor Laevskye0317182015-05-19 15:59:05 +00001563 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001564 for (size_t i = 0; i < Records.size(); i++) {
1565 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001566
Igor Laevsky285fe842015-05-19 16:29:43 +00001567 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001568 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001569 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001570 continue;
1571
1572 emitAllocaFor(OriginalValue);
1573 ++NumRematerializedValues;
1574 }
1575 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001576
Philip Reamesd16a9b12015-02-20 01:06:44 +00001577 // The next two loops are part of the same conceptual operation. We need to
1578 // insert a store to the alloca after the original def and at each
1579 // redefinition. We need to insert a load before each use. These are split
1580 // into distinct loops for performance reasons.
1581
1582 // update gc pointer after each statepoint
1583 // either store a relocated value or null (if no relocated value found for
1584 // this gc pointer and it is not a gc_result)
1585 // this must happen before we update the statepoint with load of alloca
1586 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001587 for (size_t i = 0; i < Records.size(); i++) {
1588 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1589 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001590
1591 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001592 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001593
1594 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001595 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001596
1597 // In case if it was invoke statepoint
1598 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001599 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001600 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1601 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001602 }
1603
Igor Laevskye0317182015-05-19 15:59:05 +00001604 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001605 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1606 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001607
Philip Reamese73300b2015-04-13 16:41:32 +00001608 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001609 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001610 // the gc.statepoint. This will turn some subtle GC problems into
1611 // slightly easier to debug SEGVs. Note that on large IR files with
1612 // lots of gc.statepoints this is extremely costly both memory and time
1613 // wise.
1614 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001615 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001616 Value *Def = Pair.first;
1617 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001618
Philip Reamese73300b2015-04-13 16:41:32 +00001619 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001620 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001621 continue;
1622 }
1623 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001624 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001625
Philip Reamese73300b2015-04-13 16:41:32 +00001626 auto InsertClobbersAt = [&](Instruction *IP) {
1627 for (auto *AI : ToClobber) {
1628 auto AIType = cast<PointerType>(AI->getType());
1629 auto PT = cast<PointerType>(AIType->getElementType());
1630 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001631 StoreInst *Store = new StoreInst(CPN, AI);
1632 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001633 }
1634 };
1635
1636 // Insert the clobbering stores. These may get intermixed with the
1637 // gc.results and gc.relocates, but that's fine.
1638 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1639 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1640 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1641 } else {
1642 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1643 Next++;
1644 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001645 }
David Blaikie82ad7872015-02-20 23:44:24 +00001646 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001647 }
1648 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001649 for (auto Pair : AllocaMap) {
1650 Value *Def = Pair.first;
1651 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001652
1653 // we pre-record the uses of allocas so that we dont have to worry about
1654 // later update
1655 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001656 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001657 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001658 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1659 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001660 if (!isa<ConstantExpr>(U)) {
1661 // If the def has a ConstantExpr use, then the def is either a
1662 // ConstantExpr use itself or null. In either case
1663 // (recursively in the first, directly in the second), the oop
1664 // it is ultimately dependent on is null and this particular
1665 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001666 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001667 }
1668 }
1669
Igor Laevsky285fe842015-05-19 16:29:43 +00001670 std::sort(Uses.begin(), Uses.end());
1671 auto Last = std::unique(Uses.begin(), Uses.end());
1672 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001673
Igor Laevsky285fe842015-05-19 16:29:43 +00001674 for (Instruction *Use : Uses) {
1675 if (isa<PHINode>(Use)) {
1676 PHINode *Phi = cast<PHINode>(Use);
1677 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1678 if (Def == Phi->getIncomingValue(i)) {
1679 LoadInst *Load = new LoadInst(
1680 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1681 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001682 }
1683 }
1684 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001685 LoadInst *Load = new LoadInst(Alloca, "", Use);
1686 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001687 }
1688 }
1689
1690 // emit store for the initial gc value
1691 // store must be inserted after load, otherwise store will be in alloca's
1692 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001693 StoreInst *Store = new StoreInst(Def, Alloca);
1694 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1695 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001696 // InvokeInst is a TerminatorInst so the store need to be inserted
1697 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001698 BasicBlock *NormalDest = Invoke->getNormalDest();
1699 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001700 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001701 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001702 "The only TerminatorInst that can produce a value is "
1703 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001704 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001705 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001706 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001707 assert(isa<Argument>(Def));
1708 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001709 }
1710 }
1711
Igor Laevsky285fe842015-05-19 16:29:43 +00001712 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001713 "we must have the same allocas with lives");
1714 if (!PromotableAllocas.empty()) {
1715 // apply mem2reg to promote alloca to SSA
1716 PromoteMemToReg(PromotableAllocas, DT);
1717 }
1718
1719#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001720 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1721 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001722 if (isa<AllocaInst>(*I))
1723 InitialAllocaNum--;
1724 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001725#endif
1726}
1727
1728/// Implement a unique function which doesn't require we sort the input
1729/// vector. Doing so has the effect of changing the output of a couple of
1730/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001731template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001732 SmallSet<T, 8> Seen;
1733 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1734 return !Seen.insert(V).second;
1735 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001736}
1737
Philip Reamesd16a9b12015-02-20 01:06:44 +00001738/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001739/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001740static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001741 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001742 if (Values.empty())
1743 // No values to hold live, might as well not insert the empty holder
1744 return;
1745
Philip Reamesd16a9b12015-02-20 01:06:44 +00001746 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001747 // Use a dummy vararg function to actually hold the values live
1748 Function *Func = cast<Function>(M->getOrInsertFunction(
1749 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001750 if (CS.isCall()) {
1751 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001752 BasicBlock::iterator Next(CS.getInstruction());
1753 Next++;
1754 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1755 return;
1756 }
1757 // For invoke safepooints insert dummy calls both in normal and
1758 // exceptional destination blocks
1759 auto *II = cast<InvokeInst>(CS.getInstruction());
1760 Holders.push_back(CallInst::Create(
1761 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1762 Holders.push_back(CallInst::Create(
1763 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001764}
1765
1766static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001767 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1768 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001769 GCPtrLivenessData OriginalLivenessData;
1770 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001771 for (size_t i = 0; i < records.size(); i++) {
1772 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001773 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001774 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001775 }
1776}
1777
Philip Reames8531d8c2015-04-10 21:48:25 +00001778/// Remove any vector of pointers from the liveset by scalarizing them over the
1779/// statepoint instruction. Adds the scalarized pieces to the liveset. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001780/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001781/// the lowering code currently does not handle that. Extending it would be
1782/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001783/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001784static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001785 StatepointLiveSetTy &LiveSet,
1786 DenseMap<Value *, Value *>& PointerToBase,
1787 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001788 SmallVector<Value *, 16> ToSplit;
1789 for (Value *V : LiveSet)
1790 if (isa<VectorType>(V->getType()))
1791 ToSplit.push_back(V);
1792
1793 if (ToSplit.empty())
1794 return;
1795
Philip Reames8fe7f132015-06-26 22:47:37 +00001796 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1797
Philip Reames8531d8c2015-04-10 21:48:25 +00001798 Function &F = *(StatepointInst->getParent()->getParent());
1799
Philip Reames704e78b2015-04-10 22:34:56 +00001800 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001801 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001802 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001803 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001804 AllocaInst *Alloca =
1805 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001806 AllocaMap[V] = Alloca;
1807
1808 VectorType *VT = cast<VectorType>(V->getType());
1809 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001810 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001811 for (unsigned i = 0; i < VT->getNumElements(); i++)
1812 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001813 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001814
1815 auto InsertVectorReform = [&](Instruction *IP) {
1816 Builder.SetInsertPoint(IP);
1817 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1818 Value *ResultVec = UndefValue::get(VT);
1819 for (unsigned i = 0; i < VT->getNumElements(); i++)
1820 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1821 Builder.getInt32(i));
1822 return ResultVec;
1823 };
1824
1825 if (isa<CallInst>(StatepointInst)) {
1826 BasicBlock::iterator Next(StatepointInst);
1827 Next++;
1828 Instruction *IP = &*(Next);
1829 Replacements[V].first = InsertVectorReform(IP);
1830 Replacements[V].second = nullptr;
1831 } else {
1832 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1833 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001834 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001835 BasicBlock *NormalDest = Invoke->getNormalDest();
1836 assert(!isa<PHINode>(NormalDest->begin()));
1837 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1838 assert(!isa<PHINode>(UnwindDest->begin()));
1839 // Insert insert element sequences in both successors
1840 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1841 Replacements[V].first = InsertVectorReform(IP);
1842 IP = &*(UnwindDest->getFirstInsertionPt());
1843 Replacements[V].second = InsertVectorReform(IP);
1844 }
1845 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001846
Philip Reames8531d8c2015-04-10 21:48:25 +00001847 for (Value *V : ToSplit) {
1848 AllocaInst *Alloca = AllocaMap[V];
1849
1850 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001851 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001852 for (User *U : V->users())
1853 Users.push_back(cast<Instruction>(U));
1854
1855 for (Instruction *I : Users) {
1856 if (auto Phi = dyn_cast<PHINode>(I)) {
1857 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1858 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001859 LoadInst *Load = new LoadInst(
1860 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001861 Phi->setIncomingValue(i, Load);
1862 }
1863 } else {
1864 LoadInst *Load = new LoadInst(Alloca, "", I);
1865 I->replaceUsesOfWith(V, Load);
1866 }
1867 }
1868
1869 // Store the original value and the replacement value into the alloca
1870 StoreInst *Store = new StoreInst(V, Alloca);
1871 if (auto I = dyn_cast<Instruction>(V))
1872 Store->insertAfter(I);
1873 else
1874 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001875
Philip Reames8531d8c2015-04-10 21:48:25 +00001876 // Normal return for invoke, or call return
1877 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1878 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1879 // Unwind return for invoke only
1880 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1881 if (Replacement)
1882 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1883 }
1884
1885 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001886 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001887 for (Value *V : ToSplit)
1888 Allocas.push_back(AllocaMap[V]);
1889 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001890
1891 // Update our tracking of live pointers and base mappings to account for the
1892 // changes we just made.
1893 for (Value *V : ToSplit) {
1894 auto &Elements = ElementMapping[V];
1895
1896 LiveSet.erase(V);
1897 LiveSet.insert(Elements.begin(), Elements.end());
1898 // We need to update the base mapping as well.
1899 assert(PointerToBase.count(V));
1900 Value *OldBase = PointerToBase[V];
1901 auto &BaseElements = ElementMapping[OldBase];
1902 PointerToBase.erase(V);
1903 assert(Elements.size() == BaseElements.size());
1904 for (unsigned i = 0; i < Elements.size(); i++) {
1905 Value *Elem = Elements[i];
1906 PointerToBase[Elem] = BaseElements[i];
1907 }
1908 }
Philip Reames8531d8c2015-04-10 21:48:25 +00001909}
1910
Igor Laevskye0317182015-05-19 15:59:05 +00001911// Helper function for the "rematerializeLiveValues". It walks use chain
1912// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1913// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001914// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00001915// Fills "ChainToBase" array with all visited values. "BaseValue" is not
1916// recorded.
1917static bool findRematerializableChainToBasePointer(
1918 SmallVectorImpl<Instruction*> &ChainToBase,
1919 Value *CurrentValue, Value *BaseValue) {
1920
1921 // We have found a base value
1922 if (CurrentValue == BaseValue) {
1923 return true;
1924 }
1925
1926 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1927 ChainToBase.push_back(GEP);
1928 return findRematerializableChainToBasePointer(ChainToBase,
1929 GEP->getPointerOperand(),
1930 BaseValue);
1931 }
1932
1933 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1934 Value *Def = CI->stripPointerCasts();
1935
1936 // This two checks are basically similar. First one is here for the
1937 // consistency with findBasePointers logic.
1938 assert(!isa<CastInst>(Def) && "not a pointer cast found");
1939 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1940 return false;
1941
1942 ChainToBase.push_back(CI);
1943 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1944 }
1945
1946 // Not supported instruction in the chain
1947 return false;
1948}
1949
1950// Helper function for the "rematerializeLiveValues". Compute cost of the use
1951// chain we are going to rematerialize.
1952static unsigned
1953chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1954 TargetTransformInfo &TTI) {
1955 unsigned Cost = 0;
1956
1957 for (Instruction *Instr : Chain) {
1958 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1959 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1960 "non noop cast is found during rematerialization");
1961
1962 Type *SrcTy = CI->getOperand(0)->getType();
1963 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1964
1965 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1966 // Cost of the address calculation
1967 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
1968 Cost += TTI.getAddressComputationCost(ValTy);
1969
1970 // And cost of the GEP itself
1971 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1972 // allowed for the external usage)
1973 if (!GEP->hasAllConstantIndices())
1974 Cost += 2;
1975
1976 } else {
1977 llvm_unreachable("unsupported instruciton type during rematerialization");
1978 }
1979 }
1980
1981 return Cost;
1982}
1983
1984// From the statepoint liveset pick values that are cheaper to recompute then to
1985// relocate. Remove this values from the liveset, rematerialize them after
1986// statepoint and record them in "Info" structure. Note that similar to
1987// relocated values we don't do any user adjustments here.
1988static void rematerializeLiveValues(CallSite CS,
1989 PartiallyConstructedSafepointRecord &Info,
1990 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00001991 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00001992
Igor Laevskye0317182015-05-19 15:59:05 +00001993 // Record values we are going to delete from this statepoint live set.
1994 // We can not di this in following loop due to iterator invalidation.
1995 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1996
1997 for (Value *LiveValue: Info.liveset) {
1998 // For each live pointer find it's defining chain
1999 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002000 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002001 bool FoundChain =
2002 findRematerializableChainToBasePointer(ChainToBase,
2003 LiveValue,
2004 Info.PointerToBase[LiveValue]);
2005 // Nothing to do, or chain is too long
2006 if (!FoundChain ||
2007 ChainToBase.size() == 0 ||
2008 ChainToBase.size() > ChainLengthThreshold)
2009 continue;
2010
2011 // Compute cost of this chain
2012 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2013 // TODO: We can also account for cases when we will be able to remove some
2014 // of the rematerialized values by later optimization passes. I.e if
2015 // we rematerialized several intersecting chains. Or if original values
2016 // don't have any uses besides this statepoint.
2017
2018 // For invokes we need to rematerialize each chain twice - for normal and
2019 // for unwind basic blocks. Model this by multiplying cost by two.
2020 if (CS.isInvoke()) {
2021 Cost *= 2;
2022 }
2023 // If it's too expensive - skip it
2024 if (Cost >= RematerializationThreshold)
2025 continue;
2026
2027 // Remove value from the live set
2028 LiveValuesToBeDeleted.push_back(LiveValue);
2029
2030 // Clone instructions and record them inside "Info" structure
2031
2032 // Walk backwards to visit top-most instructions first
2033 std::reverse(ChainToBase.begin(), ChainToBase.end());
2034
2035 // Utility function which clones all instructions from "ChainToBase"
2036 // and inserts them before "InsertBefore". Returns rematerialized value
2037 // which should be used after statepoint.
2038 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2039 Instruction *LastClonedValue = nullptr;
2040 Instruction *LastValue = nullptr;
2041 for (Instruction *Instr: ChainToBase) {
2042 // Only GEP's and casts are suported as we need to be careful to not
2043 // introduce any new uses of pointers not in the liveset.
2044 // Note that it's fine to introduce new uses of pointers which were
2045 // otherwise not used after this statepoint.
2046 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2047
2048 Instruction *ClonedValue = Instr->clone();
2049 ClonedValue->insertBefore(InsertBefore);
2050 ClonedValue->setName(Instr->getName() + ".remat");
2051
2052 // If it is not first instruction in the chain then it uses previously
2053 // cloned value. We should update it to use cloned value.
2054 if (LastClonedValue) {
2055 assert(LastValue);
2056 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2057#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002058 // Assert that cloned instruction does not use any instructions from
2059 // this chain other than LastClonedValue
2060 for (auto OpValue : ClonedValue->operand_values()) {
2061 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2062 ChainToBase.end() &&
2063 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002064 }
2065#endif
2066 }
2067
2068 LastClonedValue = ClonedValue;
2069 LastValue = Instr;
2070 }
2071 assert(LastClonedValue);
2072 return LastClonedValue;
2073 };
2074
2075 // Different cases for calls and invokes. For invokes we need to clone
2076 // instructions both on normal and unwind path.
2077 if (CS.isCall()) {
2078 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2079 assert(InsertBefore);
2080 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2081 Info.RematerializedValues[RematerializedValue] = LiveValue;
2082 } else {
2083 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2084
2085 Instruction *NormalInsertBefore =
2086 Invoke->getNormalDest()->getFirstInsertionPt();
2087 Instruction *UnwindInsertBefore =
2088 Invoke->getUnwindDest()->getFirstInsertionPt();
2089
2090 Instruction *NormalRematerializedValue =
2091 rematerializeChain(NormalInsertBefore);
2092 Instruction *UnwindRematerializedValue =
2093 rematerializeChain(UnwindInsertBefore);
2094
2095 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2096 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2097 }
2098 }
2099
2100 // Remove rematerializaed values from the live set
2101 for (auto LiveValue: LiveValuesToBeDeleted) {
2102 Info.liveset.erase(LiveValue);
2103 }
2104}
2105
Philip Reamesd16a9b12015-02-20 01:06:44 +00002106static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00002107 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002108#ifndef NDEBUG
2109 // sanity check the input
2110 std::set<CallSite> uniqued;
2111 uniqued.insert(toUpdate.begin(), toUpdate.end());
2112 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2113
2114 for (size_t i = 0; i < toUpdate.size(); i++) {
2115 CallSite &CS = toUpdate[i];
2116 assert(CS.getInstruction()->getParent()->getParent() == &F);
2117 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2118 }
2119#endif
2120
Philip Reames69e51ca2015-04-13 18:07:21 +00002121 // When inserting gc.relocates for invokes, we need to be able to insert at
2122 // the top of the successor blocks. See the comment on
2123 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002124 // may restructure the CFG.
2125 for (CallSite CS : toUpdate) {
2126 if (!CS.isInvoke())
2127 continue;
2128 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2129 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002130 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002131 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002132 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002133 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002134
Philip Reamesd16a9b12015-02-20 01:06:44 +00002135 // A list of dummy calls added to the IR to keep various values obviously
2136 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002137 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002138
2139 // Insert a dummy call with all of the arguments to the vm_state we'll need
2140 // for the actual safepoint insertion. This ensures reference arguments in
2141 // the deopt argument list are considered live through the safepoint (and
2142 // thus makes sure they get relocated.)
2143 for (size_t i = 0; i < toUpdate.size(); i++) {
2144 CallSite &CS = toUpdate[i];
2145 Statepoint StatepointCS(CS);
2146
2147 SmallVector<Value *, 64> DeoptValues;
2148 for (Use &U : StatepointCS.vm_state_args()) {
2149 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002150 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2151 "support for FCA unimplemented");
2152 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002153 DeoptValues.push_back(Arg);
2154 }
2155 insertUseHolderAfter(CS, DeoptValues, holders);
2156 }
2157
Philip Reamesd2b66462015-02-20 22:39:41 +00002158 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002159 records.reserve(toUpdate.size());
2160 for (size_t i = 0; i < toUpdate.size(); i++) {
2161 struct PartiallyConstructedSafepointRecord info;
2162 records.push_back(info);
2163 }
2164 assert(records.size() == toUpdate.size());
2165
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002166 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002167 // site.
2168 findLiveReferences(F, DT, P, toUpdate, records);
2169
2170 // B) Find the base pointers for each live pointer
2171 /* scope for caching */ {
2172 // Cache the 'defining value' relation used in the computation and
2173 // insertion of base phis and selects. This ensures that we don't insert
2174 // large numbers of duplicate base_phis.
2175 DefiningValueMapTy DVCache;
2176
2177 for (size_t i = 0; i < records.size(); i++) {
2178 struct PartiallyConstructedSafepointRecord &info = records[i];
2179 CallSite &CS = toUpdate[i];
2180 findBasePointers(DT, DVCache, CS, info);
2181 }
2182 } // end of cache scope
2183
2184 // The base phi insertion logic (for any safepoint) may have inserted new
2185 // instructions which are now live at some safepoint. The simplest such
2186 // example is:
2187 // loop:
2188 // phi a <-- will be a new base_phi here
2189 // safepoint 1 <-- that needs to be live here
2190 // gep a + 1
2191 // safepoint 2
2192 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002193 // We insert some dummy calls after each safepoint to definitely hold live
2194 // the base pointers which were identified for that safepoint. We'll then
2195 // ask liveness for _every_ base inserted to see what is now live. Then we
2196 // remove the dummy calls.
2197 holders.reserve(holders.size() + records.size());
2198 for (size_t i = 0; i < records.size(); i++) {
2199 struct PartiallyConstructedSafepointRecord &info = records[i];
2200 CallSite &CS = toUpdate[i];
2201
2202 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002203 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002204 Bases.push_back(Pair.second);
2205 }
2206 insertUseHolderAfter(CS, Bases, holders);
2207 }
2208
Philip Reamesdf1ef082015-04-10 22:53:14 +00002209 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2210 // need to rerun liveness. We may *also* have inserted new defs, but that's
2211 // not the key issue.
2212 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002213
Philip Reamesd16a9b12015-02-20 01:06:44 +00002214 if (PrintBasePointers) {
2215 for (size_t i = 0; i < records.size(); i++) {
2216 struct PartiallyConstructedSafepointRecord &info = records[i];
2217 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002218 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002219 errs() << " derived %" << Pair.first->getName() << " base %"
2220 << Pair.second->getName() << "\n";
2221 }
2222 }
2223 }
2224 for (size_t i = 0; i < holders.size(); i++) {
2225 holders[i]->eraseFromParent();
2226 holders[i] = nullptr;
2227 }
2228 holders.clear();
2229
Philip Reames8fe7f132015-06-26 22:47:37 +00002230 // Do a limited scalarization of any live at safepoint vector values which
2231 // contain pointers. This enables this pass to run after vectorization at
2232 // the cost of some possible performance loss. TODO: it would be nice to
2233 // natively support vectors all the way through the backend so we don't need
2234 // to scalarize here.
2235 for (size_t i = 0; i < records.size(); i++) {
2236 struct PartiallyConstructedSafepointRecord &info = records[i];
2237 Instruction *statepoint = toUpdate[i].getInstruction();
2238 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2239 info.PointerToBase, DT);
2240 }
2241
Igor Laevskye0317182015-05-19 15:59:05 +00002242 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002243 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002244 // does not influence correctness.
2245 TargetTransformInfo &TTI =
2246 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2247
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002248 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002249 struct PartiallyConstructedSafepointRecord &info = records[i];
2250 CallSite &CS = toUpdate[i];
2251
2252 rematerializeLiveValues(CS, info, TTI);
2253 }
2254
Philip Reamesd16a9b12015-02-20 01:06:44 +00002255 // Now run through and replace the existing statepoints with new ones with
2256 // the live variables listed. We do not yet update uses of the values being
2257 // relocated. We have references to live variables that need to
2258 // survive to the last iteration of this loop. (By construction, the
2259 // previous statepoint can not be a live variable, thus we can and remove
2260 // the old statepoint calls as we go.)
2261 for (size_t i = 0; i < records.size(); i++) {
2262 struct PartiallyConstructedSafepointRecord &info = records[i];
2263 CallSite &CS = toUpdate[i];
2264 makeStatepointExplicit(DT, CS, P, info);
2265 }
2266 toUpdate.clear(); // prevent accident use of invalid CallSites
2267
Philip Reamesd16a9b12015-02-20 01:06:44 +00002268 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002269 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002270 for (size_t i = 0; i < records.size(); i++) {
2271 struct PartiallyConstructedSafepointRecord &info = records[i];
2272 // We can't simply save the live set from the original insertion. One of
2273 // the live values might be the result of a call which needs a safepoint.
2274 // That Value* no longer exists and we need to use the new gc_result.
2275 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2276 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002277 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002278 live.insert(live.end(), statepoint.gc_args_begin(),
2279 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002280#ifndef NDEBUG
2281 // Do some basic sanity checks on our liveness results before performing
2282 // relocation. Relocation can and will turn mistakes in liveness results
2283 // into non-sensical code which is must harder to debug.
2284 // TODO: It would be nice to test consistency as well
2285 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2286 "statepoint must be reachable or liveness is meaningless");
2287 for (Value *V : statepoint.gc_args()) {
2288 if (!isa<Instruction>(V))
2289 // Non-instruction values trivial dominate all possible uses
2290 continue;
2291 auto LiveInst = cast<Instruction>(V);
2292 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2293 "unreachable values should never be live");
2294 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2295 "basic SSA liveness expectation violated by liveness analysis");
2296 }
2297#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002298 }
2299 unique_unsorted(live);
2300
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002301#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002302 // sanity check
2303 for (auto ptr : live) {
2304 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2305 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002306#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002307
2308 relocationViaAlloca(F, DT, live, records);
2309 return !records.empty();
2310}
2311
Sanjoy Das353a19e2015-06-02 22:33:37 +00002312// Handles both return values and arguments for Functions and CallSites.
2313template <typename AttrHolder>
2314static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2315 unsigned Index) {
2316 AttrBuilder R;
2317 if (AH.getDereferenceableBytes(Index))
2318 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2319 AH.getDereferenceableBytes(Index)));
2320 if (AH.getDereferenceableOrNullBytes(Index))
2321 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2322 AH.getDereferenceableOrNullBytes(Index)));
2323
2324 if (!R.empty())
2325 AH.setAttributes(AH.getAttributes().removeAttributes(
2326 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002327}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002328
2329void
2330RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2331 LLVMContext &Ctx = F.getContext();
2332
2333 for (Argument &A : F.args())
2334 if (isa<PointerType>(A.getType()))
2335 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2336
2337 if (isa<PointerType>(F.getReturnType()))
2338 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2339}
2340
2341void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2342 if (F.empty())
2343 return;
2344
2345 LLVMContext &Ctx = F.getContext();
2346 MDBuilder Builder(Ctx);
2347
Nico Rieck78199512015-08-06 19:10:45 +00002348 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002349 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2350 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2351 bool IsImmutableTBAA =
2352 MD->getNumOperands() == 4 &&
2353 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2354
2355 if (!IsImmutableTBAA)
2356 continue; // no work to do, MD_tbaa is already marked mutable
2357
2358 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2359 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2360 uint64_t Offset =
2361 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2362
2363 MDNode *MutableTBAA =
2364 Builder.createTBAAStructTagNode(Base, Access, Offset);
2365 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2366 }
2367
2368 if (CallSite CS = CallSite(&I)) {
2369 for (int i = 0, e = CS.arg_size(); i != e; i++)
2370 if (isa<PointerType>(CS.getArgument(i)->getType()))
2371 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2372 if (isa<PointerType>(CS.getType()))
2373 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2374 }
2375 }
2376}
2377
Philip Reamesd16a9b12015-02-20 01:06:44 +00002378/// Returns true if this function should be rewritten by this pass. The main
2379/// point of this function is as an extension point for custom logic.
2380static bool shouldRewriteStatepointsIn(Function &F) {
2381 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002382 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002383 const char *FunctionGCName = F.getGC();
2384 const StringRef StatepointExampleName("statepoint-example");
2385 const StringRef CoreCLRName("coreclr");
2386 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002387 (CoreCLRName == FunctionGCName);
2388 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002389 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002390}
2391
Sanjoy Das353a19e2015-06-02 22:33:37 +00002392void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2393#ifndef NDEBUG
2394 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2395 "precondition!");
2396#endif
2397
2398 for (Function &F : M)
2399 stripDereferenceabilityInfoFromPrototype(F);
2400
2401 for (Function &F : M)
2402 stripDereferenceabilityInfoFromBody(F);
2403}
2404
Philip Reamesd16a9b12015-02-20 01:06:44 +00002405bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2406 // Nothing to do for declarations.
2407 if (F.isDeclaration() || F.empty())
2408 return false;
2409
2410 // Policy choice says not to rewrite - the most common reason is that we're
2411 // compiling code without a GCStrategy.
2412 if (!shouldRewriteStatepointsIn(F))
2413 return false;
2414
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002415 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002416
Philip Reames85b36a82015-04-10 22:07:04 +00002417 // Gather all the statepoints which need rewritten. Be careful to only
2418 // consider those in reachable code since we need to ask dominance queries
2419 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002420 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002421 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002422 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002423 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002424 if (isStatepoint(I)) {
2425 if (DT.isReachableFromEntry(I.getParent()))
2426 ParsePointNeeded.push_back(CallSite(&I));
2427 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002428 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002429 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002430 }
2431
Philip Reames85b36a82015-04-10 22:07:04 +00002432 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002433
Philip Reames85b36a82015-04-10 22:07:04 +00002434 // Delete any unreachable statepoints so that we don't have unrewritten
2435 // statepoints surviving this pass. This makes testing easier and the
2436 // resulting IR less confusing to human readers. Rather than be fancy, we
2437 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002438 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002439 MadeChange |= removeUnreachableBlocks(F);
2440
Philip Reamesd16a9b12015-02-20 01:06:44 +00002441 // Return early if no work to do.
2442 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002443 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002444
Philip Reames85b36a82015-04-10 22:07:04 +00002445 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2446 // These are created by LCSSA. They have the effect of increasing the size
2447 // of liveness sets for no good reason. It may be harder to do this post
2448 // insertion since relocations and base phis can confuse things.
2449 for (BasicBlock &BB : F)
2450 if (BB.getUniquePredecessor()) {
2451 MadeChange = true;
2452 FoldSingleEntryPHINodes(&BB);
2453 }
2454
Philip Reames971dc3a2015-08-12 22:11:45 +00002455 // Before we start introducing relocations, we want to tweak the IR a bit to
2456 // avoid unfortunate code generation effects. The main example is that we
2457 // want to try to make sure the comparison feeding a branch is after any
2458 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2459 // values feeding a branch after relocation. This is semantically correct,
2460 // but results in extra register pressure since both the pre-relocation and
2461 // post-relocation copies must be available in registers. For code without
2462 // relocations this is handled elsewhere, but teaching the scheduler to
2463 // reverse the transform we're about to do would be slightly complex.
2464 // Note: This may extend the live range of the inputs to the icmp and thus
2465 // increase the liveset of any statepoint we move over. This is profitable
2466 // as long as all statepoints are in rare blocks. If we had in-register
2467 // lowering for live values this would be a much safer transform.
2468 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2469 if (auto *BI = dyn_cast<BranchInst>(TI))
2470 if (BI->isConditional())
2471 return dyn_cast<Instruction>(BI->getCondition());
2472 // TODO: Extend this to handle switches
2473 return nullptr;
2474 };
2475 for (BasicBlock &BB : F) {
2476 TerminatorInst *TI = BB.getTerminator();
2477 if (auto *Cond = getConditionInst(TI))
2478 // TODO: Handle more than just ICmps here. We should be able to move
2479 // most instructions without side effects or memory access.
2480 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2481 MadeChange = true;
2482 Cond->moveBefore(TI);
2483 }
2484 }
2485
Philip Reames85b36a82015-04-10 22:07:04 +00002486 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2487 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002488}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002489
2490// liveness computation via standard dataflow
2491// -------------------------------------------------------------------
2492
2493// TODO: Consider using bitvectors for liveness, the set of potentially
2494// interesting values should be small and easy to pre-compute.
2495
Philip Reamesdf1ef082015-04-10 22:53:14 +00002496/// Compute the live-in set for the location rbegin starting from
2497/// the live-out set of the basic block
2498static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2499 BasicBlock::reverse_iterator rend,
2500 DenseSet<Value *> &LiveTmp) {
2501
2502 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2503 Instruction *I = &*ritr;
2504
2505 // KILL/Def - Remove this definition from LiveIn
2506 LiveTmp.erase(I);
2507
2508 // Don't consider *uses* in PHI nodes, we handle their contribution to
2509 // predecessor blocks when we seed the LiveOut sets
2510 if (isa<PHINode>(I))
2511 continue;
2512
2513 // USE - Add to the LiveIn set for this instruction
2514 for (Value *V : I->operands()) {
2515 assert(!isUnhandledGCPointerType(V->getType()) &&
2516 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002517 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2518 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002519 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002520 // - We assume that things which are constant (from LLVM's definition)
2521 // do not move at runtime. For example, the address of a global
2522 // variable is fixed, even though it's contents may not be.
2523 // - Second, we can't disallow arbitrary inttoptr constants even
2524 // if the language frontend does. Optimization passes are free to
2525 // locally exploit facts without respect to global reachability. This
2526 // can create sections of code which are dynamically unreachable and
2527 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002528 LiveTmp.insert(V);
2529 }
2530 }
2531 }
2532}
2533
2534static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2535
2536 for (BasicBlock *Succ : successors(BB)) {
2537 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2538 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2539 PHINode *Phi = cast<PHINode>(&*I);
2540 Value *V = Phi->getIncomingValueForBlock(BB);
2541 assert(!isUnhandledGCPointerType(V->getType()) &&
2542 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002543 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002544 LiveTmp.insert(V);
2545 }
2546 }
2547 }
2548}
2549
2550static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2551 DenseSet<Value *> KillSet;
2552 for (Instruction &I : *BB)
2553 if (isHandledGCPointerType(I.getType()))
2554 KillSet.insert(&I);
2555 return KillSet;
2556}
2557
Philip Reames9638ff92015-04-11 00:06:47 +00002558#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002559/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2560/// sanity check for the liveness computation.
2561static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2562 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002563 for (Value *V : Live) {
2564 if (auto *I = dyn_cast<Instruction>(V)) {
2565 // The terminator can be a member of the LiveOut set. LLVM's definition
2566 // of instruction dominance states that V does not dominate itself. As
2567 // such, we need to special case this to allow it.
2568 if (TermOkay && TI == I)
2569 continue;
2570 assert(DT.dominates(I, TI) &&
2571 "basic SSA liveness expectation violated by liveness analysis");
2572 }
2573 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002574}
2575
2576/// Check that all the liveness sets used during the computation of liveness
2577/// obey basic SSA properties. This is useful for finding cases where we miss
2578/// a def.
2579static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2580 BasicBlock &BB) {
2581 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2582 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2583 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2584}
Philip Reames9638ff92015-04-11 00:06:47 +00002585#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002586
2587static void computeLiveInValues(DominatorTree &DT, Function &F,
2588 GCPtrLivenessData &Data) {
2589
Philip Reames4d80ede2015-04-10 23:11:26 +00002590 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002591 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002592 // We use a SetVector so that we don't have duplicates in the worklist.
2593 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002594 };
2595 auto NextItem = [&]() {
2596 BasicBlock *BB = Worklist.back();
2597 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002598 return BB;
2599 };
2600
2601 // Seed the liveness for each individual block
2602 for (BasicBlock &BB : F) {
2603 Data.KillSet[&BB] = computeKillSet(&BB);
2604 Data.LiveSet[&BB].clear();
2605 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2606
2607#ifndef NDEBUG
2608 for (Value *Kill : Data.KillSet[&BB])
2609 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2610#endif
2611
2612 Data.LiveOut[&BB] = DenseSet<Value *>();
2613 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2614 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2615 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2616 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2617 if (!Data.LiveIn[&BB].empty())
2618 AddPredsToWorklist(&BB);
2619 }
2620
2621 // Propagate that liveness until stable
2622 while (!Worklist.empty()) {
2623 BasicBlock *BB = NextItem();
2624
2625 // Compute our new liveout set, then exit early if it hasn't changed
2626 // despite the contribution of our successor.
2627 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2628 const auto OldLiveOutSize = LiveOut.size();
2629 for (BasicBlock *Succ : successors(BB)) {
2630 assert(Data.LiveIn.count(Succ));
2631 set_union(LiveOut, Data.LiveIn[Succ]);
2632 }
2633 // assert OutLiveOut is a subset of LiveOut
2634 if (OldLiveOutSize == LiveOut.size()) {
2635 // If the sets are the same size, then we didn't actually add anything
2636 // when unioning our successors LiveIn Thus, the LiveIn of this block
2637 // hasn't changed.
2638 continue;
2639 }
2640 Data.LiveOut[BB] = LiveOut;
2641
2642 // Apply the effects of this basic block
2643 DenseSet<Value *> LiveTmp = LiveOut;
2644 set_union(LiveTmp, Data.LiveSet[BB]);
2645 set_subtract(LiveTmp, Data.KillSet[BB]);
2646
2647 assert(Data.LiveIn.count(BB));
2648 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2649 // assert: OldLiveIn is a subset of LiveTmp
2650 if (OldLiveIn.size() != LiveTmp.size()) {
2651 Data.LiveIn[BB] = LiveTmp;
2652 AddPredsToWorklist(BB);
2653 }
2654 } // while( !worklist.empty() )
2655
2656#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002657 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002658 // missing kills during the above iteration.
2659 for (BasicBlock &BB : F) {
2660 checkBasicSSA(DT, Data, BB);
2661 }
2662#endif
2663}
2664
2665static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2666 StatepointLiveSetTy &Out) {
2667
2668 BasicBlock *BB = Inst->getParent();
2669
2670 // Note: The copy is intentional and required
2671 assert(Data.LiveOut.count(BB));
2672 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2673
2674 // We want to handle the statepoint itself oddly. It's
2675 // call result is not live (normal), nor are it's arguments
2676 // (unless they're used again later). This adjustment is
2677 // specifically what we need to relocate
2678 BasicBlock::reverse_iterator rend(Inst);
2679 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2680 LiveOut.erase(Inst);
2681 Out.insert(LiveOut.begin(), LiveOut.end());
2682}
2683
2684static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2685 const CallSite &CS,
2686 PartiallyConstructedSafepointRecord &Info) {
2687 Instruction *Inst = CS.getInstruction();
2688 StatepointLiveSetTy Updated;
2689 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2690
2691#ifndef NDEBUG
2692 DenseSet<Value *> Bases;
2693 for (auto KVPair : Info.PointerToBase) {
2694 Bases.insert(KVPair.second);
2695 }
2696#endif
2697 // We may have base pointers which are now live that weren't before. We need
2698 // to update the PointerToBase structure to reflect this.
2699 for (auto V : Updated)
2700 if (!Info.PointerToBase.count(V)) {
2701 assert(Bases.count(V) && "can't find base for unexpected live value");
2702 Info.PointerToBase[V] = V;
2703 continue;
2704 }
2705
2706#ifndef NDEBUG
2707 for (auto V : Updated) {
2708 assert(Info.PointerToBase.count(V) &&
2709 "must be able to find base for live value");
2710 }
2711#endif
2712
2713 // Remove any stale base mappings - this can happen since our liveness is
2714 // more precise then the one inherent in the base pointer analysis
2715 DenseSet<Value *> ToErase;
2716 for (auto KVPair : Info.PointerToBase)
2717 if (!Updated.count(KVPair.first))
2718 ToErase.insert(KVPair.first);
2719 for (auto V : ToErase)
2720 Info.PointerToBase.erase(V);
2721
2722#ifndef NDEBUG
2723 for (auto KVPair : Info.PointerToBase)
2724 assert(Updated.count(KVPair.first) && "record for non-live value");
2725#endif
2726
2727 Info.liveset = Updated;
2728}