blob: 98ed46fb12ed4e950bb103c5ec3b077f1bc0a321 [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 Reames15d55632015-09-09 23:26:08 +000024#include "llvm/ADT/MapVector.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000025#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallSite.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InstIterator.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Module.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000035#include "llvm/IR/MDBuilder.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000036#include "llvm/IR/Statepoint.h"
37#include "llvm/IR/Value.h"
38#include "llvm/IR/Verifier.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43#include "llvm/Transforms/Utils/Cloning.h"
44#include "llvm/Transforms/Utils/Local.h"
45#include "llvm/Transforms/Utils/PromoteMemToReg.h"
46
47#define DEBUG_TYPE "rewrite-statepoints-for-gc"
48
49using namespace llvm;
50
Philip Reamesd16a9b12015-02-20 01:06:44 +000051// Print the liveset found at the insert location
52static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
53 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000054static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
55 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000056// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000057static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
58 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000059
Igor Laevskye0317182015-05-19 15:59:05 +000060// Cost threshold measuring when it is profitable to rematerialize value instead
61// of relocating it
62static cl::opt<unsigned>
63RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
64 cl::init(6));
65
Philip Reamese73300b2015-04-13 16:41:32 +000066#ifdef XDEBUG
67static bool ClobberNonLive = true;
68#else
69static bool ClobberNonLive = false;
70#endif
71static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
72 cl::location(ClobberNonLive),
73 cl::Hidden);
74
Sanjoy Das25ec1a32015-10-16 02:41:00 +000075static cl::opt<bool> UseDeoptBundles("rs4gc-use-deopt-bundles", cl::Hidden,
76 cl::init(false));
77static cl::opt<bool>
78 AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
79 cl::Hidden, cl::init(true));
80
Benjamin Kramer6f665452015-02-20 14:00:58 +000081namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000082struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000083 static char ID; // Pass identification, replacement for typeid
84
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000085 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000086 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
87 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000088 bool runOnFunction(Function &F);
89 bool runOnModule(Module &M) override {
90 bool Changed = false;
91 for (Function &F : M)
92 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000093
94 if (Changed) {
95 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
96 // returns true for at least one function in the module. Since at least
97 // one function changed, we know that the precondition is satisfied.
98 stripDereferenceabilityInfo(M);
99 }
100
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000101 return Changed;
102 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000103
104 void getAnalysisUsage(AnalysisUsage &AU) const override {
105 // We add and rewrite a bunch of instructions, but don't really do much
106 // else. We could in theory preserve a lot more analyses here.
107 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000108 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000109 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000110
111 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
112 /// dereferenceability that are no longer valid/correct after
113 /// RewriteStatepointsForGC has run. This is because semantically, after
114 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
115 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
116 /// by erasing all attributes in the module that externally imply
117 /// dereferenceability.
118 ///
119 void stripDereferenceabilityInfo(Module &M);
120
121 // Helpers for stripDereferenceabilityInfo
122 void stripDereferenceabilityInfoFromBody(Function &F);
123 void stripDereferenceabilityInfoFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000124};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000125} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000126
127char RewriteStatepointsForGC::ID = 0;
128
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000129ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000130 return new RewriteStatepointsForGC();
131}
132
133INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
134 "Make relocations explicit at statepoints", false, false)
135INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
136INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
137 "Make relocations explicit at statepoints", false, false)
138
139namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000140struct GCPtrLivenessData {
141 /// Values defined in this block.
142 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
143 /// Values used in this block (and thus live); does not included values
144 /// killed within this block.
145 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
146
147 /// Values live into this basic block (i.e. used by any
148 /// instruction in this basic block or ones reachable from here)
149 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
150
151 /// Values live out of this basic block (i.e. live into
152 /// any successor block)
153 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
154};
155
Philip Reamesd16a9b12015-02-20 01:06:44 +0000156// The type of the internal cache used inside the findBasePointers family
157// of functions. From the callers perspective, this is an opaque type and
158// should not be inspected.
159//
160// In the actual implementation this caches two relations:
161// - The base relation itself (i.e. this pointer is based on that one)
162// - The base defining value relation (i.e. before base_phi insertion)
163// Generally, after the execution of a full findBasePointer call, only the
164// base relation will remain. Internally, we add a mixture of the two
165// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000166typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000167typedef DenseSet<Value *> StatepointLiveSetTy;
Sanjoy Das40bdd042015-10-07 21:32:35 +0000168typedef DenseMap<AssertingVH<Instruction>, AssertingVH<Value>>
169 RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000170
Philip Reamesd16a9b12015-02-20 01:06:44 +0000171struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000172 /// The set of values known to be live across this safepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000173 StatepointLiveSetTy LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000174
175 /// Mapping from live pointers to a base-defining-value
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000176 DenseMap<Value *, Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000177
Philip Reames0a3240f2015-02-20 21:34:11 +0000178 /// The *new* gc.statepoint instruction itself. This produces the token
179 /// that normal path gc.relocates and the gc.result are tied to.
180 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000181
Philip Reamesf2041322015-02-20 19:26:04 +0000182 /// Instruction to which exceptional gc relocates are attached
183 /// Makes it easier to iterate through them during relocationViaAlloca.
184 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000185
186 /// Record live values we are rematerialized instead of relocating.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000187 /// They are not included into 'LiveSet' field.
Igor Laevskye0317182015-05-19 15:59:05 +0000188 /// Maps rematerialized copy to it's original value.
189 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000190};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000191}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000192
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000193static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
194 assert(UseDeoptBundles && "Should not be called otherwise!");
195
196 Optional<OperandBundleUse> DeoptBundle = CS.getOperandBundle("deopt");
197
198 if (!DeoptBundle.hasValue()) {
199 assert(AllowStatepointWithNoDeoptInfo &&
200 "Found non-leaf call without deopt info!");
201 return None;
202 }
203
204 return DeoptBundle.getValue().Inputs;
205}
206
Philip Reamesdf1ef082015-04-10 22:53:14 +0000207/// Compute the live-in set for every basic block in the function
208static void computeLiveInValues(DominatorTree &DT, Function &F,
209 GCPtrLivenessData &Data);
210
211/// Given results from the dataflow liveness computation, find the set of live
212/// Values at a particular instruction.
213static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
214 StatepointLiveSetTy &out);
215
Philip Reamesd16a9b12015-02-20 01:06:44 +0000216// TODO: Once we can get to the GCStrategy, this becomes
217// Optional<bool> isGCManagedPointer(const Value *V) const override {
218
Craig Toppere3dcce92015-08-01 22:20:21 +0000219static bool isGCPointerType(Type *T) {
220 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000221 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
222 // GC managed heap. We know that a pointer into this heap needs to be
223 // updated and that no other pointer does.
224 return (1 == PT->getAddressSpace());
225 return false;
226}
227
Philip Reames8531d8c2015-04-10 21:48:25 +0000228// Return true if this type is one which a) is a gc pointer or contains a GC
229// pointer and b) is of a type this code expects to encounter as a live value.
230// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000231// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000232static bool isHandledGCPointerType(Type *T) {
233 // We fully support gc pointers
234 if (isGCPointerType(T))
235 return true;
236 // We partially support vectors of gc pointers. The code will assert if it
237 // can't handle something.
238 if (auto VT = dyn_cast<VectorType>(T))
239 if (isGCPointerType(VT->getElementType()))
240 return true;
241 return false;
242}
243
244#ifndef NDEBUG
245/// Returns true if this type contains a gc pointer whether we know how to
246/// handle that type or not.
247static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000248 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000249 return true;
250 if (VectorType *VT = dyn_cast<VectorType>(Ty))
251 return isGCPointerType(VT->getScalarType());
252 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
253 return containsGCPtrType(AT->getElementType());
254 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000255 return std::any_of(
256 ST->subtypes().begin(), ST->subtypes().end(),
257 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000258 return false;
259}
260
261// Returns true if this is a type which a) is a gc pointer or contains a GC
262// pointer and b) is of a type which the code doesn't expect (i.e. first class
263// aggregates). Used to trip assertions.
264static bool isUnhandledGCPointerType(Type *Ty) {
265 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
266}
267#endif
268
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000269static bool order_by_name(Value *a, Value *b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000270 if (a->hasName() && b->hasName()) {
271 return -1 == a->getName().compare(b->getName());
272 } else if (a->hasName() && !b->hasName()) {
273 return true;
274 } else if (!a->hasName() && b->hasName()) {
275 return false;
276 } else {
277 // Better than nothing, but not stable
278 return a < b;
279 }
280}
281
Philip Reamesece70b82015-09-09 23:57:18 +0000282// Return the name of the value suffixed with the provided value, or if the
283// value didn't have a name, the default value specified.
284static std::string suffixed_name_or(Value *V, StringRef Suffix,
285 StringRef DefaultName) {
286 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
287}
288
Philip Reamesdf1ef082015-04-10 22:53:14 +0000289// Conservatively identifies any definitions which might be live at the
290// given instruction. The analysis is performed immediately before the
291// given instruction. Values defined by that instruction are not considered
292// live. Values used by that instruction are considered live.
293static void analyzeParsePointLiveness(
294 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
295 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000296 Instruction *inst = CS.getInstruction();
297
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000298 StatepointLiveSetTy LiveSet;
299 findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000300
301 if (PrintLiveSet) {
302 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000303 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000304 // by name
Philip Reamesdab35f32015-09-02 21:11:44 +0000305 SmallVector<Value *, 64> Temp;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000306 Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
Philip Reamesdab35f32015-09-02 21:11:44 +0000307 std::sort(Temp.begin(), Temp.end(), order_by_name);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000308 errs() << "Live Variables:\n";
Philip Reamesdab35f32015-09-02 21:11:44 +0000309 for (Value *V : Temp)
310 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000311 }
312 if (PrintLiveSetSize) {
313 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000314 errs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000315 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000316 result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000317}
318
Philip Reamesf5b8e472015-09-03 21:34:30 +0000319static bool isKnownBaseResult(Value *V);
320namespace {
321/// A single base defining value - An immediate base defining value for an
322/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
323/// For instructions which have multiple pointer [vector] inputs or that
324/// transition between vector and scalar types, there is no immediate base
325/// defining value. The 'base defining value' for 'Def' is the transitive
326/// closure of this relation stopping at the first instruction which has no
327/// immediate base defining value. The b.d.v. might itself be a base pointer,
328/// but it can also be an arbitrary derived pointer.
329struct BaseDefiningValueResult {
330 /// Contains the value which is the base defining value.
331 Value * const BDV;
332 /// True if the base defining value is also known to be an actual base
333 /// pointer.
334 const bool IsKnownBase;
335 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
336 : BDV(BDV), IsKnownBase(IsKnownBase) {
337#ifndef NDEBUG
338 // Check consistency between new and old means of checking whether a BDV is
339 // a base.
340 bool MustBeBase = isKnownBaseResult(BDV);
341 assert(!MustBeBase || MustBeBase == IsKnownBase);
342#endif
343 }
344};
345}
346
347static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000348
Philip Reames8fe7f132015-06-26 22:47:37 +0000349/// Return a base defining value for the 'Index' element of the given vector
350/// instruction 'I'. If Index is null, returns a BDV for the entire vector
351/// 'I'. As an optimization, this method will try to determine when the
352/// element is known to already be a base pointer. If this can be established,
353/// the second value in the returned pair will be true. Note that either a
354/// vector or a pointer typed value can be returned. For the former, the
355/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
356/// If the later, the return pointer is a BDV (or possibly a base) for the
357/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000358static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000359findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000360 assert(I->getType()->isVectorTy() &&
361 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
362 "Illegal to ask for the base pointer of a non-pointer type");
363
364 // Each case parallels findBaseDefiningValue below, see that code for
365 // detailed motivation.
366
367 if (isa<Argument>(I))
368 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000369 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000370
371 // We shouldn't see the address of a global as a vector value?
372 assert(!isa<GlobalVariable>(I) &&
373 "unexpected global variable found in base of vector");
374
375 // inlining could possibly introduce phi node that contains
376 // undef if callee has multiple returns
377 if (isa<UndefValue>(I))
378 // utterly meaningless, but useful for dealing with partially optimized
379 // code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000380 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000381
382 // Due to inheritance, this must be _after_ the global variable and undef
383 // checks
384 if (Constant *Con = dyn_cast<Constant>(I)) {
385 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
386 "order of checks wrong!");
387 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000388 return BaseDefiningValueResult(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000389 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000390
Philip Reames8531d8c2015-04-10 21:48:25 +0000391 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000392 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000393
Philip Reames66287132015-09-09 23:40:12 +0000394 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000395 // 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.
Philip Reames66287132015-09-09 23:40:12 +0000398 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000399
Philip Reames8fe7f132015-06-26 22:47:37 +0000400 if (isa<ShuffleVectorInst>(I))
401 // We don't know whether this vector contains entirely base pointers or
402 // not. To be conservatively correct, we treat it as a BDV and will
403 // duplicate code as needed to construct a parallel vector of bases.
404 // TODO: There a number of local optimizations which could be applied here
405 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000406 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000407
408 // A PHI or Select is a base defining value. The outer findBasePointer
409 // algorithm is responsible for constructing a base value for this BDV.
410 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
411 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000412 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000413}
414
Philip Reamesd16a9b12015-02-20 01:06:44 +0000415/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000416/// defines the base pointer for the input, b) blocks the simple search
417/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
418/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000419static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000420 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000421 return findBaseDefiningValueOfVector(I);
Philip Reames8fe7f132015-06-26 22:47:37 +0000422
Philip Reamesd16a9b12015-02-20 01:06:44 +0000423 assert(I->getType()->isPointerTy() &&
424 "Illegal to ask for the base pointer of a non-pointer type");
425
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000426 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000427 // An incoming argument to the function is a base pointer
428 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000429 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000430
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000431 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000432 // base case
Philip Reamesf5b8e472015-09-03 21:34:30 +0000433 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000434
435 // inlining could possibly introduce phi node that contains
436 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000437 if (isa<UndefValue>(I))
438 // utterly meaningless, but useful for dealing with
439 // partially optimized code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000440 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000441
442 // Due to inheritance, this must be _after_ the global variable and undef
443 // checks
Philip Reames3ea15892015-09-03 21:57:40 +0000444 if (isa<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000445 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
446 "order of checks wrong!");
447 // Note: Finding a constant base for something marked for relocation
448 // doesn't really make sense. The most likely case is either a) some
449 // screwed up the address space usage or b) your validating against
450 // compiled C++ code w/o the proper separation. The only real exception
451 // is a null pointer. You could have generic code written to index of
452 // off a potentially null value and have proven it null. We also use
453 // null pointers in dead paths of relocation phis (which we might later
454 // want to find a base pointer for).
Philip Reames3ea15892015-09-03 21:57:40 +0000455 assert(isa<ConstantPointerNull>(I) &&
Philip Reames24c6cd52015-03-27 05:47:00 +0000456 "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000457 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000458 }
459
460 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000461 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000462 // If we find a cast instruction here, it means we've found a cast which is
463 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
464 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000465 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
466 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000467 }
468
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000469 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000470 // The value loaded is an gc base itself
471 return BaseDefiningValueResult(I, true);
472
Philip Reamesd16a9b12015-02-20 01:06:44 +0000473
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000474 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
475 // The base of this GEP is the base
476 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000477
478 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
479 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000480 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000481 default:
482 // fall through to general call handling
483 break;
484 case Intrinsic::experimental_gc_statepoint:
485 case Intrinsic::experimental_gc_result_float:
486 case Intrinsic::experimental_gc_result_int:
487 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000488 case Intrinsic::experimental_gc_relocate: {
489 // Rerunning safepoint insertion after safepoints are already
490 // inserted is not supported. It could probably be made to work,
491 // but why are you doing this? There's no good reason.
492 llvm_unreachable("repeat safepoint insertion is not supported");
493 }
494 case Intrinsic::gcroot:
495 // Currently, this mechanism hasn't been extended to work with gcroot.
496 // There's no reason it couldn't be, but I haven't thought about the
497 // implications much.
498 llvm_unreachable(
499 "interaction with the gcroot mechanism is not supported");
500 }
501 }
502 // We assume that functions in the source language only return base
503 // pointers. This should probably be generalized via attributes to support
504 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000505 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000506 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000507
508 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000509 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000510 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
511
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000512 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000513 // A CAS is effectively a atomic store and load combined under a
514 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000515 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000516 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000517
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000518 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000519 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000520
521 // The aggregate ops. Aggregates can either be in the heap or on the
522 // stack, but in either case, this is simply a field load. As a result,
523 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000524 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000525 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000526
527 // We should never see an insert vector since that would require we be
528 // tracing back a struct value not a pointer value.
529 assert(!isa<InsertValueInst>(I) &&
530 "Base pointer for a struct is meaningless");
531
Philip Reames9ac4e382015-08-12 21:00:20 +0000532 // An extractelement produces a base result exactly when it's input does.
533 // We may need to insert a parallel instruction to extract the appropriate
534 // element out of the base vector corresponding to the input. Given this,
535 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000536 if (isa<ExtractElementInst>(I))
537 // Note: There a lot of obvious peephole cases here. This are deliberately
538 // handled after the main base pointer inference algorithm to make writing
539 // test cases to exercise that code easier.
540 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000541
Philip Reamesd16a9b12015-02-20 01:06:44 +0000542 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000543 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000544 // derived pointers (each with it's own base potentially). It's the job of
545 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000546 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000547 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000548 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000549}
550
551/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000552static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
553 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000554 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000555 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000556 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
557 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000558 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000559 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000560 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000561}
562
563/// Return a base pointer for this value if known. Otherwise, return it's
564/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000565static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
566 Value *Def = findBaseDefiningValueCached(I, Cache);
567 auto Found = Cache.find(Def);
568 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000569 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000570 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000571 }
572 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000573 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000574}
575
576/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
577/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000578static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000579 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
580 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
581 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000582 // no recursion possible
583 return true;
584 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000585 if (isa<Instruction>(V) &&
586 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000587 // This is a previously inserted base phi or select. We know
588 // that this is a base value.
589 return true;
590 }
591
592 // We need to keep searching
593 return false;
594}
595
Philip Reamesd16a9b12015-02-20 01:06:44 +0000596namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000597/// Models the state of a single base defining value in the findBasePointer
598/// algorithm for determining where a new instruction is needed to propagate
599/// the base of this BDV.
600class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000601public:
602 enum Status { Unknown, Base, Conflict };
603
Philip Reames9b141ed2015-07-23 22:49:14 +0000604 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000605 assert(status != Base || b);
606 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000607 explicit BDVState(Value *b) : status(Base), base(b) {}
608 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000609
610 Status getStatus() const { return status; }
611 Value *getBase() const { return base; }
612
613 bool isBase() const { return getStatus() == Base; }
614 bool isUnknown() const { return getStatus() == Unknown; }
615 bool isConflict() const { return getStatus() == Conflict; }
616
Philip Reames9b141ed2015-07-23 22:49:14 +0000617 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000618 return base == other.base && status == other.status;
619 }
620
Philip Reames9b141ed2015-07-23 22:49:14 +0000621 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000622
Philip Reames2a892a62015-07-23 22:25:26 +0000623 LLVM_DUMP_METHOD
624 void dump() const { print(dbgs()); dbgs() << '\n'; }
625
626 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000627 switch (status) {
628 case Unknown:
629 OS << "U";
630 break;
631 case Base:
632 OS << "B";
633 break;
634 case Conflict:
635 OS << "C";
636 break;
637 };
638 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000639 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000640 }
641
642private:
643 Status status;
644 Value *base; // non null only if status == base
645};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000646}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000647
Philip Reames6906e922015-09-02 21:57:17 +0000648#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000649static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000650 State.print(OS);
651 return OS;
652}
Philip Reames6906e922015-09-02 21:57:17 +0000653#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000654
Philip Reamesb3967cd2015-09-02 22:30:53 +0000655namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000656// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000657// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000658// operation is implemented in MeetBDVStates::pureMeet
659class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000660public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000661 /// Initializes the currentResult to the TOP state so that if can be met with
662 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000663 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000664
Philip Reames9b141ed2015-07-23 22:49:14 +0000665 // Destructively meet the current result with the given BDVState
666 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000667 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000668 }
669
Philip Reames9b141ed2015-07-23 22:49:14 +0000670 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000671
672private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000673 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000674
Philip Reames9b141ed2015-07-23 22:49:14 +0000675 /// Perform a meet operation on two elements of the BDVState lattice.
676 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000677 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
678 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000679 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000680 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
681 << " produced " << Result << "\n");
682 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000683 }
684
Philip Reames9b141ed2015-07-23 22:49:14 +0000685 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000686 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000687 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000688 return stateB;
689
Philip Reames9b141ed2015-07-23 22:49:14 +0000690 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000691 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000692 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000693 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000694
695 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000696 if (stateA.getBase() == stateB.getBase()) {
697 assert(stateA == stateB && "equality broken!");
698 return stateA;
699 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000700 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000701 }
David Blaikie82ad7872015-02-20 23:44:24 +0000702 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000703 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000704
Philip Reames9b141ed2015-07-23 22:49:14 +0000705 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000706 return stateA;
707 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000708 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000709 }
710};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000711}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000712
713
Philip Reamesd16a9b12015-02-20 01:06:44 +0000714/// For a given value or instruction, figure out what base ptr it's derived
715/// from. For gc objects, this is simply itself. On success, returns a value
716/// which is the base pointer. (This is reliable and can be used for
717/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000718static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000719 Value *def = findBaseOrBDV(I, cache);
720
721 if (isKnownBaseResult(def)) {
722 return def;
723 }
724
725 // Here's the rough algorithm:
726 // - For every SSA value, construct a mapping to either an actual base
727 // pointer or a PHI which obscures the base pointer.
728 // - Construct a mapping from PHI to unknown TOP state. Use an
729 // optimistic algorithm to propagate base pointer information. Lattice
730 // looks like:
731 // UNKNOWN
732 // b1 b2 b3 b4
733 // CONFLICT
734 // When algorithm terminates, all PHIs will either have a single concrete
735 // base or be in a conflict state.
736 // - For every conflict, insert a dummy PHI node without arguments. Add
737 // these to the base[Instruction] = BasePtr mapping. For every
738 // non-conflict, add the actual base.
739 // - For every conflict, add arguments for the base[a] of each input
740 // arguments.
741 //
742 // Note: A simpler form of this would be to add the conflict form of all
743 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000744 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000745 // overall worse solution.
746
Philip Reames29e9ae72015-07-24 00:42:55 +0000747#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000748 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000749 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
750 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000751 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000752#endif
Philip Reames88958b22015-07-24 00:02:11 +0000753
754 // Once populated, will contain a mapping from each potentially non-base BDV
755 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000756 // We use the order of insertion (DFS over the def/use graph) to provide a
757 // stable deterministic ordering for visiting DenseMaps (which are unordered)
758 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000759 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000760
761 // Recursively fill in all base defining values reachable from the initial
762 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000763 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000764 SmallVector<Value*, 16> Worklist;
765 Worklist.push_back(def);
Philip Reames34d7a742015-09-10 00:22:49 +0000766 States.insert(std::make_pair(def, BDVState()));
Philip Reames88958b22015-07-24 00:02:11 +0000767 while (!Worklist.empty()) {
768 Value *Current = Worklist.pop_back_val();
769 assert(!isKnownBaseResult(Current) && "why did it get added?");
770
771 auto visitIncomingValue = [&](Value *InVal) {
772 Value *Base = findBaseOrBDV(InVal, cache);
773 if (isKnownBaseResult(Base))
774 // Known bases won't need new instructions introduced and can be
775 // ignored safely
776 return;
777 assert(isExpectedBDVType(Base) && "the only non-base values "
778 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000779 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000780 Worklist.push_back(Base);
781 };
782 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
783 for (Value *InVal : Phi->incoming_values())
784 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000785 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000786 visitIncomingValue(Sel->getTrueValue());
787 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000788 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
789 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000790 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
791 visitIncomingValue(IE->getOperand(0)); // vector operand
792 visitIncomingValue(IE->getOperand(1)); // scalar operand
Philip Reames9ac4e382015-08-12 21:00:20 +0000793 } else {
Philip Reames66287132015-09-09 23:40:12 +0000794 // There is one known class of instructions we know we don't handle.
795 assert(isa<ShuffleVectorInst>(Current));
Philip Reames9ac4e382015-08-12 21:00:20 +0000796 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000797 }
798 }
799 }
800
Philip Reamesdab35f32015-09-02 21:11:44 +0000801#ifndef NDEBUG
802 DEBUG(dbgs() << "States after initialization:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000803 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000804 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000805 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000806#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000807
Philip Reames273e6bb2015-07-23 21:41:27 +0000808 // Return a phi state for a base defining value. We'll generate a new
809 // base state for known bases and expect to find a cached state otherwise.
810 auto getStateForBDV = [&](Value *baseValue) {
811 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000812 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000813 auto I = States.find(baseValue);
814 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000815 return I->second;
816 };
817
Philip Reamesd16a9b12015-02-20 01:06:44 +0000818 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000819 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000820#ifndef NDEBUG
Philip Reamesb4e55f32015-09-10 00:32:56 +0000821 const size_t oldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000822#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000823 progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000824 // We're only changing values in this loop, thus safe to keep iterators.
825 // Since this is computing a fixed point, the order of visit does not
826 // effect the result. TODO: We could use a worklist here and make this run
827 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000828 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000829 Value *BDV = Pair.first;
830 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000831
Philip Reames9b141ed2015-07-23 22:49:14 +0000832 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000833 // instance which represents the BDV of that value.
834 auto getStateForInput = [&](Value *V) mutable {
835 Value *BDV = findBaseOrBDV(V, cache);
836 return getStateForBDV(BDV);
837 };
838
Philip Reames9b141ed2015-07-23 22:49:14 +0000839 MeetBDVStates calculateMeet;
Philip Reamesece70b82015-09-09 23:57:18 +0000840 if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000841 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
842 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reamesece70b82015-09-09 23:57:18 +0000843 } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000844 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000845 calculateMeet.meetWith(getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000846 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000847 // The 'meet' for an extractelement is slightly trivial, but it's still
848 // useful in that it drives us to conflict if our input is.
Philip Reames9ac4e382015-08-12 21:00:20 +0000849 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
Philip Reames66287132015-09-09 23:40:12 +0000850 } else {
851 // Given there's a inherent type mismatch between the operands, will
852 // *always* produce Conflict.
Philip Reamesece70b82015-09-09 23:57:18 +0000853 auto *IE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +0000854 calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
855 calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000856 }
857
Philip Reames34d7a742015-09-10 00:22:49 +0000858 BDVState oldState = States[BDV];
Philip Reames9b141ed2015-07-23 22:49:14 +0000859 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000860 if (oldState != newState) {
861 progress = true;
Philip Reames34d7a742015-09-10 00:22:49 +0000862 States[BDV] = newState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000863 }
864 }
865
Philip Reamesb4e55f32015-09-10 00:32:56 +0000866 assert(oldSize == States.size() &&
867 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000868 }
869
Philip Reamesdab35f32015-09-02 21:11:44 +0000870#ifndef NDEBUG
871 DEBUG(dbgs() << "States after meet iteration:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000872 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000873 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000874 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000875#endif
876
Philip Reamesd16a9b12015-02-20 01:06:44 +0000877 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000878 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000879 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000880 Instruction *I = cast<Instruction>(Pair.first);
881 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000882 assert(!isKnownBaseResult(I) && "why did it get added?");
883 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000884
885 // extractelement instructions are a bit special in that we may need to
886 // insert an extract even when we know an exact base for the instruction.
887 // The problem is that we need to convert from a vector base to a scalar
888 // base for the particular indice we're interested in.
889 if (State.isBase() && isa<ExtractElementInst>(I) &&
890 isa<VectorType>(State.getBase()->getType())) {
891 auto *EE = cast<ExtractElementInst>(I);
892 // TODO: In many cases, the new instruction is just EE itself. We should
893 // exploit this, but can't do it here since it would break the invariant
894 // about the BDV not being known to be a base.
895 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
896 EE->getIndexOperand(),
897 "base_ee", EE);
898 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000899 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000900 }
Philip Reames66287132015-09-09 23:40:12 +0000901
902 // Since we're joining a vector and scalar base, they can never be the
903 // same. As a result, we should always see insert element having reached
904 // the conflict state.
905 if (isa<InsertElementInst>(I)) {
906 assert(State.isConflict());
907 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000908
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000909 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000910 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000911
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000912 /// Create and insert a new instruction which will represent the base of
913 /// the given instruction 'I'.
914 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
915 if (isa<PHINode>(I)) {
916 BasicBlock *BB = I->getParent();
917 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
918 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000919 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000920 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000921 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
922 // The undef will be replaced later
923 UndefValue *Undef = UndefValue::get(Sel->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000924 std::string Name = suffixed_name_or(I, ".base", "base_select");
Philip Reames9ac4e382015-08-12 21:00:20 +0000925 return SelectInst::Create(Sel->getCondition(), Undef,
926 Undef, Name, Sel);
Philip Reames66287132015-09-09 23:40:12 +0000927 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000928 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000929 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000930 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
931 EE);
Philip Reames66287132015-09-09 23:40:12 +0000932 } else {
933 auto *IE = cast<InsertElementInst>(I);
934 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
935 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000936 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000937 return InsertElementInst::Create(VecUndef, ScalarUndef,
938 IE->getOperand(2), Name, IE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000939 }
Philip Reames66287132015-09-09 23:40:12 +0000940
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000941 };
942 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
943 // Add metadata marking this as a base value
944 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000945 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000946 }
947
Philip Reames3ea15892015-09-03 21:57:40 +0000948 // Returns a instruction which produces the base pointer for a given
949 // instruction. The instruction is assumed to be an input to one of the BDVs
950 // seen in the inference algorithm above. As such, we must either already
951 // know it's base defining value is a base, or have inserted a new
952 // instruction to propagate the base of it's BDV and have entered that newly
953 // introduced instruction into the state table. In either case, we are
954 // assured to be able to determine an instruction which produces it's base
955 // pointer.
956 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
957 Value *BDV = findBaseOrBDV(Input, cache);
958 Value *Base = nullptr;
959 if (isKnownBaseResult(BDV)) {
960 Base = BDV;
961 } else {
962 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000963 assert(States.count(BDV));
964 Base = States[BDV].getBase();
Philip Reames3ea15892015-09-03 21:57:40 +0000965 }
966 assert(Base && "can't be null");
967 // The cast is needed since base traversal may strip away bitcasts
968 if (Base->getType() != Input->getType() &&
969 InsertPt) {
970 Base = new BitCastInst(Base, Input->getType(), "cast",
971 InsertPt);
972 }
973 return Base;
974 };
975
Philip Reames15d55632015-09-09 23:26:08 +0000976 // Fixup all the inputs of the new PHIs. Visit order needs to be
977 // deterministic and predictable because we're naming newly created
978 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000979 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000980 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000981 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000982
Philip Reames7540e3a2015-09-10 00:01:53 +0000983 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000984 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
985 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000986 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000987
Philip Reamesc8ded462015-09-10 00:27:50 +0000988 if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000989 PHINode *phi = cast<PHINode>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +0000990 unsigned NumPHIValues = phi->getNumIncomingValues();
991 for (unsigned i = 0; i < NumPHIValues; i++) {
992 Value *InVal = phi->getIncomingValue(i);
993 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000994
Philip Reames28e61ce2015-02-28 01:57:44 +0000995 // If we've already seen InBB, add the same incoming value
996 // we added for it earlier. The IR verifier requires phi
997 // nodes with multiple entries from the same basic block
998 // to have the same incoming value for each of those
999 // entries. If we don't do this check here and basephi
1000 // has a different type than base, we'll end up adding two
1001 // bitcasts (and hence two distinct values) as incoming
1002 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001003
Philip Reames28e61ce2015-02-28 01:57:44 +00001004 int blockIndex = basephi->getBasicBlockIndex(InBB);
1005 if (blockIndex != -1) {
1006 Value *oldBase = basephi->getIncomingValue(blockIndex);
1007 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +00001008
Philip Reamesd16a9b12015-02-20 01:06:44 +00001009#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +00001010 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001011 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +00001012 // values incoming from the same basic block may be
1013 // different is by being different bitcasts of the same
1014 // value. A cleanup that remains TODO is changing
1015 // findBaseOrBDV to return an llvm::Value of the correct
1016 // type (and still remain pure). This will remove the
1017 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +00001018 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +00001019 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001020#endif
Philip Reames28e61ce2015-02-28 01:57:44 +00001021 continue;
1022 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001023
Philip Reames3ea15892015-09-03 21:57:40 +00001024 // Find the instruction which produces the base for each input. We may
1025 // need to insert a bitcast in the incoming block.
1026 // TODO: Need to split critical edges if insertion is needed
1027 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1028 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001029 }
1030 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reamesc8ded462015-09-10 00:27:50 +00001031 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001032 SelectInst *Sel = cast<SelectInst>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +00001033 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1034 // something more safe and less hacky.
1035 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001036 Value *InVal = Sel->getOperand(i);
1037 // Find the instruction which produces the base for each input. We may
1038 // need to insert a bitcast.
1039 Value *Base = getBaseForInput(InVal, BaseSel);
1040 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001041 }
Philip Reamesc8ded462015-09-10 00:27:50 +00001042 } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001043 Value *InVal = cast<ExtractElementInst>(BDV)->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 Reames66287132015-09-09 23:40:12 +00001048 } else {
Philip Reamesc8ded462015-09-10 00:27:50 +00001049 auto *BaseIE = cast<InsertElementInst>(State.getBase());
Philip Reames7540e3a2015-09-10 00:01:53 +00001050 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001051 auto UpdateOperand = [&](int OperandIdx) {
1052 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001053 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001054 BaseIE->setOperand(OperandIdx, Base);
1055 };
1056 UpdateOperand(0); // vector operand
1057 UpdateOperand(1); // scalar operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001058 }
Philip Reames66287132015-09-09 23:40:12 +00001059
Philip Reamesd16a9b12015-02-20 01:06:44 +00001060 }
1061
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001062 // Now that we're done with the algorithm, see if we can optimize the
1063 // results slightly by reducing the number of new instructions needed.
1064 // Arguably, this should be integrated into the algorithm above, but
1065 // doing as a post process step is easier to reason about for the moment.
1066 DenseMap<Value *, Value *> ReverseMap;
1067 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001068 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001069 // Note: We need to visit the states in a deterministic order. We uses the
1070 // Keys we sorted above for this purpose. Note that we are papering over a
1071 // bigger problem with the algorithm above - it's visit order is not
1072 // deterministic. A larger change is needed to fix this.
Philip Reames34d7a742015-09-10 00:22:49 +00001073 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001074 auto *BDV = Pair.first;
1075 auto State = Pair.second;
Philip Reames246e6182015-09-03 20:24:29 +00001076 Value *Base = State.getBase();
Philip Reames15d55632015-09-09 23:26:08 +00001077 assert(BDV && Base);
1078 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001079 assert(isKnownBaseResult(Base) &&
1080 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001081 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001082 continue;
1083
Philip Reames15d55632015-09-09 23:26:08 +00001084 ReverseMap[Base] = BDV;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001085 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1086 NewInsts.insert(BaseI);
1087 Worklist.insert(BaseI);
1088 }
1089 }
Philip Reames9546f362015-09-02 22:25:07 +00001090 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1091 Value *Replacement) {
1092 // Add users which are new instructions (excluding self references)
1093 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001094 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001095 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001096 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001097 // Then do the actual replacement
1098 NewInsts.erase(BaseI);
1099 ReverseMap.erase(BaseI);
1100 BaseI->replaceAllUsesWith(Replacement);
1101 BaseI->eraseFromParent();
Philip Reames34d7a742015-09-10 00:22:49 +00001102 assert(States.count(BDV));
1103 assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
1104 States[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001105 };
1106 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1107 while (!Worklist.empty()) {
1108 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001109 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001110 Value *Bdv = ReverseMap[BaseI];
1111 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1112 if (BaseI->isIdenticalTo(BdvI)) {
1113 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001114 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001115 continue;
1116 }
1117 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1118 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001119 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001120 continue;
1121 }
1122 }
1123
Philip Reamesd16a9b12015-02-20 01:06:44 +00001124 // Cache all of our results so we can cheaply reuse them
1125 // NOTE: This is actually two caches: one of the base defining value
1126 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001127 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001128 auto *BDV = Pair.first;
1129 Value *base = Pair.second.getBase();
1130 assert(BDV && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001131
Philip Reamesece70b82015-09-09 23:57:18 +00001132 std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
Philip Reamesdab35f32015-09-02 21:11:44 +00001133 DEBUG(dbgs() << "Updating base value cache"
Philip Reamesece70b82015-09-09 23:57:18 +00001134 << " for: " << BDV->getName()
Philip Reamesdab35f32015-09-02 21:11:44 +00001135 << " from: " << fromstr
Philip Reamesece70b82015-09-09 23:57:18 +00001136 << " to: " << base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001137
Philip Reames15d55632015-09-09 23:26:08 +00001138 if (cache.count(BDV)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001139 // Once we transition from the BDV relation being store in the cache to
1140 // the base relation being stored, it must be stable
Philip Reames15d55632015-09-09 23:26:08 +00001141 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001142 "base relation should be stable");
1143 }
Philip Reames15d55632015-09-09 23:26:08 +00001144 cache[BDV] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001145 }
1146 assert(cache.find(def) != cache.end());
1147 return cache[def];
1148}
1149
1150// For a set of live pointers (base and/or derived), identify the base
1151// pointer of the object which they are derived from. This routine will
1152// mutate the IR graph as needed to make the 'base' pointer live at the
1153// definition site of 'derived'. This ensures that any use of 'derived' can
1154// also use 'base'. This may involve the insertion of a number of
1155// additional PHI nodes.
1156//
1157// preconditions: live is a set of pointer type Values
1158//
1159// side effects: may insert PHI nodes into the existing CFG, will preserve
1160// CFG, will not remove or mutate any existing nodes
1161//
Philip Reamesf2041322015-02-20 19:26:04 +00001162// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001163// pointer in live. Note that derived can be equal to base if the original
1164// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001165static void
1166findBasePointers(const StatepointLiveSetTy &live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001167 DenseMap<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001168 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001169 // For the naming of values inserted to be deterministic - which makes for
1170 // much cleaner and more stable tests - we need to assign an order to the
1171 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001172 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001173 Temp.insert(Temp.end(), live.begin(), live.end());
1174 std::sort(Temp.begin(), Temp.end(), order_by_name);
1175 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001176 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001177 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001178 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001179 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1180 DT->dominates(cast<Instruction>(base)->getParent(),
1181 cast<Instruction>(ptr)->getParent())) &&
1182 "The base we found better dominate the derived pointer");
1183
David Blaikie82ad7872015-02-20 23:44:24 +00001184 // If you see this trip and like to live really dangerously, the code should
1185 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001186 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001187 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001188 "the relocation code needs adjustment to handle the relocation of "
1189 "a null pointer constant without causing false positives in the "
1190 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001191 }
1192}
1193
1194/// Find the required based pointers (and adjust the live set) for the given
1195/// parse point.
1196static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1197 const CallSite &CS,
1198 PartiallyConstructedSafepointRecord &result) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001199 DenseMap<Value *, Value *> PointerToBase;
1200 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001201
1202 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001203 // Note: Need to print these in a stable order since this is checked in
1204 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001205 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001206 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001207 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001208 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001209 Temp.push_back(Pair.first);
1210 }
1211 std::sort(Temp.begin(), Temp.end(), order_by_name);
1212 for (Value *Ptr : Temp) {
1213 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001214 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1215 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001216 }
1217 }
1218
Philip Reamesf2041322015-02-20 19:26:04 +00001219 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001220}
1221
Philip Reamesdf1ef082015-04-10 22:53:14 +00001222/// Given an updated version of the dataflow liveness results, update the
1223/// liveset and base pointer maps for the call site CS.
1224static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1225 const CallSite &CS,
1226 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001227
Philip Reamesdf1ef082015-04-10 22:53:14 +00001228static void recomputeLiveInValues(
1229 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001230 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001231 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001232 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001233 GCPtrLivenessData RevisedLivenessData;
1234 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001235 for (size_t i = 0; i < records.size(); i++) {
1236 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001237 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001238 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001239 }
1240}
1241
Philip Reames69e51ca2015-04-13 18:07:21 +00001242// When inserting gc.relocate calls, we need to ensure there are no uses
1243// of the original value between the gc.statepoint and the gc.relocate call.
1244// One case which can arise is a phi node starting one of the successor blocks.
1245// We also need to be able to insert the gc.relocates only on the path which
1246// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001247// possible.
1248static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001249normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1250 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001251 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001252 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001253 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001254 }
1255
Philip Reames69e51ca2015-04-13 18:07:21 +00001256 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1257 // from it
1258 FoldSingleEntryPHINodes(Ret);
1259 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001260
Philip Reames69e51ca2015-04-13 18:07:21 +00001261 // At this point, we can safely insert a gc.relocate as the first instruction
1262 // in Ret if needed.
1263 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001264}
1265
Philip Reamesd2b66462015-02-20 22:39:41 +00001266static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001267 auto itr = std::find(livevec.begin(), livevec.end(), val);
1268 assert(livevec.end() != itr);
1269 size_t index = std::distance(livevec.begin(), itr);
1270 assert(index < livevec.size());
1271 return index;
1272}
1273
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001274// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001275// from original call to the safepoint.
1276static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1277 AttributeSet ret;
1278
1279 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1280 unsigned index = AS.getSlotIndex(Slot);
1281
1282 if (index == AttributeSet::ReturnIndex ||
1283 index == AttributeSet::FunctionIndex) {
1284
1285 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1286 ++it) {
1287 Attribute attr = *it;
1288
1289 // Do not allow certain attributes - just skip them
1290 // Safepoint can not be read only or read none.
1291 if (attr.hasAttribute(Attribute::ReadNone) ||
1292 attr.hasAttribute(Attribute::ReadOnly))
1293 continue;
1294
1295 ret = ret.addAttributes(
1296 AS.getContext(), index,
1297 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1298 }
1299 }
1300
1301 // Just skip parameter attributes for now
1302 }
1303
1304 return ret;
1305}
1306
1307/// Helper function to place all gc relocates necessary for the given
1308/// statepoint.
1309/// Inputs:
1310/// liveVariables - list of variables to be relocated.
1311/// liveStart - index of the first live variable.
1312/// basePtrs - base pointers.
1313/// statepointToken - statepoint instruction to which relocates should be
1314/// bound.
1315/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001316static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001317 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001318 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001319 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001320 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001321 if (LiveVariables.empty())
1322 return;
1323
1324 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1325 // unique declarations for each pointer type, but this proved problematic
1326 // because the intrinsic mangling code is incomplete and fragile. Since
1327 // we're moving towards a single unified pointer type anyways, we can just
1328 // cast everything to an i8* of the right address space. A bitcast is added
1329 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001330 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001331 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1332 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1333 Value *GCRelocateDecl =
1334 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001335
Sanjoy Das5665c992015-05-11 23:47:27 +00001336 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001337 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001338 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001339 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1340 Value *LiveIdx =
1341 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001342
1343 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001344 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001345 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001346 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001347 // Trick CodeGen into thinking there are lots of free registers at this
1348 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001349 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001350 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001351}
1352
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001353namespace {
1354
1355/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1356/// avoids having to worry about keeping around dangling pointers to Values.
1357class DeferredReplacement {
1358 AssertingVH<Instruction> Old;
1359 AssertingVH<Instruction> New;
1360
1361public:
1362 explicit DeferredReplacement(Instruction *Old, Instruction *New) :
1363 Old(Old), New(New) {
1364 assert(Old != New && "Not allowed!");
1365 }
1366
1367 /// Does the task represented by this instance.
1368 void doReplacement() {
1369 Instruction *OldI = Old;
1370 Instruction *NewI = New;
1371
1372 assert(OldI != NewI && "Disallowed at construction?!");
1373
1374 Old = nullptr;
1375 New = nullptr;
1376
1377 if (NewI)
1378 OldI->replaceAllUsesWith(NewI);
1379 OldI->eraseFromParent();
1380 }
1381};
1382}
1383
Philip Reamesd16a9b12015-02-20 01:06:44 +00001384static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001385makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1386 const SmallVectorImpl<Value *> &BasePtrs,
1387 const SmallVectorImpl<Value *> &LiveVariables,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001388 PartiallyConstructedSafepointRecord &Result,
1389 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001390 assert(BasePtrs.size() == LiveVariables.size());
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001391 assert((UseDeoptBundles || isStatepoint(CS)) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001392 "This method expects to be rewriting a statepoint");
1393
Philip Reamesd16a9b12015-02-20 01:06:44 +00001394 // Then go ahead and use the builder do actually do the inserts. We insert
1395 // immediately before the previous instruction under the assumption that all
1396 // arguments will be available here. We can't insert afterwards since we may
1397 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001398 Instruction *InsertBefore = CS.getInstruction();
1399 IRBuilder<> Builder(InsertBefore);
1400
Sanjoy Das3c520a12015-10-08 23:18:38 +00001401 ArrayRef<Value *> GCArgs(LiveVariables);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001402 uint64_t StatepointID = 0xABCDEF00;
1403 uint32_t NumPatchBytes = 0;
1404 uint32_t Flags = uint32_t(StatepointFlags::None);
Sanjoy Das3c520a12015-10-08 23:18:38 +00001405
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001406 ArrayRef<Use> CallArgs;
1407 ArrayRef<Use> DeoptArgs;
1408 ArrayRef<Use> TransitionArgs;
1409
1410 Value *CallTarget = nullptr;
1411
1412 if (UseDeoptBundles) {
1413 CallArgs = {CS.arg_begin(), CS.arg_end()};
1414 DeoptArgs = GetDeoptBundleOperands(CS);
1415 // TODO: we don't fill in TransitionArgs or Flags in this branch, but we
1416 // could have an operand bundle for that too.
1417 AttributeSet OriginalAttrs = CS.getAttributes();
1418
1419 Attribute AttrID = OriginalAttrs.getAttribute(AttributeSet::FunctionIndex,
1420 "statepoint-id");
1421 if (AttrID.isStringAttribute())
1422 AttrID.getValueAsString().getAsInteger(10, StatepointID);
1423
1424 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
1425 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
1426 if (AttrNumPatchBytes.isStringAttribute())
1427 AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
1428
1429 CallTarget = CS.getCalledValue();
1430 } else {
1431 // This branch will be gone soon, and we will soon only support the
1432 // UseDeoptBundles == true configuration.
1433 Statepoint OldSP(CS);
1434 StatepointID = OldSP.getID();
1435 NumPatchBytes = OldSP.getNumPatchBytes();
1436 Flags = OldSP.getFlags();
1437
1438 CallArgs = {OldSP.arg_begin(), OldSP.arg_end()};
1439 DeoptArgs = {OldSP.vm_state_begin(), OldSP.vm_state_end()};
1440 TransitionArgs = {OldSP.gc_transition_args_begin(),
1441 OldSP.gc_transition_args_end()};
1442 CallTarget = OldSP.getCalledValue();
1443 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001444
1445 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001446 Instruction *Token = nullptr;
1447 AttributeSet ReturnAttrs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001448 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001449 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Das3c520a12015-10-08 23:18:38 +00001450 CallInst *Call = Builder.CreateGCStatepointCall(
1451 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1452 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1453
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001454 Call->setTailCall(ToReplace->isTailCall());
1455 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001456
1457 // Currently we will fail on parameter attributes and on certain
1458 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001459 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001460 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001461 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001462 Call->setAttributes(NewAttrs.getFnAttributes());
1463 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001464
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001465 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001466
1467 // Put the following gc_result and gc_relocate calls immediately after the
1468 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001469 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1470 Builder.SetInsertPoint(ToReplace->getNextNode());
1471 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001472 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001473 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001474
1475 // Insert the new invoke into the old block. We'll remove the old one in a
1476 // moment at which point this will become the new terminator for the
1477 // original block.
Sanjoy Das3c520a12015-10-08 23:18:38 +00001478 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1479 StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1480 ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1481 GCArgs, "statepoint_token");
1482
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001483 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001484
1485 // Currently we will fail on parameter attributes and on certain
1486 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001487 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001488 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001489 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001490 Invoke->setAttributes(NewAttrs.getFnAttributes());
1491 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001492
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001493 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001494
1495 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001496 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1497 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1498 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001499 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001500
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001501 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001502 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001503
1504 // Extract second element from landingpad return value. We will attach
1505 // exceptional gc relocates to it.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001506 Instruction *ExceptionalToken =
Philip Reamesd16a9b12015-02-20 01:06:44 +00001507 cast<Instruction>(Builder.CreateExtractValue(
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001508 UnwindBlock->getLandingPadInst(), 1, "relocate_token"));
1509 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001510
Sanjoy Das3c520a12015-10-08 23:18:38 +00001511 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001512 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1513 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001514
1515 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001516 BasicBlock *NormalDest = ToReplace->getNormalDest();
1517 assert(!isa<PHINode>(NormalDest->begin()) &&
1518 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001519 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001520
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001521 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001522
1523 // gc relocates will be generated later as if it were regular call
1524 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001525 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001526 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001527
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001528 if (UseDeoptBundles) {
1529 Token->setName("statepoint_token");
1530 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1531 StringRef Name =
1532 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1533 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
1534 GCResult->setAttributes(CS.getAttributes().getRetAttributes());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001535
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001536 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1537 // live set of some other safepoint, in which case that safepoint's
1538 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1539 // llvm::Instruction. Instead, we defer the replacement and deletion to
1540 // after the live sets have been made explicit in the IR, and we no longer
1541 // have raw pointers to worry about.
1542 Replacements.emplace_back(CS.getInstruction(), GCResult);
1543 } else {
1544 Replacements.emplace_back(CS.getInstruction(), nullptr);
1545 }
1546 } else {
1547 assert(!CS.getInstruction()->hasNUsesOrMore(2) &&
1548 "only valid use before rewrite is gc.result");
1549 assert(!CS.getInstruction()->hasOneUse() ||
1550 isGCResult(cast<Instruction>(*CS.getInstruction()->user_begin())));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001551
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001552 // Take the name of the original statepoint token if there was one.
1553 Token->takeName(CS.getInstruction());
1554
1555 // Update the gc.result of the original statepoint (if any) to use the newly
1556 // inserted statepoint. This is safe to do here since the token can't be
1557 // considered a live reference.
1558 CS.getInstruction()->replaceAllUsesWith(Token);
1559 CS.getInstruction()->eraseFromParent();
1560 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001561
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001562 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001563
Philip Reamesd16a9b12015-02-20 01:06:44 +00001564 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001565 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001566 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001567}
1568
1569namespace {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001570struct NameOrdering {
1571 Value *Base;
1572 Value *Derived;
1573
1574 bool operator()(NameOrdering const &a, NameOrdering const &b) {
1575 return -1 == a.Derived->getName().compare(b.Derived->getName());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001576 }
1577};
1578}
Philip Reamesd16a9b12015-02-20 01:06:44 +00001579
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001580static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
1581 SmallVectorImpl<Value *> &LiveVec) {
1582 assert(BaseVec.size() == LiveVec.size());
1583
1584 SmallVector<NameOrdering, 64> Temp;
1585 for (size_t i = 0; i < BaseVec.size(); i++) {
1586 NameOrdering v;
1587 v.Base = BaseVec[i];
1588 v.Derived = LiveVec[i];
1589 Temp.push_back(v);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001590 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001591
1592 std::sort(Temp.begin(), Temp.end(), NameOrdering());
1593 for (size_t i = 0; i < BaseVec.size(); i++) {
1594 BaseVec[i] = Temp[i].Base;
1595 LiveVec[i] = Temp[i].Derived;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001596 }
1597}
1598
1599// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1600// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001601//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001602// WARNING: Does not do any fixup to adjust users of the original live
1603// values. That's the callers responsibility.
1604static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001605makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001606 PartiallyConstructedSafepointRecord &Result,
1607 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001608 const auto &LiveSet = Result.LiveSet;
1609 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001610
1611 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001612 SmallVector<Value *, 64> BaseVec, LiveVec;
1613 LiveVec.reserve(LiveSet.size());
1614 BaseVec.reserve(LiveSet.size());
1615 for (Value *L : LiveSet) {
1616 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001617 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001618 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001619 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001620 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001621 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001622
1623 // To make the output IR slightly more stable (for use in diffs), ensure a
1624 // fixed order of the values in the safepoint (by sorting the value name).
1625 // The order is otherwise meaningless.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001626 StabilizeOrder(BaseVec, LiveVec);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001627
1628 // Do the actual rewriting and delete the old statepoint
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001629 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001630}
1631
1632// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001633//
1634// It receives iterator to the statepoint gc relocates and emits a store to the
1635// assigned location (via allocaMap) for the each one of them. It adds the
1636// visited values into the visitedLiveValues set, which we will later use them
1637// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001638static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001639insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1640 DenseMap<Value *, Value *> &AllocaMap,
1641 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001642
Sanjoy Das5665c992015-05-11 23:47:27 +00001643 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001644 if (!isa<IntrinsicInst>(U))
1645 continue;
1646
Sanjoy Das5665c992015-05-11 23:47:27 +00001647 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001648
1649 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001650 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001651 Intrinsic::experimental_gc_relocate) {
1652 continue;
1653 }
1654
Sanjoy Das5665c992015-05-11 23:47:27 +00001655 GCRelocateOperands RelocateOperands(RelocatedValue);
1656 Value *OriginalValue =
1657 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1658 assert(AllocaMap.count(OriginalValue));
1659 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001660
1661 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001662 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001663 // the correct type according to alloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001664 assert(RelocatedValue->getNextNode() &&
1665 "Should always have one since it's not a terminator");
Sanjoy Das5665c992015-05-11 23:47:27 +00001666 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001667 Value *CastedRelocatedValue =
Philip Reamesece70b82015-09-09 23:57:18 +00001668 Builder.CreateBitCast(RelocatedValue,
1669 cast<AllocaInst>(Alloca)->getAllocatedType(),
1670 suffixed_name_or(RelocatedValue, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001671
Sanjoy Das5665c992015-05-11 23:47:27 +00001672 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1673 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001674
1675#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001676 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001677#endif
1678 }
1679}
1680
Igor Laevskye0317182015-05-19 15:59:05 +00001681// Helper function for the "relocationViaAlloca". Similar to the
1682// "insertRelocationStores" but works for rematerialized values.
1683static void
1684insertRematerializationStores(
1685 RematerializedValueMapTy RematerializedValues,
1686 DenseMap<Value *, Value *> &AllocaMap,
1687 DenseSet<Value *> &VisitedLiveValues) {
1688
1689 for (auto RematerializedValuePair: RematerializedValues) {
1690 Instruction *RematerializedValue = RematerializedValuePair.first;
1691 Value *OriginalValue = RematerializedValuePair.second;
1692
1693 assert(AllocaMap.count(OriginalValue) &&
1694 "Can not find alloca for rematerialized value");
1695 Value *Alloca = AllocaMap[OriginalValue];
1696
1697 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1698 Store->insertAfter(RematerializedValue);
1699
1700#ifndef NDEBUG
1701 VisitedLiveValues.insert(OriginalValue);
1702#endif
1703 }
1704}
1705
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001706/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001707static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001708 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001709 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001710#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001711 // record initial number of (static) allocas; we'll check we have the same
1712 // number when we get done.
1713 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001714 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1715 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001716 if (isa<AllocaInst>(*I))
1717 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001718#endif
1719
1720 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001721 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001722 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001723 // Used later to chack that we have enough allocas to store all values
1724 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001725 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001726
Igor Laevskye0317182015-05-19 15:59:05 +00001727 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1728 // "PromotableAllocas"
1729 auto emitAllocaFor = [&](Value *LiveValue) {
1730 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1731 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001732 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001733 PromotableAllocas.push_back(Alloca);
1734 };
1735
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001736 // Emit alloca for each live gc pointer
1737 for (Value *V : Live)
1738 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001739
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001740 // Emit allocas for rematerialized values
1741 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001742 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001743 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001744 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001745 continue;
1746
1747 emitAllocaFor(OriginalValue);
1748 ++NumRematerializedValues;
1749 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001750
Philip Reamesd16a9b12015-02-20 01:06:44 +00001751 // The next two loops are part of the same conceptual operation. We need to
1752 // insert a store to the alloca after the original def and at each
1753 // redefinition. We need to insert a load before each use. These are split
1754 // into distinct loops for performance reasons.
1755
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001756 // Update gc pointer after each statepoint: either store a relocated value or
1757 // null (if no relocated value was found for this gc pointer and it is not a
1758 // gc_result). This must happen before we update the statepoint with load of
1759 // alloca otherwise we lose the link between statepoint and old def.
1760 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001761 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001762
1763 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001764 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001765
1766 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001767 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001768
1769 // In case if it was invoke statepoint
1770 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001771 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001772 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1773 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001774 }
1775
Igor Laevskye0317182015-05-19 15:59:05 +00001776 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001777 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1778 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001779
Philip Reamese73300b2015-04-13 16:41:32 +00001780 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001781 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001782 // the gc.statepoint. This will turn some subtle GC problems into
1783 // slightly easier to debug SEGVs. Note that on large IR files with
1784 // lots of gc.statepoints this is extremely costly both memory and time
1785 // wise.
1786 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001787 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001788 Value *Def = Pair.first;
1789 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001790
Philip Reamese73300b2015-04-13 16:41:32 +00001791 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001792 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001793 continue;
1794 }
1795 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001796 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001797
Philip Reamese73300b2015-04-13 16:41:32 +00001798 auto InsertClobbersAt = [&](Instruction *IP) {
1799 for (auto *AI : ToClobber) {
1800 auto AIType = cast<PointerType>(AI->getType());
1801 auto PT = cast<PointerType>(AIType->getElementType());
1802 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001803 StoreInst *Store = new StoreInst(CPN, AI);
1804 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001805 }
1806 };
1807
1808 // Insert the clobbering stores. These may get intermixed with the
1809 // gc.results and gc.relocates, but that's fine.
1810 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001811 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1812 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001813 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001814 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001815 }
David Blaikie82ad7872015-02-20 23:44:24 +00001816 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001817 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001818
1819 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001820 for (auto Pair : AllocaMap) {
1821 Value *Def = Pair.first;
1822 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001823
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001824 // We pre-record the uses of allocas so that we dont have to worry about
1825 // later update that changes the user information..
1826
Igor Laevsky285fe842015-05-19 16:29:43 +00001827 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001828 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001829 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1830 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001831 if (!isa<ConstantExpr>(U)) {
1832 // If the def has a ConstantExpr use, then the def is either a
1833 // ConstantExpr use itself or null. In either case
1834 // (recursively in the first, directly in the second), the oop
1835 // it is ultimately dependent on is null and this particular
1836 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001837 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001838 }
1839 }
1840
Igor Laevsky285fe842015-05-19 16:29:43 +00001841 std::sort(Uses.begin(), Uses.end());
1842 auto Last = std::unique(Uses.begin(), Uses.end());
1843 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001844
Igor Laevsky285fe842015-05-19 16:29:43 +00001845 for (Instruction *Use : Uses) {
1846 if (isa<PHINode>(Use)) {
1847 PHINode *Phi = cast<PHINode>(Use);
1848 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1849 if (Def == Phi->getIncomingValue(i)) {
1850 LoadInst *Load = new LoadInst(
1851 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1852 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001853 }
1854 }
1855 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001856 LoadInst *Load = new LoadInst(Alloca, "", Use);
1857 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001858 }
1859 }
1860
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001861 // Emit store for the initial gc value. Store must be inserted after load,
1862 // otherwise store will be in alloca's use list and an extra load will be
1863 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001864 StoreInst *Store = new StoreInst(Def, Alloca);
1865 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1866 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001867 // InvokeInst is a TerminatorInst so the store need to be inserted
1868 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001869 BasicBlock *NormalDest = Invoke->getNormalDest();
1870 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001871 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001872 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001873 "The only TerminatorInst that can produce a value is "
1874 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001875 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001876 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001877 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001878 assert(isa<Argument>(Def));
1879 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001880 }
1881 }
1882
Igor Laevsky285fe842015-05-19 16:29:43 +00001883 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001884 "we must have the same allocas with lives");
1885 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001886 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001887 PromoteMemToReg(PromotableAllocas, DT);
1888 }
1889
1890#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001891 for (auto &I : F.getEntryBlock())
1892 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001893 InitialAllocaNum--;
1894 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001895#endif
1896}
1897
1898/// Implement a unique function which doesn't require we sort the input
1899/// vector. Doing so has the effect of changing the output of a couple of
1900/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001901template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001902 SmallSet<T, 8> Seen;
1903 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1904 return !Seen.insert(V).second;
1905 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001906}
1907
Philip Reamesd16a9b12015-02-20 01:06:44 +00001908/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001909/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001910static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001911 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001912 if (Values.empty())
1913 // No values to hold live, might as well not insert the empty holder
1914 return;
1915
Philip Reamesd16a9b12015-02-20 01:06:44 +00001916 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001917 // Use a dummy vararg function to actually hold the values live
1918 Function *Func = cast<Function>(M->getOrInsertFunction(
1919 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001920 if (CS.isCall()) {
1921 // For call safepoints insert dummy calls right after safepoint
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001922 Holders.push_back(CallInst::Create(Func, Values, "",
1923 &*++CS.getInstruction()->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001924 return;
1925 }
1926 // For invoke safepooints insert dummy calls both in normal and
1927 // exceptional destination blocks
1928 auto *II = cast<InvokeInst>(CS.getInstruction());
1929 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001930 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001931 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001932 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001933}
1934
1935static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001936 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1937 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001938 GCPtrLivenessData OriginalLivenessData;
1939 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001940 for (size_t i = 0; i < records.size(); i++) {
1941 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001942 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001943 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001944 }
1945}
1946
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001947/// Remove any vector of pointers from the live set by scalarizing them over the
1948/// statepoint instruction. Adds the scalarized pieces to the live set. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001949/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001950/// the lowering code currently does not handle that. Extending it would be
1951/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001952/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001953static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001954 StatepointLiveSetTy &LiveSet,
1955 DenseMap<Value *, Value *>& PointerToBase,
1956 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001957 SmallVector<Value *, 16> ToSplit;
1958 for (Value *V : LiveSet)
1959 if (isa<VectorType>(V->getType()))
1960 ToSplit.push_back(V);
1961
1962 if (ToSplit.empty())
1963 return;
1964
Philip Reames8fe7f132015-06-26 22:47:37 +00001965 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1966
Philip Reames8531d8c2015-04-10 21:48:25 +00001967 Function &F = *(StatepointInst->getParent()->getParent());
1968
Philip Reames704e78b2015-04-10 22:34:56 +00001969 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001970 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001971 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001972 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001973 AllocaInst *Alloca =
1974 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001975 AllocaMap[V] = Alloca;
1976
1977 VectorType *VT = cast<VectorType>(V->getType());
1978 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001979 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001980 for (unsigned i = 0; i < VT->getNumElements(); i++)
1981 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001982 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001983
1984 auto InsertVectorReform = [&](Instruction *IP) {
1985 Builder.SetInsertPoint(IP);
1986 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1987 Value *ResultVec = UndefValue::get(VT);
1988 for (unsigned i = 0; i < VT->getNumElements(); i++)
1989 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1990 Builder.getInt32(i));
1991 return ResultVec;
1992 };
1993
1994 if (isa<CallInst>(StatepointInst)) {
1995 BasicBlock::iterator Next(StatepointInst);
1996 Next++;
1997 Instruction *IP = &*(Next);
1998 Replacements[V].first = InsertVectorReform(IP);
1999 Replacements[V].second = nullptr;
2000 } else {
2001 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
2002 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00002003 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00002004 BasicBlock *NormalDest = Invoke->getNormalDest();
2005 assert(!isa<PHINode>(NormalDest->begin()));
2006 BasicBlock *UnwindDest = Invoke->getUnwindDest();
2007 assert(!isa<PHINode>(UnwindDest->begin()));
2008 // Insert insert element sequences in both successors
2009 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
2010 Replacements[V].first = InsertVectorReform(IP);
2011 IP = &*(UnwindDest->getFirstInsertionPt());
2012 Replacements[V].second = InsertVectorReform(IP);
2013 }
2014 }
Philip Reames8fe7f132015-06-26 22:47:37 +00002015
Philip Reames8531d8c2015-04-10 21:48:25 +00002016 for (Value *V : ToSplit) {
2017 AllocaInst *Alloca = AllocaMap[V];
2018
2019 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00002020 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00002021 for (User *U : V->users())
2022 Users.push_back(cast<Instruction>(U));
2023
2024 for (Instruction *I : Users) {
2025 if (auto Phi = dyn_cast<PHINode>(I)) {
2026 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
2027 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00002028 LoadInst *Load = new LoadInst(
2029 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00002030 Phi->setIncomingValue(i, Load);
2031 }
2032 } else {
2033 LoadInst *Load = new LoadInst(Alloca, "", I);
2034 I->replaceUsesOfWith(V, Load);
2035 }
2036 }
2037
2038 // Store the original value and the replacement value into the alloca
2039 StoreInst *Store = new StoreInst(V, Alloca);
2040 if (auto I = dyn_cast<Instruction>(V))
2041 Store->insertAfter(I);
2042 else
2043 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00002044
Philip Reames8531d8c2015-04-10 21:48:25 +00002045 // Normal return for invoke, or call return
2046 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
2047 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2048 // Unwind return for invoke only
2049 Replacement = cast_or_null<Instruction>(Replacements[V].second);
2050 if (Replacement)
2051 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2052 }
2053
2054 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00002055 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00002056 for (Value *V : ToSplit)
2057 Allocas.push_back(AllocaMap[V]);
2058 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00002059
2060 // Update our tracking of live pointers and base mappings to account for the
2061 // changes we just made.
2062 for (Value *V : ToSplit) {
2063 auto &Elements = ElementMapping[V];
2064
2065 LiveSet.erase(V);
2066 LiveSet.insert(Elements.begin(), Elements.end());
2067 // We need to update the base mapping as well.
2068 assert(PointerToBase.count(V));
2069 Value *OldBase = PointerToBase[V];
2070 auto &BaseElements = ElementMapping[OldBase];
2071 PointerToBase.erase(V);
2072 assert(Elements.size() == BaseElements.size());
2073 for (unsigned i = 0; i < Elements.size(); i++) {
2074 Value *Elem = Elements[i];
2075 PointerToBase[Elem] = BaseElements[i];
2076 }
2077 }
Philip Reames8531d8c2015-04-10 21:48:25 +00002078}
2079
Igor Laevskye0317182015-05-19 15:59:05 +00002080// Helper function for the "rematerializeLiveValues". It walks use chain
2081// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2082// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002083// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00002084// Fills "ChainToBase" array with all visited values. "BaseValue" is not
2085// recorded.
2086static bool findRematerializableChainToBasePointer(
2087 SmallVectorImpl<Instruction*> &ChainToBase,
2088 Value *CurrentValue, Value *BaseValue) {
2089
2090 // We have found a base value
2091 if (CurrentValue == BaseValue) {
2092 return true;
2093 }
2094
2095 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2096 ChainToBase.push_back(GEP);
2097 return findRematerializableChainToBasePointer(ChainToBase,
2098 GEP->getPointerOperand(),
2099 BaseValue);
2100 }
2101
2102 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2103 Value *Def = CI->stripPointerCasts();
2104
2105 // This two checks are basically similar. First one is here for the
2106 // consistency with findBasePointers logic.
2107 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2108 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2109 return false;
2110
2111 ChainToBase.push_back(CI);
2112 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2113 }
2114
2115 // Not supported instruction in the chain
2116 return false;
2117}
2118
2119// Helper function for the "rematerializeLiveValues". Compute cost of the use
2120// chain we are going to rematerialize.
2121static unsigned
2122chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2123 TargetTransformInfo &TTI) {
2124 unsigned Cost = 0;
2125
2126 for (Instruction *Instr : Chain) {
2127 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2128 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2129 "non noop cast is found during rematerialization");
2130
2131 Type *SrcTy = CI->getOperand(0)->getType();
2132 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2133
2134 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2135 // Cost of the address calculation
2136 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2137 Cost += TTI.getAddressComputationCost(ValTy);
2138
2139 // And cost of the GEP itself
2140 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2141 // allowed for the external usage)
2142 if (!GEP->hasAllConstantIndices())
2143 Cost += 2;
2144
2145 } else {
2146 llvm_unreachable("unsupported instruciton type during rematerialization");
2147 }
2148 }
2149
2150 return Cost;
2151}
2152
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002153// From the statepoint live set pick values that are cheaper to recompute then
2154// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00002155// statepoint and record them in "Info" structure. Note that similar to
2156// relocated values we don't do any user adjustments here.
2157static void rematerializeLiveValues(CallSite CS,
2158 PartiallyConstructedSafepointRecord &Info,
2159 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002160 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002161
Igor Laevskye0317182015-05-19 15:59:05 +00002162 // Record values we are going to delete from this statepoint live set.
2163 // We can not di this in following loop due to iterator invalidation.
2164 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2165
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002166 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00002167 // For each live pointer find it's defining chain
2168 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002169 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002170 bool FoundChain =
2171 findRematerializableChainToBasePointer(ChainToBase,
2172 LiveValue,
2173 Info.PointerToBase[LiveValue]);
2174 // Nothing to do, or chain is too long
2175 if (!FoundChain ||
2176 ChainToBase.size() == 0 ||
2177 ChainToBase.size() > ChainLengthThreshold)
2178 continue;
2179
2180 // Compute cost of this chain
2181 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2182 // TODO: We can also account for cases when we will be able to remove some
2183 // of the rematerialized values by later optimization passes. I.e if
2184 // we rematerialized several intersecting chains. Or if original values
2185 // don't have any uses besides this statepoint.
2186
2187 // For invokes we need to rematerialize each chain twice - for normal and
2188 // for unwind basic blocks. Model this by multiplying cost by two.
2189 if (CS.isInvoke()) {
2190 Cost *= 2;
2191 }
2192 // If it's too expensive - skip it
2193 if (Cost >= RematerializationThreshold)
2194 continue;
2195
2196 // Remove value from the live set
2197 LiveValuesToBeDeleted.push_back(LiveValue);
2198
2199 // Clone instructions and record them inside "Info" structure
2200
2201 // Walk backwards to visit top-most instructions first
2202 std::reverse(ChainToBase.begin(), ChainToBase.end());
2203
2204 // Utility function which clones all instructions from "ChainToBase"
2205 // and inserts them before "InsertBefore". Returns rematerialized value
2206 // which should be used after statepoint.
2207 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2208 Instruction *LastClonedValue = nullptr;
2209 Instruction *LastValue = nullptr;
2210 for (Instruction *Instr: ChainToBase) {
2211 // Only GEP's and casts are suported as we need to be careful to not
2212 // introduce any new uses of pointers not in the liveset.
2213 // Note that it's fine to introduce new uses of pointers which were
2214 // otherwise not used after this statepoint.
2215 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2216
2217 Instruction *ClonedValue = Instr->clone();
2218 ClonedValue->insertBefore(InsertBefore);
2219 ClonedValue->setName(Instr->getName() + ".remat");
2220
2221 // If it is not first instruction in the chain then it uses previously
2222 // cloned value. We should update it to use cloned value.
2223 if (LastClonedValue) {
2224 assert(LastValue);
2225 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2226#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002227 // Assert that cloned instruction does not use any instructions from
2228 // this chain other than LastClonedValue
2229 for (auto OpValue : ClonedValue->operand_values()) {
2230 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2231 ChainToBase.end() &&
2232 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002233 }
2234#endif
2235 }
2236
2237 LastClonedValue = ClonedValue;
2238 LastValue = Instr;
2239 }
2240 assert(LastClonedValue);
2241 return LastClonedValue;
2242 };
2243
2244 // Different cases for calls and invokes. For invokes we need to clone
2245 // instructions both on normal and unwind path.
2246 if (CS.isCall()) {
2247 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2248 assert(InsertBefore);
2249 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2250 Info.RematerializedValues[RematerializedValue] = LiveValue;
2251 } else {
2252 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2253
2254 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002255 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002256 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002257 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002258
2259 Instruction *NormalRematerializedValue =
2260 rematerializeChain(NormalInsertBefore);
2261 Instruction *UnwindRematerializedValue =
2262 rematerializeChain(UnwindInsertBefore);
2263
2264 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2265 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2266 }
2267 }
2268
2269 // Remove rematerializaed values from the live set
2270 for (auto LiveValue: LiveValuesToBeDeleted) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002271 Info.LiveSet.erase(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002272 }
2273}
2274
Philip Reamesd16a9b12015-02-20 01:06:44 +00002275static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002276 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002277#ifndef NDEBUG
2278 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002279 std::set<CallSite> Uniqued;
2280 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2281 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002282
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002283 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002284 assert(CS.getInstruction()->getParent()->getParent() == &F);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002285 assert((UseDeoptBundles || isStatepoint(CS)) &&
2286 "expected to already be a deopt statepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002287 }
2288#endif
2289
Philip Reames69e51ca2015-04-13 18:07:21 +00002290 // When inserting gc.relocates for invokes, we need to be able to insert at
2291 // the top of the successor blocks. See the comment on
2292 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002293 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002294 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002295 if (!CS.isInvoke())
2296 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002297 auto *II = cast<InvokeInst>(CS.getInstruction());
2298 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2299 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002300 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002301
Philip Reamesd16a9b12015-02-20 01:06:44 +00002302 // A list of dummy calls added to the IR to keep various values obviously
2303 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002304 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002305
2306 // Insert a dummy call with all of the arguments to the vm_state we'll need
2307 // for the actual safepoint insertion. This ensures reference arguments in
2308 // the deopt argument list are considered live through the safepoint (and
2309 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002310 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002311 SmallVector<Value *, 64> DeoptValues;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002312
2313 iterator_range<const Use *> DeoptStateRange =
2314 UseDeoptBundles
2315 ? iterator_range<const Use *>(GetDeoptBundleOperands(CS))
2316 : iterator_range<const Use *>(Statepoint(CS).vm_state_args());
2317
2318 for (Value *Arg : DeoptStateRange) {
Philip Reames8531d8c2015-04-10 21:48:25 +00002319 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2320 "support for FCA unimplemented");
2321 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002322 DeoptValues.push_back(Arg);
2323 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002324
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002325 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002326 }
2327
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002328 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002329
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002330 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002331 // site.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002332 findLiveReferences(F, DT, P, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002333
2334 // B) Find the base pointers for each live pointer
2335 /* scope for caching */ {
2336 // Cache the 'defining value' relation used in the computation and
2337 // insertion of base phis and selects. This ensures that we don't insert
2338 // large numbers of duplicate base_phis.
2339 DefiningValueMapTy DVCache;
2340
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002341 for (size_t i = 0; i < Records.size(); i++) {
2342 PartiallyConstructedSafepointRecord &info = Records[i];
2343 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002344 }
2345 } // end of cache scope
2346
2347 // The base phi insertion logic (for any safepoint) may have inserted new
2348 // instructions which are now live at some safepoint. The simplest such
2349 // example is:
2350 // loop:
2351 // phi a <-- will be a new base_phi here
2352 // safepoint 1 <-- that needs to be live here
2353 // gep a + 1
2354 // safepoint 2
2355 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002356 // We insert some dummy calls after each safepoint to definitely hold live
2357 // the base pointers which were identified for that safepoint. We'll then
2358 // ask liveness for _every_ base inserted to see what is now live. Then we
2359 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002360 Holders.reserve(Holders.size() + Records.size());
2361 for (size_t i = 0; i < Records.size(); i++) {
2362 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002363
2364 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002365 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002366 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002367
2368 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002369 }
2370
Philip Reamesdf1ef082015-04-10 22:53:14 +00002371 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2372 // need to rerun liveness. We may *also* have inserted new defs, but that's
2373 // not the key issue.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002374 recomputeLiveInValues(F, DT, P, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002375
Philip Reamesd16a9b12015-02-20 01:06:44 +00002376 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002377 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002378 errs() << "Base Pairs: (w/Relocation)\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002379 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002380 errs() << " derived %" << Pair.first->getName() << " base %"
2381 << Pair.second->getName() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00002382 }
2383 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002384
2385 for (CallInst *CI : Holders)
2386 CI->eraseFromParent();
2387
2388 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002389
Philip Reames8fe7f132015-06-26 22:47:37 +00002390 // Do a limited scalarization of any live at safepoint vector values which
2391 // contain pointers. This enables this pass to run after vectorization at
2392 // the cost of some possible performance loss. TODO: it would be nice to
2393 // natively support vectors all the way through the backend so we don't need
2394 // to scalarize here.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002395 for (size_t i = 0; i < Records.size(); i++) {
2396 PartiallyConstructedSafepointRecord &Info = Records[i];
2397 Instruction *Statepoint = ToUpdate[i].getInstruction();
2398 splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
2399 Info.PointerToBase, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00002400 }
2401
Igor Laevskye0317182015-05-19 15:59:05 +00002402 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002403 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002404 // does not influence correctness.
2405 TargetTransformInfo &TTI =
2406 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2407
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002408 for (size_t i = 0; i < Records.size(); i++)
2409 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002410
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002411 // We need this to safely RAUW and delete call or invoke return values that
2412 // may themselves be live over a statepoint. For details, please see usage in
2413 // makeStatepointExplicitImpl.
2414 std::vector<DeferredReplacement> Replacements;
2415
Philip Reamesd16a9b12015-02-20 01:06:44 +00002416 // Now run through and replace the existing statepoints with new ones with
2417 // the live variables listed. We do not yet update uses of the values being
2418 // relocated. We have references to live variables that need to
2419 // survive to the last iteration of this loop. (By construction, the
2420 // previous statepoint can not be a live variable, thus we can and remove
2421 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002422 for (size_t i = 0; i < Records.size(); i++)
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002423 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002424
2425 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002426
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002427 for (auto &PR : Replacements)
2428 PR.doReplacement();
2429
2430 Replacements.clear();
2431
2432 for (auto &Info : Records) {
2433 // These live sets may contain state Value pointers, since we replaced calls
2434 // with operand bundles with calls wrapped in gc.statepoint, and some of
2435 // those calls may have been def'ing live gc pointers. Clear these out to
2436 // avoid accidentally using them.
2437 //
2438 // TODO: We should create a separate data structure that does not contain
2439 // these live sets, and migrate to using that data structure from this point
2440 // onward.
2441 Info.LiveSet.clear();
2442 Info.PointerToBase.clear();
2443 }
2444
Philip Reamesd16a9b12015-02-20 01:06:44 +00002445 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002446 SmallVector<Value *, 128> Live;
2447 for (size_t i = 0; i < Records.size(); i++) {
2448 PartiallyConstructedSafepointRecord &Info = Records[i];
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002449
Philip Reamesd16a9b12015-02-20 01:06:44 +00002450 // We can't simply save the live set from the original insertion. One of
2451 // the live values might be the result of a call which needs a safepoint.
2452 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002453 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002454 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002455 Statepoint Statepoint(Info.StatepointToken);
2456 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2457 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002458#ifndef NDEBUG
2459 // Do some basic sanity checks on our liveness results before performing
2460 // relocation. Relocation can and will turn mistakes in liveness results
2461 // into non-sensical code which is must harder to debug.
2462 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002463 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002464 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002465 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002466 if (!isa<Instruction>(V))
2467 // Non-instruction values trivial dominate all possible uses
2468 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002469 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002470 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2471 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002472 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002473 "basic SSA liveness expectation violated by liveness analysis");
2474 }
2475#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002476 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002477 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002478
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002479#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002480 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002481 for (auto *Ptr : Live)
2482 assert(isGCPointerType(Ptr->getType()) && "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002483#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002484
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002485 relocationViaAlloca(F, DT, Live, Records);
2486 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002487}
2488
Sanjoy Das353a19e2015-06-02 22:33:37 +00002489// Handles both return values and arguments for Functions and CallSites.
2490template <typename AttrHolder>
2491static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2492 unsigned Index) {
2493 AttrBuilder R;
2494 if (AH.getDereferenceableBytes(Index))
2495 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2496 AH.getDereferenceableBytes(Index)));
2497 if (AH.getDereferenceableOrNullBytes(Index))
2498 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2499 AH.getDereferenceableOrNullBytes(Index)));
2500
2501 if (!R.empty())
2502 AH.setAttributes(AH.getAttributes().removeAttributes(
2503 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002504}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002505
2506void
2507RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2508 LLVMContext &Ctx = F.getContext();
2509
2510 for (Argument &A : F.args())
2511 if (isa<PointerType>(A.getType()))
2512 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2513
2514 if (isa<PointerType>(F.getReturnType()))
2515 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2516}
2517
2518void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2519 if (F.empty())
2520 return;
2521
2522 LLVMContext &Ctx = F.getContext();
2523 MDBuilder Builder(Ctx);
2524
Nico Rieck78199512015-08-06 19:10:45 +00002525 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002526 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2527 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2528 bool IsImmutableTBAA =
2529 MD->getNumOperands() == 4 &&
2530 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2531
2532 if (!IsImmutableTBAA)
2533 continue; // no work to do, MD_tbaa is already marked mutable
2534
2535 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2536 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2537 uint64_t Offset =
2538 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2539
2540 MDNode *MutableTBAA =
2541 Builder.createTBAAStructTagNode(Base, Access, Offset);
2542 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2543 }
2544
2545 if (CallSite CS = CallSite(&I)) {
2546 for (int i = 0, e = CS.arg_size(); i != e; i++)
2547 if (isa<PointerType>(CS.getArgument(i)->getType()))
2548 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2549 if (isa<PointerType>(CS.getType()))
2550 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2551 }
2552 }
2553}
2554
Philip Reamesd16a9b12015-02-20 01:06:44 +00002555/// Returns true if this function should be rewritten by this pass. The main
2556/// point of this function is as an extension point for custom logic.
2557static bool shouldRewriteStatepointsIn(Function &F) {
2558 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002559 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002560 const char *FunctionGCName = F.getGC();
2561 const StringRef StatepointExampleName("statepoint-example");
2562 const StringRef CoreCLRName("coreclr");
2563 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002564 (CoreCLRName == FunctionGCName);
2565 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002566 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002567}
2568
Sanjoy Das353a19e2015-06-02 22:33:37 +00002569void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2570#ifndef NDEBUG
2571 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2572 "precondition!");
2573#endif
2574
2575 for (Function &F : M)
2576 stripDereferenceabilityInfoFromPrototype(F);
2577
2578 for (Function &F : M)
2579 stripDereferenceabilityInfoFromBody(F);
2580}
2581
Philip Reamesd16a9b12015-02-20 01:06:44 +00002582bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2583 // Nothing to do for declarations.
2584 if (F.isDeclaration() || F.empty())
2585 return false;
2586
2587 // Policy choice says not to rewrite - the most common reason is that we're
2588 // compiling code without a GCStrategy.
2589 if (!shouldRewriteStatepointsIn(F))
2590 return false;
2591
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002592 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002593
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002594 auto NeedsRewrite = [](Instruction &I) {
2595 if (UseDeoptBundles) {
2596 if (ImmutableCallSite CS = ImmutableCallSite(&I))
2597 return !callsGCLeafFunction(CS);
2598 return false;
2599 }
2600
2601 return isStatepoint(I);
2602 };
2603
Philip Reames85b36a82015-04-10 22:07:04 +00002604 // Gather all the statepoints which need rewritten. Be careful to only
2605 // consider those in reachable code since we need to ask dominance queries
2606 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002607 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002608 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002609 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002610 // TODO: only the ones with the flag set!
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002611 if (NeedsRewrite(I)) {
Philip Reames85b36a82015-04-10 22:07:04 +00002612 if (DT.isReachableFromEntry(I.getParent()))
2613 ParsePointNeeded.push_back(CallSite(&I));
2614 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002615 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002616 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002617 }
2618
Philip Reames85b36a82015-04-10 22:07:04 +00002619 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002620
Philip Reames85b36a82015-04-10 22:07:04 +00002621 // Delete any unreachable statepoints so that we don't have unrewritten
2622 // statepoints surviving this pass. This makes testing easier and the
2623 // resulting IR less confusing to human readers. Rather than be fancy, we
2624 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002625 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002626 MadeChange |= removeUnreachableBlocks(F);
2627
Philip Reamesd16a9b12015-02-20 01:06:44 +00002628 // Return early if no work to do.
2629 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002630 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002631
Philip Reames85b36a82015-04-10 22:07:04 +00002632 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2633 // These are created by LCSSA. They have the effect of increasing the size
2634 // of liveness sets for no good reason. It may be harder to do this post
2635 // insertion since relocations and base phis can confuse things.
2636 for (BasicBlock &BB : F)
2637 if (BB.getUniquePredecessor()) {
2638 MadeChange = true;
2639 FoldSingleEntryPHINodes(&BB);
2640 }
2641
Philip Reames971dc3a2015-08-12 22:11:45 +00002642 // Before we start introducing relocations, we want to tweak the IR a bit to
2643 // avoid unfortunate code generation effects. The main example is that we
2644 // want to try to make sure the comparison feeding a branch is after any
2645 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2646 // values feeding a branch after relocation. This is semantically correct,
2647 // but results in extra register pressure since both the pre-relocation and
2648 // post-relocation copies must be available in registers. For code without
2649 // relocations this is handled elsewhere, but teaching the scheduler to
2650 // reverse the transform we're about to do would be slightly complex.
2651 // Note: This may extend the live range of the inputs to the icmp and thus
2652 // increase the liveset of any statepoint we move over. This is profitable
2653 // as long as all statepoints are in rare blocks. If we had in-register
2654 // lowering for live values this would be a much safer transform.
2655 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2656 if (auto *BI = dyn_cast<BranchInst>(TI))
2657 if (BI->isConditional())
2658 return dyn_cast<Instruction>(BI->getCondition());
2659 // TODO: Extend this to handle switches
2660 return nullptr;
2661 };
2662 for (BasicBlock &BB : F) {
2663 TerminatorInst *TI = BB.getTerminator();
2664 if (auto *Cond = getConditionInst(TI))
2665 // TODO: Handle more than just ICmps here. We should be able to move
2666 // most instructions without side effects or memory access.
2667 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2668 MadeChange = true;
2669 Cond->moveBefore(TI);
2670 }
2671 }
2672
Philip Reames85b36a82015-04-10 22:07:04 +00002673 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2674 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002675}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002676
2677// liveness computation via standard dataflow
2678// -------------------------------------------------------------------
2679
2680// TODO: Consider using bitvectors for liveness, the set of potentially
2681// interesting values should be small and easy to pre-compute.
2682
Philip Reamesdf1ef082015-04-10 22:53:14 +00002683/// Compute the live-in set for the location rbegin starting from
2684/// the live-out set of the basic block
2685static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2686 BasicBlock::reverse_iterator rend,
2687 DenseSet<Value *> &LiveTmp) {
2688
2689 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2690 Instruction *I = &*ritr;
2691
2692 // KILL/Def - Remove this definition from LiveIn
2693 LiveTmp.erase(I);
2694
2695 // Don't consider *uses* in PHI nodes, we handle their contribution to
2696 // predecessor blocks when we seed the LiveOut sets
2697 if (isa<PHINode>(I))
2698 continue;
2699
2700 // USE - Add to the LiveIn set for this instruction
2701 for (Value *V : I->operands()) {
2702 assert(!isUnhandledGCPointerType(V->getType()) &&
2703 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002704 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2705 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002706 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002707 // - We assume that things which are constant (from LLVM's definition)
2708 // do not move at runtime. For example, the address of a global
2709 // variable is fixed, even though it's contents may not be.
2710 // - Second, we can't disallow arbitrary inttoptr constants even
2711 // if the language frontend does. Optimization passes are free to
2712 // locally exploit facts without respect to global reachability. This
2713 // can create sections of code which are dynamically unreachable and
2714 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002715 LiveTmp.insert(V);
2716 }
2717 }
2718 }
2719}
2720
2721static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2722
2723 for (BasicBlock *Succ : successors(BB)) {
2724 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2725 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2726 PHINode *Phi = cast<PHINode>(&*I);
2727 Value *V = Phi->getIncomingValueForBlock(BB);
2728 assert(!isUnhandledGCPointerType(V->getType()) &&
2729 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002730 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002731 LiveTmp.insert(V);
2732 }
2733 }
2734 }
2735}
2736
2737static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2738 DenseSet<Value *> KillSet;
2739 for (Instruction &I : *BB)
2740 if (isHandledGCPointerType(I.getType()))
2741 KillSet.insert(&I);
2742 return KillSet;
2743}
2744
Philip Reames9638ff92015-04-11 00:06:47 +00002745#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002746/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2747/// sanity check for the liveness computation.
2748static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2749 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002750 for (Value *V : Live) {
2751 if (auto *I = dyn_cast<Instruction>(V)) {
2752 // The terminator can be a member of the LiveOut set. LLVM's definition
2753 // of instruction dominance states that V does not dominate itself. As
2754 // such, we need to special case this to allow it.
2755 if (TermOkay && TI == I)
2756 continue;
2757 assert(DT.dominates(I, TI) &&
2758 "basic SSA liveness expectation violated by liveness analysis");
2759 }
2760 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002761}
2762
2763/// Check that all the liveness sets used during the computation of liveness
2764/// obey basic SSA properties. This is useful for finding cases where we miss
2765/// a def.
2766static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2767 BasicBlock &BB) {
2768 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2769 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2770 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2771}
Philip Reames9638ff92015-04-11 00:06:47 +00002772#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002773
2774static void computeLiveInValues(DominatorTree &DT, Function &F,
2775 GCPtrLivenessData &Data) {
2776
Philip Reames4d80ede2015-04-10 23:11:26 +00002777 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002778 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002779 // We use a SetVector so that we don't have duplicates in the worklist.
2780 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002781 };
2782 auto NextItem = [&]() {
2783 BasicBlock *BB = Worklist.back();
2784 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002785 return BB;
2786 };
2787
2788 // Seed the liveness for each individual block
2789 for (BasicBlock &BB : F) {
2790 Data.KillSet[&BB] = computeKillSet(&BB);
2791 Data.LiveSet[&BB].clear();
2792 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2793
2794#ifndef NDEBUG
2795 for (Value *Kill : Data.KillSet[&BB])
2796 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2797#endif
2798
2799 Data.LiveOut[&BB] = DenseSet<Value *>();
2800 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2801 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2802 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2803 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2804 if (!Data.LiveIn[&BB].empty())
2805 AddPredsToWorklist(&BB);
2806 }
2807
2808 // Propagate that liveness until stable
2809 while (!Worklist.empty()) {
2810 BasicBlock *BB = NextItem();
2811
2812 // Compute our new liveout set, then exit early if it hasn't changed
2813 // despite the contribution of our successor.
2814 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2815 const auto OldLiveOutSize = LiveOut.size();
2816 for (BasicBlock *Succ : successors(BB)) {
2817 assert(Data.LiveIn.count(Succ));
2818 set_union(LiveOut, Data.LiveIn[Succ]);
2819 }
2820 // assert OutLiveOut is a subset of LiveOut
2821 if (OldLiveOutSize == LiveOut.size()) {
2822 // If the sets are the same size, then we didn't actually add anything
2823 // when unioning our successors LiveIn Thus, the LiveIn of this block
2824 // hasn't changed.
2825 continue;
2826 }
2827 Data.LiveOut[BB] = LiveOut;
2828
2829 // Apply the effects of this basic block
2830 DenseSet<Value *> LiveTmp = LiveOut;
2831 set_union(LiveTmp, Data.LiveSet[BB]);
2832 set_subtract(LiveTmp, Data.KillSet[BB]);
2833
2834 assert(Data.LiveIn.count(BB));
2835 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2836 // assert: OldLiveIn is a subset of LiveTmp
2837 if (OldLiveIn.size() != LiveTmp.size()) {
2838 Data.LiveIn[BB] = LiveTmp;
2839 AddPredsToWorklist(BB);
2840 }
2841 } // while( !worklist.empty() )
2842
2843#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002844 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002845 // missing kills during the above iteration.
2846 for (BasicBlock &BB : F) {
2847 checkBasicSSA(DT, Data, BB);
2848 }
2849#endif
2850}
2851
2852static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2853 StatepointLiveSetTy &Out) {
2854
2855 BasicBlock *BB = Inst->getParent();
2856
2857 // Note: The copy is intentional and required
2858 assert(Data.LiveOut.count(BB));
2859 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2860
2861 // We want to handle the statepoint itself oddly. It's
2862 // call result is not live (normal), nor are it's arguments
2863 // (unless they're used again later). This adjustment is
2864 // specifically what we need to relocate
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002865 BasicBlock::reverse_iterator rend(Inst->getIterator());
Philip Reamesdf1ef082015-04-10 22:53:14 +00002866 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2867 LiveOut.erase(Inst);
2868 Out.insert(LiveOut.begin(), LiveOut.end());
2869}
2870
2871static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2872 const CallSite &CS,
2873 PartiallyConstructedSafepointRecord &Info) {
2874 Instruction *Inst = CS.getInstruction();
2875 StatepointLiveSetTy Updated;
2876 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2877
2878#ifndef NDEBUG
2879 DenseSet<Value *> Bases;
2880 for (auto KVPair : Info.PointerToBase) {
2881 Bases.insert(KVPair.second);
2882 }
2883#endif
2884 // We may have base pointers which are now live that weren't before. We need
2885 // to update the PointerToBase structure to reflect this.
2886 for (auto V : Updated)
2887 if (!Info.PointerToBase.count(V)) {
2888 assert(Bases.count(V) && "can't find base for unexpected live value");
2889 Info.PointerToBase[V] = V;
2890 continue;
2891 }
2892
2893#ifndef NDEBUG
2894 for (auto V : Updated) {
2895 assert(Info.PointerToBase.count(V) &&
2896 "must be able to find base for live value");
2897 }
2898#endif
2899
2900 // Remove any stale base mappings - this can happen since our liveness is
2901 // more precise then the one inherent in the base pointer analysis
2902 DenseSet<Value *> ToErase;
2903 for (auto KVPair : Info.PointerToBase)
2904 if (!Updated.count(KVPair.first))
2905 ToErase.insert(KVPair.first);
2906 for (auto V : ToErase)
2907 Info.PointerToBase.erase(V);
2908
2909#ifndef NDEBUG
2910 for (auto KVPair : Info.PointerToBase)
2911 assert(Updated.count(KVPair.first) && "record for non-live value");
2912#endif
2913
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002914 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002915}