blob: b8b739644856b1c2c28692cdf7ec68bffd6077ed [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 Reamesf5b8e472015-09-03 21:34:30 +0000290static bool isKnownBaseResult(Value *V);
291namespace {
292/// A single base defining value - An immediate base defining value for an
293/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
294/// For instructions which have multiple pointer [vector] inputs or that
295/// transition between vector and scalar types, there is no immediate base
296/// defining value. The 'base defining value' for 'Def' is the transitive
297/// closure of this relation stopping at the first instruction which has no
298/// immediate base defining value. The b.d.v. might itself be a base pointer,
299/// but it can also be an arbitrary derived pointer.
300struct BaseDefiningValueResult {
301 /// Contains the value which is the base defining value.
302 Value * const BDV;
303 /// True if the base defining value is also known to be an actual base
304 /// pointer.
305 const bool IsKnownBase;
306 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
307 : BDV(BDV), IsKnownBase(IsKnownBase) {
308#ifndef NDEBUG
309 // Check consistency between new and old means of checking whether a BDV is
310 // a base.
311 bool MustBeBase = isKnownBaseResult(BDV);
312 assert(!MustBeBase || MustBeBase == IsKnownBase);
313#endif
314 }
315};
316}
317
318static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000319
Philip Reames8fe7f132015-06-26 22:47:37 +0000320/// Return a base defining value for the 'Index' element of the given vector
321/// instruction 'I'. If Index is null, returns a BDV for the entire vector
322/// 'I'. As an optimization, this method will try to determine when the
323/// element is known to already be a base pointer. If this can be established,
324/// the second value in the returned pair will be true. Note that either a
325/// vector or a pointer typed value can be returned. For the former, the
326/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
327/// If the later, the return pointer is a BDV (or possibly a base) for the
328/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000329static BaseDefiningValueResult
Philip Reames8fe7f132015-06-26 22:47:37 +0000330findBaseDefiningValueOfVector(Value *I, Value *Index = nullptr) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000331 assert(I->getType()->isVectorTy() &&
332 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
333 "Illegal to ask for the base pointer of a non-pointer type");
334
335 // Each case parallels findBaseDefiningValue below, see that code for
336 // detailed motivation.
337
338 if (isa<Argument>(I))
339 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000340 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000341
342 // We shouldn't see the address of a global as a vector value?
343 assert(!isa<GlobalVariable>(I) &&
344 "unexpected global variable found in base of vector");
345
346 // inlining could possibly introduce phi node that contains
347 // undef if callee has multiple returns
348 if (isa<UndefValue>(I))
349 // utterly meaningless, but useful for dealing with partially optimized
350 // code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000351 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000352
353 // Due to inheritance, this must be _after_ the global variable and undef
354 // checks
355 if (Constant *Con = dyn_cast<Constant>(I)) {
356 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
357 "order of checks wrong!");
358 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000359 return BaseDefiningValueResult(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000360 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000361
Philip Reames8531d8c2015-04-10 21:48:25 +0000362 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000363 return BaseDefiningValueResult(I, true);
Philip Reames8fe7f132015-06-26 22:47:37 +0000364
Philip Reames311f7102015-05-12 22:19:52 +0000365 // For an insert element, we might be able to look through it if we know
Philip Reames8fe7f132015-06-26 22:47:37 +0000366 // something about the indexes.
Philip Reames311f7102015-05-12 22:19:52 +0000367 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000368 if (Index) {
369 Value *InsertIndex = IEI->getOperand(2);
370 // This index is inserting the value, look for its BDV
371 if (InsertIndex == Index)
Philip Reamesf5b8e472015-09-03 21:34:30 +0000372 return findBaseDefiningValue(IEI->getOperand(1));
Philip Reames8fe7f132015-06-26 22:47:37 +0000373 // Both constant, and can't be equal per above. This insert is definitely
374 // not relevant, look back at the rest of the vector and keep trying.
375 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
376 return findBaseDefiningValueOfVector(IEI->getOperand(0), Index);
377 }
Philip Reamesf5b8e472015-09-03 21:34:30 +0000378
379 // If both inputs to the insertelement are known bases, then so is the
380 // insertelement itself. NOTE: This should be handled within the generic
381 // base pointer inference code and after http://reviews.llvm.org/D12583,
382 // will be. However, when strengthening asserts I needed to add this to
383 // keep an existing test passing which was 'working'. FIXME
384 if (findBaseDefiningValue(IEI->getOperand(0)).IsKnownBase &&
385 findBaseDefiningValue(IEI->getOperand(1)).IsKnownBase)
386 return BaseDefiningValueResult(IEI, true);
Philip Reames8fe7f132015-06-26 22:47:37 +0000387
388 // We don't know whether this vector contains entirely base pointers or
389 // not. To be conservatively correct, we treat it as a BDV and will
390 // duplicate code as needed to construct a parallel vector of bases.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000391 return BaseDefiningValueResult(IEI, false);
Philip Reames311f7102015-05-12 22:19:52 +0000392 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000393
Philip Reames8fe7f132015-06-26 22:47:37 +0000394 if (isa<ShuffleVectorInst>(I))
395 // We don't know whether this vector contains entirely base pointers or
396 // not. To be conservatively correct, we treat it as a BDV and will
397 // duplicate code as needed to construct a parallel vector of bases.
398 // TODO: There a number of local optimizations which could be applied here
399 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000400 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000401
402 // A PHI or Select is a base defining value. The outer findBasePointer
403 // algorithm is responsible for constructing a base value for this BDV.
404 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
405 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000406 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000407}
408
Philip Reamesd16a9b12015-02-20 01:06:44 +0000409/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000410/// defines the base pointer for the input, b) blocks the simple search
411/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
412/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000413static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000414 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000415 return findBaseDefiningValueOfVector(I);
Philip Reames8fe7f132015-06-26 22:47:37 +0000416
Philip Reamesd16a9b12015-02-20 01:06:44 +0000417 assert(I->getType()->isPointerTy() &&
418 "Illegal to ask for the base pointer of a non-pointer type");
419
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000420 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000421 // An incoming argument to the function is a base pointer
422 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000423 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000424
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000425 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000426 // base case
Philip Reamesf5b8e472015-09-03 21:34:30 +0000427 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000428
429 // inlining could possibly introduce phi node that contains
430 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000431 if (isa<UndefValue>(I))
432 // utterly meaningless, but useful for dealing with
433 // partially optimized code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000434 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000435
436 // Due to inheritance, this must be _after_ the global variable and undef
437 // checks
Philip Reames3ea15892015-09-03 21:57:40 +0000438 if (isa<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000439 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
440 "order of checks wrong!");
441 // Note: Finding a constant base for something marked for relocation
442 // doesn't really make sense. The most likely case is either a) some
443 // screwed up the address space usage or b) your validating against
444 // compiled C++ code w/o the proper separation. The only real exception
445 // is a null pointer. You could have generic code written to index of
446 // off a potentially null value and have proven it null. We also use
447 // null pointers in dead paths of relocation phis (which we might later
448 // want to find a base pointer for).
Philip Reames3ea15892015-09-03 21:57:40 +0000449 assert(isa<ConstantPointerNull>(I) &&
Philip Reames24c6cd52015-03-27 05:47:00 +0000450 "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000451 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000452 }
453
454 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000455 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000456 // If we find a cast instruction here, it means we've found a cast which is
457 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
458 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000459 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
460 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000461 }
462
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000463 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000464 // The value loaded is an gc base itself
465 return BaseDefiningValueResult(I, true);
466
Philip Reamesd16a9b12015-02-20 01:06:44 +0000467
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000468 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
469 // The base of this GEP is the base
470 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000471
472 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
473 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000474 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000475 default:
476 // fall through to general call handling
477 break;
478 case Intrinsic::experimental_gc_statepoint:
479 case Intrinsic::experimental_gc_result_float:
480 case Intrinsic::experimental_gc_result_int:
481 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000482 case Intrinsic::experimental_gc_relocate: {
483 // Rerunning safepoint insertion after safepoints are already
484 // inserted is not supported. It could probably be made to work,
485 // but why are you doing this? There's no good reason.
486 llvm_unreachable("repeat safepoint insertion is not supported");
487 }
488 case Intrinsic::gcroot:
489 // Currently, this mechanism hasn't been extended to work with gcroot.
490 // There's no reason it couldn't be, but I haven't thought about the
491 // implications much.
492 llvm_unreachable(
493 "interaction with the gcroot mechanism is not supported");
494 }
495 }
496 // We assume that functions in the source language only return base
497 // pointers. This should probably be generalized via attributes to support
498 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000499 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000500 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000501
502 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000503 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000504 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
505
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000506 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000507 // A CAS is effectively a atomic store and load combined under a
508 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000509 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000510 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000511
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000512 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000513 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000514
515 // The aggregate ops. Aggregates can either be in the heap or on the
516 // stack, but in either case, this is simply a field load. As a result,
517 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000518 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000519 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000520
521 // We should never see an insert vector since that would require we be
522 // tracing back a struct value not a pointer value.
523 assert(!isa<InsertValueInst>(I) &&
524 "Base pointer for a struct is meaningless");
525
Philip Reames9ac4e382015-08-12 21:00:20 +0000526 // An extractelement produces a base result exactly when it's input does.
527 // We may need to insert a parallel instruction to extract the appropriate
528 // element out of the base vector corresponding to the input. Given this,
529 // it's analogous to the phi and select case even though it's not a merge.
530 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
531 Value *VectorOperand = EEI->getVectorOperand();
532 Value *Index = EEI->getIndexOperand();
Philip Reamesf5b8e472015-09-03 21:34:30 +0000533 auto VecResult = findBaseDefiningValueOfVector(VectorOperand, Index);
534 Value *VectorBase = VecResult.BDV;
Philip Reames9ac4e382015-08-12 21:00:20 +0000535 if (VectorBase->getType()->isPointerTy())
536 // We found a BDV for this specific element with the vector. This is an
537 // optimization, but in practice it covers most of the useful cases
538 // created via scalarization. Note: The peephole optimization here is
539 // currently needed for correctness since the general algorithm doesn't
540 // yet handle insertelements. That will change shortly.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000541 return BaseDefiningValueResult(VectorBase, VecResult.IsKnownBase);
Philip Reames9ac4e382015-08-12 21:00:20 +0000542 else {
543 assert(VectorBase->getType()->isVectorTy());
544 // Otherwise, we have an instruction which potentially produces a
545 // derived pointer and we need findBasePointers to clone code for us
546 // such that we can create an instruction which produces the
547 // accompanying base pointer.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000548 return BaseDefiningValueResult(I, VecResult.IsKnownBase);
Philip Reames9ac4e382015-08-12 21:00:20 +0000549 }
550 }
551
Philip Reamesd16a9b12015-02-20 01:06:44 +0000552 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000553 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000554 // derived pointers (each with it's own base potentially). It's the job of
555 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000556 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000557 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000558 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000559}
560
561/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000562static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
563 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000564 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000565 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000566 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
567 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000568 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000569 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000570 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000571}
572
573/// Return a base pointer for this value if known. Otherwise, return it's
574/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000575static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
576 Value *Def = findBaseDefiningValueCached(I, Cache);
577 auto Found = Cache.find(Def);
578 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000579 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000580 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000581 }
582 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000583 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000584}
585
586/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
587/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000588static bool isKnownBaseResult(Value *V) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000589 if (!isa<PHINode>(V) && !isa<SelectInst>(V) && !isa<ExtractElementInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000590 // no recursion possible
591 return true;
592 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000593 if (isa<Instruction>(V) &&
594 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000595 // This is a previously inserted base phi or select. We know
596 // that this is a base value.
597 return true;
598 }
599
600 // We need to keep searching
601 return false;
602}
603
Philip Reamesd16a9b12015-02-20 01:06:44 +0000604namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000605/// Models the state of a single base defining value in the findBasePointer
606/// algorithm for determining where a new instruction is needed to propagate
607/// the base of this BDV.
608class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000609public:
610 enum Status { Unknown, Base, Conflict };
611
Philip Reames9b141ed2015-07-23 22:49:14 +0000612 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000613 assert(status != Base || b);
614 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000615 explicit BDVState(Value *b) : status(Base), base(b) {}
616 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000617
618 Status getStatus() const { return status; }
619 Value *getBase() const { return base; }
620
621 bool isBase() const { return getStatus() == Base; }
622 bool isUnknown() const { return getStatus() == Unknown; }
623 bool isConflict() const { return getStatus() == Conflict; }
624
Philip Reames9b141ed2015-07-23 22:49:14 +0000625 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000626 return base == other.base && status == other.status;
627 }
628
Philip Reames9b141ed2015-07-23 22:49:14 +0000629 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000630
Philip Reames2a892a62015-07-23 22:25:26 +0000631 LLVM_DUMP_METHOD
632 void dump() const { print(dbgs()); dbgs() << '\n'; }
633
634 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000635 switch (status) {
636 case Unknown:
637 OS << "U";
638 break;
639 case Base:
640 OS << "B";
641 break;
642 case Conflict:
643 OS << "C";
644 break;
645 };
646 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000647 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000648 }
649
650private:
651 Status status;
652 Value *base; // non null only if status == base
653};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000654}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000655
Philip Reames6906e922015-09-02 21:57:17 +0000656#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000657static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000658 State.print(OS);
659 return OS;
660}
Philip Reames6906e922015-09-02 21:57:17 +0000661#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000662
Philip Reamesb3967cd2015-09-02 22:30:53 +0000663namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000664typedef DenseMap<Value *, BDVState> ConflictStateMapTy;
665// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000666// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000667// operation is implemented in MeetBDVStates::pureMeet
668class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000669public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000670 /// Initializes the currentResult to the TOP state so that if can be met with
671 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000672 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000673
Philip Reames9b141ed2015-07-23 22:49:14 +0000674 // Destructively meet the current result with the given BDVState
675 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000676 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000677 }
678
Philip Reames9b141ed2015-07-23 22:49:14 +0000679 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000680
681private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000682 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000683
Philip Reames9b141ed2015-07-23 22:49:14 +0000684 /// Perform a meet operation on two elements of the BDVState lattice.
685 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000686 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
687 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000688 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000689 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
690 << " produced " << Result << "\n");
691 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000692 }
693
Philip Reames9b141ed2015-07-23 22:49:14 +0000694 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000695 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000696 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000697 return stateB;
698
Philip Reames9b141ed2015-07-23 22:49:14 +0000699 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000700 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000701 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000702 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000703
704 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000705 if (stateA.getBase() == stateB.getBase()) {
706 assert(stateA == stateB && "equality broken!");
707 return stateA;
708 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000709 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000710 }
David Blaikie82ad7872015-02-20 23:44:24 +0000711 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000712 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000713
Philip Reames9b141ed2015-07-23 22:49:14 +0000714 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000715 return stateA;
716 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000717 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000718 }
719};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000720}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000721
722
Philip Reamesd16a9b12015-02-20 01:06:44 +0000723/// For a given value or instruction, figure out what base ptr it's derived
724/// from. For gc objects, this is simply itself. On success, returns a value
725/// which is the base pointer. (This is reliable and can be used for
726/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000727static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000728 Value *def = findBaseOrBDV(I, cache);
729
730 if (isKnownBaseResult(def)) {
731 return def;
732 }
733
734 // Here's the rough algorithm:
735 // - For every SSA value, construct a mapping to either an actual base
736 // pointer or a PHI which obscures the base pointer.
737 // - Construct a mapping from PHI to unknown TOP state. Use an
738 // optimistic algorithm to propagate base pointer information. Lattice
739 // looks like:
740 // UNKNOWN
741 // b1 b2 b3 b4
742 // CONFLICT
743 // When algorithm terminates, all PHIs will either have a single concrete
744 // base or be in a conflict state.
745 // - For every conflict, insert a dummy PHI node without arguments. Add
746 // these to the base[Instruction] = BasePtr mapping. For every
747 // non-conflict, add the actual base.
748 // - For every conflict, add arguments for the base[a] of each input
749 // arguments.
750 //
751 // Note: A simpler form of this would be to add the conflict form of all
752 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000753 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000754 // overall worse solution.
755
Philip Reames29e9ae72015-07-24 00:42:55 +0000756#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000757 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000758 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) || isa<ExtractElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000759 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000760#endif
Philip Reames88958b22015-07-24 00:02:11 +0000761
762 // Once populated, will contain a mapping from each potentially non-base BDV
763 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames860660e2015-02-20 22:05:18 +0000764 ConflictStateMapTy states;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000765 // Recursively fill in all phis & selects reachable from the initial one
766 // for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000767 /* scope */ {
768 DenseSet<Value *> Visited;
769 SmallVector<Value*, 16> Worklist;
770 Worklist.push_back(def);
771 Visited.insert(def);
772 while (!Worklist.empty()) {
773 Value *Current = Worklist.pop_back_val();
774 assert(!isKnownBaseResult(Current) && "why did it get added?");
775
776 auto visitIncomingValue = [&](Value *InVal) {
777 Value *Base = findBaseOrBDV(InVal, cache);
778 if (isKnownBaseResult(Base))
779 // Known bases won't need new instructions introduced and can be
780 // ignored safely
781 return;
782 assert(isExpectedBDVType(Base) && "the only non-base values "
783 "we see should be base defining values");
784 if (Visited.insert(Base).second)
785 Worklist.push_back(Base);
786 };
787 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
788 for (Value *InVal : Phi->incoming_values())
789 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000790 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000791 visitIncomingValue(Sel->getTrueValue());
792 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000793 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
794 visitIncomingValue(EE->getVectorOperand());
795 } else {
796 // There are two classes of instructions we know we don't handle.
797 assert(isa<ShuffleVectorInst>(Current) ||
798 isa<InsertElementInst>(Current));
799 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000800 }
801 }
Philip Reames88958b22015-07-24 00:02:11 +0000802 // The frontier of visited instructions are the ones we might need to
803 // duplicate, so fill in the starting state for the optimistic algorithm
804 // that follows.
805 for (Value *BDV : Visited) {
806 states[BDV] = BDVState();
807 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000808 }
809
Philip Reamesdab35f32015-09-02 21:11:44 +0000810#ifndef NDEBUG
811 DEBUG(dbgs() << "States after initialization:\n");
812 for (auto Pair : states) {
813 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000814 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000815#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000816
Philip Reames273e6bb2015-07-23 21:41:27 +0000817 // Return a phi state for a base defining value. We'll generate a new
818 // base state for known bases and expect to find a cached state otherwise.
819 auto getStateForBDV = [&](Value *baseValue) {
820 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000821 return BDVState(baseValue);
Philip Reames273e6bb2015-07-23 21:41:27 +0000822 auto I = states.find(baseValue);
823 assert(I != states.end() && "lookup failed!");
824 return I->second;
825 };
826
Philip Reamesd16a9b12015-02-20 01:06:44 +0000827 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000828 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000829#ifndef NDEBUG
830 size_t oldSize = states.size();
831#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000832 progress = false;
Philip Reamesa226e612015-02-28 00:47:50 +0000833 // We're only changing keys in this loop, thus safe to keep iterators
Philip Reamesd16a9b12015-02-20 01:06:44 +0000834 for (auto Pair : states) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000835 Value *v = Pair.first;
836 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000837
Philip Reames9b141ed2015-07-23 22:49:14 +0000838 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000839 // instance which represents the BDV of that value.
840 auto getStateForInput = [&](Value *V) mutable {
841 Value *BDV = findBaseOrBDV(V, cache);
842 return getStateForBDV(BDV);
843 };
844
Philip Reames9b141ed2015-07-23 22:49:14 +0000845 MeetBDVStates calculateMeet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000846 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000847 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
848 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reames9ac4e382015-08-12 21:00:20 +0000849 } else if (PHINode *Phi = dyn_cast<PHINode>(v)) {
850 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000851 calculateMeet.meetWith(getStateForInput(Val));
Philip Reames9ac4e382015-08-12 21:00:20 +0000852 } else {
853 // The 'meet' for an extractelement is slightly trivial, but it's still
854 // useful in that it drives us to conflict if our input is.
855 auto *EE = cast<ExtractElementInst>(v);
856 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
857 }
858
Philip Reamesd16a9b12015-02-20 01:06:44 +0000859
Philip Reames9b141ed2015-07-23 22:49:14 +0000860 BDVState oldState = states[v];
861 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000862 if (oldState != newState) {
863 progress = true;
864 states[v] = newState;
865 }
866 }
867
868 assert(oldSize <= states.size());
869 assert(oldSize == states.size() || progress);
870 }
871
Philip Reamesdab35f32015-09-02 21:11:44 +0000872#ifndef NDEBUG
873 DEBUG(dbgs() << "States after meet iteration:\n");
874 for (auto Pair : states) {
875 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000876 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000877#endif
878
Philip Reamesd16a9b12015-02-20 01:06:44 +0000879 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000880 // We want to keep naming deterministic in the loop that follows, so
881 // sort the keys before iteration. This is useful in allowing us to
882 // write stable tests. Note that there is no invalidation issue here.
Philip Reames704e78b2015-04-10 22:34:56 +0000883 SmallVector<Value *, 16> Keys;
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000884 Keys.reserve(states.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000885 for (auto Pair : states) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000886 Value *V = Pair.first;
887 Keys.push_back(V);
888 }
889 std::sort(Keys.begin(), Keys.end(), order_by_name);
890 // TODO: adjust naming patterns to avoid this order of iteration dependency
891 for (Value *V : Keys) {
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000892 Instruction *I = cast<Instruction>(V);
Philip Reames9b141ed2015-07-23 22:49:14 +0000893 BDVState State = states[I];
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000894 assert(!isKnownBaseResult(I) && "why did it get added?");
895 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000896
897 // extractelement instructions are a bit special in that we may need to
898 // insert an extract even when we know an exact base for the instruction.
899 // The problem is that we need to convert from a vector base to a scalar
900 // base for the particular indice we're interested in.
901 if (State.isBase() && isa<ExtractElementInst>(I) &&
902 isa<VectorType>(State.getBase()->getType())) {
903 auto *EE = cast<ExtractElementInst>(I);
904 // TODO: In many cases, the new instruction is just EE itself. We should
905 // exploit this, but can't do it here since it would break the invariant
906 // about the BDV not being known to be a base.
907 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
908 EE->getIndexOperand(),
909 "base_ee", EE);
910 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
911 states[I] = BDVState(BDVState::Base, BaseInst);
912 }
913
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000914 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000915 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000916
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000917 /// Create and insert a new instruction which will represent the base of
918 /// the given instruction 'I'.
919 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
920 if (isa<PHINode>(I)) {
921 BasicBlock *BB = I->getParent();
922 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
923 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000924 std::string Name = I->hasName() ?
925 (I->getName() + ".base").str() : "base_phi";
926 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000927 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
928 // The undef will be replaced later
929 UndefValue *Undef = UndefValue::get(Sel->getType());
930 std::string Name = I->hasName() ?
931 (I->getName() + ".base").str() : "base_select";
932 return SelectInst::Create(Sel->getCondition(), Undef,
933 Undef, Name, Sel);
934 } else {
935 auto *EE = cast<ExtractElementInst>(I);
936 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
937 std::string Name = I->hasName() ?
938 (I->getName() + ".base").str() : "base_ee";
939 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
940 EE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000941 }
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000942 };
943 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
944 // Add metadata marking this as a base value
945 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames9b141ed2015-07-23 22:49:14 +0000946 states[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000947 }
948
Philip Reames3ea15892015-09-03 21:57:40 +0000949 // Returns a instruction which produces the base pointer for a given
950 // instruction. The instruction is assumed to be an input to one of the BDVs
951 // seen in the inference algorithm above. As such, we must either already
952 // know it's base defining value is a base, or have inserted a new
953 // instruction to propagate the base of it's BDV and have entered that newly
954 // introduced instruction into the state table. In either case, we are
955 // assured to be able to determine an instruction which produces it's base
956 // pointer.
957 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
958 Value *BDV = findBaseOrBDV(Input, cache);
959 Value *Base = nullptr;
960 if (isKnownBaseResult(BDV)) {
961 Base = BDV;
962 } else {
963 // Either conflict or base.
964 assert(states.count(BDV));
965 Base = states[BDV].getBase();
966 }
967 assert(Base && "can't be null");
968 // The cast is needed since base traversal may strip away bitcasts
969 if (Base->getType() != Input->getType() &&
970 InsertPt) {
971 Base = new BitCastInst(Base, Input->getType(), "cast",
972 InsertPt);
973 }
974 return Base;
975 };
976
Philip Reamesd16a9b12015-02-20 01:06:44 +0000977 // Fixup all the inputs of the new PHIs
978 for (auto Pair : states) {
979 Instruction *v = cast<Instruction>(Pair.first);
Philip Reames9b141ed2015-07-23 22:49:14 +0000980 BDVState state = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000981
982 assert(!isKnownBaseResult(v) && "why did it get added?");
983 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000984 if (!state.isConflict())
985 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000986
Philip Reames28e61ce2015-02-28 01:57:44 +0000987 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
988 PHINode *phi = cast<PHINode>(v);
989 unsigned NumPHIValues = phi->getNumIncomingValues();
990 for (unsigned i = 0; i < NumPHIValues; i++) {
991 Value *InVal = phi->getIncomingValue(i);
992 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000993
Philip Reames28e61ce2015-02-28 01:57:44 +0000994 // If we've already seen InBB, add the same incoming value
995 // we added for it earlier. The IR verifier requires phi
996 // nodes with multiple entries from the same basic block
997 // to have the same incoming value for each of those
998 // entries. If we don't do this check here and basephi
999 // has a different type than base, we'll end up adding two
1000 // bitcasts (and hence two distinct values) as incoming
1001 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001002
Philip Reames28e61ce2015-02-28 01:57:44 +00001003 int blockIndex = basephi->getBasicBlockIndex(InBB);
1004 if (blockIndex != -1) {
1005 Value *oldBase = basephi->getIncomingValue(blockIndex);
1006 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +00001007
Philip Reamesd16a9b12015-02-20 01:06:44 +00001008#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +00001009 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001010 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +00001011 // values incoming from the same basic block may be
1012 // different is by being different bitcasts of the same
1013 // value. A cleanup that remains TODO is changing
1014 // findBaseOrBDV to return an llvm::Value of the correct
1015 // type (and still remain pure). This will remove the
1016 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +00001017 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +00001018 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001019#endif
Philip Reames28e61ce2015-02-28 01:57:44 +00001020 continue;
1021 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001022
Philip Reames3ea15892015-09-03 21:57:40 +00001023 // Find the instruction which produces the base for each input. We may
1024 // need to insert a bitcast in the incoming block.
1025 // TODO: Need to split critical edges if insertion is needed
1026 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1027 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001028 }
1029 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reames3ea15892015-09-03 21:57:40 +00001030 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(state.getBase())) {
1031 SelectInst *Sel = cast<SelectInst>(v);
Philip Reames28e61ce2015-02-28 01:57:44 +00001032 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1033 // something more safe and less hacky.
1034 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001035 Value *InVal = Sel->getOperand(i);
1036 // Find the instruction which produces the base for each input. We may
1037 // need to insert a bitcast.
1038 Value *Base = getBaseForInput(InVal, BaseSel);
1039 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001040 }
Philip Reames9ac4e382015-08-12 21:00:20 +00001041 } else {
1042 auto *BaseEE = cast<ExtractElementInst>(state.getBase());
1043 Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001044 // Find the instruction which produces the base for each input. We may
1045 // need to insert a bitcast.
1046 Value *Base = getBaseForInput(InVal, BaseEE);
Philip Reames9ac4e382015-08-12 21:00:20 +00001047 BaseEE->setOperand(0, Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001048 }
1049 }
1050
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001051 // Now that we're done with the algorithm, see if we can optimize the
1052 // results slightly by reducing the number of new instructions needed.
1053 // Arguably, this should be integrated into the algorithm above, but
1054 // doing as a post process step is easier to reason about for the moment.
1055 DenseMap<Value *, Value *> ReverseMap;
1056 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001057 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001058 // Note: We need to visit the states in a deterministic order. We uses the
1059 // Keys we sorted above for this purpose. Note that we are papering over a
1060 // bigger problem with the algorithm above - it's visit order is not
1061 // deterministic. A larger change is needed to fix this.
1062 for (auto Key : Keys) {
1063 Value *V = Key;
1064 auto State = states[Key];
1065 Value *Base = State.getBase();
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001066 assert(V && Base);
1067 assert(!isKnownBaseResult(V) && "why did it get added?");
1068 assert(isKnownBaseResult(Base) &&
1069 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001070 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001071 continue;
1072
1073 ReverseMap[Base] = V;
1074 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1075 NewInsts.insert(BaseI);
1076 Worklist.insert(BaseI);
1077 }
1078 }
Philip Reames9546f362015-09-02 22:25:07 +00001079 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1080 Value *Replacement) {
1081 // Add users which are new instructions (excluding self references)
1082 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001083 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001084 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001085 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001086 // Then do the actual replacement
1087 NewInsts.erase(BaseI);
1088 ReverseMap.erase(BaseI);
1089 BaseI->replaceAllUsesWith(Replacement);
1090 BaseI->eraseFromParent();
1091 assert(states.count(BDV));
1092 assert(states[BDV].isConflict() && states[BDV].getBase() == BaseI);
1093 states[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001094 };
1095 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1096 while (!Worklist.empty()) {
1097 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001098 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001099 Value *Bdv = ReverseMap[BaseI];
1100 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1101 if (BaseI->isIdenticalTo(BdvI)) {
1102 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001103 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001104 continue;
1105 }
1106 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1107 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001108 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001109 continue;
1110 }
1111 }
1112
Philip Reamesd16a9b12015-02-20 01:06:44 +00001113 // Cache all of our results so we can cheaply reuse them
1114 // NOTE: This is actually two caches: one of the base defining value
1115 // relation and one of the base pointer relation! FIXME
1116 for (auto item : states) {
1117 Value *v = item.first;
1118 Value *base = item.second.getBase();
1119 assert(v && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001120
Philip Reamesdab35f32015-09-02 21:11:44 +00001121 std::string fromstr =
1122 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
1123 : "none";
1124 DEBUG(dbgs() << "Updating base value cache"
1125 << " for: " << (v->hasName() ? v->getName() : "")
1126 << " from: " << fromstr
1127 << " to: " << (base->hasName() ? base->getName() : "") << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001128
Philip Reamesd16a9b12015-02-20 01:06:44 +00001129 if (cache.count(v)) {
1130 // Once we transition from the BDV relation being store in the cache to
1131 // the base relation being stored, it must be stable
1132 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
1133 "base relation should be stable");
1134 }
1135 cache[v] = base;
1136 }
1137 assert(cache.find(def) != cache.end());
1138 return cache[def];
1139}
1140
1141// For a set of live pointers (base and/or derived), identify the base
1142// pointer of the object which they are derived from. This routine will
1143// mutate the IR graph as needed to make the 'base' pointer live at the
1144// definition site of 'derived'. This ensures that any use of 'derived' can
1145// also use 'base'. This may involve the insertion of a number of
1146// additional PHI nodes.
1147//
1148// preconditions: live is a set of pointer type Values
1149//
1150// side effects: may insert PHI nodes into the existing CFG, will preserve
1151// CFG, will not remove or mutate any existing nodes
1152//
Philip Reamesf2041322015-02-20 19:26:04 +00001153// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001154// pointer in live. Note that derived can be equal to base if the original
1155// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001156static void
1157findBasePointers(const StatepointLiveSetTy &live,
1158 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001159 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001160 // For the naming of values inserted to be deterministic - which makes for
1161 // much cleaner and more stable tests - we need to assign an order to the
1162 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001163 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001164 Temp.insert(Temp.end(), live.begin(), live.end());
1165 std::sort(Temp.begin(), Temp.end(), order_by_name);
1166 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001167 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001168 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001169 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001170 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1171 DT->dominates(cast<Instruction>(base)->getParent(),
1172 cast<Instruction>(ptr)->getParent())) &&
1173 "The base we found better dominate the derived pointer");
1174
David Blaikie82ad7872015-02-20 23:44:24 +00001175 // If you see this trip and like to live really dangerously, the code should
1176 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001177 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001178 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001179 "the relocation code needs adjustment to handle the relocation of "
1180 "a null pointer constant without causing false positives in the "
1181 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001182 }
1183}
1184
1185/// Find the required based pointers (and adjust the live set) for the given
1186/// parse point.
1187static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1188 const CallSite &CS,
1189 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001190 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +00001191 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001192
1193 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001194 // Note: Need to print these in a stable order since this is checked in
1195 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001196 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001197 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001198 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001199 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001200 Temp.push_back(Pair.first);
1201 }
1202 std::sort(Temp.begin(), Temp.end(), order_by_name);
1203 for (Value *Ptr : Temp) {
1204 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001205 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1206 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001207 }
1208 }
1209
Philip Reamesf2041322015-02-20 19:26:04 +00001210 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001211}
1212
Philip Reamesdf1ef082015-04-10 22:53:14 +00001213/// Given an updated version of the dataflow liveness results, update the
1214/// liveset and base pointer maps for the call site CS.
1215static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1216 const CallSite &CS,
1217 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001218
Philip Reamesdf1ef082015-04-10 22:53:14 +00001219static void recomputeLiveInValues(
1220 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001221 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001222 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001223 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001224 GCPtrLivenessData RevisedLivenessData;
1225 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001226 for (size_t i = 0; i < records.size(); i++) {
1227 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001228 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001229 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001230 }
1231}
1232
Philip Reames69e51ca2015-04-13 18:07:21 +00001233// When inserting gc.relocate calls, we need to ensure there are no uses
1234// of the original value between the gc.statepoint and the gc.relocate call.
1235// One case which can arise is a phi node starting one of the successor blocks.
1236// We also need to be able to insert the gc.relocates only on the path which
1237// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001238// possible.
1239static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001240normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1241 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001242 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001243 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001244 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001245 }
1246
Philip Reames69e51ca2015-04-13 18:07:21 +00001247 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1248 // from it
1249 FoldSingleEntryPHINodes(Ret);
1250 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001251
Philip Reames69e51ca2015-04-13 18:07:21 +00001252 // At this point, we can safely insert a gc.relocate as the first instruction
1253 // in Ret if needed.
1254 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001255}
1256
Philip Reamesd2b66462015-02-20 22:39:41 +00001257static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001258 auto itr = std::find(livevec.begin(), livevec.end(), val);
1259 assert(livevec.end() != itr);
1260 size_t index = std::distance(livevec.begin(), itr);
1261 assert(index < livevec.size());
1262 return index;
1263}
1264
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001265// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001266// from original call to the safepoint.
1267static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1268 AttributeSet ret;
1269
1270 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1271 unsigned index = AS.getSlotIndex(Slot);
1272
1273 if (index == AttributeSet::ReturnIndex ||
1274 index == AttributeSet::FunctionIndex) {
1275
1276 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1277 ++it) {
1278 Attribute attr = *it;
1279
1280 // Do not allow certain attributes - just skip them
1281 // Safepoint can not be read only or read none.
1282 if (attr.hasAttribute(Attribute::ReadNone) ||
1283 attr.hasAttribute(Attribute::ReadOnly))
1284 continue;
1285
1286 ret = ret.addAttributes(
1287 AS.getContext(), index,
1288 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1289 }
1290 }
1291
1292 // Just skip parameter attributes for now
1293 }
1294
1295 return ret;
1296}
1297
1298/// Helper function to place all gc relocates necessary for the given
1299/// statepoint.
1300/// Inputs:
1301/// liveVariables - list of variables to be relocated.
1302/// liveStart - index of the first live variable.
1303/// basePtrs - base pointers.
1304/// statepointToken - statepoint instruction to which relocates should be
1305/// bound.
1306/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001307static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1308 const int LiveStart,
1309 ArrayRef<llvm::Value *> BasePtrs,
1310 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001311 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001312 if (LiveVariables.empty())
1313 return;
1314
1315 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1316 // unique declarations for each pointer type, but this proved problematic
1317 // because the intrinsic mangling code is incomplete and fragile. Since
1318 // we're moving towards a single unified pointer type anyways, we can just
1319 // cast everything to an i8* of the right address space. A bitcast is added
1320 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001321 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001322 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1323 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1324 Value *GCRelocateDecl =
1325 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001326
Sanjoy Das5665c992015-05-11 23:47:27 +00001327 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001328 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001329 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001330 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1331 Value *LiveIdx =
1332 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001333
1334 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001335 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001336 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001337 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001338 : "");
1339 // Trick CodeGen into thinking there are lots of free registers at this
1340 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001341 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001342 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001343}
1344
1345static void
1346makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1347 const SmallVectorImpl<llvm::Value *> &basePtrs,
1348 const SmallVectorImpl<llvm::Value *> &liveVariables,
1349 Pass *P,
1350 PartiallyConstructedSafepointRecord &result) {
1351 assert(basePtrs.size() == liveVariables.size());
1352 assert(isStatepoint(CS) &&
1353 "This method expects to be rewriting a statepoint");
1354
1355 BasicBlock *BB = CS.getInstruction()->getParent();
1356 assert(BB);
1357 Function *F = BB->getParent();
1358 assert(F && "must be set");
1359 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001360 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001361 assert(M && "must be set");
1362
1363 // We're not changing the function signature of the statepoint since the gc
1364 // arguments go into the var args section.
1365 Function *gc_statepoint_decl = CS.getCalledFunction();
1366
1367 // Then go ahead and use the builder do actually do the inserts. We insert
1368 // immediately before the previous instruction under the assumption that all
1369 // arguments will be available here. We can't insert afterwards since we may
1370 // be replacing a terminator.
1371 Instruction *insertBefore = CS.getInstruction();
1372 IRBuilder<> Builder(insertBefore);
1373 // Copy all of the arguments from the original statepoint - this includes the
1374 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001375 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001376 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1377 // TODO: Clear the 'needs rewrite' flag
1378
1379 // add all the pointers to be relocated (gc arguments)
1380 // Capture the start of the live variable list for use in the gc_relocates
1381 const int live_start = args.size();
1382 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1383
1384 // Create the statepoint given all the arguments
1385 Instruction *token = nullptr;
1386 AttributeSet return_attributes;
1387 if (CS.isCall()) {
1388 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1389 CallInst *call =
1390 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1391 call->setTailCall(toReplace->isTailCall());
1392 call->setCallingConv(toReplace->getCallingConv());
1393
1394 // Currently we will fail on parameter attributes and on certain
1395 // function attributes.
1396 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001397 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001398 // directly on statepoint and return attrs later for gc_result intrinsic.
1399 call->setAttributes(new_attrs.getFnAttributes());
1400 return_attributes = new_attrs.getRetAttributes();
1401
1402 token = call;
1403
1404 // Put the following gc_result and gc_relocate calls immediately after the
1405 // the old call (which we're about to delete)
1406 BasicBlock::iterator next(toReplace);
1407 assert(BB->end() != next && "not a terminator, must have next");
1408 next++;
1409 Instruction *IP = &*(next);
1410 Builder.SetInsertPoint(IP);
1411 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1412
David Blaikie82ad7872015-02-20 23:44:24 +00001413 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001414 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1415
1416 // Insert the new invoke into the old block. We'll remove the old one in a
1417 // moment at which point this will become the new terminator for the
1418 // original block.
1419 InvokeInst *invoke = InvokeInst::Create(
1420 gc_statepoint_decl, toReplace->getNormalDest(),
Philip Reamesfa2c6302015-07-24 19:01:39 +00001421 toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001422 invoke->setCallingConv(toReplace->getCallingConv());
1423
1424 // Currently we will fail on parameter attributes and on certain
1425 // function attributes.
1426 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001427 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001428 // directly on statepoint and return attrs later for gc_result intrinsic.
1429 invoke->setAttributes(new_attrs.getFnAttributes());
1430 return_attributes = new_attrs.getRetAttributes();
1431
1432 token = invoke;
1433
1434 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001435 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1436 assert(!isa<PHINode>(unwindBlock->begin()) &&
1437 unwindBlock->getUniquePredecessor() &&
1438 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001439
1440 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1441 Builder.SetInsertPoint(IP);
1442 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1443
1444 // Extract second element from landingpad return value. We will attach
1445 // exceptional gc relocates to it.
1446 const unsigned idx = 1;
1447 Instruction *exceptional_token =
1448 cast<Instruction>(Builder.CreateExtractValue(
1449 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001450 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001451
Philip Reames6ff1a1e32015-07-21 19:04:38 +00001452 CreateGCRelocates(liveVariables, live_start, basePtrs,
1453 exceptional_token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001454
1455 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001456 BasicBlock *normalDest = toReplace->getNormalDest();
1457 assert(!isa<PHINode>(normalDest->begin()) &&
1458 normalDest->getUniquePredecessor() &&
1459 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001460
1461 IP = &*(normalDest->getFirstInsertionPt());
1462 Builder.SetInsertPoint(IP);
1463
1464 // gc relocates will be generated later as if it were regular call
1465 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001466 }
1467 assert(token);
1468
1469 // Take the name of the original value call if it had one.
1470 token->takeName(CS.getInstruction());
1471
Philip Reames704e78b2015-04-10 22:34:56 +00001472// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001473#ifndef NDEBUG
1474 Instruction *toReplace = CS.getInstruction();
1475 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1476 "only valid use before rewrite is gc.result");
1477 assert(!toReplace->hasOneUse() ||
1478 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1479#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001480
1481 // Update the gc.result of the original statepoint (if any) to use the newly
1482 // inserted statepoint. This is safe to do here since the token can't be
1483 // considered a live reference.
1484 CS.getInstruction()->replaceAllUsesWith(token);
1485
Philip Reames0a3240f2015-02-20 21:34:11 +00001486 result.StatepointToken = token;
1487
Philip Reamesd16a9b12015-02-20 01:06:44 +00001488 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001489 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001490}
1491
1492namespace {
1493struct name_ordering {
1494 Value *base;
1495 Value *derived;
1496 bool operator()(name_ordering const &a, name_ordering const &b) {
1497 return -1 == a.derived->getName().compare(b.derived->getName());
1498 }
1499};
1500}
1501static void stablize_order(SmallVectorImpl<Value *> &basevec,
1502 SmallVectorImpl<Value *> &livevec) {
1503 assert(basevec.size() == livevec.size());
1504
Philip Reames860660e2015-02-20 22:05:18 +00001505 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001506 for (size_t i = 0; i < basevec.size(); i++) {
1507 name_ordering v;
1508 v.base = basevec[i];
1509 v.derived = livevec[i];
1510 temp.push_back(v);
1511 }
1512 std::sort(temp.begin(), temp.end(), name_ordering());
1513 for (size_t i = 0; i < basevec.size(); i++) {
1514 basevec[i] = temp[i].base;
1515 livevec[i] = temp[i].derived;
1516 }
1517}
1518
1519// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1520// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001521//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001522// WARNING: Does not do any fixup to adjust users of the original live
1523// values. That's the callers responsibility.
1524static void
1525makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1526 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001527 auto liveset = result.liveset;
1528 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001529
1530 // Convert to vector for efficient cross referencing.
1531 SmallVector<Value *, 64> basevec, livevec;
1532 livevec.reserve(liveset.size());
1533 basevec.reserve(liveset.size());
1534 for (Value *L : liveset) {
1535 livevec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001536 assert(PointerToBase.count(L));
Philip Reamesf2041322015-02-20 19:26:04 +00001537 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001538 basevec.push_back(base);
1539 }
1540 assert(livevec.size() == basevec.size());
1541
1542 // To make the output IR slightly more stable (for use in diffs), ensure a
1543 // fixed order of the values in the safepoint (by sorting the value name).
1544 // The order is otherwise meaningless.
1545 stablize_order(basevec, livevec);
1546
1547 // Do the actual rewriting and delete the old statepoint
1548 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1549 CS.getInstruction()->eraseFromParent();
1550}
1551
1552// Helper function for the relocationViaAlloca.
1553// It receives iterator to the statepoint gc relocates and emits store to the
1554// assigned
1555// location (via allocaMap) for the each one of them.
1556// Add visited values into the visitedLiveValues set we will later use them
1557// for sanity check.
1558static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001559insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1560 DenseMap<Value *, Value *> &AllocaMap,
1561 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001562
Sanjoy Das5665c992015-05-11 23:47:27 +00001563 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001564 if (!isa<IntrinsicInst>(U))
1565 continue;
1566
Sanjoy Das5665c992015-05-11 23:47:27 +00001567 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001568
1569 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001570 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001571 Intrinsic::experimental_gc_relocate) {
1572 continue;
1573 }
1574
Sanjoy Das5665c992015-05-11 23:47:27 +00001575 GCRelocateOperands RelocateOperands(RelocatedValue);
1576 Value *OriginalValue =
1577 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1578 assert(AllocaMap.count(OriginalValue));
1579 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001580
1581 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001582 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1583 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001584 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1585 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001586 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001587 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1588 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001589
Sanjoy Das5665c992015-05-11 23:47:27 +00001590 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1591 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001592
1593#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001594 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001595#endif
1596 }
1597}
1598
Igor Laevskye0317182015-05-19 15:59:05 +00001599// Helper function for the "relocationViaAlloca". Similar to the
1600// "insertRelocationStores" but works for rematerialized values.
1601static void
1602insertRematerializationStores(
1603 RematerializedValueMapTy RematerializedValues,
1604 DenseMap<Value *, Value *> &AllocaMap,
1605 DenseSet<Value *> &VisitedLiveValues) {
1606
1607 for (auto RematerializedValuePair: RematerializedValues) {
1608 Instruction *RematerializedValue = RematerializedValuePair.first;
1609 Value *OriginalValue = RematerializedValuePair.second;
1610
1611 assert(AllocaMap.count(OriginalValue) &&
1612 "Can not find alloca for rematerialized value");
1613 Value *Alloca = AllocaMap[OriginalValue];
1614
1615 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1616 Store->insertAfter(RematerializedValue);
1617
1618#ifndef NDEBUG
1619 VisitedLiveValues.insert(OriginalValue);
1620#endif
1621 }
1622}
1623
Philip Reamesd16a9b12015-02-20 01:06:44 +00001624/// do all the relocation update via allocas and mem2reg
1625static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001626 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1627 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001628#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001629 // record initial number of (static) allocas; we'll check we have the same
1630 // number when we get done.
1631 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001632 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1633 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001634 if (isa<AllocaInst>(*I))
1635 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001636#endif
1637
1638 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001639 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001640 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001641 // Used later to chack that we have enough allocas to store all values
1642 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001643 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001644
Igor Laevskye0317182015-05-19 15:59:05 +00001645 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1646 // "PromotableAllocas"
1647 auto emitAllocaFor = [&](Value *LiveValue) {
1648 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1649 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001650 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001651 PromotableAllocas.push_back(Alloca);
1652 };
1653
Philip Reamesd16a9b12015-02-20 01:06:44 +00001654 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001655 for (unsigned i = 0; i < Live.size(); i++) {
1656 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001657 }
1658
Igor Laevskye0317182015-05-19 15:59:05 +00001659 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001660 for (size_t i = 0; i < Records.size(); i++) {
1661 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001662
Igor Laevsky285fe842015-05-19 16:29:43 +00001663 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001664 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001665 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001666 continue;
1667
1668 emitAllocaFor(OriginalValue);
1669 ++NumRematerializedValues;
1670 }
1671 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001672
Philip Reamesd16a9b12015-02-20 01:06:44 +00001673 // The next two loops are part of the same conceptual operation. We need to
1674 // insert a store to the alloca after the original def and at each
1675 // redefinition. We need to insert a load before each use. These are split
1676 // into distinct loops for performance reasons.
1677
1678 // update gc pointer after each statepoint
1679 // either store a relocated value or null (if no relocated value found for
1680 // this gc pointer and it is not a gc_result)
1681 // this must happen before we update the statepoint with load of alloca
1682 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001683 for (size_t i = 0; i < Records.size(); i++) {
1684 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1685 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001686
1687 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001688 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001689
1690 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001691 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001692
1693 // In case if it was invoke statepoint
1694 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001695 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001696 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1697 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001698 }
1699
Igor Laevskye0317182015-05-19 15:59:05 +00001700 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001701 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1702 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001703
Philip Reamese73300b2015-04-13 16:41:32 +00001704 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001705 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001706 // the gc.statepoint. This will turn some subtle GC problems into
1707 // slightly easier to debug SEGVs. Note that on large IR files with
1708 // lots of gc.statepoints this is extremely costly both memory and time
1709 // wise.
1710 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001711 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001712 Value *Def = Pair.first;
1713 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001714
Philip Reamese73300b2015-04-13 16:41:32 +00001715 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001716 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001717 continue;
1718 }
1719 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001720 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001721
Philip Reamese73300b2015-04-13 16:41:32 +00001722 auto InsertClobbersAt = [&](Instruction *IP) {
1723 for (auto *AI : ToClobber) {
1724 auto AIType = cast<PointerType>(AI->getType());
1725 auto PT = cast<PointerType>(AIType->getElementType());
1726 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001727 StoreInst *Store = new StoreInst(CPN, AI);
1728 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001729 }
1730 };
1731
1732 // Insert the clobbering stores. These may get intermixed with the
1733 // gc.results and gc.relocates, but that's fine.
1734 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1735 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1736 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1737 } else {
1738 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1739 Next++;
1740 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001741 }
David Blaikie82ad7872015-02-20 23:44:24 +00001742 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001743 }
1744 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001745 for (auto Pair : AllocaMap) {
1746 Value *Def = Pair.first;
1747 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001748
1749 // we pre-record the uses of allocas so that we dont have to worry about
1750 // later update
1751 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001752 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001753 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001754 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1755 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001756 if (!isa<ConstantExpr>(U)) {
1757 // If the def has a ConstantExpr use, then the def is either a
1758 // ConstantExpr use itself or null. In either case
1759 // (recursively in the first, directly in the second), the oop
1760 // it is ultimately dependent on is null and this particular
1761 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001762 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001763 }
1764 }
1765
Igor Laevsky285fe842015-05-19 16:29:43 +00001766 std::sort(Uses.begin(), Uses.end());
1767 auto Last = std::unique(Uses.begin(), Uses.end());
1768 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001769
Igor Laevsky285fe842015-05-19 16:29:43 +00001770 for (Instruction *Use : Uses) {
1771 if (isa<PHINode>(Use)) {
1772 PHINode *Phi = cast<PHINode>(Use);
1773 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1774 if (Def == Phi->getIncomingValue(i)) {
1775 LoadInst *Load = new LoadInst(
1776 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1777 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001778 }
1779 }
1780 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001781 LoadInst *Load = new LoadInst(Alloca, "", Use);
1782 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001783 }
1784 }
1785
1786 // emit store for the initial gc value
1787 // store must be inserted after load, otherwise store will be in alloca's
1788 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001789 StoreInst *Store = new StoreInst(Def, Alloca);
1790 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1791 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001792 // InvokeInst is a TerminatorInst so the store need to be inserted
1793 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001794 BasicBlock *NormalDest = Invoke->getNormalDest();
1795 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001796 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001797 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001798 "The only TerminatorInst that can produce a value is "
1799 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001800 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001801 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001802 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001803 assert(isa<Argument>(Def));
1804 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001805 }
1806 }
1807
Igor Laevsky285fe842015-05-19 16:29:43 +00001808 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001809 "we must have the same allocas with lives");
1810 if (!PromotableAllocas.empty()) {
1811 // apply mem2reg to promote alloca to SSA
1812 PromoteMemToReg(PromotableAllocas, DT);
1813 }
1814
1815#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001816 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1817 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001818 if (isa<AllocaInst>(*I))
1819 InitialAllocaNum--;
1820 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001821#endif
1822}
1823
1824/// Implement a unique function which doesn't require we sort the input
1825/// vector. Doing so has the effect of changing the output of a couple of
1826/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001827template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001828 SmallSet<T, 8> Seen;
1829 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1830 return !Seen.insert(V).second;
1831 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001832}
1833
Philip Reamesd16a9b12015-02-20 01:06:44 +00001834/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001835/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001836static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001837 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001838 if (Values.empty())
1839 // No values to hold live, might as well not insert the empty holder
1840 return;
1841
Philip Reamesd16a9b12015-02-20 01:06:44 +00001842 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001843 // Use a dummy vararg function to actually hold the values live
1844 Function *Func = cast<Function>(M->getOrInsertFunction(
1845 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001846 if (CS.isCall()) {
1847 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001848 BasicBlock::iterator Next(CS.getInstruction());
1849 Next++;
1850 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1851 return;
1852 }
1853 // For invoke safepooints insert dummy calls both in normal and
1854 // exceptional destination blocks
1855 auto *II = cast<InvokeInst>(CS.getInstruction());
1856 Holders.push_back(CallInst::Create(
1857 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1858 Holders.push_back(CallInst::Create(
1859 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001860}
1861
1862static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001863 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1864 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001865 GCPtrLivenessData OriginalLivenessData;
1866 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001867 for (size_t i = 0; i < records.size(); i++) {
1868 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001869 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001870 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001871 }
1872}
1873
Philip Reames8531d8c2015-04-10 21:48:25 +00001874/// Remove any vector of pointers from the liveset by scalarizing them over the
1875/// statepoint instruction. Adds the scalarized pieces to the liveset. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001876/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001877/// the lowering code currently does not handle that. Extending it would be
1878/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001879/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001880static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001881 StatepointLiveSetTy &LiveSet,
1882 DenseMap<Value *, Value *>& PointerToBase,
1883 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001884 SmallVector<Value *, 16> ToSplit;
1885 for (Value *V : LiveSet)
1886 if (isa<VectorType>(V->getType()))
1887 ToSplit.push_back(V);
1888
1889 if (ToSplit.empty())
1890 return;
1891
Philip Reames8fe7f132015-06-26 22:47:37 +00001892 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1893
Philip Reames8531d8c2015-04-10 21:48:25 +00001894 Function &F = *(StatepointInst->getParent()->getParent());
1895
Philip Reames704e78b2015-04-10 22:34:56 +00001896 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001897 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001898 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001899 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001900 AllocaInst *Alloca =
1901 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001902 AllocaMap[V] = Alloca;
1903
1904 VectorType *VT = cast<VectorType>(V->getType());
1905 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001906 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001907 for (unsigned i = 0; i < VT->getNumElements(); i++)
1908 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001909 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001910
1911 auto InsertVectorReform = [&](Instruction *IP) {
1912 Builder.SetInsertPoint(IP);
1913 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1914 Value *ResultVec = UndefValue::get(VT);
1915 for (unsigned i = 0; i < VT->getNumElements(); i++)
1916 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1917 Builder.getInt32(i));
1918 return ResultVec;
1919 };
1920
1921 if (isa<CallInst>(StatepointInst)) {
1922 BasicBlock::iterator Next(StatepointInst);
1923 Next++;
1924 Instruction *IP = &*(Next);
1925 Replacements[V].first = InsertVectorReform(IP);
1926 Replacements[V].second = nullptr;
1927 } else {
1928 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1929 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001930 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001931 BasicBlock *NormalDest = Invoke->getNormalDest();
1932 assert(!isa<PHINode>(NormalDest->begin()));
1933 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1934 assert(!isa<PHINode>(UnwindDest->begin()));
1935 // Insert insert element sequences in both successors
1936 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1937 Replacements[V].first = InsertVectorReform(IP);
1938 IP = &*(UnwindDest->getFirstInsertionPt());
1939 Replacements[V].second = InsertVectorReform(IP);
1940 }
1941 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001942
Philip Reames8531d8c2015-04-10 21:48:25 +00001943 for (Value *V : ToSplit) {
1944 AllocaInst *Alloca = AllocaMap[V];
1945
1946 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001947 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001948 for (User *U : V->users())
1949 Users.push_back(cast<Instruction>(U));
1950
1951 for (Instruction *I : Users) {
1952 if (auto Phi = dyn_cast<PHINode>(I)) {
1953 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1954 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001955 LoadInst *Load = new LoadInst(
1956 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001957 Phi->setIncomingValue(i, Load);
1958 }
1959 } else {
1960 LoadInst *Load = new LoadInst(Alloca, "", I);
1961 I->replaceUsesOfWith(V, Load);
1962 }
1963 }
1964
1965 // Store the original value and the replacement value into the alloca
1966 StoreInst *Store = new StoreInst(V, Alloca);
1967 if (auto I = dyn_cast<Instruction>(V))
1968 Store->insertAfter(I);
1969 else
1970 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001971
Philip Reames8531d8c2015-04-10 21:48:25 +00001972 // Normal return for invoke, or call return
1973 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1974 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1975 // Unwind return for invoke only
1976 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1977 if (Replacement)
1978 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1979 }
1980
1981 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001982 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001983 for (Value *V : ToSplit)
1984 Allocas.push_back(AllocaMap[V]);
1985 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001986
1987 // Update our tracking of live pointers and base mappings to account for the
1988 // changes we just made.
1989 for (Value *V : ToSplit) {
1990 auto &Elements = ElementMapping[V];
1991
1992 LiveSet.erase(V);
1993 LiveSet.insert(Elements.begin(), Elements.end());
1994 // We need to update the base mapping as well.
1995 assert(PointerToBase.count(V));
1996 Value *OldBase = PointerToBase[V];
1997 auto &BaseElements = ElementMapping[OldBase];
1998 PointerToBase.erase(V);
1999 assert(Elements.size() == BaseElements.size());
2000 for (unsigned i = 0; i < Elements.size(); i++) {
2001 Value *Elem = Elements[i];
2002 PointerToBase[Elem] = BaseElements[i];
2003 }
2004 }
Philip Reames8531d8c2015-04-10 21:48:25 +00002005}
2006
Igor Laevskye0317182015-05-19 15:59:05 +00002007// Helper function for the "rematerializeLiveValues". It walks use chain
2008// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2009// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002010// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00002011// Fills "ChainToBase" array with all visited values. "BaseValue" is not
2012// recorded.
2013static bool findRematerializableChainToBasePointer(
2014 SmallVectorImpl<Instruction*> &ChainToBase,
2015 Value *CurrentValue, Value *BaseValue) {
2016
2017 // We have found a base value
2018 if (CurrentValue == BaseValue) {
2019 return true;
2020 }
2021
2022 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2023 ChainToBase.push_back(GEP);
2024 return findRematerializableChainToBasePointer(ChainToBase,
2025 GEP->getPointerOperand(),
2026 BaseValue);
2027 }
2028
2029 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2030 Value *Def = CI->stripPointerCasts();
2031
2032 // This two checks are basically similar. First one is here for the
2033 // consistency with findBasePointers logic.
2034 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2035 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2036 return false;
2037
2038 ChainToBase.push_back(CI);
2039 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2040 }
2041
2042 // Not supported instruction in the chain
2043 return false;
2044}
2045
2046// Helper function for the "rematerializeLiveValues". Compute cost of the use
2047// chain we are going to rematerialize.
2048static unsigned
2049chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2050 TargetTransformInfo &TTI) {
2051 unsigned Cost = 0;
2052
2053 for (Instruction *Instr : Chain) {
2054 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2055 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2056 "non noop cast is found during rematerialization");
2057
2058 Type *SrcTy = CI->getOperand(0)->getType();
2059 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2060
2061 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2062 // Cost of the address calculation
2063 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2064 Cost += TTI.getAddressComputationCost(ValTy);
2065
2066 // And cost of the GEP itself
2067 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2068 // allowed for the external usage)
2069 if (!GEP->hasAllConstantIndices())
2070 Cost += 2;
2071
2072 } else {
2073 llvm_unreachable("unsupported instruciton type during rematerialization");
2074 }
2075 }
2076
2077 return Cost;
2078}
2079
2080// From the statepoint liveset pick values that are cheaper to recompute then to
2081// relocate. Remove this values from the liveset, rematerialize them after
2082// statepoint and record them in "Info" structure. Note that similar to
2083// relocated values we don't do any user adjustments here.
2084static void rematerializeLiveValues(CallSite CS,
2085 PartiallyConstructedSafepointRecord &Info,
2086 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002087 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002088
Igor Laevskye0317182015-05-19 15:59:05 +00002089 // Record values we are going to delete from this statepoint live set.
2090 // We can not di this in following loop due to iterator invalidation.
2091 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2092
2093 for (Value *LiveValue: Info.liveset) {
2094 // For each live pointer find it's defining chain
2095 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002096 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002097 bool FoundChain =
2098 findRematerializableChainToBasePointer(ChainToBase,
2099 LiveValue,
2100 Info.PointerToBase[LiveValue]);
2101 // Nothing to do, or chain is too long
2102 if (!FoundChain ||
2103 ChainToBase.size() == 0 ||
2104 ChainToBase.size() > ChainLengthThreshold)
2105 continue;
2106
2107 // Compute cost of this chain
2108 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2109 // TODO: We can also account for cases when we will be able to remove some
2110 // of the rematerialized values by later optimization passes. I.e if
2111 // we rematerialized several intersecting chains. Or if original values
2112 // don't have any uses besides this statepoint.
2113
2114 // For invokes we need to rematerialize each chain twice - for normal and
2115 // for unwind basic blocks. Model this by multiplying cost by two.
2116 if (CS.isInvoke()) {
2117 Cost *= 2;
2118 }
2119 // If it's too expensive - skip it
2120 if (Cost >= RematerializationThreshold)
2121 continue;
2122
2123 // Remove value from the live set
2124 LiveValuesToBeDeleted.push_back(LiveValue);
2125
2126 // Clone instructions and record them inside "Info" structure
2127
2128 // Walk backwards to visit top-most instructions first
2129 std::reverse(ChainToBase.begin(), ChainToBase.end());
2130
2131 // Utility function which clones all instructions from "ChainToBase"
2132 // and inserts them before "InsertBefore". Returns rematerialized value
2133 // which should be used after statepoint.
2134 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2135 Instruction *LastClonedValue = nullptr;
2136 Instruction *LastValue = nullptr;
2137 for (Instruction *Instr: ChainToBase) {
2138 // Only GEP's and casts are suported as we need to be careful to not
2139 // introduce any new uses of pointers not in the liveset.
2140 // Note that it's fine to introduce new uses of pointers which were
2141 // otherwise not used after this statepoint.
2142 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2143
2144 Instruction *ClonedValue = Instr->clone();
2145 ClonedValue->insertBefore(InsertBefore);
2146 ClonedValue->setName(Instr->getName() + ".remat");
2147
2148 // If it is not first instruction in the chain then it uses previously
2149 // cloned value. We should update it to use cloned value.
2150 if (LastClonedValue) {
2151 assert(LastValue);
2152 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2153#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002154 // Assert that cloned instruction does not use any instructions from
2155 // this chain other than LastClonedValue
2156 for (auto OpValue : ClonedValue->operand_values()) {
2157 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2158 ChainToBase.end() &&
2159 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002160 }
2161#endif
2162 }
2163
2164 LastClonedValue = ClonedValue;
2165 LastValue = Instr;
2166 }
2167 assert(LastClonedValue);
2168 return LastClonedValue;
2169 };
2170
2171 // Different cases for calls and invokes. For invokes we need to clone
2172 // instructions both on normal and unwind path.
2173 if (CS.isCall()) {
2174 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2175 assert(InsertBefore);
2176 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2177 Info.RematerializedValues[RematerializedValue] = LiveValue;
2178 } else {
2179 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2180
2181 Instruction *NormalInsertBefore =
2182 Invoke->getNormalDest()->getFirstInsertionPt();
2183 Instruction *UnwindInsertBefore =
2184 Invoke->getUnwindDest()->getFirstInsertionPt();
2185
2186 Instruction *NormalRematerializedValue =
2187 rematerializeChain(NormalInsertBefore);
2188 Instruction *UnwindRematerializedValue =
2189 rematerializeChain(UnwindInsertBefore);
2190
2191 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2192 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2193 }
2194 }
2195
2196 // Remove rematerializaed values from the live set
2197 for (auto LiveValue: LiveValuesToBeDeleted) {
2198 Info.liveset.erase(LiveValue);
2199 }
2200}
2201
Philip Reamesd16a9b12015-02-20 01:06:44 +00002202static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00002203 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002204#ifndef NDEBUG
2205 // sanity check the input
2206 std::set<CallSite> uniqued;
2207 uniqued.insert(toUpdate.begin(), toUpdate.end());
2208 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2209
2210 for (size_t i = 0; i < toUpdate.size(); i++) {
2211 CallSite &CS = toUpdate[i];
2212 assert(CS.getInstruction()->getParent()->getParent() == &F);
2213 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2214 }
2215#endif
2216
Philip Reames69e51ca2015-04-13 18:07:21 +00002217 // When inserting gc.relocates for invokes, we need to be able to insert at
2218 // the top of the successor blocks. See the comment on
2219 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002220 // may restructure the CFG.
2221 for (CallSite CS : toUpdate) {
2222 if (!CS.isInvoke())
2223 continue;
2224 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2225 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002226 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002227 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002228 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002229 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002230
Philip Reamesd16a9b12015-02-20 01:06:44 +00002231 // A list of dummy calls added to the IR to keep various values obviously
2232 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002233 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002234
2235 // Insert a dummy call with all of the arguments to the vm_state we'll need
2236 // for the actual safepoint insertion. This ensures reference arguments in
2237 // the deopt argument list are considered live through the safepoint (and
2238 // thus makes sure they get relocated.)
2239 for (size_t i = 0; i < toUpdate.size(); i++) {
2240 CallSite &CS = toUpdate[i];
2241 Statepoint StatepointCS(CS);
2242
2243 SmallVector<Value *, 64> DeoptValues;
2244 for (Use &U : StatepointCS.vm_state_args()) {
2245 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002246 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2247 "support for FCA unimplemented");
2248 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002249 DeoptValues.push_back(Arg);
2250 }
2251 insertUseHolderAfter(CS, DeoptValues, holders);
2252 }
2253
Philip Reamesd2b66462015-02-20 22:39:41 +00002254 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002255 records.reserve(toUpdate.size());
2256 for (size_t i = 0; i < toUpdate.size(); i++) {
2257 struct PartiallyConstructedSafepointRecord info;
2258 records.push_back(info);
2259 }
2260 assert(records.size() == toUpdate.size());
2261
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002262 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002263 // site.
2264 findLiveReferences(F, DT, P, toUpdate, records);
2265
2266 // B) Find the base pointers for each live pointer
2267 /* scope for caching */ {
2268 // Cache the 'defining value' relation used in the computation and
2269 // insertion of base phis and selects. This ensures that we don't insert
2270 // large numbers of duplicate base_phis.
2271 DefiningValueMapTy DVCache;
2272
2273 for (size_t i = 0; i < records.size(); i++) {
2274 struct PartiallyConstructedSafepointRecord &info = records[i];
2275 CallSite &CS = toUpdate[i];
2276 findBasePointers(DT, DVCache, CS, info);
2277 }
2278 } // end of cache scope
2279
2280 // The base phi insertion logic (for any safepoint) may have inserted new
2281 // instructions which are now live at some safepoint. The simplest such
2282 // example is:
2283 // loop:
2284 // phi a <-- will be a new base_phi here
2285 // safepoint 1 <-- that needs to be live here
2286 // gep a + 1
2287 // safepoint 2
2288 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002289 // We insert some dummy calls after each safepoint to definitely hold live
2290 // the base pointers which were identified for that safepoint. We'll then
2291 // ask liveness for _every_ base inserted to see what is now live. Then we
2292 // remove the dummy calls.
2293 holders.reserve(holders.size() + records.size());
2294 for (size_t i = 0; i < records.size(); i++) {
2295 struct PartiallyConstructedSafepointRecord &info = records[i];
2296 CallSite &CS = toUpdate[i];
2297
2298 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002299 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002300 Bases.push_back(Pair.second);
2301 }
2302 insertUseHolderAfter(CS, Bases, holders);
2303 }
2304
Philip Reamesdf1ef082015-04-10 22:53:14 +00002305 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2306 // need to rerun liveness. We may *also* have inserted new defs, but that's
2307 // not the key issue.
2308 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002309
Philip Reamesd16a9b12015-02-20 01:06:44 +00002310 if (PrintBasePointers) {
2311 for (size_t i = 0; i < records.size(); i++) {
2312 struct PartiallyConstructedSafepointRecord &info = records[i];
2313 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002314 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002315 errs() << " derived %" << Pair.first->getName() << " base %"
2316 << Pair.second->getName() << "\n";
2317 }
2318 }
2319 }
2320 for (size_t i = 0; i < holders.size(); i++) {
2321 holders[i]->eraseFromParent();
2322 holders[i] = nullptr;
2323 }
2324 holders.clear();
2325
Philip Reames8fe7f132015-06-26 22:47:37 +00002326 // Do a limited scalarization of any live at safepoint vector values which
2327 // contain pointers. This enables this pass to run after vectorization at
2328 // the cost of some possible performance loss. TODO: it would be nice to
2329 // natively support vectors all the way through the backend so we don't need
2330 // to scalarize here.
2331 for (size_t i = 0; i < records.size(); i++) {
2332 struct PartiallyConstructedSafepointRecord &info = records[i];
2333 Instruction *statepoint = toUpdate[i].getInstruction();
2334 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2335 info.PointerToBase, DT);
2336 }
2337
Igor Laevskye0317182015-05-19 15:59:05 +00002338 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002339 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002340 // does not influence correctness.
2341 TargetTransformInfo &TTI =
2342 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2343
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002344 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002345 struct PartiallyConstructedSafepointRecord &info = records[i];
2346 CallSite &CS = toUpdate[i];
2347
2348 rematerializeLiveValues(CS, info, TTI);
2349 }
2350
Philip Reamesd16a9b12015-02-20 01:06:44 +00002351 // Now run through and replace the existing statepoints with new ones with
2352 // the live variables listed. We do not yet update uses of the values being
2353 // relocated. We have references to live variables that need to
2354 // survive to the last iteration of this loop. (By construction, the
2355 // previous statepoint can not be a live variable, thus we can and remove
2356 // the old statepoint calls as we go.)
2357 for (size_t i = 0; i < records.size(); i++) {
2358 struct PartiallyConstructedSafepointRecord &info = records[i];
2359 CallSite &CS = toUpdate[i];
2360 makeStatepointExplicit(DT, CS, P, info);
2361 }
2362 toUpdate.clear(); // prevent accident use of invalid CallSites
2363
Philip Reamesd16a9b12015-02-20 01:06:44 +00002364 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002365 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002366 for (size_t i = 0; i < records.size(); i++) {
2367 struct PartiallyConstructedSafepointRecord &info = records[i];
2368 // We can't simply save the live set from the original insertion. One of
2369 // the live values might be the result of a call which needs a safepoint.
2370 // That Value* no longer exists and we need to use the new gc_result.
2371 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2372 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002373 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002374 live.insert(live.end(), statepoint.gc_args_begin(),
2375 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002376#ifndef NDEBUG
2377 // Do some basic sanity checks on our liveness results before performing
2378 // relocation. Relocation can and will turn mistakes in liveness results
2379 // into non-sensical code which is must harder to debug.
2380 // TODO: It would be nice to test consistency as well
2381 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2382 "statepoint must be reachable or liveness is meaningless");
2383 for (Value *V : statepoint.gc_args()) {
2384 if (!isa<Instruction>(V))
2385 // Non-instruction values trivial dominate all possible uses
2386 continue;
2387 auto LiveInst = cast<Instruction>(V);
2388 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2389 "unreachable values should never be live");
2390 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2391 "basic SSA liveness expectation violated by liveness analysis");
2392 }
2393#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002394 }
2395 unique_unsorted(live);
2396
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002397#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002398 // sanity check
2399 for (auto ptr : live) {
2400 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2401 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002402#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002403
2404 relocationViaAlloca(F, DT, live, records);
2405 return !records.empty();
2406}
2407
Sanjoy Das353a19e2015-06-02 22:33:37 +00002408// Handles both return values and arguments for Functions and CallSites.
2409template <typename AttrHolder>
2410static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2411 unsigned Index) {
2412 AttrBuilder R;
2413 if (AH.getDereferenceableBytes(Index))
2414 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2415 AH.getDereferenceableBytes(Index)));
2416 if (AH.getDereferenceableOrNullBytes(Index))
2417 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2418 AH.getDereferenceableOrNullBytes(Index)));
2419
2420 if (!R.empty())
2421 AH.setAttributes(AH.getAttributes().removeAttributes(
2422 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002423}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002424
2425void
2426RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2427 LLVMContext &Ctx = F.getContext();
2428
2429 for (Argument &A : F.args())
2430 if (isa<PointerType>(A.getType()))
2431 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2432
2433 if (isa<PointerType>(F.getReturnType()))
2434 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2435}
2436
2437void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2438 if (F.empty())
2439 return;
2440
2441 LLVMContext &Ctx = F.getContext();
2442 MDBuilder Builder(Ctx);
2443
Nico Rieck78199512015-08-06 19:10:45 +00002444 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002445 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2446 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2447 bool IsImmutableTBAA =
2448 MD->getNumOperands() == 4 &&
2449 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2450
2451 if (!IsImmutableTBAA)
2452 continue; // no work to do, MD_tbaa is already marked mutable
2453
2454 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2455 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2456 uint64_t Offset =
2457 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2458
2459 MDNode *MutableTBAA =
2460 Builder.createTBAAStructTagNode(Base, Access, Offset);
2461 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2462 }
2463
2464 if (CallSite CS = CallSite(&I)) {
2465 for (int i = 0, e = CS.arg_size(); i != e; i++)
2466 if (isa<PointerType>(CS.getArgument(i)->getType()))
2467 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2468 if (isa<PointerType>(CS.getType()))
2469 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2470 }
2471 }
2472}
2473
Philip Reamesd16a9b12015-02-20 01:06:44 +00002474/// Returns true if this function should be rewritten by this pass. The main
2475/// point of this function is as an extension point for custom logic.
2476static bool shouldRewriteStatepointsIn(Function &F) {
2477 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002478 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002479 const char *FunctionGCName = F.getGC();
2480 const StringRef StatepointExampleName("statepoint-example");
2481 const StringRef CoreCLRName("coreclr");
2482 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002483 (CoreCLRName == FunctionGCName);
2484 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002485 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002486}
2487
Sanjoy Das353a19e2015-06-02 22:33:37 +00002488void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2489#ifndef NDEBUG
2490 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2491 "precondition!");
2492#endif
2493
2494 for (Function &F : M)
2495 stripDereferenceabilityInfoFromPrototype(F);
2496
2497 for (Function &F : M)
2498 stripDereferenceabilityInfoFromBody(F);
2499}
2500
Philip Reamesd16a9b12015-02-20 01:06:44 +00002501bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2502 // Nothing to do for declarations.
2503 if (F.isDeclaration() || F.empty())
2504 return false;
2505
2506 // Policy choice says not to rewrite - the most common reason is that we're
2507 // compiling code without a GCStrategy.
2508 if (!shouldRewriteStatepointsIn(F))
2509 return false;
2510
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002511 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002512
Philip Reames85b36a82015-04-10 22:07:04 +00002513 // Gather all the statepoints which need rewritten. Be careful to only
2514 // consider those in reachable code since we need to ask dominance queries
2515 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002516 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002517 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002518 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002519 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002520 if (isStatepoint(I)) {
2521 if (DT.isReachableFromEntry(I.getParent()))
2522 ParsePointNeeded.push_back(CallSite(&I));
2523 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002524 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002525 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002526 }
2527
Philip Reames85b36a82015-04-10 22:07:04 +00002528 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002529
Philip Reames85b36a82015-04-10 22:07:04 +00002530 // Delete any unreachable statepoints so that we don't have unrewritten
2531 // statepoints surviving this pass. This makes testing easier and the
2532 // resulting IR less confusing to human readers. Rather than be fancy, we
2533 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002534 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002535 MadeChange |= removeUnreachableBlocks(F);
2536
Philip Reamesd16a9b12015-02-20 01:06:44 +00002537 // Return early if no work to do.
2538 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002539 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002540
Philip Reames85b36a82015-04-10 22:07:04 +00002541 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2542 // These are created by LCSSA. They have the effect of increasing the size
2543 // of liveness sets for no good reason. It may be harder to do this post
2544 // insertion since relocations and base phis can confuse things.
2545 for (BasicBlock &BB : F)
2546 if (BB.getUniquePredecessor()) {
2547 MadeChange = true;
2548 FoldSingleEntryPHINodes(&BB);
2549 }
2550
Philip Reames971dc3a2015-08-12 22:11:45 +00002551 // Before we start introducing relocations, we want to tweak the IR a bit to
2552 // avoid unfortunate code generation effects. The main example is that we
2553 // want to try to make sure the comparison feeding a branch is after any
2554 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2555 // values feeding a branch after relocation. This is semantically correct,
2556 // but results in extra register pressure since both the pre-relocation and
2557 // post-relocation copies must be available in registers. For code without
2558 // relocations this is handled elsewhere, but teaching the scheduler to
2559 // reverse the transform we're about to do would be slightly complex.
2560 // Note: This may extend the live range of the inputs to the icmp and thus
2561 // increase the liveset of any statepoint we move over. This is profitable
2562 // as long as all statepoints are in rare blocks. If we had in-register
2563 // lowering for live values this would be a much safer transform.
2564 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2565 if (auto *BI = dyn_cast<BranchInst>(TI))
2566 if (BI->isConditional())
2567 return dyn_cast<Instruction>(BI->getCondition());
2568 // TODO: Extend this to handle switches
2569 return nullptr;
2570 };
2571 for (BasicBlock &BB : F) {
2572 TerminatorInst *TI = BB.getTerminator();
2573 if (auto *Cond = getConditionInst(TI))
2574 // TODO: Handle more than just ICmps here. We should be able to move
2575 // most instructions without side effects or memory access.
2576 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2577 MadeChange = true;
2578 Cond->moveBefore(TI);
2579 }
2580 }
2581
Philip Reames85b36a82015-04-10 22:07:04 +00002582 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2583 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002584}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002585
2586// liveness computation via standard dataflow
2587// -------------------------------------------------------------------
2588
2589// TODO: Consider using bitvectors for liveness, the set of potentially
2590// interesting values should be small and easy to pre-compute.
2591
Philip Reamesdf1ef082015-04-10 22:53:14 +00002592/// Compute the live-in set for the location rbegin starting from
2593/// the live-out set of the basic block
2594static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2595 BasicBlock::reverse_iterator rend,
2596 DenseSet<Value *> &LiveTmp) {
2597
2598 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2599 Instruction *I = &*ritr;
2600
2601 // KILL/Def - Remove this definition from LiveIn
2602 LiveTmp.erase(I);
2603
2604 // Don't consider *uses* in PHI nodes, we handle their contribution to
2605 // predecessor blocks when we seed the LiveOut sets
2606 if (isa<PHINode>(I))
2607 continue;
2608
2609 // USE - Add to the LiveIn set for this instruction
2610 for (Value *V : I->operands()) {
2611 assert(!isUnhandledGCPointerType(V->getType()) &&
2612 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002613 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2614 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002615 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002616 // - We assume that things which are constant (from LLVM's definition)
2617 // do not move at runtime. For example, the address of a global
2618 // variable is fixed, even though it's contents may not be.
2619 // - Second, we can't disallow arbitrary inttoptr constants even
2620 // if the language frontend does. Optimization passes are free to
2621 // locally exploit facts without respect to global reachability. This
2622 // can create sections of code which are dynamically unreachable and
2623 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002624 LiveTmp.insert(V);
2625 }
2626 }
2627 }
2628}
2629
2630static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2631
2632 for (BasicBlock *Succ : successors(BB)) {
2633 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2634 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2635 PHINode *Phi = cast<PHINode>(&*I);
2636 Value *V = Phi->getIncomingValueForBlock(BB);
2637 assert(!isUnhandledGCPointerType(V->getType()) &&
2638 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002639 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002640 LiveTmp.insert(V);
2641 }
2642 }
2643 }
2644}
2645
2646static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2647 DenseSet<Value *> KillSet;
2648 for (Instruction &I : *BB)
2649 if (isHandledGCPointerType(I.getType()))
2650 KillSet.insert(&I);
2651 return KillSet;
2652}
2653
Philip Reames9638ff92015-04-11 00:06:47 +00002654#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002655/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2656/// sanity check for the liveness computation.
2657static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2658 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002659 for (Value *V : Live) {
2660 if (auto *I = dyn_cast<Instruction>(V)) {
2661 // The terminator can be a member of the LiveOut set. LLVM's definition
2662 // of instruction dominance states that V does not dominate itself. As
2663 // such, we need to special case this to allow it.
2664 if (TermOkay && TI == I)
2665 continue;
2666 assert(DT.dominates(I, TI) &&
2667 "basic SSA liveness expectation violated by liveness analysis");
2668 }
2669 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002670}
2671
2672/// Check that all the liveness sets used during the computation of liveness
2673/// obey basic SSA properties. This is useful for finding cases where we miss
2674/// a def.
2675static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2676 BasicBlock &BB) {
2677 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2678 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2679 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2680}
Philip Reames9638ff92015-04-11 00:06:47 +00002681#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002682
2683static void computeLiveInValues(DominatorTree &DT, Function &F,
2684 GCPtrLivenessData &Data) {
2685
Philip Reames4d80ede2015-04-10 23:11:26 +00002686 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002687 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002688 // We use a SetVector so that we don't have duplicates in the worklist.
2689 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002690 };
2691 auto NextItem = [&]() {
2692 BasicBlock *BB = Worklist.back();
2693 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002694 return BB;
2695 };
2696
2697 // Seed the liveness for each individual block
2698 for (BasicBlock &BB : F) {
2699 Data.KillSet[&BB] = computeKillSet(&BB);
2700 Data.LiveSet[&BB].clear();
2701 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2702
2703#ifndef NDEBUG
2704 for (Value *Kill : Data.KillSet[&BB])
2705 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2706#endif
2707
2708 Data.LiveOut[&BB] = DenseSet<Value *>();
2709 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2710 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2711 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2712 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2713 if (!Data.LiveIn[&BB].empty())
2714 AddPredsToWorklist(&BB);
2715 }
2716
2717 // Propagate that liveness until stable
2718 while (!Worklist.empty()) {
2719 BasicBlock *BB = NextItem();
2720
2721 // Compute our new liveout set, then exit early if it hasn't changed
2722 // despite the contribution of our successor.
2723 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2724 const auto OldLiveOutSize = LiveOut.size();
2725 for (BasicBlock *Succ : successors(BB)) {
2726 assert(Data.LiveIn.count(Succ));
2727 set_union(LiveOut, Data.LiveIn[Succ]);
2728 }
2729 // assert OutLiveOut is a subset of LiveOut
2730 if (OldLiveOutSize == LiveOut.size()) {
2731 // If the sets are the same size, then we didn't actually add anything
2732 // when unioning our successors LiveIn Thus, the LiveIn of this block
2733 // hasn't changed.
2734 continue;
2735 }
2736 Data.LiveOut[BB] = LiveOut;
2737
2738 // Apply the effects of this basic block
2739 DenseSet<Value *> LiveTmp = LiveOut;
2740 set_union(LiveTmp, Data.LiveSet[BB]);
2741 set_subtract(LiveTmp, Data.KillSet[BB]);
2742
2743 assert(Data.LiveIn.count(BB));
2744 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2745 // assert: OldLiveIn is a subset of LiveTmp
2746 if (OldLiveIn.size() != LiveTmp.size()) {
2747 Data.LiveIn[BB] = LiveTmp;
2748 AddPredsToWorklist(BB);
2749 }
2750 } // while( !worklist.empty() )
2751
2752#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002753 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002754 // missing kills during the above iteration.
2755 for (BasicBlock &BB : F) {
2756 checkBasicSSA(DT, Data, BB);
2757 }
2758#endif
2759}
2760
2761static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2762 StatepointLiveSetTy &Out) {
2763
2764 BasicBlock *BB = Inst->getParent();
2765
2766 // Note: The copy is intentional and required
2767 assert(Data.LiveOut.count(BB));
2768 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2769
2770 // We want to handle the statepoint itself oddly. It's
2771 // call result is not live (normal), nor are it's arguments
2772 // (unless they're used again later). This adjustment is
2773 // specifically what we need to relocate
2774 BasicBlock::reverse_iterator rend(Inst);
2775 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2776 LiveOut.erase(Inst);
2777 Out.insert(LiveOut.begin(), LiveOut.end());
2778}
2779
2780static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2781 const CallSite &CS,
2782 PartiallyConstructedSafepointRecord &Info) {
2783 Instruction *Inst = CS.getInstruction();
2784 StatepointLiveSetTy Updated;
2785 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2786
2787#ifndef NDEBUG
2788 DenseSet<Value *> Bases;
2789 for (auto KVPair : Info.PointerToBase) {
2790 Bases.insert(KVPair.second);
2791 }
2792#endif
2793 // We may have base pointers which are now live that weren't before. We need
2794 // to update the PointerToBase structure to reflect this.
2795 for (auto V : Updated)
2796 if (!Info.PointerToBase.count(V)) {
2797 assert(Bases.count(V) && "can't find base for unexpected live value");
2798 Info.PointerToBase[V] = V;
2799 continue;
2800 }
2801
2802#ifndef NDEBUG
2803 for (auto V : Updated) {
2804 assert(Info.PointerToBase.count(V) &&
2805 "must be able to find base for live value");
2806 }
2807#endif
2808
2809 // Remove any stale base mappings - this can happen since our liveness is
2810 // more precise then the one inherent in the base pointer analysis
2811 DenseSet<Value *> ToErase;
2812 for (auto KVPair : Info.PointerToBase)
2813 if (!Updated.count(KVPair.first))
2814 ToErase.insert(KVPair.first);
2815 for (auto V : ToErase)
2816 Info.PointerToBase.erase(V);
2817
2818#ifndef NDEBUG
2819 for (auto KVPair : Info.PointerToBase)
2820 assert(Updated.count(KVPair.first) && "record for non-live value");
2821#endif
2822
2823 Info.liveset = Updated;
2824}