blob: 929a4eb3968be1da4f06021af9beafdd07786d7e [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"
Philip Reamesabcdc5e2015-08-27 01:02:28 +000017#include "llvm/Analysis/InstructionSimplify.h"
Igor Laevskye0317182015-05-19 15:59:05 +000018#include "llvm/Analysis/TargetTransformInfo.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000019#include "llvm/ADT/SetOperations.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/DenseSet.h"
Philip Reames4d80ede2015-04-10 23:11:26 +000022#include "llvm/ADT/SetVector.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000023#include "llvm/ADT/StringRef.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000024#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallSite.h"
26#include "llvm/IR/Dominators.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/InstIterator.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/Module.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000034#include "llvm/IR/MDBuilder.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000035#include "llvm/IR/Statepoint.h"
36#include "llvm/IR/Value.h"
37#include "llvm/IR/Verifier.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Transforms/Scalar.h"
41#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42#include "llvm/Transforms/Utils/Cloning.h"
43#include "llvm/Transforms/Utils/Local.h"
44#include "llvm/Transforms/Utils/PromoteMemToReg.h"
45
46#define DEBUG_TYPE "rewrite-statepoints-for-gc"
47
48using namespace llvm;
49
Philip Reamesd16a9b12015-02-20 01:06:44 +000050// Print the liveset found at the insert location
51static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
52 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000053static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
54 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000055// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000056static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
57 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000058
Igor Laevskye0317182015-05-19 15:59:05 +000059// Cost threshold measuring when it is profitable to rematerialize value instead
60// of relocating it
61static cl::opt<unsigned>
62RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
63 cl::init(6));
64
Philip Reamese73300b2015-04-13 16:41:32 +000065#ifdef XDEBUG
66static bool ClobberNonLive = true;
67#else
68static bool ClobberNonLive = false;
69#endif
70static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
71 cl::location(ClobberNonLive),
72 cl::Hidden);
73
Benjamin Kramer6f665452015-02-20 14:00:58 +000074namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000075struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000076 static char ID; // Pass identification, replacement for typeid
77
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000078 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000079 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
80 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000081 bool runOnFunction(Function &F);
82 bool runOnModule(Module &M) override {
83 bool Changed = false;
84 for (Function &F : M)
85 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000086
87 if (Changed) {
88 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
89 // returns true for at least one function in the module. Since at least
90 // one function changed, we know that the precondition is satisfied.
91 stripDereferenceabilityInfo(M);
92 }
93
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000094 return Changed;
95 }
Philip Reamesd16a9b12015-02-20 01:06:44 +000096
97 void getAnalysisUsage(AnalysisUsage &AU) const override {
98 // We add and rewrite a bunch of instructions, but don't really do much
99 // else. We could in theory preserve a lot more analyses here.
100 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000101 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000102 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000103
104 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
105 /// dereferenceability that are no longer valid/correct after
106 /// RewriteStatepointsForGC has run. This is because semantically, after
107 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
108 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
109 /// by erasing all attributes in the module that externally imply
110 /// dereferenceability.
111 ///
112 void stripDereferenceabilityInfo(Module &M);
113
114 // Helpers for stripDereferenceabilityInfo
115 void stripDereferenceabilityInfoFromBody(Function &F);
116 void stripDereferenceabilityInfoFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000117};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000118} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000119
120char RewriteStatepointsForGC::ID = 0;
121
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000122ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000123 return new RewriteStatepointsForGC();
124}
125
126INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
127 "Make relocations explicit at statepoints", false, false)
128INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
129INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
130 "Make relocations explicit at statepoints", false, false)
131
132namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000133struct GCPtrLivenessData {
134 /// Values defined in this block.
135 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
136 /// Values used in this block (and thus live); does not included values
137 /// killed within this block.
138 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
139
140 /// Values live into this basic block (i.e. used by any
141 /// instruction in this basic block or ones reachable from here)
142 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
143
144 /// Values live out of this basic block (i.e. live into
145 /// any successor block)
146 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
147};
148
Philip Reamesd16a9b12015-02-20 01:06:44 +0000149// The type of the internal cache used inside the findBasePointers family
150// of functions. From the callers perspective, this is an opaque type and
151// should not be inspected.
152//
153// In the actual implementation this caches two relations:
154// - The base relation itself (i.e. this pointer is based on that one)
155// - The base defining value relation (i.e. before base_phi insertion)
156// Generally, after the execution of a full findBasePointer call, only the
157// base relation will remain. Internally, we add a mixture of the two
158// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000159typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Philip Reames1f017542015-02-20 23:16:52 +0000160typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
Igor Laevskye0317182015-05-19 15:59:05 +0000161typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000162
Philip Reamesd16a9b12015-02-20 01:06:44 +0000163struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000164 /// The set of values known to be live across this safepoint
Philip Reames860660e2015-02-20 22:05:18 +0000165 StatepointLiveSetTy liveset;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000166
167 /// Mapping from live pointers to a base-defining-value
Philip Reamesf2041322015-02-20 19:26:04 +0000168 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000169
Philip Reames0a3240f2015-02-20 21:34:11 +0000170 /// The *new* gc.statepoint instruction itself. This produces the token
171 /// that normal path gc.relocates and the gc.result are tied to.
172 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000173
Philip Reamesf2041322015-02-20 19:26:04 +0000174 /// Instruction to which exceptional gc relocates are attached
175 /// Makes it easier to iterate through them during relocationViaAlloca.
176 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000177
178 /// Record live values we are rematerialized instead of relocating.
179 /// They are not included into 'liveset' field.
180 /// Maps rematerialized copy to it's original value.
181 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000182};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000183}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000184
Philip Reamesdf1ef082015-04-10 22:53:14 +0000185/// Compute the live-in set for every basic block in the function
186static void computeLiveInValues(DominatorTree &DT, Function &F,
187 GCPtrLivenessData &Data);
188
189/// Given results from the dataflow liveness computation, find the set of live
190/// Values at a particular instruction.
191static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
192 StatepointLiveSetTy &out);
193
Philip Reamesd16a9b12015-02-20 01:06:44 +0000194// TODO: Once we can get to the GCStrategy, this becomes
195// Optional<bool> isGCManagedPointer(const Value *V) const override {
196
Craig Toppere3dcce92015-08-01 22:20:21 +0000197static bool isGCPointerType(Type *T) {
198 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000199 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
200 // GC managed heap. We know that a pointer into this heap needs to be
201 // updated and that no other pointer does.
202 return (1 == PT->getAddressSpace());
203 return false;
204}
205
Philip Reames8531d8c2015-04-10 21:48:25 +0000206// Return true if this type is one which a) is a gc pointer or contains a GC
207// pointer and b) is of a type this code expects to encounter as a live value.
208// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000209// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000210static bool isHandledGCPointerType(Type *T) {
211 // We fully support gc pointers
212 if (isGCPointerType(T))
213 return true;
214 // We partially support vectors of gc pointers. The code will assert if it
215 // can't handle something.
216 if (auto VT = dyn_cast<VectorType>(T))
217 if (isGCPointerType(VT->getElementType()))
218 return true;
219 return false;
220}
221
222#ifndef NDEBUG
223/// Returns true if this type contains a gc pointer whether we know how to
224/// handle that type or not.
225static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000226 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000227 return true;
228 if (VectorType *VT = dyn_cast<VectorType>(Ty))
229 return isGCPointerType(VT->getScalarType());
230 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
231 return containsGCPtrType(AT->getElementType());
232 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000233 return std::any_of(
234 ST->subtypes().begin(), ST->subtypes().end(),
235 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000236 return false;
237}
238
239// Returns true if this is a type which a) is a gc pointer or contains a GC
240// pointer and b) is of a type which the code doesn't expect (i.e. first class
241// aggregates). Used to trip assertions.
242static bool isUnhandledGCPointerType(Type *Ty) {
243 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
244}
245#endif
246
Philip Reamesd16a9b12015-02-20 01:06:44 +0000247static bool order_by_name(llvm::Value *a, llvm::Value *b) {
248 if (a->hasName() && b->hasName()) {
249 return -1 == a->getName().compare(b->getName());
250 } else if (a->hasName() && !b->hasName()) {
251 return true;
252 } else if (!a->hasName() && b->hasName()) {
253 return false;
254 } else {
255 // Better than nothing, but not stable
256 return a < b;
257 }
258}
259
Philip Reamesdf1ef082015-04-10 22:53:14 +0000260// Conservatively identifies any definitions which might be live at the
261// given instruction. The analysis is performed immediately before the
262// given instruction. Values defined by that instruction are not considered
263// live. Values used by that instruction are considered live.
264static void analyzeParsePointLiveness(
265 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
266 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000267 Instruction *inst = CS.getInstruction();
268
Philip Reames1f017542015-02-20 23:16:52 +0000269 StatepointLiveSetTy liveset;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000270 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000271
272 if (PrintLiveSet) {
273 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000274 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000275 // by name
Philip Reamesdab35f32015-09-02 21:11:44 +0000276 SmallVector<Value *, 64> Temp;
277 Temp.insert(Temp.end(), liveset.begin(), liveset.end());
278 std::sort(Temp.begin(), Temp.end(), order_by_name);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000279 errs() << "Live Variables:\n";
Philip Reamesdab35f32015-09-02 21:11:44 +0000280 for (Value *V : Temp)
281 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000282 }
283 if (PrintLiveSetSize) {
284 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
285 errs() << "Number live values: " << liveset.size() << "\n";
286 }
287 result.liveset = liveset;
288}
289
Philip Reames311f7102015-05-12 22:19:52 +0000290static Value *findBaseDefiningValue(Value *I);
291
Philip Reames8fe7f132015-06-26 22:47:37 +0000292/// Return a base defining value for the 'Index' element of the given vector
293/// instruction 'I'. If Index is null, returns a BDV for the entire vector
294/// 'I'. As an optimization, this method will try to determine when the
295/// element is known to already be a base pointer. If this can be established,
296/// the second value in the returned pair will be true. Note that either a
297/// vector or a pointer typed value can be returned. For the former, the
298/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
299/// If the later, the return pointer is a BDV (or possibly a base) for the
300/// particular element in 'I'.
301static std::pair<Value *, bool>
302findBaseDefiningValueOfVector(Value *I, Value *Index = nullptr) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000303 assert(I->getType()->isVectorTy() &&
304 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
305 "Illegal to ask for the base pointer of a non-pointer type");
306
307 // Each case parallels findBaseDefiningValue below, see that code for
308 // detailed motivation.
309
310 if (isa<Argument>(I))
311 // An incoming argument to the function is a base pointer
Philip Reames8fe7f132015-06-26 22:47:37 +0000312 return std::make_pair(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000313
314 // We shouldn't see the address of a global as a vector value?
315 assert(!isa<GlobalVariable>(I) &&
316 "unexpected global variable found in base of vector");
317
318 // inlining could possibly introduce phi node that contains
319 // undef if callee has multiple returns
320 if (isa<UndefValue>(I))
321 // utterly meaningless, but useful for dealing with partially optimized
322 // code.
Philip Reames8fe7f132015-06-26 22:47:37 +0000323 return std::make_pair(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000324
325 // Due to inheritance, this must be _after_ the global variable and undef
326 // checks
327 if (Constant *Con = dyn_cast<Constant>(I)) {
328 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
329 "order of checks wrong!");
330 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reames8fe7f132015-06-26 22:47:37 +0000331 return std::make_pair(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000332 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000333
Philip Reames8531d8c2015-04-10 21:48:25 +0000334 if (isa<LoadInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000335 return std::make_pair(I, true);
336
Philip Reames311f7102015-05-12 22:19:52 +0000337 // For an insert element, we might be able to look through it if we know
Philip Reames8fe7f132015-06-26 22:47:37 +0000338 // something about the indexes.
Philip Reames311f7102015-05-12 22:19:52 +0000339 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000340 if (Index) {
341 Value *InsertIndex = IEI->getOperand(2);
342 // This index is inserting the value, look for its BDV
343 if (InsertIndex == Index)
344 return std::make_pair(findBaseDefiningValue(IEI->getOperand(1)), false);
345 // Both constant, and can't be equal per above. This insert is definitely
346 // not relevant, look back at the rest of the vector and keep trying.
347 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
348 return findBaseDefiningValueOfVector(IEI->getOperand(0), Index);
349 }
350
351 // We don't know whether this vector contains entirely base pointers or
352 // not. To be conservatively correct, we treat it as a BDV and will
353 // duplicate code as needed to construct a parallel vector of bases.
354 return std::make_pair(IEI, false);
Philip Reames311f7102015-05-12 22:19:52 +0000355 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000356
Philip Reames8fe7f132015-06-26 22:47:37 +0000357 if (isa<ShuffleVectorInst>(I))
358 // We don't know whether this vector contains entirely base pointers or
359 // not. To be conservatively correct, we treat it as a BDV and will
360 // duplicate code as needed to construct a parallel vector of bases.
361 // TODO: There a number of local optimizations which could be applied here
362 // for particular sufflevector patterns.
363 return std::make_pair(I, false);
364
365 // A PHI or Select is a base defining value. The outer findBasePointer
366 // algorithm is responsible for constructing a base value for this BDV.
367 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
368 "unknown vector instruction - no base found for vector element");
369 return std::make_pair(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000370}
371
Philip Reames8fe7f132015-06-26 22:47:37 +0000372static bool isKnownBaseResult(Value *V);
373
Philip Reamesd16a9b12015-02-20 01:06:44 +0000374/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000375/// defines the base pointer for the input, b) blocks the simple search
376/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
377/// from pointer to vector type or back.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000378static Value *findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000379 if (I->getType()->isVectorTy())
380 return findBaseDefiningValueOfVector(I).first;
381
Philip Reamesd16a9b12015-02-20 01:06:44 +0000382 assert(I->getType()->isPointerTy() &&
383 "Illegal to ask for the base pointer of a non-pointer type");
384
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000385 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000386 // An incoming argument to the function is a base pointer
387 // We should have never reached here if this argument isn't an gc value
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000388 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000389
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000390 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000391 // base case
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000392 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000393
394 // inlining could possibly introduce phi node that contains
395 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000396 if (isa<UndefValue>(I))
397 // utterly meaningless, but useful for dealing with
398 // partially optimized code.
Philip Reames704e78b2015-04-10 22:34:56 +0000399 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000400
401 // Due to inheritance, this must be _after_ the global variable and undef
402 // checks
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000403 if (Constant *Con = dyn_cast<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000404 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
405 "order of checks wrong!");
406 // Note: Finding a constant base for something marked for relocation
407 // doesn't really make sense. The most likely case is either a) some
408 // screwed up the address space usage or b) your validating against
409 // compiled C++ code w/o the proper separation. The only real exception
410 // is a null pointer. You could have generic code written to index of
411 // off a potentially null value and have proven it null. We also use
412 // null pointers in dead paths of relocation phis (which we might later
413 // want to find a base pointer for).
Philip Reames24c6cd52015-03-27 05:47:00 +0000414 assert(isa<ConstantPointerNull>(Con) &&
415 "null is the only case which makes sense");
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000416 return Con;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000417 }
418
419 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000420 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000421 // If we find a cast instruction here, it means we've found a cast which is
422 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
423 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000424 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
425 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000426 }
427
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000428 if (isa<LoadInst>(I))
429 return I; // The value loaded is an gc base itself
Philip Reamesd16a9b12015-02-20 01:06:44 +0000430
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000431 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
432 // The base of this GEP is the base
433 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000434
435 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
436 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000437 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000438 default:
439 // fall through to general call handling
440 break;
441 case Intrinsic::experimental_gc_statepoint:
442 case Intrinsic::experimental_gc_result_float:
443 case Intrinsic::experimental_gc_result_int:
444 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000445 case Intrinsic::experimental_gc_relocate: {
446 // Rerunning safepoint insertion after safepoints are already
447 // inserted is not supported. It could probably be made to work,
448 // but why are you doing this? There's no good reason.
449 llvm_unreachable("repeat safepoint insertion is not supported");
450 }
451 case Intrinsic::gcroot:
452 // Currently, this mechanism hasn't been extended to work with gcroot.
453 // There's no reason it couldn't be, but I haven't thought about the
454 // implications much.
455 llvm_unreachable(
456 "interaction with the gcroot mechanism is not supported");
457 }
458 }
459 // We assume that functions in the source language only return base
460 // pointers. This should probably be generalized via attributes to support
461 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000462 if (isa<CallInst>(I) || isa<InvokeInst>(I))
463 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000464
465 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000466 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000467 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
468
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000469 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000470 // A CAS is effectively a atomic store and load combined under a
471 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000472 // like a load.
473 return I;
Philip Reames704e78b2015-04-10 22:34:56 +0000474
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000475 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000476 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000477
478 // The aggregate ops. Aggregates can either be in the heap or on the
479 // stack, but in either case, this is simply a field load. As a result,
480 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000481 if (isa<ExtractValueInst>(I))
482 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000483
484 // We should never see an insert vector since that would require we be
485 // tracing back a struct value not a pointer value.
486 assert(!isa<InsertValueInst>(I) &&
487 "Base pointer for a struct is meaningless");
488
Philip Reames9ac4e382015-08-12 21:00:20 +0000489 // An extractelement produces a base result exactly when it's input does.
490 // We may need to insert a parallel instruction to extract the appropriate
491 // element out of the base vector corresponding to the input. Given this,
492 // it's analogous to the phi and select case even though it's not a merge.
493 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
494 Value *VectorOperand = EEI->getVectorOperand();
495 Value *Index = EEI->getIndexOperand();
496 std::pair<Value *, bool> pair =
497 findBaseDefiningValueOfVector(VectorOperand, Index);
498 Value *VectorBase = pair.first;
499 if (VectorBase->getType()->isPointerTy())
500 // We found a BDV for this specific element with the vector. This is an
501 // optimization, but in practice it covers most of the useful cases
502 // created via scalarization. Note: The peephole optimization here is
503 // currently needed for correctness since the general algorithm doesn't
504 // yet handle insertelements. That will change shortly.
505 return VectorBase;
506 else {
507 assert(VectorBase->getType()->isVectorTy());
508 // Otherwise, we have an instruction which potentially produces a
509 // derived pointer and we need findBasePointers to clone code for us
510 // such that we can create an instruction which produces the
511 // accompanying base pointer.
512 return EEI;
513 }
514 }
515
Philip Reamesd16a9b12015-02-20 01:06:44 +0000516 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000517 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000518 // derived pointers (each with it's own base potentially). It's the job of
519 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000520 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000521 "missing instruction case in findBaseDefiningValing");
522 return I;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000523}
524
525/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000526static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
527 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000528 if (!Cached) {
529 Cached = findBaseDefiningValue(I);
Philip Reames2a892a62015-07-23 22:25:26 +0000530 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
531 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000532 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000533 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000534 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000535}
536
537/// Return a base pointer for this value if known. Otherwise, return it's
538/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000539static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
540 Value *Def = findBaseDefiningValueCached(I, Cache);
541 auto Found = Cache.find(Def);
542 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000543 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000544 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000545 }
546 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000547 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000548}
549
550/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
551/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000552static bool isKnownBaseResult(Value *V) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000553 if (!isa<PHINode>(V) && !isa<SelectInst>(V) && !isa<ExtractElementInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000554 // no recursion possible
555 return true;
556 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000557 if (isa<Instruction>(V) &&
558 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000559 // This is a previously inserted base phi or select. We know
560 // that this is a base value.
561 return true;
562 }
563
564 // We need to keep searching
565 return false;
566}
567
Philip Reamesd16a9b12015-02-20 01:06:44 +0000568namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000569/// Models the state of a single base defining value in the findBasePointer
570/// algorithm for determining where a new instruction is needed to propagate
571/// the base of this BDV.
572class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000573public:
574 enum Status { Unknown, Base, Conflict };
575
Philip Reames9b141ed2015-07-23 22:49:14 +0000576 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000577 assert(status != Base || b);
578 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000579 explicit BDVState(Value *b) : status(Base), base(b) {}
580 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000581
582 Status getStatus() const { return status; }
583 Value *getBase() const { return base; }
584
585 bool isBase() const { return getStatus() == Base; }
586 bool isUnknown() const { return getStatus() == Unknown; }
587 bool isConflict() const { return getStatus() == Conflict; }
588
Philip Reames9b141ed2015-07-23 22:49:14 +0000589 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000590 return base == other.base && status == other.status;
591 }
592
Philip Reames9b141ed2015-07-23 22:49:14 +0000593 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000594
Philip Reames2a892a62015-07-23 22:25:26 +0000595 LLVM_DUMP_METHOD
596 void dump() const { print(dbgs()); dbgs() << '\n'; }
597
598 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000599 switch (status) {
600 case Unknown:
601 OS << "U";
602 break;
603 case Base:
604 OS << "B";
605 break;
606 case Conflict:
607 OS << "C";
608 break;
609 };
610 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000611 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000612 }
613
614private:
615 Status status;
616 Value *base; // non null only if status == base
617};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000618}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000619
Philip Reames6906e922015-09-02 21:57:17 +0000620#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000621static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000622 State.print(OS);
623 return OS;
624}
Philip Reames6906e922015-09-02 21:57:17 +0000625#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000626
Philip Reamesb3967cd2015-09-02 22:30:53 +0000627namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000628typedef DenseMap<Value *, BDVState> ConflictStateMapTy;
629// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000630// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000631// operation is implemented in MeetBDVStates::pureMeet
632class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000633public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000634 /// Initializes the currentResult to the TOP state so that if can be met with
635 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000636 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000637
Philip Reames9b141ed2015-07-23 22:49:14 +0000638 // Destructively meet the current result with the given BDVState
639 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000640 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000641 }
642
Philip Reames9b141ed2015-07-23 22:49:14 +0000643 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000644
645private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000646 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000647
Philip Reames9b141ed2015-07-23 22:49:14 +0000648 /// Perform a meet operation on two elements of the BDVState lattice.
649 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000650 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
651 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000652 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000653 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
654 << " produced " << Result << "\n");
655 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000656 }
657
Philip Reames9b141ed2015-07-23 22:49:14 +0000658 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000659 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000660 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000661 return stateB;
662
Philip Reames9b141ed2015-07-23 22:49:14 +0000663 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000664 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000665 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000666 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000667
668 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000669 if (stateA.getBase() == stateB.getBase()) {
670 assert(stateA == stateB && "equality broken!");
671 return stateA;
672 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000673 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000674 }
David Blaikie82ad7872015-02-20 23:44:24 +0000675 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000676 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000677
Philip Reames9b141ed2015-07-23 22:49:14 +0000678 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000679 return stateA;
680 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000681 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000682 }
683};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000684}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000685
686
Philip Reamesd16a9b12015-02-20 01:06:44 +0000687/// For a given value or instruction, figure out what base ptr it's derived
688/// from. For gc objects, this is simply itself. On success, returns a value
689/// which is the base pointer. (This is reliable and can be used for
690/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000691static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000692 Value *def = findBaseOrBDV(I, cache);
693
694 if (isKnownBaseResult(def)) {
695 return def;
696 }
697
698 // Here's the rough algorithm:
699 // - For every SSA value, construct a mapping to either an actual base
700 // pointer or a PHI which obscures the base pointer.
701 // - Construct a mapping from PHI to unknown TOP state. Use an
702 // optimistic algorithm to propagate base pointer information. Lattice
703 // looks like:
704 // UNKNOWN
705 // b1 b2 b3 b4
706 // CONFLICT
707 // When algorithm terminates, all PHIs will either have a single concrete
708 // base or be in a conflict state.
709 // - For every conflict, insert a dummy PHI node without arguments. Add
710 // these to the base[Instruction] = BasePtr mapping. For every
711 // non-conflict, add the actual base.
712 // - For every conflict, add arguments for the base[a] of each input
713 // arguments.
714 //
715 // Note: A simpler form of this would be to add the conflict form of all
716 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000717 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000718 // overall worse solution.
719
Philip Reames29e9ae72015-07-24 00:42:55 +0000720#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000721 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000722 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) || isa<ExtractElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000723 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000724#endif
Philip Reames88958b22015-07-24 00:02:11 +0000725
726 // Once populated, will contain a mapping from each potentially non-base BDV
727 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames860660e2015-02-20 22:05:18 +0000728 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000729 // Recursively fill in all phis & selects reachable from the initial one
730 // for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000731 /* scope */ {
732 DenseSet<Value *> Visited;
733 SmallVector<Value*, 16> Worklist;
734 Worklist.push_back(def);
735 Visited.insert(def);
736 while (!Worklist.empty()) {
737 Value *Current = Worklist.pop_back_val();
738 assert(!isKnownBaseResult(Current) && "why did it get added?");
739
740 auto visitIncomingValue = [&](Value *InVal) {
741 Value *Base = findBaseOrBDV(InVal, cache);
742 if (isKnownBaseResult(Base))
743 // Known bases won't need new instructions introduced and can be
744 // ignored safely
745 return;
746 assert(isExpectedBDVType(Base) && "the only non-base values "
747 "we see should be base defining values");
748 if (Visited.insert(Base).second)
749 Worklist.push_back(Base);
750 };
751 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
752 for (Value *InVal : Phi->incoming_values())
753 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000754 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000755 visitIncomingValue(Sel->getTrueValue());
756 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000757 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
758 visitIncomingValue(EE->getVectorOperand());
759 } else {
760 // There are two classes of instructions we know we don't handle.
761 assert(isa<ShuffleVectorInst>(Current) ||
762 isa<InsertElementInst>(Current));
763 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000764 }
765 }
Philip Reames88958b22015-07-24 00:02:11 +0000766 // The frontier of visited instructions are the ones we might need to
767 // duplicate, so fill in the starting state for the optimistic algorithm
768 // that follows.
769 for (Value *BDV : Visited) {
770 states[BDV] = BDVState();
771 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000772 }
773
Philip Reamesdab35f32015-09-02 21:11:44 +0000774#ifndef NDEBUG
775 DEBUG(dbgs() << "States after initialization:\n");
776 for (auto Pair : states) {
777 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000778 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000779#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000780
781 // TODO: come back and revisit the state transitions around inputs which
782 // have reached conflict state. The current version seems too conservative.
783
Philip Reames273e6bb2015-07-23 21:41:27 +0000784 // Return a phi state for a base defining value. We'll generate a new
785 // base state for known bases and expect to find a cached state otherwise.
786 auto getStateForBDV = [&](Value *baseValue) {
787 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000788 return BDVState(baseValue);
Philip Reames273e6bb2015-07-23 21:41:27 +0000789 auto I = states.find(baseValue);
790 assert(I != states.end() && "lookup failed!");
791 return I->second;
792 };
793
Philip Reamesd16a9b12015-02-20 01:06:44 +0000794 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000795 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000796#ifndef NDEBUG
797 size_t oldSize = states.size();
798#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000799 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000800 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000801 for (auto Pair : states) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000802 Value *v = Pair.first;
803 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000804
Philip Reames9b141ed2015-07-23 22:49:14 +0000805 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000806 // instance which represents the BDV of that value.
807 auto getStateForInput = [&](Value *V) mutable {
808 Value *BDV = findBaseOrBDV(V, cache);
809 return getStateForBDV(BDV);
810 };
811
Philip Reames9b141ed2015-07-23 22:49:14 +0000812 MeetBDVStates calculateMeet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000813 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000814 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
815 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reames9ac4e382015-08-12 21:00:20 +0000816 } else if (PHINode *Phi = dyn_cast<PHINode>(v)) {
817 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000818 calculateMeet.meetWith(getStateForInput(Val));
Philip Reames9ac4e382015-08-12 21:00:20 +0000819 } else {
820 // The 'meet' for an extractelement is slightly trivial, but it's still
821 // useful in that it drives us to conflict if our input is.
822 auto *EE = cast<ExtractElementInst>(v);
823 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
824 }
825
Philip Reamesd16a9b12015-02-20 01:06:44 +0000826
Philip Reames9b141ed2015-07-23 22:49:14 +0000827 BDVState oldState = states[v];
828 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000829 if (oldState != newState) {
830 progress = true;
831 states[v] = newState;
832 }
833 }
834
835 assert(oldSize <= states.size());
836 assert(oldSize == states.size() || progress);
837 }
838
Philip Reamesdab35f32015-09-02 21:11:44 +0000839#ifndef NDEBUG
840 DEBUG(dbgs() << "States after meet iteration:\n");
841 for (auto Pair : states) {
842 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000843 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000844#endif
845
Philip Reamesd16a9b12015-02-20 01:06:44 +0000846 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000847 // We want to keep naming deterministic in the loop that follows, so
848 // sort the keys before iteration. This is useful in allowing us to
849 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000850 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000851 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000852 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000853 Value *V = Pair.first;
854 Keys.push_back(V);
855 }
856 std::sort(Keys.begin(), Keys.end(), order_by_name);
857 // TODO: adjust naming patterns to avoid this order of iteration dependency
858 for (Value *V : Keys) {
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000859 Instruction *I = cast<Instruction>(V);
Philip Reames9b141ed2015-07-23 22:49:14 +0000860 BDVState State = states[I];
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000861 assert(!isKnownBaseResult(I) && "why did it get added?");
862 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000863
864 // extractelement instructions are a bit special in that we may need to
865 // insert an extract even when we know an exact base for the instruction.
866 // The problem is that we need to convert from a vector base to a scalar
867 // base for the particular indice we're interested in.
868 if (State.isBase() && isa<ExtractElementInst>(I) &&
869 isa<VectorType>(State.getBase()->getType())) {
870 auto *EE = cast<ExtractElementInst>(I);
871 // TODO: In many cases, the new instruction is just EE itself. We should
872 // exploit this, but can't do it here since it would break the invariant
873 // about the BDV not being known to be a base.
874 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
875 EE->getIndexOperand(),
876 "base_ee", EE);
877 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
878 states[I] = BDVState(BDVState::Base, BaseInst);
879 }
880
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000881 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000882 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000883
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000884 /// Create and insert a new instruction which will represent the base of
885 /// the given instruction 'I'.
886 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
887 if (isa<PHINode>(I)) {
888 BasicBlock *BB = I->getParent();
889 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
890 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000891 std::string Name = I->hasName() ?
892 (I->getName() + ".base").str() : "base_phi";
893 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000894 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
895 // The undef will be replaced later
896 UndefValue *Undef = UndefValue::get(Sel->getType());
897 std::string Name = I->hasName() ?
898 (I->getName() + ".base").str() : "base_select";
899 return SelectInst::Create(Sel->getCondition(), Undef,
900 Undef, Name, Sel);
901 } else {
902 auto *EE = cast<ExtractElementInst>(I);
903 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
904 std::string Name = I->hasName() ?
905 (I->getName() + ".base").str() : "base_ee";
906 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
907 EE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000908 }
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000909 };
910 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
911 // Add metadata marking this as a base value
912 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames9b141ed2015-07-23 22:49:14 +0000913 states[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000914 }
915
916 // Fixup all the inputs of the new PHIs
917 for (auto Pair : states) {
918 Instruction *v = cast<Instruction>(Pair.first);
Philip Reames9b141ed2015-07-23 22:49:14 +0000919 BDVState state = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000920
921 assert(!isKnownBaseResult(v) && "why did it get added?");
922 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000923 if (!state.isConflict())
924 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000925
Philip Reames28e61ce2015-02-28 01:57:44 +0000926 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
927 PHINode *phi = cast<PHINode>(v);
928 unsigned NumPHIValues = phi->getNumIncomingValues();
929 for (unsigned i = 0; i < NumPHIValues; i++) {
930 Value *InVal = phi->getIncomingValue(i);
931 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000932
Philip Reames28e61ce2015-02-28 01:57:44 +0000933 // If we've already seen InBB, add the same incoming value
934 // we added for it earlier. The IR verifier requires phi
935 // nodes with multiple entries from the same basic block
936 // to have the same incoming value for each of those
937 // entries. If we don't do this check here and basephi
938 // has a different type than base, we'll end up adding two
939 // bitcasts (and hence two distinct values) as incoming
940 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000941
Philip Reames28e61ce2015-02-28 01:57:44 +0000942 int blockIndex = basephi->getBasicBlockIndex(InBB);
943 if (blockIndex != -1) {
944 Value *oldBase = basephi->getIncomingValue(blockIndex);
945 basephi->addIncoming(oldBase, InBB);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000946#ifndef NDEBUG
Philip Reames28e61ce2015-02-28 01:57:44 +0000947 Value *base = findBaseOrBDV(InVal, cache);
948 if (!isKnownBaseResult(base)) {
949 // Either conflict or base.
950 assert(states.count(base));
951 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000952 assert(base != nullptr && "unknown BDVState!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000953 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000954
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000955 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +0000956 // values incoming from the same basic block may be
957 // different is by being different bitcasts of the same
958 // value. A cleanup that remains TODO is changing
959 // findBaseOrBDV to return an llvm::Value of the correct
960 // type (and still remain pure). This will remove the
961 // need to add bitcasts.
962 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
963 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000964#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000965 continue;
966 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000967
Philip Reames28e61ce2015-02-28 01:57:44 +0000968 // Find either the defining value for the PHI or the normal base for
969 // a non-phi node
970 Value *base = findBaseOrBDV(InVal, cache);
971 if (!isKnownBaseResult(base)) {
972 // Either conflict or base.
973 assert(states.count(base));
974 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +0000975 assert(base != nullptr && "unknown BDVState!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000976 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000977 assert(base && "can't be null");
978 // Must use original input BB since base may not be Instruction
979 // The cast is needed since base traversal may strip away bitcasts
980 if (base->getType() != basephi->getType()) {
981 base = new BitCastInst(base, basephi->getType(), "cast",
982 InBB->getTerminator());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000983 }
Philip Reames28e61ce2015-02-28 01:57:44 +0000984 basephi->addIncoming(base, InBB);
985 }
986 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reames9ac4e382015-08-12 21:00:20 +0000987 } else if (SelectInst *basesel = dyn_cast<SelectInst>(state.getBase())) {
Philip Reames28e61ce2015-02-28 01:57:44 +0000988 SelectInst *sel = cast<SelectInst>(v);
989 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
990 // something more safe and less hacky.
991 for (int i = 1; i <= 2; i++) {
992 Value *InVal = sel->getOperand(i);
993 // Find either the defining value for the PHI or the normal base for
994 // a non-phi node
995 Value *base = findBaseOrBDV(InVal, cache);
996 if (!isKnownBaseResult(base)) {
997 // Either conflict or base.
998 assert(states.count(base));
999 base = states[base].getBase();
Philip Reames9b141ed2015-07-23 22:49:14 +00001000 assert(base != nullptr && "unknown BDVState!");
Philip Reames28e61ce2015-02-28 01:57:44 +00001001 }
1002 assert(base && "can't be null");
1003 // Must use original input BB since base may not be Instruction
1004 // The cast is needed since base traversal may strip away bitcasts
1005 if (base->getType() != basesel->getType()) {
1006 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
Philip Reames28e61ce2015-02-28 01:57:44 +00001007 }
1008 basesel->setOperand(i, base);
1009 }
Philip Reames9ac4e382015-08-12 21:00:20 +00001010 } else {
1011 auto *BaseEE = cast<ExtractElementInst>(state.getBase());
1012 Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
1013 Value *Base = findBaseOrBDV(InVal, cache);
1014 if (!isKnownBaseResult(Base)) {
1015 // Either conflict or base.
1016 assert(states.count(Base));
1017 Base = states[Base].getBase();
1018 assert(Base != nullptr && "unknown BDVState!");
1019 }
1020 assert(Base && "can't be null");
1021 BaseEE->setOperand(0, Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001022 }
1023 }
1024
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001025 // Now that we're done with the algorithm, see if we can optimize the
1026 // results slightly by reducing the number of new instructions needed.
1027 // Arguably, this should be integrated into the algorithm above, but
1028 // doing as a post process step is easier to reason about for the moment.
1029 DenseMap<Value *, Value *> ReverseMap;
1030 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001031 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001032 for (auto Item : states) {
1033 Value *V = Item.first;
1034 Value *Base = Item.second.getBase();
1035 assert(V && Base);
1036 assert(!isKnownBaseResult(V) && "why did it get added?");
1037 assert(isKnownBaseResult(Base) &&
1038 "must be something we 'know' is a base pointer");
1039 if (!Item.second.isConflict())
1040 continue;
1041
1042 ReverseMap[Base] = V;
1043 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1044 NewInsts.insert(BaseI);
1045 Worklist.insert(BaseI);
1046 }
1047 }
Philip Reames9546f362015-09-02 22:25:07 +00001048 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1049 Value *Replacement) {
1050 // Add users which are new instructions (excluding self references)
1051 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001052 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001053 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001054 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001055 // Then do the actual replacement
1056 NewInsts.erase(BaseI);
1057 ReverseMap.erase(BaseI);
1058 BaseI->replaceAllUsesWith(Replacement);
1059 BaseI->eraseFromParent();
1060 assert(states.count(BDV));
1061 assert(states[BDV].isConflict() && states[BDV].getBase() == BaseI);
1062 states[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001063 };
1064 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1065 while (!Worklist.empty()) {
1066 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001067 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001068 Value *Bdv = ReverseMap[BaseI];
1069 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1070 if (BaseI->isIdenticalTo(BdvI)) {
1071 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001072 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001073 continue;
1074 }
1075 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1076 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001077 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001078 continue;
1079 }
1080 }
1081
Philip Reamesd16a9b12015-02-20 01:06:44 +00001082 // Cache all of our results so we can cheaply reuse them
1083 // NOTE: This is actually two caches: one of the base defining value
1084 // relation and one of the base pointer relation! FIXME
1085 for (auto item : states) {
1086 Value *v = item.first;
1087 Value *base = item.second.getBase();
1088 assert(v && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001089
Philip Reamesdab35f32015-09-02 21:11:44 +00001090 std::string fromstr =
1091 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
1092 : "none";
1093 DEBUG(dbgs() << "Updating base value cache"
1094 << " for: " << (v->hasName() ? v->getName() : "")
1095 << " from: " << fromstr
1096 << " to: " << (base->hasName() ? base->getName() : "") << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001097
Philip Reamesd16a9b12015-02-20 01:06:44 +00001098 if (cache.count(v)) {
1099 // Once we transition from the BDV relation being store in the cache to
1100 // the base relation being stored, it must be stable
1101 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
1102 "base relation should be stable");
1103 }
1104 cache[v] = base;
1105 }
1106 assert(cache.find(def) != cache.end());
1107 return cache[def];
1108}
1109
1110// For a set of live pointers (base and/or derived), identify the base
1111// pointer of the object which they are derived from. This routine will
1112// mutate the IR graph as needed to make the 'base' pointer live at the
1113// definition site of 'derived'. This ensures that any use of 'derived' can
1114// also use 'base'. This may involve the insertion of a number of
1115// additional PHI nodes.
1116//
1117// preconditions: live is a set of pointer type Values
1118//
1119// side effects: may insert PHI nodes into the existing CFG, will preserve
1120// CFG, will not remove or mutate any existing nodes
1121//
Philip Reamesf2041322015-02-20 19:26:04 +00001122// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001123// pointer in live. Note that derived can be equal to base if the original
1124// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001125static void
1126findBasePointers(const StatepointLiveSetTy &live,
1127 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001128 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001129 // For the naming of values inserted to be deterministic - which makes for
1130 // much cleaner and more stable tests - we need to assign an order to the
1131 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001132 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001133 Temp.insert(Temp.end(), live.begin(), live.end());
1134 std::sort(Temp.begin(), Temp.end(), order_by_name);
1135 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001136 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001137 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001138 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001139 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1140 DT->dominates(cast<Instruction>(base)->getParent(),
1141 cast<Instruction>(ptr)->getParent())) &&
1142 "The base we found better dominate the derived pointer");
1143
David Blaikie82ad7872015-02-20 23:44:24 +00001144 // If you see this trip and like to live really dangerously, the code should
1145 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001146 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001147 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001148 "the relocation code needs adjustment to handle the relocation of "
1149 "a null pointer constant without causing false positives in the "
1150 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001151 }
1152}
1153
1154/// Find the required based pointers (and adjust the live set) for the given
1155/// parse point.
1156static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1157 const CallSite &CS,
1158 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001159 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +00001160 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001161
1162 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001163 // Note: Need to print these in a stable order since this is checked in
1164 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001165 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001166 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001167 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001168 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001169 Temp.push_back(Pair.first);
1170 }
1171 std::sort(Temp.begin(), Temp.end(), order_by_name);
1172 for (Value *Ptr : Temp) {
1173 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001174 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1175 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001176 }
1177 }
1178
Philip Reamesf2041322015-02-20 19:26:04 +00001179 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001180}
1181
Philip Reamesdf1ef082015-04-10 22:53:14 +00001182/// Given an updated version of the dataflow liveness results, update the
1183/// liveset and base pointer maps for the call site CS.
1184static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1185 const CallSite &CS,
1186 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001187
Philip Reamesdf1ef082015-04-10 22:53:14 +00001188static void recomputeLiveInValues(
1189 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001190 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001191 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001192 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001193 GCPtrLivenessData RevisedLivenessData;
1194 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001195 for (size_t i = 0; i < records.size(); i++) {
1196 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001197 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001198 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001199 }
1200}
1201
Philip Reames69e51ca2015-04-13 18:07:21 +00001202// When inserting gc.relocate calls, we need to ensure there are no uses
1203// of the original value between the gc.statepoint and the gc.relocate call.
1204// One case which can arise is a phi node starting one of the successor blocks.
1205// We also need to be able to insert the gc.relocates only on the path which
1206// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001207// possible.
1208static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001209normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1210 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001211 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001212 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001213 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001214 }
1215
Philip Reames69e51ca2015-04-13 18:07:21 +00001216 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1217 // from it
1218 FoldSingleEntryPHINodes(Ret);
1219 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001220
Philip Reames69e51ca2015-04-13 18:07:21 +00001221 // At this point, we can safely insert a gc.relocate as the first instruction
1222 // in Ret if needed.
1223 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001224}
1225
Philip Reamesd2b66462015-02-20 22:39:41 +00001226static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001227 auto itr = std::find(livevec.begin(), livevec.end(), val);
1228 assert(livevec.end() != itr);
1229 size_t index = std::distance(livevec.begin(), itr);
1230 assert(index < livevec.size());
1231 return index;
1232}
1233
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001234// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001235// from original call to the safepoint.
1236static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1237 AttributeSet ret;
1238
1239 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1240 unsigned index = AS.getSlotIndex(Slot);
1241
1242 if (index == AttributeSet::ReturnIndex ||
1243 index == AttributeSet::FunctionIndex) {
1244
1245 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1246 ++it) {
1247 Attribute attr = *it;
1248
1249 // Do not allow certain attributes - just skip them
1250 // Safepoint can not be read only or read none.
1251 if (attr.hasAttribute(Attribute::ReadNone) ||
1252 attr.hasAttribute(Attribute::ReadOnly))
1253 continue;
1254
1255 ret = ret.addAttributes(
1256 AS.getContext(), index,
1257 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1258 }
1259 }
1260
1261 // Just skip parameter attributes for now
1262 }
1263
1264 return ret;
1265}
1266
1267/// Helper function to place all gc relocates necessary for the given
1268/// statepoint.
1269/// Inputs:
1270/// liveVariables - list of variables to be relocated.
1271/// liveStart - index of the first live variable.
1272/// basePtrs - base pointers.
1273/// statepointToken - statepoint instruction to which relocates should be
1274/// bound.
1275/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001276static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1277 const int LiveStart,
1278 ArrayRef<llvm::Value *> BasePtrs,
1279 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001280 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001281 if (LiveVariables.empty())
1282 return;
1283
1284 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1285 // unique declarations for each pointer type, but this proved problematic
1286 // because the intrinsic mangling code is incomplete and fragile. Since
1287 // we're moving towards a single unified pointer type anyways, we can just
1288 // cast everything to an i8* of the right address space. A bitcast is added
1289 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001290 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001291 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1292 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1293 Value *GCRelocateDecl =
1294 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001295
Sanjoy Das5665c992015-05-11 23:47:27 +00001296 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001297 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001298 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001299 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1300 Value *LiveIdx =
1301 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001302
1303 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001304 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001305 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001306 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001307 : "");
1308 // Trick CodeGen into thinking there are lots of free registers at this
1309 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001310 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001311 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001312}
1313
1314static void
1315makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1316 const SmallVectorImpl<llvm::Value *> &basePtrs,
1317 const SmallVectorImpl<llvm::Value *> &liveVariables,
1318 Pass *P,
1319 PartiallyConstructedSafepointRecord &result) {
1320 assert(basePtrs.size() == liveVariables.size());
1321 assert(isStatepoint(CS) &&
1322 "This method expects to be rewriting a statepoint");
1323
1324 BasicBlock *BB = CS.getInstruction()->getParent();
1325 assert(BB);
1326 Function *F = BB->getParent();
1327 assert(F && "must be set");
1328 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001329 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001330 assert(M && "must be set");
1331
1332 // We're not changing the function signature of the statepoint since the gc
1333 // arguments go into the var args section.
1334 Function *gc_statepoint_decl = CS.getCalledFunction();
1335
1336 // Then go ahead and use the builder do actually do the inserts. We insert
1337 // immediately before the previous instruction under the assumption that all
1338 // arguments will be available here. We can't insert afterwards since we may
1339 // be replacing a terminator.
1340 Instruction *insertBefore = CS.getInstruction();
1341 IRBuilder<> Builder(insertBefore);
1342 // Copy all of the arguments from the original statepoint - this includes the
1343 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001344 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001345 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1346 // TODO: Clear the 'needs rewrite' flag
1347
1348 // add all the pointers to be relocated (gc arguments)
1349 // Capture the start of the live variable list for use in the gc_relocates
1350 const int live_start = args.size();
1351 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1352
1353 // Create the statepoint given all the arguments
1354 Instruction *token = nullptr;
1355 AttributeSet return_attributes;
1356 if (CS.isCall()) {
1357 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1358 CallInst *call =
1359 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1360 call->setTailCall(toReplace->isTailCall());
1361 call->setCallingConv(toReplace->getCallingConv());
1362
1363 // Currently we will fail on parameter attributes and on certain
1364 // function attributes.
1365 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001366 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001367 // directly on statepoint and return attrs later for gc_result intrinsic.
1368 call->setAttributes(new_attrs.getFnAttributes());
1369 return_attributes = new_attrs.getRetAttributes();
1370
1371 token = call;
1372
1373 // Put the following gc_result and gc_relocate calls immediately after the
1374 // the old call (which we're about to delete)
1375 BasicBlock::iterator next(toReplace);
1376 assert(BB->end() != next && "not a terminator, must have next");
1377 next++;
1378 Instruction *IP = &*(next);
1379 Builder.SetInsertPoint(IP);
1380 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1381
David Blaikie82ad7872015-02-20 23:44:24 +00001382 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001383 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1384
1385 // Insert the new invoke into the old block. We'll remove the old one in a
1386 // moment at which point this will become the new terminator for the
1387 // original block.
1388 InvokeInst *invoke = InvokeInst::Create(
1389 gc_statepoint_decl, toReplace->getNormalDest(),
Philip Reamesfa2c6302015-07-24 19:01:39 +00001390 toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001391 invoke->setCallingConv(toReplace->getCallingConv());
1392
1393 // Currently we will fail on parameter attributes and on certain
1394 // function attributes.
1395 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001396 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001397 // directly on statepoint and return attrs later for gc_result intrinsic.
1398 invoke->setAttributes(new_attrs.getFnAttributes());
1399 return_attributes = new_attrs.getRetAttributes();
1400
1401 token = invoke;
1402
1403 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001404 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1405 assert(!isa<PHINode>(unwindBlock->begin()) &&
1406 unwindBlock->getUniquePredecessor() &&
1407 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001408
1409 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1410 Builder.SetInsertPoint(IP);
1411 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1412
1413 // Extract second element from landingpad return value. We will attach
1414 // exceptional gc relocates to it.
1415 const unsigned idx = 1;
1416 Instruction *exceptional_token =
1417 cast<Instruction>(Builder.CreateExtractValue(
1418 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001419 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001420
Philip Reames6ff1a1e32015-07-21 19:04:38 +00001421 CreateGCRelocates(liveVariables, live_start, basePtrs,
1422 exceptional_token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001423
1424 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001425 BasicBlock *normalDest = toReplace->getNormalDest();
1426 assert(!isa<PHINode>(normalDest->begin()) &&
1427 normalDest->getUniquePredecessor() &&
1428 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001429
1430 IP = &*(normalDest->getFirstInsertionPt());
1431 Builder.SetInsertPoint(IP);
1432
1433 // gc relocates will be generated later as if it were regular call
1434 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001435 }
1436 assert(token);
1437
1438 // Take the name of the original value call if it had one.
1439 token->takeName(CS.getInstruction());
1440
Philip Reames704e78b2015-04-10 22:34:56 +00001441// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001442#ifndef NDEBUG
1443 Instruction *toReplace = CS.getInstruction();
1444 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1445 "only valid use before rewrite is gc.result");
1446 assert(!toReplace->hasOneUse() ||
1447 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1448#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001449
1450 // Update the gc.result of the original statepoint (if any) to use the newly
1451 // inserted statepoint. This is safe to do here since the token can't be
1452 // considered a live reference.
1453 CS.getInstruction()->replaceAllUsesWith(token);
1454
Philip Reames0a3240f2015-02-20 21:34:11 +00001455 result.StatepointToken = token;
1456
Philip Reamesd16a9b12015-02-20 01:06:44 +00001457 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001458 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001459}
1460
1461namespace {
1462struct name_ordering {
1463 Value *base;
1464 Value *derived;
1465 bool operator()(name_ordering const &a, name_ordering const &b) {
1466 return -1 == a.derived->getName().compare(b.derived->getName());
1467 }
1468};
1469}
1470static void stablize_order(SmallVectorImpl<Value *> &basevec,
1471 SmallVectorImpl<Value *> &livevec) {
1472 assert(basevec.size() == livevec.size());
1473
Philip Reames860660e2015-02-20 22:05:18 +00001474 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001475 for (size_t i = 0; i < basevec.size(); i++) {
1476 name_ordering v;
1477 v.base = basevec[i];
1478 v.derived = livevec[i];
1479 temp.push_back(v);
1480 }
1481 std::sort(temp.begin(), temp.end(), name_ordering());
1482 for (size_t i = 0; i < basevec.size(); i++) {
1483 basevec[i] = temp[i].base;
1484 livevec[i] = temp[i].derived;
1485 }
1486}
1487
1488// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1489// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001490//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001491// WARNING: Does not do any fixup to adjust users of the original live
1492// values. That's the callers responsibility.
1493static void
1494makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1495 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001496 auto liveset = result.liveset;
1497 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001498
1499 // Convert to vector for efficient cross referencing.
1500 SmallVector<Value *, 64> basevec, livevec;
1501 livevec.reserve(liveset.size());
1502 basevec.reserve(liveset.size());
1503 for (Value *L : liveset) {
1504 livevec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001505 assert(PointerToBase.count(L));
Philip Reamesf2041322015-02-20 19:26:04 +00001506 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001507 basevec.push_back(base);
1508 }
1509 assert(livevec.size() == basevec.size());
1510
1511 // To make the output IR slightly more stable (for use in diffs), ensure a
1512 // fixed order of the values in the safepoint (by sorting the value name).
1513 // The order is otherwise meaningless.
1514 stablize_order(basevec, livevec);
1515
1516 // Do the actual rewriting and delete the old statepoint
1517 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1518 CS.getInstruction()->eraseFromParent();
1519}
1520
1521// Helper function for the relocationViaAlloca.
1522// It receives iterator to the statepoint gc relocates and emits store to the
1523// assigned
1524// location (via allocaMap) for the each one of them.
1525// Add visited values into the visitedLiveValues set we will later use them
1526// for sanity check.
1527static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001528insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1529 DenseMap<Value *, Value *> &AllocaMap,
1530 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001531
Sanjoy Das5665c992015-05-11 23:47:27 +00001532 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001533 if (!isa<IntrinsicInst>(U))
1534 continue;
1535
Sanjoy Das5665c992015-05-11 23:47:27 +00001536 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001537
1538 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001539 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001540 Intrinsic::experimental_gc_relocate) {
1541 continue;
1542 }
1543
Sanjoy Das5665c992015-05-11 23:47:27 +00001544 GCRelocateOperands RelocateOperands(RelocatedValue);
1545 Value *OriginalValue =
1546 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1547 assert(AllocaMap.count(OriginalValue));
1548 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001549
1550 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001551 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1552 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001553 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1554 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001555 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001556 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1557 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001558
Sanjoy Das5665c992015-05-11 23:47:27 +00001559 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1560 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001561
1562#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001563 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001564#endif
1565 }
1566}
1567
Igor Laevskye0317182015-05-19 15:59:05 +00001568// Helper function for the "relocationViaAlloca". Similar to the
1569// "insertRelocationStores" but works for rematerialized values.
1570static void
1571insertRematerializationStores(
1572 RematerializedValueMapTy RematerializedValues,
1573 DenseMap<Value *, Value *> &AllocaMap,
1574 DenseSet<Value *> &VisitedLiveValues) {
1575
1576 for (auto RematerializedValuePair: RematerializedValues) {
1577 Instruction *RematerializedValue = RematerializedValuePair.first;
1578 Value *OriginalValue = RematerializedValuePair.second;
1579
1580 assert(AllocaMap.count(OriginalValue) &&
1581 "Can not find alloca for rematerialized value");
1582 Value *Alloca = AllocaMap[OriginalValue];
1583
1584 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1585 Store->insertAfter(RematerializedValue);
1586
1587#ifndef NDEBUG
1588 VisitedLiveValues.insert(OriginalValue);
1589#endif
1590 }
1591}
1592
Philip Reamesd16a9b12015-02-20 01:06:44 +00001593/// do all the relocation update via allocas and mem2reg
1594static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001595 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1596 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001597#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001598 // record initial number of (static) allocas; we'll check we have the same
1599 // number when we get done.
1600 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001601 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1602 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001603 if (isa<AllocaInst>(*I))
1604 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001605#endif
1606
1607 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001608 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001609 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001610 // Used later to chack that we have enough allocas to store all values
1611 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001612 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001613
Igor Laevskye0317182015-05-19 15:59:05 +00001614 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1615 // "PromotableAllocas"
1616 auto emitAllocaFor = [&](Value *LiveValue) {
1617 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1618 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001619 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001620 PromotableAllocas.push_back(Alloca);
1621 };
1622
Philip Reamesd16a9b12015-02-20 01:06:44 +00001623 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001624 for (unsigned i = 0; i < Live.size(); i++) {
1625 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001626 }
1627
Igor Laevskye0317182015-05-19 15:59:05 +00001628 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001629 for (size_t i = 0; i < Records.size(); i++) {
1630 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001631
Igor Laevsky285fe842015-05-19 16:29:43 +00001632 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001633 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001634 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001635 continue;
1636
1637 emitAllocaFor(OriginalValue);
1638 ++NumRematerializedValues;
1639 }
1640 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001641
Philip Reamesd16a9b12015-02-20 01:06:44 +00001642 // The next two loops are part of the same conceptual operation. We need to
1643 // insert a store to the alloca after the original def and at each
1644 // redefinition. We need to insert a load before each use. These are split
1645 // into distinct loops for performance reasons.
1646
1647 // update gc pointer after each statepoint
1648 // either store a relocated value or null (if no relocated value found for
1649 // this gc pointer and it is not a gc_result)
1650 // this must happen before we update the statepoint with load of alloca
1651 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001652 for (size_t i = 0; i < Records.size(); i++) {
1653 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1654 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001655
1656 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001657 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001658
1659 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001660 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001661
1662 // In case if it was invoke statepoint
1663 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001664 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001665 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1666 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001667 }
1668
Igor Laevskye0317182015-05-19 15:59:05 +00001669 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001670 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1671 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001672
Philip Reamese73300b2015-04-13 16:41:32 +00001673 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001674 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001675 // the gc.statepoint. This will turn some subtle GC problems into
1676 // slightly easier to debug SEGVs. Note that on large IR files with
1677 // lots of gc.statepoints this is extremely costly both memory and time
1678 // wise.
1679 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001680 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001681 Value *Def = Pair.first;
1682 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001683
Philip Reamese73300b2015-04-13 16:41:32 +00001684 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001685 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001686 continue;
1687 }
1688 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001689 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001690
Philip Reamese73300b2015-04-13 16:41:32 +00001691 auto InsertClobbersAt = [&](Instruction *IP) {
1692 for (auto *AI : ToClobber) {
1693 auto AIType = cast<PointerType>(AI->getType());
1694 auto PT = cast<PointerType>(AIType->getElementType());
1695 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001696 StoreInst *Store = new StoreInst(CPN, AI);
1697 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001698 }
1699 };
1700
1701 // Insert the clobbering stores. These may get intermixed with the
1702 // gc.results and gc.relocates, but that's fine.
1703 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1704 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1705 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1706 } else {
1707 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1708 Next++;
1709 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001710 }
David Blaikie82ad7872015-02-20 23:44:24 +00001711 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001712 }
1713 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001714 for (auto Pair : AllocaMap) {
1715 Value *Def = Pair.first;
1716 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001717
1718 // we pre-record the uses of allocas so that we dont have to worry about
1719 // later update
1720 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001721 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001722 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001723 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1724 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001725 if (!isa<ConstantExpr>(U)) {
1726 // If the def has a ConstantExpr use, then the def is either a
1727 // ConstantExpr use itself or null. In either case
1728 // (recursively in the first, directly in the second), the oop
1729 // it is ultimately dependent on is null and this particular
1730 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001731 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001732 }
1733 }
1734
Igor Laevsky285fe842015-05-19 16:29:43 +00001735 std::sort(Uses.begin(), Uses.end());
1736 auto Last = std::unique(Uses.begin(), Uses.end());
1737 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001738
Igor Laevsky285fe842015-05-19 16:29:43 +00001739 for (Instruction *Use : Uses) {
1740 if (isa<PHINode>(Use)) {
1741 PHINode *Phi = cast<PHINode>(Use);
1742 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1743 if (Def == Phi->getIncomingValue(i)) {
1744 LoadInst *Load = new LoadInst(
1745 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1746 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001747 }
1748 }
1749 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001750 LoadInst *Load = new LoadInst(Alloca, "", Use);
1751 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001752 }
1753 }
1754
1755 // emit store for the initial gc value
1756 // store must be inserted after load, otherwise store will be in alloca's
1757 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001758 StoreInst *Store = new StoreInst(Def, Alloca);
1759 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1760 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001761 // InvokeInst is a TerminatorInst so the store need to be inserted
1762 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001763 BasicBlock *NormalDest = Invoke->getNormalDest();
1764 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001765 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001766 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001767 "The only TerminatorInst that can produce a value is "
1768 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001769 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001770 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001771 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001772 assert(isa<Argument>(Def));
1773 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001774 }
1775 }
1776
Igor Laevsky285fe842015-05-19 16:29:43 +00001777 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001778 "we must have the same allocas with lives");
1779 if (!PromotableAllocas.empty()) {
1780 // apply mem2reg to promote alloca to SSA
1781 PromoteMemToReg(PromotableAllocas, DT);
1782 }
1783
1784#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001785 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1786 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001787 if (isa<AllocaInst>(*I))
1788 InitialAllocaNum--;
1789 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001790#endif
1791}
1792
1793/// Implement a unique function which doesn't require we sort the input
1794/// vector. Doing so has the effect of changing the output of a couple of
1795/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001796template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001797 SmallSet<T, 8> Seen;
1798 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1799 return !Seen.insert(V).second;
1800 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001801}
1802
Philip Reamesd16a9b12015-02-20 01:06:44 +00001803/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001804/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001805static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001806 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001807 if (Values.empty())
1808 // No values to hold live, might as well not insert the empty holder
1809 return;
1810
Philip Reamesd16a9b12015-02-20 01:06:44 +00001811 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001812 // Use a dummy vararg function to actually hold the values live
1813 Function *Func = cast<Function>(M->getOrInsertFunction(
1814 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001815 if (CS.isCall()) {
1816 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001817 BasicBlock::iterator Next(CS.getInstruction());
1818 Next++;
1819 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1820 return;
1821 }
1822 // For invoke safepooints insert dummy calls both in normal and
1823 // exceptional destination blocks
1824 auto *II = cast<InvokeInst>(CS.getInstruction());
1825 Holders.push_back(CallInst::Create(
1826 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1827 Holders.push_back(CallInst::Create(
1828 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001829}
1830
1831static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001832 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1833 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001834 GCPtrLivenessData OriginalLivenessData;
1835 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001836 for (size_t i = 0; i < records.size(); i++) {
1837 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001838 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001839 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001840 }
1841}
1842
Philip Reames8531d8c2015-04-10 21:48:25 +00001843/// Remove any vector of pointers from the liveset by scalarizing them over the
1844/// statepoint instruction. Adds the scalarized pieces to the liveset. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001845/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001846/// the lowering code currently does not handle that. Extending it would be
1847/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001848/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001849static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001850 StatepointLiveSetTy &LiveSet,
1851 DenseMap<Value *, Value *>& PointerToBase,
1852 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001853 SmallVector<Value *, 16> ToSplit;
1854 for (Value *V : LiveSet)
1855 if (isa<VectorType>(V->getType()))
1856 ToSplit.push_back(V);
1857
1858 if (ToSplit.empty())
1859 return;
1860
Philip Reames8fe7f132015-06-26 22:47:37 +00001861 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1862
Philip Reames8531d8c2015-04-10 21:48:25 +00001863 Function &F = *(StatepointInst->getParent()->getParent());
1864
Philip Reames704e78b2015-04-10 22:34:56 +00001865 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001866 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001867 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001868 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001869 AllocaInst *Alloca =
1870 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001871 AllocaMap[V] = Alloca;
1872
1873 VectorType *VT = cast<VectorType>(V->getType());
1874 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001875 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001876 for (unsigned i = 0; i < VT->getNumElements(); i++)
1877 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001878 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001879
1880 auto InsertVectorReform = [&](Instruction *IP) {
1881 Builder.SetInsertPoint(IP);
1882 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1883 Value *ResultVec = UndefValue::get(VT);
1884 for (unsigned i = 0; i < VT->getNumElements(); i++)
1885 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1886 Builder.getInt32(i));
1887 return ResultVec;
1888 };
1889
1890 if (isa<CallInst>(StatepointInst)) {
1891 BasicBlock::iterator Next(StatepointInst);
1892 Next++;
1893 Instruction *IP = &*(Next);
1894 Replacements[V].first = InsertVectorReform(IP);
1895 Replacements[V].second = nullptr;
1896 } else {
1897 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1898 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001899 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001900 BasicBlock *NormalDest = Invoke->getNormalDest();
1901 assert(!isa<PHINode>(NormalDest->begin()));
1902 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1903 assert(!isa<PHINode>(UnwindDest->begin()));
1904 // Insert insert element sequences in both successors
1905 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1906 Replacements[V].first = InsertVectorReform(IP);
1907 IP = &*(UnwindDest->getFirstInsertionPt());
1908 Replacements[V].second = InsertVectorReform(IP);
1909 }
1910 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001911
Philip Reames8531d8c2015-04-10 21:48:25 +00001912 for (Value *V : ToSplit) {
1913 AllocaInst *Alloca = AllocaMap[V];
1914
1915 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001916 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001917 for (User *U : V->users())
1918 Users.push_back(cast<Instruction>(U));
1919
1920 for (Instruction *I : Users) {
1921 if (auto Phi = dyn_cast<PHINode>(I)) {
1922 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1923 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001924 LoadInst *Load = new LoadInst(
1925 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001926 Phi->setIncomingValue(i, Load);
1927 }
1928 } else {
1929 LoadInst *Load = new LoadInst(Alloca, "", I);
1930 I->replaceUsesOfWith(V, Load);
1931 }
1932 }
1933
1934 // Store the original value and the replacement value into the alloca
1935 StoreInst *Store = new StoreInst(V, Alloca);
1936 if (auto I = dyn_cast<Instruction>(V))
1937 Store->insertAfter(I);
1938 else
1939 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001940
Philip Reames8531d8c2015-04-10 21:48:25 +00001941 // Normal return for invoke, or call return
1942 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1943 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1944 // Unwind return for invoke only
1945 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1946 if (Replacement)
1947 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1948 }
1949
1950 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001951 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001952 for (Value *V : ToSplit)
1953 Allocas.push_back(AllocaMap[V]);
1954 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001955
1956 // Update our tracking of live pointers and base mappings to account for the
1957 // changes we just made.
1958 for (Value *V : ToSplit) {
1959 auto &Elements = ElementMapping[V];
1960
1961 LiveSet.erase(V);
1962 LiveSet.insert(Elements.begin(), Elements.end());
1963 // We need to update the base mapping as well.
1964 assert(PointerToBase.count(V));
1965 Value *OldBase = PointerToBase[V];
1966 auto &BaseElements = ElementMapping[OldBase];
1967 PointerToBase.erase(V);
1968 assert(Elements.size() == BaseElements.size());
1969 for (unsigned i = 0; i < Elements.size(); i++) {
1970 Value *Elem = Elements[i];
1971 PointerToBase[Elem] = BaseElements[i];
1972 }
1973 }
Philip Reames8531d8c2015-04-10 21:48:25 +00001974}
1975
Igor Laevskye0317182015-05-19 15:59:05 +00001976// Helper function for the "rematerializeLiveValues". It walks use chain
1977// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1978// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001979// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00001980// Fills "ChainToBase" array with all visited values. "BaseValue" is not
1981// recorded.
1982static bool findRematerializableChainToBasePointer(
1983 SmallVectorImpl<Instruction*> &ChainToBase,
1984 Value *CurrentValue, Value *BaseValue) {
1985
1986 // We have found a base value
1987 if (CurrentValue == BaseValue) {
1988 return true;
1989 }
1990
1991 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1992 ChainToBase.push_back(GEP);
1993 return findRematerializableChainToBasePointer(ChainToBase,
1994 GEP->getPointerOperand(),
1995 BaseValue);
1996 }
1997
1998 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1999 Value *Def = CI->stripPointerCasts();
2000
2001 // This two checks are basically similar. First one is here for the
2002 // consistency with findBasePointers logic.
2003 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2004 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2005 return false;
2006
2007 ChainToBase.push_back(CI);
2008 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2009 }
2010
2011 // Not supported instruction in the chain
2012 return false;
2013}
2014
2015// Helper function for the "rematerializeLiveValues". Compute cost of the use
2016// chain we are going to rematerialize.
2017static unsigned
2018chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2019 TargetTransformInfo &TTI) {
2020 unsigned Cost = 0;
2021
2022 for (Instruction *Instr : Chain) {
2023 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2024 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2025 "non noop cast is found during rematerialization");
2026
2027 Type *SrcTy = CI->getOperand(0)->getType();
2028 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2029
2030 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2031 // Cost of the address calculation
2032 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2033 Cost += TTI.getAddressComputationCost(ValTy);
2034
2035 // And cost of the GEP itself
2036 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2037 // allowed for the external usage)
2038 if (!GEP->hasAllConstantIndices())
2039 Cost += 2;
2040
2041 } else {
2042 llvm_unreachable("unsupported instruciton type during rematerialization");
2043 }
2044 }
2045
2046 return Cost;
2047}
2048
2049// From the statepoint liveset pick values that are cheaper to recompute then to
2050// relocate. Remove this values from the liveset, rematerialize them after
2051// statepoint and record them in "Info" structure. Note that similar to
2052// relocated values we don't do any user adjustments here.
2053static void rematerializeLiveValues(CallSite CS,
2054 PartiallyConstructedSafepointRecord &Info,
2055 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002056 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002057
Igor Laevskye0317182015-05-19 15:59:05 +00002058 // Record values we are going to delete from this statepoint live set.
2059 // We can not di this in following loop due to iterator invalidation.
2060 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2061
2062 for (Value *LiveValue: Info.liveset) {
2063 // For each live pointer find it's defining chain
2064 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002065 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002066 bool FoundChain =
2067 findRematerializableChainToBasePointer(ChainToBase,
2068 LiveValue,
2069 Info.PointerToBase[LiveValue]);
2070 // Nothing to do, or chain is too long
2071 if (!FoundChain ||
2072 ChainToBase.size() == 0 ||
2073 ChainToBase.size() > ChainLengthThreshold)
2074 continue;
2075
2076 // Compute cost of this chain
2077 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2078 // TODO: We can also account for cases when we will be able to remove some
2079 // of the rematerialized values by later optimization passes. I.e if
2080 // we rematerialized several intersecting chains. Or if original values
2081 // don't have any uses besides this statepoint.
2082
2083 // For invokes we need to rematerialize each chain twice - for normal and
2084 // for unwind basic blocks. Model this by multiplying cost by two.
2085 if (CS.isInvoke()) {
2086 Cost *= 2;
2087 }
2088 // If it's too expensive - skip it
2089 if (Cost >= RematerializationThreshold)
2090 continue;
2091
2092 // Remove value from the live set
2093 LiveValuesToBeDeleted.push_back(LiveValue);
2094
2095 // Clone instructions and record them inside "Info" structure
2096
2097 // Walk backwards to visit top-most instructions first
2098 std::reverse(ChainToBase.begin(), ChainToBase.end());
2099
2100 // Utility function which clones all instructions from "ChainToBase"
2101 // and inserts them before "InsertBefore". Returns rematerialized value
2102 // which should be used after statepoint.
2103 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2104 Instruction *LastClonedValue = nullptr;
2105 Instruction *LastValue = nullptr;
2106 for (Instruction *Instr: ChainToBase) {
2107 // Only GEP's and casts are suported as we need to be careful to not
2108 // introduce any new uses of pointers not in the liveset.
2109 // Note that it's fine to introduce new uses of pointers which were
2110 // otherwise not used after this statepoint.
2111 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2112
2113 Instruction *ClonedValue = Instr->clone();
2114 ClonedValue->insertBefore(InsertBefore);
2115 ClonedValue->setName(Instr->getName() + ".remat");
2116
2117 // If it is not first instruction in the chain then it uses previously
2118 // cloned value. We should update it to use cloned value.
2119 if (LastClonedValue) {
2120 assert(LastValue);
2121 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2122#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002123 // Assert that cloned instruction does not use any instructions from
2124 // this chain other than LastClonedValue
2125 for (auto OpValue : ClonedValue->operand_values()) {
2126 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2127 ChainToBase.end() &&
2128 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002129 }
2130#endif
2131 }
2132
2133 LastClonedValue = ClonedValue;
2134 LastValue = Instr;
2135 }
2136 assert(LastClonedValue);
2137 return LastClonedValue;
2138 };
2139
2140 // Different cases for calls and invokes. For invokes we need to clone
2141 // instructions both on normal and unwind path.
2142 if (CS.isCall()) {
2143 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2144 assert(InsertBefore);
2145 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2146 Info.RematerializedValues[RematerializedValue] = LiveValue;
2147 } else {
2148 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2149
2150 Instruction *NormalInsertBefore =
2151 Invoke->getNormalDest()->getFirstInsertionPt();
2152 Instruction *UnwindInsertBefore =
2153 Invoke->getUnwindDest()->getFirstInsertionPt();
2154
2155 Instruction *NormalRematerializedValue =
2156 rematerializeChain(NormalInsertBefore);
2157 Instruction *UnwindRematerializedValue =
2158 rematerializeChain(UnwindInsertBefore);
2159
2160 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2161 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2162 }
2163 }
2164
2165 // Remove rematerializaed values from the live set
2166 for (auto LiveValue: LiveValuesToBeDeleted) {
2167 Info.liveset.erase(LiveValue);
2168 }
2169}
2170
Philip Reamesd16a9b12015-02-20 01:06:44 +00002171static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00002172 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002173#ifndef NDEBUG
2174 // sanity check the input
2175 std::set<CallSite> uniqued;
2176 uniqued.insert(toUpdate.begin(), toUpdate.end());
2177 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2178
2179 for (size_t i = 0; i < toUpdate.size(); i++) {
2180 CallSite &CS = toUpdate[i];
2181 assert(CS.getInstruction()->getParent()->getParent() == &F);
2182 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2183 }
2184#endif
2185
Philip Reames69e51ca2015-04-13 18:07:21 +00002186 // When inserting gc.relocates for invokes, we need to be able to insert at
2187 // the top of the successor blocks. See the comment on
2188 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002189 // may restructure the CFG.
2190 for (CallSite CS : toUpdate) {
2191 if (!CS.isInvoke())
2192 continue;
2193 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2194 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002195 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002196 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002197 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002198 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002199
Philip Reamesd16a9b12015-02-20 01:06:44 +00002200 // A list of dummy calls added to the IR to keep various values obviously
2201 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002202 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002203
2204 // Insert a dummy call with all of the arguments to the vm_state we'll need
2205 // for the actual safepoint insertion. This ensures reference arguments in
2206 // the deopt argument list are considered live through the safepoint (and
2207 // thus makes sure they get relocated.)
2208 for (size_t i = 0; i < toUpdate.size(); i++) {
2209 CallSite &CS = toUpdate[i];
2210 Statepoint StatepointCS(CS);
2211
2212 SmallVector<Value *, 64> DeoptValues;
2213 for (Use &U : StatepointCS.vm_state_args()) {
2214 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002215 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2216 "support for FCA unimplemented");
2217 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002218 DeoptValues.push_back(Arg);
2219 }
2220 insertUseHolderAfter(CS, DeoptValues, holders);
2221 }
2222
Philip Reamesd2b66462015-02-20 22:39:41 +00002223 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002224 records.reserve(toUpdate.size());
2225 for (size_t i = 0; i < toUpdate.size(); i++) {
2226 struct PartiallyConstructedSafepointRecord info;
2227 records.push_back(info);
2228 }
2229 assert(records.size() == toUpdate.size());
2230
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002231 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002232 // site.
2233 findLiveReferences(F, DT, P, toUpdate, records);
2234
2235 // B) Find the base pointers for each live pointer
2236 /* scope for caching */ {
2237 // Cache the 'defining value' relation used in the computation and
2238 // insertion of base phis and selects. This ensures that we don't insert
2239 // large numbers of duplicate base_phis.
2240 DefiningValueMapTy DVCache;
2241
2242 for (size_t i = 0; i < records.size(); i++) {
2243 struct PartiallyConstructedSafepointRecord &info = records[i];
2244 CallSite &CS = toUpdate[i];
2245 findBasePointers(DT, DVCache, CS, info);
2246 }
2247 } // end of cache scope
2248
2249 // The base phi insertion logic (for any safepoint) may have inserted new
2250 // instructions which are now live at some safepoint. The simplest such
2251 // example is:
2252 // loop:
2253 // phi a <-- will be a new base_phi here
2254 // safepoint 1 <-- that needs to be live here
2255 // gep a + 1
2256 // safepoint 2
2257 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002258 // We insert some dummy calls after each safepoint to definitely hold live
2259 // the base pointers which were identified for that safepoint. We'll then
2260 // ask liveness for _every_ base inserted to see what is now live. Then we
2261 // remove the dummy calls.
2262 holders.reserve(holders.size() + records.size());
2263 for (size_t i = 0; i < records.size(); i++) {
2264 struct PartiallyConstructedSafepointRecord &info = records[i];
2265 CallSite &CS = toUpdate[i];
2266
2267 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002268 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002269 Bases.push_back(Pair.second);
2270 }
2271 insertUseHolderAfter(CS, Bases, holders);
2272 }
2273
Philip Reamesdf1ef082015-04-10 22:53:14 +00002274 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2275 // need to rerun liveness. We may *also* have inserted new defs, but that's
2276 // not the key issue.
2277 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002278
Philip Reamesd16a9b12015-02-20 01:06:44 +00002279 if (PrintBasePointers) {
2280 for (size_t i = 0; i < records.size(); i++) {
2281 struct PartiallyConstructedSafepointRecord &info = records[i];
2282 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002283 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002284 errs() << " derived %" << Pair.first->getName() << " base %"
2285 << Pair.second->getName() << "\n";
2286 }
2287 }
2288 }
2289 for (size_t i = 0; i < holders.size(); i++) {
2290 holders[i]->eraseFromParent();
2291 holders[i] = nullptr;
2292 }
2293 holders.clear();
2294
Philip Reames8fe7f132015-06-26 22:47:37 +00002295 // Do a limited scalarization of any live at safepoint vector values which
2296 // contain pointers. This enables this pass to run after vectorization at
2297 // the cost of some possible performance loss. TODO: it would be nice to
2298 // natively support vectors all the way through the backend so we don't need
2299 // to scalarize here.
2300 for (size_t i = 0; i < records.size(); i++) {
2301 struct PartiallyConstructedSafepointRecord &info = records[i];
2302 Instruction *statepoint = toUpdate[i].getInstruction();
2303 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2304 info.PointerToBase, DT);
2305 }
2306
Igor Laevskye0317182015-05-19 15:59:05 +00002307 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002308 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002309 // does not influence correctness.
2310 TargetTransformInfo &TTI =
2311 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2312
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002313 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002314 struct PartiallyConstructedSafepointRecord &info = records[i];
2315 CallSite &CS = toUpdate[i];
2316
2317 rematerializeLiveValues(CS, info, TTI);
2318 }
2319
Philip Reamesd16a9b12015-02-20 01:06:44 +00002320 // Now run through and replace the existing statepoints with new ones with
2321 // the live variables listed. We do not yet update uses of the values being
2322 // relocated. We have references to live variables that need to
2323 // survive to the last iteration of this loop. (By construction, the
2324 // previous statepoint can not be a live variable, thus we can and remove
2325 // the old statepoint calls as we go.)
2326 for (size_t i = 0; i < records.size(); i++) {
2327 struct PartiallyConstructedSafepointRecord &info = records[i];
2328 CallSite &CS = toUpdate[i];
2329 makeStatepointExplicit(DT, CS, P, info);
2330 }
2331 toUpdate.clear(); // prevent accident use of invalid CallSites
2332
Philip Reamesd16a9b12015-02-20 01:06:44 +00002333 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002334 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002335 for (size_t i = 0; i < records.size(); i++) {
2336 struct PartiallyConstructedSafepointRecord &info = records[i];
2337 // We can't simply save the live set from the original insertion. One of
2338 // the live values might be the result of a call which needs a safepoint.
2339 // That Value* no longer exists and we need to use the new gc_result.
2340 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2341 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002342 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002343 live.insert(live.end(), statepoint.gc_args_begin(),
2344 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002345#ifndef NDEBUG
2346 // Do some basic sanity checks on our liveness results before performing
2347 // relocation. Relocation can and will turn mistakes in liveness results
2348 // into non-sensical code which is must harder to debug.
2349 // TODO: It would be nice to test consistency as well
2350 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2351 "statepoint must be reachable or liveness is meaningless");
2352 for (Value *V : statepoint.gc_args()) {
2353 if (!isa<Instruction>(V))
2354 // Non-instruction values trivial dominate all possible uses
2355 continue;
2356 auto LiveInst = cast<Instruction>(V);
2357 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2358 "unreachable values should never be live");
2359 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2360 "basic SSA liveness expectation violated by liveness analysis");
2361 }
2362#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002363 }
2364 unique_unsorted(live);
2365
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002366#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002367 // sanity check
2368 for (auto ptr : live) {
2369 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2370 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002371#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002372
2373 relocationViaAlloca(F, DT, live, records);
2374 return !records.empty();
2375}
2376
Sanjoy Das353a19e2015-06-02 22:33:37 +00002377// Handles both return values and arguments for Functions and CallSites.
2378template <typename AttrHolder>
2379static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2380 unsigned Index) {
2381 AttrBuilder R;
2382 if (AH.getDereferenceableBytes(Index))
2383 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2384 AH.getDereferenceableBytes(Index)));
2385 if (AH.getDereferenceableOrNullBytes(Index))
2386 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2387 AH.getDereferenceableOrNullBytes(Index)));
2388
2389 if (!R.empty())
2390 AH.setAttributes(AH.getAttributes().removeAttributes(
2391 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002392}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002393
2394void
2395RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2396 LLVMContext &Ctx = F.getContext();
2397
2398 for (Argument &A : F.args())
2399 if (isa<PointerType>(A.getType()))
2400 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2401
2402 if (isa<PointerType>(F.getReturnType()))
2403 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2404}
2405
2406void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2407 if (F.empty())
2408 return;
2409
2410 LLVMContext &Ctx = F.getContext();
2411 MDBuilder Builder(Ctx);
2412
Nico Rieck78199512015-08-06 19:10:45 +00002413 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002414 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2415 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2416 bool IsImmutableTBAA =
2417 MD->getNumOperands() == 4 &&
2418 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2419
2420 if (!IsImmutableTBAA)
2421 continue; // no work to do, MD_tbaa is already marked mutable
2422
2423 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2424 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2425 uint64_t Offset =
2426 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2427
2428 MDNode *MutableTBAA =
2429 Builder.createTBAAStructTagNode(Base, Access, Offset);
2430 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2431 }
2432
2433 if (CallSite CS = CallSite(&I)) {
2434 for (int i = 0, e = CS.arg_size(); i != e; i++)
2435 if (isa<PointerType>(CS.getArgument(i)->getType()))
2436 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2437 if (isa<PointerType>(CS.getType()))
2438 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2439 }
2440 }
2441}
2442
Philip Reamesd16a9b12015-02-20 01:06:44 +00002443/// Returns true if this function should be rewritten by this pass. The main
2444/// point of this function is as an extension point for custom logic.
2445static bool shouldRewriteStatepointsIn(Function &F) {
2446 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002447 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002448 const char *FunctionGCName = F.getGC();
2449 const StringRef StatepointExampleName("statepoint-example");
2450 const StringRef CoreCLRName("coreclr");
2451 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002452 (CoreCLRName == FunctionGCName);
2453 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002454 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002455}
2456
Sanjoy Das353a19e2015-06-02 22:33:37 +00002457void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2458#ifndef NDEBUG
2459 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2460 "precondition!");
2461#endif
2462
2463 for (Function &F : M)
2464 stripDereferenceabilityInfoFromPrototype(F);
2465
2466 for (Function &F : M)
2467 stripDereferenceabilityInfoFromBody(F);
2468}
2469
Philip Reamesd16a9b12015-02-20 01:06:44 +00002470bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2471 // Nothing to do for declarations.
2472 if (F.isDeclaration() || F.empty())
2473 return false;
2474
2475 // Policy choice says not to rewrite - the most common reason is that we're
2476 // compiling code without a GCStrategy.
2477 if (!shouldRewriteStatepointsIn(F))
2478 return false;
2479
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002480 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002481
Philip Reames85b36a82015-04-10 22:07:04 +00002482 // Gather all the statepoints which need rewritten. Be careful to only
2483 // consider those in reachable code since we need to ask dominance queries
2484 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002485 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002486 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002487 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002488 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002489 if (isStatepoint(I)) {
2490 if (DT.isReachableFromEntry(I.getParent()))
2491 ParsePointNeeded.push_back(CallSite(&I));
2492 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002493 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002494 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002495 }
2496
Philip Reames85b36a82015-04-10 22:07:04 +00002497 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002498
Philip Reames85b36a82015-04-10 22:07:04 +00002499 // Delete any unreachable statepoints so that we don't have unrewritten
2500 // statepoints surviving this pass. This makes testing easier and the
2501 // resulting IR less confusing to human readers. Rather than be fancy, we
2502 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002503 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002504 MadeChange |= removeUnreachableBlocks(F);
2505
Philip Reamesd16a9b12015-02-20 01:06:44 +00002506 // Return early if no work to do.
2507 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002508 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002509
Philip Reames85b36a82015-04-10 22:07:04 +00002510 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2511 // These are created by LCSSA. They have the effect of increasing the size
2512 // of liveness sets for no good reason. It may be harder to do this post
2513 // insertion since relocations and base phis can confuse things.
2514 for (BasicBlock &BB : F)
2515 if (BB.getUniquePredecessor()) {
2516 MadeChange = true;
2517 FoldSingleEntryPHINodes(&BB);
2518 }
2519
Philip Reames971dc3a2015-08-12 22:11:45 +00002520 // Before we start introducing relocations, we want to tweak the IR a bit to
2521 // avoid unfortunate code generation effects. The main example is that we
2522 // want to try to make sure the comparison feeding a branch is after any
2523 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2524 // values feeding a branch after relocation. This is semantically correct,
2525 // but results in extra register pressure since both the pre-relocation and
2526 // post-relocation copies must be available in registers. For code without
2527 // relocations this is handled elsewhere, but teaching the scheduler to
2528 // reverse the transform we're about to do would be slightly complex.
2529 // Note: This may extend the live range of the inputs to the icmp and thus
2530 // increase the liveset of any statepoint we move over. This is profitable
2531 // as long as all statepoints are in rare blocks. If we had in-register
2532 // lowering for live values this would be a much safer transform.
2533 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2534 if (auto *BI = dyn_cast<BranchInst>(TI))
2535 if (BI->isConditional())
2536 return dyn_cast<Instruction>(BI->getCondition());
2537 // TODO: Extend this to handle switches
2538 return nullptr;
2539 };
2540 for (BasicBlock &BB : F) {
2541 TerminatorInst *TI = BB.getTerminator();
2542 if (auto *Cond = getConditionInst(TI))
2543 // TODO: Handle more than just ICmps here. We should be able to move
2544 // most instructions without side effects or memory access.
2545 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2546 MadeChange = true;
2547 Cond->moveBefore(TI);
2548 }
2549 }
2550
Philip Reames85b36a82015-04-10 22:07:04 +00002551 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2552 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002553}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002554
2555// liveness computation via standard dataflow
2556// -------------------------------------------------------------------
2557
2558// TODO: Consider using bitvectors for liveness, the set of potentially
2559// interesting values should be small and easy to pre-compute.
2560
Philip Reamesdf1ef082015-04-10 22:53:14 +00002561/// Compute the live-in set for the location rbegin starting from
2562/// the live-out set of the basic block
2563static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2564 BasicBlock::reverse_iterator rend,
2565 DenseSet<Value *> &LiveTmp) {
2566
2567 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2568 Instruction *I = &*ritr;
2569
2570 // KILL/Def - Remove this definition from LiveIn
2571 LiveTmp.erase(I);
2572
2573 // Don't consider *uses* in PHI nodes, we handle their contribution to
2574 // predecessor blocks when we seed the LiveOut sets
2575 if (isa<PHINode>(I))
2576 continue;
2577
2578 // USE - Add to the LiveIn set for this instruction
2579 for (Value *V : I->operands()) {
2580 assert(!isUnhandledGCPointerType(V->getType()) &&
2581 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002582 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2583 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002584 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002585 // - We assume that things which are constant (from LLVM's definition)
2586 // do not move at runtime. For example, the address of a global
2587 // variable is fixed, even though it's contents may not be.
2588 // - Second, we can't disallow arbitrary inttoptr constants even
2589 // if the language frontend does. Optimization passes are free to
2590 // locally exploit facts without respect to global reachability. This
2591 // can create sections of code which are dynamically unreachable and
2592 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002593 LiveTmp.insert(V);
2594 }
2595 }
2596 }
2597}
2598
2599static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2600
2601 for (BasicBlock *Succ : successors(BB)) {
2602 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2603 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2604 PHINode *Phi = cast<PHINode>(&*I);
2605 Value *V = Phi->getIncomingValueForBlock(BB);
2606 assert(!isUnhandledGCPointerType(V->getType()) &&
2607 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002608 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002609 LiveTmp.insert(V);
2610 }
2611 }
2612 }
2613}
2614
2615static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2616 DenseSet<Value *> KillSet;
2617 for (Instruction &I : *BB)
2618 if (isHandledGCPointerType(I.getType()))
2619 KillSet.insert(&I);
2620 return KillSet;
2621}
2622
Philip Reames9638ff92015-04-11 00:06:47 +00002623#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002624/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2625/// sanity check for the liveness computation.
2626static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2627 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002628 for (Value *V : Live) {
2629 if (auto *I = dyn_cast<Instruction>(V)) {
2630 // The terminator can be a member of the LiveOut set. LLVM's definition
2631 // of instruction dominance states that V does not dominate itself. As
2632 // such, we need to special case this to allow it.
2633 if (TermOkay && TI == I)
2634 continue;
2635 assert(DT.dominates(I, TI) &&
2636 "basic SSA liveness expectation violated by liveness analysis");
2637 }
2638 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002639}
2640
2641/// Check that all the liveness sets used during the computation of liveness
2642/// obey basic SSA properties. This is useful for finding cases where we miss
2643/// a def.
2644static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2645 BasicBlock &BB) {
2646 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2647 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2648 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2649}
Philip Reames9638ff92015-04-11 00:06:47 +00002650#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002651
2652static void computeLiveInValues(DominatorTree &DT, Function &F,
2653 GCPtrLivenessData &Data) {
2654
Philip Reames4d80ede2015-04-10 23:11:26 +00002655 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002656 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002657 // We use a SetVector so that we don't have duplicates in the worklist.
2658 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002659 };
2660 auto NextItem = [&]() {
2661 BasicBlock *BB = Worklist.back();
2662 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002663 return BB;
2664 };
2665
2666 // Seed the liveness for each individual block
2667 for (BasicBlock &BB : F) {
2668 Data.KillSet[&BB] = computeKillSet(&BB);
2669 Data.LiveSet[&BB].clear();
2670 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2671
2672#ifndef NDEBUG
2673 for (Value *Kill : Data.KillSet[&BB])
2674 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2675#endif
2676
2677 Data.LiveOut[&BB] = DenseSet<Value *>();
2678 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2679 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2680 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2681 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2682 if (!Data.LiveIn[&BB].empty())
2683 AddPredsToWorklist(&BB);
2684 }
2685
2686 // Propagate that liveness until stable
2687 while (!Worklist.empty()) {
2688 BasicBlock *BB = NextItem();
2689
2690 // Compute our new liveout set, then exit early if it hasn't changed
2691 // despite the contribution of our successor.
2692 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2693 const auto OldLiveOutSize = LiveOut.size();
2694 for (BasicBlock *Succ : successors(BB)) {
2695 assert(Data.LiveIn.count(Succ));
2696 set_union(LiveOut, Data.LiveIn[Succ]);
2697 }
2698 // assert OutLiveOut is a subset of LiveOut
2699 if (OldLiveOutSize == LiveOut.size()) {
2700 // If the sets are the same size, then we didn't actually add anything
2701 // when unioning our successors LiveIn Thus, the LiveIn of this block
2702 // hasn't changed.
2703 continue;
2704 }
2705 Data.LiveOut[BB] = LiveOut;
2706
2707 // Apply the effects of this basic block
2708 DenseSet<Value *> LiveTmp = LiveOut;
2709 set_union(LiveTmp, Data.LiveSet[BB]);
2710 set_subtract(LiveTmp, Data.KillSet[BB]);
2711
2712 assert(Data.LiveIn.count(BB));
2713 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2714 // assert: OldLiveIn is a subset of LiveTmp
2715 if (OldLiveIn.size() != LiveTmp.size()) {
2716 Data.LiveIn[BB] = LiveTmp;
2717 AddPredsToWorklist(BB);
2718 }
2719 } // while( !worklist.empty() )
2720
2721#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002722 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002723 // missing kills during the above iteration.
2724 for (BasicBlock &BB : F) {
2725 checkBasicSSA(DT, Data, BB);
2726 }
2727#endif
2728}
2729
2730static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2731 StatepointLiveSetTy &Out) {
2732
2733 BasicBlock *BB = Inst->getParent();
2734
2735 // Note: The copy is intentional and required
2736 assert(Data.LiveOut.count(BB));
2737 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2738
2739 // We want to handle the statepoint itself oddly. It's
2740 // call result is not live (normal), nor are it's arguments
2741 // (unless they're used again later). This adjustment is
2742 // specifically what we need to relocate
2743 BasicBlock::reverse_iterator rend(Inst);
2744 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2745 LiveOut.erase(Inst);
2746 Out.insert(LiveOut.begin(), LiveOut.end());
2747}
2748
2749static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2750 const CallSite &CS,
2751 PartiallyConstructedSafepointRecord &Info) {
2752 Instruction *Inst = CS.getInstruction();
2753 StatepointLiveSetTy Updated;
2754 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2755
2756#ifndef NDEBUG
2757 DenseSet<Value *> Bases;
2758 for (auto KVPair : Info.PointerToBase) {
2759 Bases.insert(KVPair.second);
2760 }
2761#endif
2762 // We may have base pointers which are now live that weren't before. We need
2763 // to update the PointerToBase structure to reflect this.
2764 for (auto V : Updated)
2765 if (!Info.PointerToBase.count(V)) {
2766 assert(Bases.count(V) && "can't find base for unexpected live value");
2767 Info.PointerToBase[V] = V;
2768 continue;
2769 }
2770
2771#ifndef NDEBUG
2772 for (auto V : Updated) {
2773 assert(Info.PointerToBase.count(V) &&
2774 "must be able to find base for live value");
2775 }
2776#endif
2777
2778 // Remove any stale base mappings - this can happen since our liveness is
2779 // more precise then the one inherent in the base pointer analysis
2780 DenseSet<Value *> ToErase;
2781 for (auto KVPair : Info.PointerToBase)
2782 if (!Updated.count(KVPair.first))
2783 ToErase.insert(KVPair.first);
2784 for (auto V : ToErase)
2785 Info.PointerToBase.erase(V);
2786
2787#ifndef NDEBUG
2788 for (auto KVPair : Info.PointerToBase)
2789 assert(Updated.count(KVPair.first) && "record for non-live value");
2790#endif
2791
2792 Info.liveset = Updated;
2793}