blob: a1c9dc1032530f7398f3ce6974bf0e286e4370ef [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
Philip Reames103d2382016-01-07 02:20:11 +000081/// Should we split vectors of pointers into their individual elements? This
82/// is known to be buggy, but the alternate implementation isn't yet ready.
83/// This is purely to provide a debugging and dianostic hook until the vector
84/// split is replaced with vector relocations.
85static cl::opt<bool> UseVectorSplit("rs4gc-split-vector-values", cl::Hidden,
86 cl::init(true));
87
Benjamin Kramer6f665452015-02-20 14:00:58 +000088namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000089struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000090 static char ID; // Pass identification, replacement for typeid
91
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000092 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000093 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
94 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000095 bool runOnFunction(Function &F);
96 bool runOnModule(Module &M) override {
97 bool Changed = false;
98 for (Function &F : M)
99 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000100
101 if (Changed) {
Igor Laevskydde00292015-10-23 22:42:44 +0000102 // stripNonValidAttributes asserts that shouldRewriteStatepointsIn
Sanjoy Das353a19e2015-06-02 22:33:37 +0000103 // returns true for at least one function in the module. Since at least
104 // one function changed, we know that the precondition is satisfied.
Igor Laevskydde00292015-10-23 22:42:44 +0000105 stripNonValidAttributes(M);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000106 }
107
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000108 return Changed;
109 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000110
111 void getAnalysisUsage(AnalysisUsage &AU) const override {
112 // We add and rewrite a bunch of instructions, but don't really do much
113 // else. We could in theory preserve a lot more analyses here.
114 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000115 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000116 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000117
118 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
119 /// dereferenceability that are no longer valid/correct after
120 /// RewriteStatepointsForGC has run. This is because semantically, after
121 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
Igor Laevskydde00292015-10-23 22:42:44 +0000122 /// heap. stripNonValidAttributes (conservatively) restores correctness
Sanjoy Das353a19e2015-06-02 22:33:37 +0000123 /// by erasing all attributes in the module that externally imply
124 /// dereferenceability.
Igor Laevsky1ef06552015-10-26 19:06:01 +0000125 /// Similar reasoning also applies to the noalias attributes. gc.statepoint
126 /// can touch the entire heap including noalias objects.
Igor Laevskydde00292015-10-23 22:42:44 +0000127 void stripNonValidAttributes(Module &M);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000128
Igor Laevskydde00292015-10-23 22:42:44 +0000129 // Helpers for stripNonValidAttributes
130 void stripNonValidAttributesFromBody(Function &F);
131 void stripNonValidAttributesFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000132};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000133} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000134
135char RewriteStatepointsForGC::ID = 0;
136
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000137ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000138 return new RewriteStatepointsForGC();
139}
140
141INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
142 "Make relocations explicit at statepoints", false, false)
143INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
144INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
145 "Make relocations explicit at statepoints", false, false)
146
147namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000148struct GCPtrLivenessData {
149 /// Values defined in this block.
150 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
151 /// Values used in this block (and thus live); does not included values
152 /// killed within this block.
153 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
154
155 /// Values live into this basic block (i.e. used by any
156 /// instruction in this basic block or ones reachable from here)
157 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
158
159 /// Values live out of this basic block (i.e. live into
160 /// any successor block)
161 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
162};
163
Philip Reamesd16a9b12015-02-20 01:06:44 +0000164// The type of the internal cache used inside the findBasePointers family
165// of functions. From the callers perspective, this is an opaque type and
166// should not be inspected.
167//
168// In the actual implementation this caches two relations:
169// - The base relation itself (i.e. this pointer is based on that one)
170// - The base defining value relation (i.e. before base_phi insertion)
171// Generally, after the execution of a full findBasePointer call, only the
172// base relation will remain. Internally, we add a mixture of the two
173// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000174typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000175typedef DenseSet<Value *> StatepointLiveSetTy;
Sanjoy Das40bdd042015-10-07 21:32:35 +0000176typedef DenseMap<AssertingVH<Instruction>, AssertingVH<Value>>
177 RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000178
Philip Reamesd16a9b12015-02-20 01:06:44 +0000179struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000180 /// The set of values known to be live across this safepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000181 StatepointLiveSetTy LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000182
183 /// Mapping from live pointers to a base-defining-value
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000184 DenseMap<Value *, Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000185
Philip Reames0a3240f2015-02-20 21:34:11 +0000186 /// The *new* gc.statepoint instruction itself. This produces the token
187 /// that normal path gc.relocates and the gc.result are tied to.
188 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000189
Philip Reamesf2041322015-02-20 19:26:04 +0000190 /// Instruction to which exceptional gc relocates are attached
191 /// Makes it easier to iterate through them during relocationViaAlloca.
192 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000193
194 /// Record live values we are rematerialized instead of relocating.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000195 /// They are not included into 'LiveSet' field.
Igor Laevskye0317182015-05-19 15:59:05 +0000196 /// Maps rematerialized copy to it's original value.
197 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000198};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000199}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000200
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000201static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
202 assert(UseDeoptBundles && "Should not be called otherwise!");
203
204 Optional<OperandBundleUse> DeoptBundle = CS.getOperandBundle("deopt");
205
206 if (!DeoptBundle.hasValue()) {
207 assert(AllowStatepointWithNoDeoptInfo &&
208 "Found non-leaf call without deopt info!");
209 return None;
210 }
211
212 return DeoptBundle.getValue().Inputs;
213}
214
Philip Reamesdf1ef082015-04-10 22:53:14 +0000215/// Compute the live-in set for every basic block in the function
216static void computeLiveInValues(DominatorTree &DT, Function &F,
217 GCPtrLivenessData &Data);
218
219/// Given results from the dataflow liveness computation, find the set of live
220/// Values at a particular instruction.
221static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
222 StatepointLiveSetTy &out);
223
Philip Reamesd16a9b12015-02-20 01:06:44 +0000224// TODO: Once we can get to the GCStrategy, this becomes
Philip Reamesee8f0552015-12-23 01:42:15 +0000225// Optional<bool> isGCManagedPointer(const Type *Ty) const override {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000226
Craig Toppere3dcce92015-08-01 22:20:21 +0000227static bool isGCPointerType(Type *T) {
228 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000229 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
230 // GC managed heap. We know that a pointer into this heap needs to be
231 // updated and that no other pointer does.
232 return (1 == PT->getAddressSpace());
233 return false;
234}
235
Philip Reames8531d8c2015-04-10 21:48:25 +0000236// Return true if this type is one which a) is a gc pointer or contains a GC
237// pointer and b) is of a type this code expects to encounter as a live value.
238// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000239// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000240static bool isHandledGCPointerType(Type *T) {
241 // We fully support gc pointers
242 if (isGCPointerType(T))
243 return true;
244 // We partially support vectors of gc pointers. The code will assert if it
245 // can't handle something.
246 if (auto VT = dyn_cast<VectorType>(T))
247 if (isGCPointerType(VT->getElementType()))
248 return true;
249 return false;
250}
251
252#ifndef NDEBUG
253/// Returns true if this type contains a gc pointer whether we know how to
254/// handle that type or not.
255static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000256 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000257 return true;
258 if (VectorType *VT = dyn_cast<VectorType>(Ty))
259 return isGCPointerType(VT->getScalarType());
260 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
261 return containsGCPtrType(AT->getElementType());
262 if (StructType *ST = dyn_cast<StructType>(Ty))
Craig Topperd896b032015-11-29 05:38:08 +0000263 return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
264 containsGCPtrType);
Philip Reames8531d8c2015-04-10 21:48:25 +0000265 return false;
266}
267
268// Returns true if this is a type which a) is a gc pointer or contains a GC
269// pointer and b) is of a type which the code doesn't expect (i.e. first class
270// aggregates). Used to trip assertions.
271static bool isUnhandledGCPointerType(Type *Ty) {
272 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
273}
274#endif
275
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000276static bool order_by_name(Value *a, Value *b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000277 if (a->hasName() && b->hasName()) {
278 return -1 == a->getName().compare(b->getName());
279 } else if (a->hasName() && !b->hasName()) {
280 return true;
281 } else if (!a->hasName() && b->hasName()) {
282 return false;
283 } else {
284 // Better than nothing, but not stable
285 return a < b;
286 }
287}
288
Philip Reamesece70b82015-09-09 23:57:18 +0000289// Return the name of the value suffixed with the provided value, or if the
290// value didn't have a name, the default value specified.
291static std::string suffixed_name_or(Value *V, StringRef Suffix,
292 StringRef DefaultName) {
293 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
294}
295
Philip Reamesdf1ef082015-04-10 22:53:14 +0000296// Conservatively identifies any definitions which might be live at the
297// given instruction. The analysis is performed immediately before the
298// given instruction. Values defined by that instruction are not considered
299// live. Values used by that instruction are considered live.
300static void analyzeParsePointLiveness(
301 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
302 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000303 Instruction *inst = CS.getInstruction();
304
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000305 StatepointLiveSetTy LiveSet;
306 findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000307
308 if (PrintLiveSet) {
309 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000310 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000311 // by name
Philip Reamesdab35f32015-09-02 21:11:44 +0000312 SmallVector<Value *, 64> Temp;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000313 Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
Philip Reamesdab35f32015-09-02 21:11:44 +0000314 std::sort(Temp.begin(), Temp.end(), order_by_name);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000315 errs() << "Live Variables:\n";
Philip Reamesdab35f32015-09-02 21:11:44 +0000316 for (Value *V : Temp)
317 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000318 }
319 if (PrintLiveSetSize) {
320 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000321 errs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000322 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000323 result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000324}
325
Philip Reamesf5b8e472015-09-03 21:34:30 +0000326static bool isKnownBaseResult(Value *V);
327namespace {
328/// A single base defining value - An immediate base defining value for an
329/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
330/// For instructions which have multiple pointer [vector] inputs or that
331/// transition between vector and scalar types, there is no immediate base
332/// defining value. The 'base defining value' for 'Def' is the transitive
333/// closure of this relation stopping at the first instruction which has no
334/// immediate base defining value. The b.d.v. might itself be a base pointer,
335/// but it can also be an arbitrary derived pointer.
336struct BaseDefiningValueResult {
337 /// Contains the value which is the base defining value.
338 Value * const BDV;
339 /// True if the base defining value is also known to be an actual base
340 /// pointer.
341 const bool IsKnownBase;
342 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
343 : BDV(BDV), IsKnownBase(IsKnownBase) {
344#ifndef NDEBUG
345 // Check consistency between new and old means of checking whether a BDV is
346 // a base.
347 bool MustBeBase = isKnownBaseResult(BDV);
348 assert(!MustBeBase || MustBeBase == IsKnownBase);
349#endif
350 }
351};
352}
353
354static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000355
Philip Reames8fe7f132015-06-26 22:47:37 +0000356/// Return a base defining value for the 'Index' element of the given vector
357/// instruction 'I'. If Index is null, returns a BDV for the entire vector
358/// 'I'. As an optimization, this method will try to determine when the
359/// element is known to already be a base pointer. If this can be established,
360/// the second value in the returned pair will be true. Note that either a
361/// vector or a pointer typed value can be returned. For the former, the
362/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
363/// If the later, the return pointer is a BDV (or possibly a base) for the
364/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000365static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000366findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000367 // Each case parallels findBaseDefiningValue below, see that code for
368 // detailed motivation.
369
370 if (isa<Argument>(I))
371 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000372 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000373
Manuel Jacob734e7332016-01-09 04:02:16 +0000374 if (isa<Constant>(I))
375 // Constant vectors consist only of constant pointers.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000376 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000377
Philip Reames8531d8c2015-04-10 21:48:25 +0000378 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000379 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000380
Philip Reames66287132015-09-09 23:40:12 +0000381 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000382 // We don't know whether this vector contains entirely base pointers or
383 // not. To be conservatively correct, we treat it as a BDV and will
384 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000385 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000386
Philip Reames8fe7f132015-06-26 22:47:37 +0000387 if (isa<ShuffleVectorInst>(I))
388 // We don't know whether this vector contains entirely base pointers or
389 // not. To be conservatively correct, we treat it as a BDV and will
390 // duplicate code as needed to construct a parallel vector of bases.
391 // TODO: There a number of local optimizations which could be applied here
392 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000393 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000394
395 // A PHI or Select is a base defining value. The outer findBasePointer
396 // algorithm is responsible for constructing a base value for this BDV.
397 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
398 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000399 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000400}
401
Philip Reamesd16a9b12015-02-20 01:06:44 +0000402/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000403/// defines the base pointer for the input, b) blocks the simple search
404/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
405/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000406static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Manuel Jacob0593cfd2016-01-09 03:08:49 +0000407 assert(I->getType()->isPtrOrPtrVectorTy() &&
408 "Illegal to ask for the base pointer of a non-pointer type");
409
Philip Reames8fe7f132015-06-26 22:47:37 +0000410 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000411 return findBaseDefiningValueOfVector(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000412
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000413 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000414 // An incoming argument to the function is a base pointer
415 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000416 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000417
Manuel Jacob75cbfdc2016-01-05 04:06:21 +0000418 if (isa<Constant>(I))
419 // We assume that objects with a constant base (e.g. a global) can't move
420 // and don't need to be reported to the collector because they are always
421 // live. All constants have constant bases. Besides global references, all
422 // kinds of constants (e.g. undef, constant expressions, null pointers) can
423 // be introduced by the inliner or the optimizer, especially on dynamically
424 // dead paths. See e.g. test4 in constants.ll.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000425 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000426
Philip Reamesd16a9b12015-02-20 01:06:44 +0000427 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000428 Value *Def = CI->stripPointerCasts();
Manuel Jacob8050a492015-12-21 01:26:46 +0000429 // If stripping pointer casts changes the address space there is an
430 // addrspacecast in between.
431 assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
432 cast<PointerType>(CI->getType())->getAddressSpace() &&
433 "unsupported addrspacecast");
David Blaikie82ad7872015-02-20 23:44:24 +0000434 // If we find a cast instruction here, it means we've found a cast which is
435 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
436 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000437 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
438 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000439 }
440
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000441 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000442 // The value loaded is an gc base itself
443 return BaseDefiningValueResult(I, true);
444
Philip Reamesd16a9b12015-02-20 01:06:44 +0000445
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000446 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
447 // The base of this GEP is the base
448 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000449
450 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
451 switch (II->getIntrinsicID()) {
452 default:
453 // fall through to general call handling
454 break;
455 case Intrinsic::experimental_gc_statepoint:
Manuel Jacob4e4f60d2015-12-22 18:44:45 +0000456 llvm_unreachable("statepoints don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000457 case Intrinsic::experimental_gc_relocate: {
458 // Rerunning safepoint insertion after safepoints are already
459 // inserted is not supported. It could probably be made to work,
460 // but why are you doing this? There's no good reason.
461 llvm_unreachable("repeat safepoint insertion is not supported");
462 }
463 case Intrinsic::gcroot:
464 // Currently, this mechanism hasn't been extended to work with gcroot.
465 // There's no reason it couldn't be, but I haven't thought about the
466 // implications much.
467 llvm_unreachable(
468 "interaction with the gcroot mechanism is not supported");
469 }
470 }
471 // We assume that functions in the source language only return base
472 // pointers. This should probably be generalized via attributes to support
473 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000474 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000475 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000476
477 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000478 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000479 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
480
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000481 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000482 // A CAS is effectively a atomic store and load combined under a
483 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000484 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000485 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000486
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000487 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000488 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000489
490 // The aggregate ops. Aggregates can either be in the heap or on the
491 // stack, but in either case, this is simply a field load. As a result,
492 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000493 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000494 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000495
496 // We should never see an insert vector since that would require we be
497 // tracing back a struct value not a pointer value.
498 assert(!isa<InsertValueInst>(I) &&
499 "Base pointer for a struct is meaningless");
500
Philip Reames9ac4e382015-08-12 21:00:20 +0000501 // An extractelement produces a base result exactly when it's input does.
502 // We may need to insert a parallel instruction to extract the appropriate
503 // element out of the base vector corresponding to the input. Given this,
504 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000505 if (isa<ExtractElementInst>(I))
506 // Note: There a lot of obvious peephole cases here. This are deliberately
507 // handled after the main base pointer inference algorithm to make writing
508 // test cases to exercise that code easier.
509 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000510
Philip Reamesd16a9b12015-02-20 01:06:44 +0000511 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000512 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000513 // derived pointers (each with it's own base potentially). It's the job of
514 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000515 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000516 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000517 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000518}
519
520/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000521static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
522 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000523 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000524 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000525 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
526 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000527 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000528 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000529 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000530}
531
532/// Return a base pointer for this value if known. Otherwise, return it's
533/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000534static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
535 Value *Def = findBaseDefiningValueCached(I, Cache);
536 auto Found = Cache.find(Def);
537 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000538 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000539 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000540 }
541 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000542 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000543}
544
545/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
546/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000547static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000548 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
549 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
550 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000551 // no recursion possible
552 return true;
553 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000554 if (isa<Instruction>(V) &&
555 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000556 // This is a previously inserted base phi or select. We know
557 // that this is a base value.
558 return true;
559 }
560
561 // We need to keep searching
562 return false;
563}
564
Philip Reamesd16a9b12015-02-20 01:06:44 +0000565namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000566/// Models the state of a single base defining value in the findBasePointer
567/// algorithm for determining where a new instruction is needed to propagate
568/// the base of this BDV.
569class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000570public:
571 enum Status { Unknown, Base, Conflict };
572
Philip Reames9b141ed2015-07-23 22:49:14 +0000573 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000574 assert(status != Base || b);
575 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000576 explicit BDVState(Value *b) : status(Base), base(b) {}
577 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000578
579 Status getStatus() const { return status; }
580 Value *getBase() const { return base; }
581
582 bool isBase() const { return getStatus() == Base; }
583 bool isUnknown() const { return getStatus() == Unknown; }
584 bool isConflict() const { return getStatus() == Conflict; }
585
Philip Reames9b141ed2015-07-23 22:49:14 +0000586 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000587 return base == other.base && status == other.status;
588 }
589
Philip Reames9b141ed2015-07-23 22:49:14 +0000590 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000591
Philip Reames2a892a62015-07-23 22:25:26 +0000592 LLVM_DUMP_METHOD
593 void dump() const { print(dbgs()); dbgs() << '\n'; }
594
595 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000596 switch (status) {
597 case Unknown:
598 OS << "U";
599 break;
600 case Base:
601 OS << "B";
602 break;
603 case Conflict:
604 OS << "C";
605 break;
606 };
607 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000608 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000609 }
610
611private:
612 Status status;
Philip Reamesdd0948a2015-12-18 03:53:28 +0000613 AssertingVH<Value> base; // non null only if status == base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000614};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000615}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000616
Philip Reames6906e922015-09-02 21:57:17 +0000617#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000618static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000619 State.print(OS);
620 return OS;
621}
Philip Reames6906e922015-09-02 21:57:17 +0000622#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000623
Philip Reamesb3967cd2015-09-02 22:30:53 +0000624namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000625// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000626// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000627// operation is implemented in MeetBDVStates::pureMeet
628class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000629public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000630 /// Initializes the currentResult to the TOP state so that if can be met with
631 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000632 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000633
Philip Reames9b141ed2015-07-23 22:49:14 +0000634 // Destructively meet the current result with the given BDVState
635 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000636 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000637 }
638
Philip Reames9b141ed2015-07-23 22:49:14 +0000639 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000640
641private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000642 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000643
Philip Reames9b141ed2015-07-23 22:49:14 +0000644 /// Perform a meet operation on two elements of the BDVState lattice.
645 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000646 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
647 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000648 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000649 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
650 << " produced " << Result << "\n");
651 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000652 }
653
Philip Reames9b141ed2015-07-23 22:49:14 +0000654 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000655 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000656 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000657 return stateB;
658
Philip Reames9b141ed2015-07-23 22:49:14 +0000659 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000660 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000661 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000662 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000663
664 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000665 if (stateA.getBase() == stateB.getBase()) {
666 assert(stateA == stateB && "equality broken!");
667 return stateA;
668 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000669 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000670 }
David Blaikie82ad7872015-02-20 23:44:24 +0000671 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000672 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000673
Philip Reames9b141ed2015-07-23 22:49:14 +0000674 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000675 return stateA;
676 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000677 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000678 }
679};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000680}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000681
682
Philip Reamesd16a9b12015-02-20 01:06:44 +0000683/// For a given value or instruction, figure out what base ptr it's derived
684/// from. For gc objects, this is simply itself. On success, returns a value
685/// which is the base pointer. (This is reliable and can be used for
686/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000687static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000688 Value *def = findBaseOrBDV(I, cache);
689
690 if (isKnownBaseResult(def)) {
691 return def;
692 }
693
694 // Here's the rough algorithm:
695 // - For every SSA value, construct a mapping to either an actual base
696 // pointer or a PHI which obscures the base pointer.
697 // - Construct a mapping from PHI to unknown TOP state. Use an
698 // optimistic algorithm to propagate base pointer information. Lattice
699 // looks like:
700 // UNKNOWN
701 // b1 b2 b3 b4
702 // CONFLICT
703 // When algorithm terminates, all PHIs will either have a single concrete
704 // base or be in a conflict state.
705 // - For every conflict, insert a dummy PHI node without arguments. Add
706 // these to the base[Instruction] = BasePtr mapping. For every
707 // non-conflict, add the actual base.
708 // - For every conflict, add arguments for the base[a] of each input
709 // arguments.
710 //
711 // Note: A simpler form of this would be to add the conflict form of all
712 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000713 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000714 // overall worse solution.
715
Philip Reames29e9ae72015-07-24 00:42:55 +0000716#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000717 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000718 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
719 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000720 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000721#endif
Philip Reames88958b22015-07-24 00:02:11 +0000722
723 // Once populated, will contain a mapping from each potentially non-base BDV
724 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000725 // We use the order of insertion (DFS over the def/use graph) to provide a
726 // stable deterministic ordering for visiting DenseMaps (which are unordered)
727 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000728 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000729
730 // Recursively fill in all base defining values reachable from the initial
731 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000732 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000733 SmallVector<Value*, 16> Worklist;
734 Worklist.push_back(def);
Philip Reames34d7a742015-09-10 00:22:49 +0000735 States.insert(std::make_pair(def, BDVState()));
Philip Reames88958b22015-07-24 00:02:11 +0000736 while (!Worklist.empty()) {
737 Value *Current = Worklist.pop_back_val();
738 assert(!isKnownBaseResult(Current) && "why did it get added?");
739
740 auto visitIncomingValue = [&](Value *InVal) {
741 Value *Base = findBaseOrBDV(InVal, cache);
742 if (isKnownBaseResult(Base))
743 // Known bases won't need new instructions introduced and can be
744 // ignored safely
745 return;
746 assert(isExpectedBDVType(Base) && "the only non-base values "
747 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000748 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000749 Worklist.push_back(Base);
750 };
751 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
752 for (Value *InVal : Phi->incoming_values())
753 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000754 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000755 visitIncomingValue(Sel->getTrueValue());
756 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000757 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
758 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000759 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
760 visitIncomingValue(IE->getOperand(0)); // vector operand
761 visitIncomingValue(IE->getOperand(1)); // scalar operand
Philip Reames9ac4e382015-08-12 21:00:20 +0000762 } else {
Philip Reames66287132015-09-09 23:40:12 +0000763 // There is one known class of instructions we know we don't handle.
764 assert(isa<ShuffleVectorInst>(Current));
Philip Reames9ac4e382015-08-12 21:00:20 +0000765 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000766 }
767 }
768 }
769
Philip Reamesdab35f32015-09-02 21:11:44 +0000770#ifndef NDEBUG
771 DEBUG(dbgs() << "States after initialization:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000772 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000773 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000774 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000775#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000776
Philip Reames273e6bb2015-07-23 21:41:27 +0000777 // Return a phi state for a base defining value. We'll generate a new
778 // base state for known bases and expect to find a cached state otherwise.
779 auto getStateForBDV = [&](Value *baseValue) {
780 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000781 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000782 auto I = States.find(baseValue);
783 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000784 return I->second;
785 };
786
Philip Reamesd16a9b12015-02-20 01:06:44 +0000787 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000788 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000789#ifndef NDEBUG
Philip Reamesb4e55f32015-09-10 00:32:56 +0000790 const size_t oldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000791#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000792 progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000793 // We're only changing values in this loop, thus safe to keep iterators.
794 // Since this is computing a fixed point, the order of visit does not
795 // effect the result. TODO: We could use a worklist here and make this run
796 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000797 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000798 Value *BDV = Pair.first;
799 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000800
Philip Reames9b141ed2015-07-23 22:49:14 +0000801 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000802 // instance which represents the BDV of that value.
803 auto getStateForInput = [&](Value *V) mutable {
804 Value *BDV = findBaseOrBDV(V, cache);
805 return getStateForBDV(BDV);
806 };
807
Philip Reames9b141ed2015-07-23 22:49:14 +0000808 MeetBDVStates calculateMeet;
Philip Reamesece70b82015-09-09 23:57:18 +0000809 if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000810 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
811 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reamesece70b82015-09-09 23:57:18 +0000812 } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000813 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000814 calculateMeet.meetWith(getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000815 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000816 // The 'meet' for an extractelement is slightly trivial, but it's still
817 // useful in that it drives us to conflict if our input is.
Philip Reames9ac4e382015-08-12 21:00:20 +0000818 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
Philip Reames66287132015-09-09 23:40:12 +0000819 } else {
820 // Given there's a inherent type mismatch between the operands, will
821 // *always* produce Conflict.
Philip Reamesece70b82015-09-09 23:57:18 +0000822 auto *IE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +0000823 calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
824 calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000825 }
826
Philip Reames34d7a742015-09-10 00:22:49 +0000827 BDVState oldState = States[BDV];
Philip Reames9b141ed2015-07-23 22:49:14 +0000828 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000829 if (oldState != newState) {
830 progress = true;
Philip Reames34d7a742015-09-10 00:22:49 +0000831 States[BDV] = newState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000832 }
833 }
834
Philip Reamesb4e55f32015-09-10 00:32:56 +0000835 assert(oldSize == States.size() &&
836 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000837 }
838
Philip Reamesdab35f32015-09-02 21:11:44 +0000839#ifndef NDEBUG
840 DEBUG(dbgs() << "States after meet iteration:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000841 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000842 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000843 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000844#endif
845
Philip Reamesd16a9b12015-02-20 01:06:44 +0000846 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000847 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000848 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000849 Instruction *I = cast<Instruction>(Pair.first);
850 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000851 assert(!isKnownBaseResult(I) && "why did it get added?");
852 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000853
854 // extractelement instructions are a bit special in that we may need to
855 // insert an extract even when we know an exact base for the instruction.
856 // The problem is that we need to convert from a vector base to a scalar
857 // base for the particular indice we're interested in.
858 if (State.isBase() && isa<ExtractElementInst>(I) &&
859 isa<VectorType>(State.getBase()->getType())) {
860 auto *EE = cast<ExtractElementInst>(I);
861 // TODO: In many cases, the new instruction is just EE itself. We should
862 // exploit this, but can't do it here since it would break the invariant
863 // about the BDV not being known to be a base.
864 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
865 EE->getIndexOperand(),
866 "base_ee", EE);
867 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000868 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000869 }
Philip Reames66287132015-09-09 23:40:12 +0000870
871 // Since we're joining a vector and scalar base, they can never be the
872 // same. As a result, we should always see insert element having reached
873 // the conflict state.
874 if (isa<InsertElementInst>(I)) {
875 assert(State.isConflict());
876 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000877
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000878 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000879 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000880
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000881 /// Create and insert a new instruction which will represent the base of
882 /// the given instruction 'I'.
883 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
884 if (isa<PHINode>(I)) {
885 BasicBlock *BB = I->getParent();
886 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
887 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000888 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000889 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000890 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
891 // The undef will be replaced later
892 UndefValue *Undef = UndefValue::get(Sel->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000893 std::string Name = suffixed_name_or(I, ".base", "base_select");
Philip Reames9ac4e382015-08-12 21:00:20 +0000894 return SelectInst::Create(Sel->getCondition(), Undef,
895 Undef, Name, Sel);
Philip Reames66287132015-09-09 23:40:12 +0000896 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000897 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000898 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000899 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
900 EE);
Philip Reames66287132015-09-09 23:40:12 +0000901 } else {
902 auto *IE = cast<InsertElementInst>(I);
903 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
904 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000905 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000906 return InsertElementInst::Create(VecUndef, ScalarUndef,
907 IE->getOperand(2), Name, IE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000908 }
Philip Reames66287132015-09-09 23:40:12 +0000909
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000910 };
911 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
912 // Add metadata marking this as a base value
913 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000914 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000915 }
916
Philip Reames3ea15892015-09-03 21:57:40 +0000917 // Returns a instruction which produces the base pointer for a given
918 // instruction. The instruction is assumed to be an input to one of the BDVs
919 // seen in the inference algorithm above. As such, we must either already
920 // know it's base defining value is a base, or have inserted a new
921 // instruction to propagate the base of it's BDV and have entered that newly
922 // introduced instruction into the state table. In either case, we are
923 // assured to be able to determine an instruction which produces it's base
924 // pointer.
925 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
926 Value *BDV = findBaseOrBDV(Input, cache);
927 Value *Base = nullptr;
928 if (isKnownBaseResult(BDV)) {
929 Base = BDV;
930 } else {
931 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000932 assert(States.count(BDV));
933 Base = States[BDV].getBase();
Philip Reames3ea15892015-09-03 21:57:40 +0000934 }
935 assert(Base && "can't be null");
936 // The cast is needed since base traversal may strip away bitcasts
937 if (Base->getType() != Input->getType() &&
938 InsertPt) {
939 Base = new BitCastInst(Base, Input->getType(), "cast",
940 InsertPt);
941 }
942 return Base;
943 };
944
Philip Reames15d55632015-09-09 23:26:08 +0000945 // Fixup all the inputs of the new PHIs. Visit order needs to be
946 // deterministic and predictable because we're naming newly created
947 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000948 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000949 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000950 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000951
Philip Reames7540e3a2015-09-10 00:01:53 +0000952 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000953 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
954 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000955 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000956
Philip Reamesc8ded462015-09-10 00:27:50 +0000957 if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000958 PHINode *phi = cast<PHINode>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +0000959 unsigned NumPHIValues = phi->getNumIncomingValues();
960 for (unsigned i = 0; i < NumPHIValues; i++) {
961 Value *InVal = phi->getIncomingValue(i);
962 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000963
Philip Reames28e61ce2015-02-28 01:57:44 +0000964 // If we've already seen InBB, add the same incoming value
965 // we added for it earlier. The IR verifier requires phi
966 // nodes with multiple entries from the same basic block
967 // to have the same incoming value for each of those
968 // entries. If we don't do this check here and basephi
969 // has a different type than base, we'll end up adding two
970 // bitcasts (and hence two distinct values) as incoming
971 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000972
Philip Reames28e61ce2015-02-28 01:57:44 +0000973 int blockIndex = basephi->getBasicBlockIndex(InBB);
974 if (blockIndex != -1) {
975 Value *oldBase = basephi->getIncomingValue(blockIndex);
976 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +0000977
Philip Reamesd16a9b12015-02-20 01:06:44 +0000978#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +0000979 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000980 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +0000981 // values incoming from the same basic block may be
982 // different is by being different bitcasts of the same
983 // value. A cleanup that remains TODO is changing
984 // findBaseOrBDV to return an llvm::Value of the correct
985 // type (and still remain pure). This will remove the
986 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +0000987 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +0000988 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000989#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000990 continue;
991 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000992
Philip Reames3ea15892015-09-03 21:57:40 +0000993 // Find the instruction which produces the base for each input. We may
994 // need to insert a bitcast in the incoming block.
995 // TODO: Need to split critical edges if insertion is needed
996 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
997 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +0000998 }
999 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reamesc8ded462015-09-10 00:27:50 +00001000 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001001 SelectInst *Sel = cast<SelectInst>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +00001002 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1003 // something more safe and less hacky.
1004 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001005 Value *InVal = Sel->getOperand(i);
1006 // Find the instruction which produces the base for each input. We may
1007 // need to insert a bitcast.
1008 Value *Base = getBaseForInput(InVal, BaseSel);
1009 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001010 }
Philip Reamesc8ded462015-09-10 00:27:50 +00001011 } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001012 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001013 // Find the instruction which produces the base for each input. We may
1014 // need to insert a bitcast.
1015 Value *Base = getBaseForInput(InVal, BaseEE);
Philip Reames9ac4e382015-08-12 21:00:20 +00001016 BaseEE->setOperand(0, Base);
Philip Reames66287132015-09-09 23:40:12 +00001017 } else {
Philip Reamesc8ded462015-09-10 00:27:50 +00001018 auto *BaseIE = cast<InsertElementInst>(State.getBase());
Philip Reames7540e3a2015-09-10 00:01:53 +00001019 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001020 auto UpdateOperand = [&](int OperandIdx) {
1021 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001022 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001023 BaseIE->setOperand(OperandIdx, Base);
1024 };
1025 UpdateOperand(0); // vector operand
1026 UpdateOperand(1); // scalar operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001027 }
Philip Reames66287132015-09-09 23:40:12 +00001028
Philip Reamesd16a9b12015-02-20 01:06:44 +00001029 }
1030
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001031 // Now that we're done with the algorithm, see if we can optimize the
1032 // results slightly by reducing the number of new instructions needed.
1033 // Arguably, this should be integrated into the algorithm above, but
1034 // doing as a post process step is easier to reason about for the moment.
1035 DenseMap<Value *, Value *> ReverseMap;
1036 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001037 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001038 // Note: We need to visit the states in a deterministic order. We uses the
1039 // Keys we sorted above for this purpose. Note that we are papering over a
1040 // bigger problem with the algorithm above - it's visit order is not
1041 // deterministic. A larger change is needed to fix this.
Philip Reames34d7a742015-09-10 00:22:49 +00001042 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001043 auto *BDV = Pair.first;
1044 auto State = Pair.second;
Philip Reames246e6182015-09-03 20:24:29 +00001045 Value *Base = State.getBase();
Philip Reames15d55632015-09-09 23:26:08 +00001046 assert(BDV && Base);
1047 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001048 assert(isKnownBaseResult(Base) &&
1049 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001050 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001051 continue;
1052
Philip Reames15d55632015-09-09 23:26:08 +00001053 ReverseMap[Base] = BDV;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001054 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1055 NewInsts.insert(BaseI);
1056 Worklist.insert(BaseI);
1057 }
1058 }
Philip Reames9546f362015-09-02 22:25:07 +00001059 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1060 Value *Replacement) {
1061 // Add users which are new instructions (excluding self references)
1062 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001063 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001064 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001065 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001066 // Then do the actual replacement
1067 NewInsts.erase(BaseI);
1068 ReverseMap.erase(BaseI);
1069 BaseI->replaceAllUsesWith(Replacement);
Philip Reames34d7a742015-09-10 00:22:49 +00001070 assert(States.count(BDV));
1071 assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
1072 States[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesdd0948a2015-12-18 03:53:28 +00001073 BaseI->eraseFromParent();
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001074 };
1075 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1076 while (!Worklist.empty()) {
1077 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001078 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001079 Value *Bdv = ReverseMap[BaseI];
1080 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1081 if (BaseI->isIdenticalTo(BdvI)) {
1082 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001083 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001084 continue;
1085 }
1086 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1087 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001088 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001089 continue;
1090 }
1091 }
1092
Philip Reamesd16a9b12015-02-20 01:06:44 +00001093 // Cache all of our results so we can cheaply reuse them
1094 // NOTE: This is actually two caches: one of the base defining value
1095 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001096 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001097 auto *BDV = Pair.first;
1098 Value *base = Pair.second.getBase();
1099 assert(BDV && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001100
Philip Reamesece70b82015-09-09 23:57:18 +00001101 std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
Philip Reamesdab35f32015-09-02 21:11:44 +00001102 DEBUG(dbgs() << "Updating base value cache"
Philip Reamesece70b82015-09-09 23:57:18 +00001103 << " for: " << BDV->getName()
Philip Reamesdab35f32015-09-02 21:11:44 +00001104 << " from: " << fromstr
Philip Reamesece70b82015-09-09 23:57:18 +00001105 << " to: " << base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001106
Philip Reames15d55632015-09-09 23:26:08 +00001107 if (cache.count(BDV)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001108 // Once we transition from the BDV relation being store in the cache to
1109 // the base relation being stored, it must be stable
Philip Reames15d55632015-09-09 23:26:08 +00001110 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001111 "base relation should be stable");
1112 }
Philip Reames15d55632015-09-09 23:26:08 +00001113 cache[BDV] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001114 }
Manuel Jacob67f1d3a2015-12-29 22:16:41 +00001115 assert(cache.count(def));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001116 return cache[def];
1117}
1118
1119// For a set of live pointers (base and/or derived), identify the base
1120// pointer of the object which they are derived from. This routine will
1121// mutate the IR graph as needed to make the 'base' pointer live at the
1122// definition site of 'derived'. This ensures that any use of 'derived' can
1123// also use 'base'. This may involve the insertion of a number of
1124// additional PHI nodes.
1125//
1126// preconditions: live is a set of pointer type Values
1127//
1128// side effects: may insert PHI nodes into the existing CFG, will preserve
1129// CFG, will not remove or mutate any existing nodes
1130//
Philip Reamesf2041322015-02-20 19:26:04 +00001131// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001132// pointer in live. Note that derived can be equal to base if the original
1133// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001134static void
1135findBasePointers(const StatepointLiveSetTy &live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001136 DenseMap<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001137 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001138 // For the naming of values inserted to be deterministic - which makes for
1139 // much cleaner and more stable tests - we need to assign an order to the
1140 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001141 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001142 Temp.insert(Temp.end(), live.begin(), live.end());
1143 std::sort(Temp.begin(), Temp.end(), order_by_name);
1144 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001145 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001146 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001147 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001148 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1149 DT->dominates(cast<Instruction>(base)->getParent(),
1150 cast<Instruction>(ptr)->getParent())) &&
1151 "The base we found better dominate the derived pointer");
1152
David Blaikie82ad7872015-02-20 23:44:24 +00001153 // If you see this trip and like to live really dangerously, the code should
1154 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001155 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001156 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001157 "the relocation code needs adjustment to handle the relocation of "
1158 "a null pointer constant without causing false positives in the "
1159 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001160 }
1161}
1162
1163/// Find the required based pointers (and adjust the live set) for the given
1164/// parse point.
1165static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1166 const CallSite &CS,
1167 PartiallyConstructedSafepointRecord &result) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001168 DenseMap<Value *, Value *> PointerToBase;
1169 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001170
1171 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001172 // Note: Need to print these in a stable order since this is checked in
1173 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001174 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001175 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001176 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001177 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001178 Temp.push_back(Pair.first);
1179 }
1180 std::sort(Temp.begin(), Temp.end(), order_by_name);
1181 for (Value *Ptr : Temp) {
1182 Value *Base = PointerToBase[Ptr];
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001183 errs() << " derived ";
1184 Ptr->printAsOperand(errs(), false);
1185 errs() << " base ";
1186 Base->printAsOperand(errs(), false);
1187 errs() << "\n";;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001188 }
1189 }
1190
Philip Reamesf2041322015-02-20 19:26:04 +00001191 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001192}
1193
Philip Reamesdf1ef082015-04-10 22:53:14 +00001194/// Given an updated version of the dataflow liveness results, update the
1195/// liveset and base pointer maps for the call site CS.
1196static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1197 const CallSite &CS,
1198 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001199
Philip Reamesdf1ef082015-04-10 22:53:14 +00001200static void recomputeLiveInValues(
Justin Bogner843fb202015-12-15 19:40:57 +00001201 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001202 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001203 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001204 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001205 GCPtrLivenessData RevisedLivenessData;
1206 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001207 for (size_t i = 0; i < records.size(); i++) {
1208 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001209 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001210 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001211 }
1212}
1213
Sanjoy Das7ad67642015-10-20 01:06:24 +00001214// When inserting gc.relocate and gc.result calls, we need to ensure there are
1215// no uses of the original value / return value between the gc.statepoint and
1216// the gc.relocate / gc.result call. One case which can arise is a phi node
1217// starting one of the successor blocks. We also need to be able to insert the
1218// gc.relocates only on the path which goes through the statepoint. We might
1219// need to split an edge to make this possible.
Philip Reamesf209a152015-04-13 20:00:30 +00001220static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001221normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1222 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001223 BasicBlock *Ret = BB;
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001224 if (!BB->getUniquePredecessor())
Chandler Carruth96ada252015-07-22 09:52:54 +00001225 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001226
Sanjoy Das7ad67642015-10-20 01:06:24 +00001227 // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
Philip Reames69e51ca2015-04-13 18:07:21 +00001228 // from it
1229 FoldSingleEntryPHINodes(Ret);
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001230 assert(!isa<PHINode>(Ret->begin()) &&
1231 "All PHI nodes should have been removed!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001232
Sanjoy Das7ad67642015-10-20 01:06:24 +00001233 // At this point, we can safely insert a gc.relocate or gc.result as the first
1234 // instruction in Ret if needed.
Philip Reames69e51ca2015-04-13 18:07:21 +00001235 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001236}
1237
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001238// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001239// from original call to the safepoint.
1240static AttributeSet legalizeCallAttributes(AttributeSet AS) {
Sanjoy Das810a59d2015-10-16 02:41:11 +00001241 AttributeSet Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001242
1243 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
Sanjoy Das810a59d2015-10-16 02:41:11 +00001244 unsigned Index = AS.getSlotIndex(Slot);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001245
Sanjoy Das810a59d2015-10-16 02:41:11 +00001246 if (Index == AttributeSet::ReturnIndex ||
1247 Index == AttributeSet::FunctionIndex) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001248
Sanjoy Das810a59d2015-10-16 02:41:11 +00001249 for (Attribute Attr : make_range(AS.begin(Slot), AS.end(Slot))) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001250
1251 // Do not allow certain attributes - just skip them
1252 // Safepoint can not be read only or read none.
Sanjoy Das810a59d2015-10-16 02:41:11 +00001253 if (Attr.hasAttribute(Attribute::ReadNone) ||
1254 Attr.hasAttribute(Attribute::ReadOnly))
Philip Reamesd16a9b12015-02-20 01:06:44 +00001255 continue;
1256
Sanjoy Das58fae7c2015-10-16 02:41:23 +00001257 // These attributes control the generation of the gc.statepoint call /
1258 // invoke itself; and once the gc.statepoint is in place, they're of no
1259 // use.
1260 if (Attr.hasAttribute("statepoint-num-patch-bytes") ||
1261 Attr.hasAttribute("statepoint-id"))
1262 continue;
1263
Sanjoy Das810a59d2015-10-16 02:41:11 +00001264 Ret = Ret.addAttributes(
1265 AS.getContext(), Index,
1266 AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001267 }
1268 }
1269
1270 // Just skip parameter attributes for now
1271 }
1272
Sanjoy Das810a59d2015-10-16 02:41:11 +00001273 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001274}
1275
1276/// Helper function to place all gc relocates necessary for the given
1277/// statepoint.
1278/// Inputs:
1279/// liveVariables - list of variables to be relocated.
1280/// liveStart - index of the first live variable.
1281/// basePtrs - base pointers.
1282/// statepointToken - statepoint instruction to which relocates should be
1283/// bound.
1284/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001285static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001286 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001287 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001288 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001289 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001290 if (LiveVariables.empty())
1291 return;
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001292
1293 auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1294 auto ValIt = std::find(LiveVec.begin(), LiveVec.end(), Val);
1295 assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1296 size_t Index = std::distance(LiveVec.begin(), ValIt);
1297 assert(Index < LiveVec.size() && "Bug in std::find?");
1298 return Index;
1299 };
Philip Reames74ce2e72015-07-21 16:51:17 +00001300 Module *M = StatepointToken->getModule();
Philip Reames5715f572016-01-09 01:31:13 +00001301
1302 // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1303 // element type is i8 addrspace(1)*). We originally generated unique
1304 // declarations for each pointer type, but this proved problematic because
1305 // the intrinsic mangling code is incomplete and fragile. Since we're moving
1306 // towards a single unified pointer type anyways, we can just cast everything
1307 // to an i8* of the right address space. A bitcast is added later to convert
1308 // gc_relocate to the actual value's type.
1309 auto getGCRelocateDecl = [&] (Type *Ty) {
1310 assert(isHandledGCPointerType(Ty));
1311 auto AS = Ty->getScalarType()->getPointerAddressSpace();
1312 Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1313 if (auto *VT = dyn_cast<VectorType>(Ty))
1314 NewTy = VectorType::get(NewTy, VT->getNumElements());
1315 return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1316 {NewTy});
1317 };
1318
1319 // Lazily populated map from input types to the canonicalized form mentioned
1320 // in the comment above. This should probably be cached somewhere more
1321 // broadly.
1322 DenseMap<Type*, Value*> TypeToDeclMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001323
Sanjoy Das5665c992015-05-11 23:47:27 +00001324 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001325 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001326 Value *BaseIdx =
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001327 Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
Sanjoy Das3020b1b2015-10-20 01:06:31 +00001328 Value *LiveIdx = Builder.getInt32(LiveStart + i);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001329
Philip Reames5715f572016-01-09 01:31:13 +00001330 Type *Ty = LiveVariables[i]->getType();
1331 if (!TypeToDeclMap.count(Ty))
1332 TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1333 Value *GCRelocateDecl = TypeToDeclMap[Ty];
1334
Philip Reamesd16a9b12015-02-20 01:06:44 +00001335 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001336 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001337 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001338 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001339 // Trick CodeGen into thinking there are lots of free registers at this
1340 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001341 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001342 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001343}
1344
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001345namespace {
1346
1347/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1348/// avoids having to worry about keeping around dangling pointers to Values.
1349class DeferredReplacement {
1350 AssertingVH<Instruction> Old;
1351 AssertingVH<Instruction> New;
1352
1353public:
1354 explicit DeferredReplacement(Instruction *Old, Instruction *New) :
1355 Old(Old), New(New) {
1356 assert(Old != New && "Not allowed!");
1357 }
1358
1359 /// Does the task represented by this instance.
1360 void doReplacement() {
1361 Instruction *OldI = Old;
1362 Instruction *NewI = New;
1363
1364 assert(OldI != NewI && "Disallowed at construction?!");
1365
1366 Old = nullptr;
1367 New = nullptr;
1368
1369 if (NewI)
1370 OldI->replaceAllUsesWith(NewI);
1371 OldI->eraseFromParent();
1372 }
1373};
1374}
1375
Philip Reamesd16a9b12015-02-20 01:06:44 +00001376static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001377makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1378 const SmallVectorImpl<Value *> &BasePtrs,
1379 const SmallVectorImpl<Value *> &LiveVariables,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001380 PartiallyConstructedSafepointRecord &Result,
1381 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001382 assert(BasePtrs.size() == LiveVariables.size());
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001383 assert((UseDeoptBundles || isStatepoint(CS)) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001384 "This method expects to be rewriting a statepoint");
1385
Philip Reamesd16a9b12015-02-20 01:06:44 +00001386 // Then go ahead and use the builder do actually do the inserts. We insert
1387 // immediately before the previous instruction under the assumption that all
1388 // arguments will be available here. We can't insert afterwards since we may
1389 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001390 Instruction *InsertBefore = CS.getInstruction();
1391 IRBuilder<> Builder(InsertBefore);
1392
Sanjoy Das3c520a12015-10-08 23:18:38 +00001393 ArrayRef<Value *> GCArgs(LiveVariables);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001394 uint64_t StatepointID = 0xABCDEF00;
1395 uint32_t NumPatchBytes = 0;
1396 uint32_t Flags = uint32_t(StatepointFlags::None);
Sanjoy Das3c520a12015-10-08 23:18:38 +00001397
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001398 ArrayRef<Use> CallArgs;
1399 ArrayRef<Use> DeoptArgs;
1400 ArrayRef<Use> TransitionArgs;
1401
1402 Value *CallTarget = nullptr;
1403
1404 if (UseDeoptBundles) {
1405 CallArgs = {CS.arg_begin(), CS.arg_end()};
1406 DeoptArgs = GetDeoptBundleOperands(CS);
1407 // TODO: we don't fill in TransitionArgs or Flags in this branch, but we
1408 // could have an operand bundle for that too.
1409 AttributeSet OriginalAttrs = CS.getAttributes();
1410
1411 Attribute AttrID = OriginalAttrs.getAttribute(AttributeSet::FunctionIndex,
1412 "statepoint-id");
1413 if (AttrID.isStringAttribute())
1414 AttrID.getValueAsString().getAsInteger(10, StatepointID);
1415
1416 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
1417 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
1418 if (AttrNumPatchBytes.isStringAttribute())
1419 AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
1420
1421 CallTarget = CS.getCalledValue();
1422 } else {
1423 // This branch will be gone soon, and we will soon only support the
1424 // UseDeoptBundles == true configuration.
1425 Statepoint OldSP(CS);
1426 StatepointID = OldSP.getID();
1427 NumPatchBytes = OldSP.getNumPatchBytes();
1428 Flags = OldSP.getFlags();
1429
1430 CallArgs = {OldSP.arg_begin(), OldSP.arg_end()};
1431 DeoptArgs = {OldSP.vm_state_begin(), OldSP.vm_state_end()};
1432 TransitionArgs = {OldSP.gc_transition_args_begin(),
1433 OldSP.gc_transition_args_end()};
1434 CallTarget = OldSP.getCalledValue();
1435 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001436
1437 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001438 Instruction *Token = nullptr;
1439 AttributeSet ReturnAttrs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001440 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001441 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Das3c520a12015-10-08 23:18:38 +00001442 CallInst *Call = Builder.CreateGCStatepointCall(
1443 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1444 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1445
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001446 Call->setTailCall(ToReplace->isTailCall());
1447 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001448
1449 // Currently we will fail on parameter attributes and on certain
1450 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001451 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001452 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001453 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001454 Call->setAttributes(NewAttrs.getFnAttributes());
1455 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001456
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001457 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001458
1459 // Put the following gc_result and gc_relocate calls immediately after the
1460 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001461 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1462 Builder.SetInsertPoint(ToReplace->getNextNode());
1463 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001464 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001465 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001466
1467 // Insert the new invoke into the old block. We'll remove the old one in a
1468 // moment at which point this will become the new terminator for the
1469 // original block.
Sanjoy Das3c520a12015-10-08 23:18:38 +00001470 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1471 StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1472 ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1473 GCArgs, "statepoint_token");
1474
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001475 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001476
1477 // Currently we will fail on parameter attributes and on certain
1478 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001479 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001480 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001481 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001482 Invoke->setAttributes(NewAttrs.getFnAttributes());
1483 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001484
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001485 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001486
1487 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001488 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1489 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1490 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001491 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001492
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001493 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001494 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001495
Chen Lid71999e2015-12-26 07:54:32 +00001496 // Attach exceptional gc relocates to the landingpad.
1497 Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001498 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001499
Sanjoy Das3c520a12015-10-08 23:18:38 +00001500 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001501 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1502 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001503
1504 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001505 BasicBlock *NormalDest = ToReplace->getNormalDest();
1506 assert(!isa<PHINode>(NormalDest->begin()) &&
1507 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001508 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001509
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001510 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001511
1512 // gc relocates will be generated later as if it were regular call
1513 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001514 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001515 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001516
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001517 if (UseDeoptBundles) {
1518 Token->setName("statepoint_token");
1519 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1520 StringRef Name =
1521 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1522 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
1523 GCResult->setAttributes(CS.getAttributes().getRetAttributes());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001524
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001525 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1526 // live set of some other safepoint, in which case that safepoint's
1527 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1528 // llvm::Instruction. Instead, we defer the replacement and deletion to
1529 // after the live sets have been made explicit in the IR, and we no longer
1530 // have raw pointers to worry about.
1531 Replacements.emplace_back(CS.getInstruction(), GCResult);
1532 } else {
1533 Replacements.emplace_back(CS.getInstruction(), nullptr);
1534 }
1535 } else {
1536 assert(!CS.getInstruction()->hasNUsesOrMore(2) &&
1537 "only valid use before rewrite is gc.result");
1538 assert(!CS.getInstruction()->hasOneUse() ||
1539 isGCResult(cast<Instruction>(*CS.getInstruction()->user_begin())));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001540
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001541 // Take the name of the original statepoint token if there was one.
1542 Token->takeName(CS.getInstruction());
1543
1544 // Update the gc.result of the original statepoint (if any) to use the newly
1545 // inserted statepoint. This is safe to do here since the token can't be
1546 // considered a live reference.
1547 CS.getInstruction()->replaceAllUsesWith(Token);
1548 CS.getInstruction()->eraseFromParent();
1549 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001550
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001551 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001552
Philip Reamesd16a9b12015-02-20 01:06:44 +00001553 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001554 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001555 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001556}
1557
1558namespace {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001559struct NameOrdering {
1560 Value *Base;
1561 Value *Derived;
1562
1563 bool operator()(NameOrdering const &a, NameOrdering const &b) {
1564 return -1 == a.Derived->getName().compare(b.Derived->getName());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001565 }
1566};
1567}
Philip Reamesd16a9b12015-02-20 01:06:44 +00001568
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001569static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
1570 SmallVectorImpl<Value *> &LiveVec) {
1571 assert(BaseVec.size() == LiveVec.size());
1572
1573 SmallVector<NameOrdering, 64> Temp;
1574 for (size_t i = 0; i < BaseVec.size(); i++) {
1575 NameOrdering v;
1576 v.Base = BaseVec[i];
1577 v.Derived = LiveVec[i];
1578 Temp.push_back(v);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001579 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001580
1581 std::sort(Temp.begin(), Temp.end(), NameOrdering());
1582 for (size_t i = 0; i < BaseVec.size(); i++) {
1583 BaseVec[i] = Temp[i].Base;
1584 LiveVec[i] = Temp[i].Derived;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001585 }
1586}
1587
1588// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1589// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001590//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001591// WARNING: Does not do any fixup to adjust users of the original live
1592// values. That's the callers responsibility.
1593static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001594makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001595 PartiallyConstructedSafepointRecord &Result,
1596 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001597 const auto &LiveSet = Result.LiveSet;
1598 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001599
1600 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001601 SmallVector<Value *, 64> BaseVec, LiveVec;
1602 LiveVec.reserve(LiveSet.size());
1603 BaseVec.reserve(LiveSet.size());
1604 for (Value *L : LiveSet) {
1605 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001606 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001607 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001608 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001609 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001610 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001611
1612 // To make the output IR slightly more stable (for use in diffs), ensure a
1613 // fixed order of the values in the safepoint (by sorting the value name).
1614 // The order is otherwise meaningless.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001615 StabilizeOrder(BaseVec, LiveVec);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001616
1617 // Do the actual rewriting and delete the old statepoint
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001618 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001619}
1620
1621// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001622//
1623// It receives iterator to the statepoint gc relocates and emits a store to the
1624// assigned location (via allocaMap) for the each one of them. It adds the
1625// visited values into the visitedLiveValues set, which we will later use them
1626// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001627static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001628insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1629 DenseMap<Value *, Value *> &AllocaMap,
1630 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001631
Sanjoy Das5665c992015-05-11 23:47:27 +00001632 for (User *U : GCRelocs) {
Manuel Jacob83eefa62016-01-05 04:03:00 +00001633 GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1634 if (!Relocate)
Philip Reamesd16a9b12015-02-20 01:06:44 +00001635 continue;
1636
Manuel Jacob83eefa62016-01-05 04:03:00 +00001637 Value *OriginalValue = const_cast<Value *>(Relocate->getDerivedPtr());
Sanjoy Das5665c992015-05-11 23:47:27 +00001638 assert(AllocaMap.count(OriginalValue));
1639 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001640
1641 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001642 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001643 // the correct type according to alloca.
Manuel Jacob83eefa62016-01-05 04:03:00 +00001644 assert(Relocate->getNextNode() &&
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001645 "Should always have one since it's not a terminator");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001646 IRBuilder<> Builder(Relocate->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001647 Value *CastedRelocatedValue =
Manuel Jacob83eefa62016-01-05 04:03:00 +00001648 Builder.CreateBitCast(Relocate,
Philip Reamesece70b82015-09-09 23:57:18 +00001649 cast<AllocaInst>(Alloca)->getAllocatedType(),
Manuel Jacob83eefa62016-01-05 04:03:00 +00001650 suffixed_name_or(Relocate, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001651
Sanjoy Das5665c992015-05-11 23:47:27 +00001652 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1653 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001654
1655#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001656 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001657#endif
1658 }
1659}
1660
Igor Laevskye0317182015-05-19 15:59:05 +00001661// Helper function for the "relocationViaAlloca". Similar to the
1662// "insertRelocationStores" but works for rematerialized values.
1663static void
1664insertRematerializationStores(
1665 RematerializedValueMapTy RematerializedValues,
1666 DenseMap<Value *, Value *> &AllocaMap,
1667 DenseSet<Value *> &VisitedLiveValues) {
1668
1669 for (auto RematerializedValuePair: RematerializedValues) {
1670 Instruction *RematerializedValue = RematerializedValuePair.first;
1671 Value *OriginalValue = RematerializedValuePair.second;
1672
1673 assert(AllocaMap.count(OriginalValue) &&
1674 "Can not find alloca for rematerialized value");
1675 Value *Alloca = AllocaMap[OriginalValue];
1676
1677 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1678 Store->insertAfter(RematerializedValue);
1679
1680#ifndef NDEBUG
1681 VisitedLiveValues.insert(OriginalValue);
1682#endif
1683 }
1684}
1685
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001686/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001687static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001688 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001689 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001690#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001691 // record initial number of (static) allocas; we'll check we have the same
1692 // number when we get done.
1693 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001694 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1695 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001696 if (isa<AllocaInst>(*I))
1697 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001698#endif
1699
1700 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001701 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001702 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001703 // Used later to chack that we have enough allocas to store all values
1704 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001705 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001706
Igor Laevskye0317182015-05-19 15:59:05 +00001707 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1708 // "PromotableAllocas"
1709 auto emitAllocaFor = [&](Value *LiveValue) {
1710 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1711 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001712 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001713 PromotableAllocas.push_back(Alloca);
1714 };
1715
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001716 // Emit alloca for each live gc pointer
1717 for (Value *V : Live)
1718 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001719
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001720 // Emit allocas for rematerialized values
1721 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001722 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001723 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001724 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001725 continue;
1726
1727 emitAllocaFor(OriginalValue);
1728 ++NumRematerializedValues;
1729 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001730
Philip Reamesd16a9b12015-02-20 01:06:44 +00001731 // The next two loops are part of the same conceptual operation. We need to
1732 // insert a store to the alloca after the original def and at each
1733 // redefinition. We need to insert a load before each use. These are split
1734 // into distinct loops for performance reasons.
1735
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001736 // Update gc pointer after each statepoint: either store a relocated value or
1737 // null (if no relocated value was found for this gc pointer and it is not a
1738 // gc_result). This must happen before we update the statepoint with load of
1739 // alloca otherwise we lose the link between statepoint and old def.
1740 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001741 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001742
1743 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001744 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001745
1746 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001747 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001748
1749 // In case if it was invoke statepoint
1750 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001751 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001752 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1753 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001754 }
1755
Igor Laevskye0317182015-05-19 15:59:05 +00001756 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001757 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1758 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001759
Philip Reamese73300b2015-04-13 16:41:32 +00001760 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001761 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001762 // the gc.statepoint. This will turn some subtle GC problems into
1763 // slightly easier to debug SEGVs. Note that on large IR files with
1764 // lots of gc.statepoints this is extremely costly both memory and time
1765 // wise.
1766 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001767 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001768 Value *Def = Pair.first;
1769 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001770
Philip Reamese73300b2015-04-13 16:41:32 +00001771 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001772 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001773 continue;
1774 }
1775 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001776 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001777
Philip Reamese73300b2015-04-13 16:41:32 +00001778 auto InsertClobbersAt = [&](Instruction *IP) {
1779 for (auto *AI : ToClobber) {
Eduard Burtescu90c44492016-01-18 00:10:01 +00001780 auto PT = cast<PointerType>(AI->getAllocatedType());
Philip Reamese73300b2015-04-13 16:41:32 +00001781 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001782 StoreInst *Store = new StoreInst(CPN, AI);
1783 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001784 }
1785 };
1786
1787 // Insert the clobbering stores. These may get intermixed with the
1788 // gc.results and gc.relocates, but that's fine.
1789 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001790 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1791 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001792 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001793 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001794 }
David Blaikie82ad7872015-02-20 23:44:24 +00001795 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001796 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001797
1798 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001799 for (auto Pair : AllocaMap) {
1800 Value *Def = Pair.first;
1801 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001802
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001803 // We pre-record the uses of allocas so that we dont have to worry about
1804 // later update that changes the user information..
1805
Igor Laevsky285fe842015-05-19 16:29:43 +00001806 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001807 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001808 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1809 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001810 if (!isa<ConstantExpr>(U)) {
1811 // If the def has a ConstantExpr use, then the def is either a
1812 // ConstantExpr use itself or null. In either case
1813 // (recursively in the first, directly in the second), the oop
1814 // it is ultimately dependent on is null and this particular
1815 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001816 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001817 }
1818 }
1819
Igor Laevsky285fe842015-05-19 16:29:43 +00001820 std::sort(Uses.begin(), Uses.end());
1821 auto Last = std::unique(Uses.begin(), Uses.end());
1822 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001823
Igor Laevsky285fe842015-05-19 16:29:43 +00001824 for (Instruction *Use : Uses) {
1825 if (isa<PHINode>(Use)) {
1826 PHINode *Phi = cast<PHINode>(Use);
1827 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1828 if (Def == Phi->getIncomingValue(i)) {
1829 LoadInst *Load = new LoadInst(
1830 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1831 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001832 }
1833 }
1834 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001835 LoadInst *Load = new LoadInst(Alloca, "", Use);
1836 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001837 }
1838 }
1839
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001840 // Emit store for the initial gc value. Store must be inserted after load,
1841 // otherwise store will be in alloca's use list and an extra load will be
1842 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001843 StoreInst *Store = new StoreInst(Def, Alloca);
1844 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1845 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001846 // InvokeInst is a TerminatorInst so the store need to be inserted
1847 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001848 BasicBlock *NormalDest = Invoke->getNormalDest();
1849 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001850 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001851 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001852 "The only TerminatorInst that can produce a value is "
1853 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001854 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001855 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001856 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001857 assert(isa<Argument>(Def));
1858 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001859 }
1860 }
1861
Igor Laevsky285fe842015-05-19 16:29:43 +00001862 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001863 "we must have the same allocas with lives");
1864 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001865 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001866 PromoteMemToReg(PromotableAllocas, DT);
1867 }
1868
1869#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001870 for (auto &I : F.getEntryBlock())
1871 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001872 InitialAllocaNum--;
1873 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001874#endif
1875}
1876
1877/// Implement a unique function which doesn't require we sort the input
1878/// vector. Doing so has the effect of changing the output of a couple of
1879/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001880template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001881 SmallSet<T, 8> Seen;
1882 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1883 return !Seen.insert(V).second;
1884 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001885}
1886
Philip Reamesd16a9b12015-02-20 01:06:44 +00001887/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001888/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001889static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001890 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001891 if (Values.empty())
1892 // No values to hold live, might as well not insert the empty holder
1893 return;
1894
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001895 Module *M = CS.getInstruction()->getModule();
Philip Reamesf209a152015-04-13 20:00:30 +00001896 // Use a dummy vararg function to actually hold the values live
1897 Function *Func = cast<Function>(M->getOrInsertFunction(
1898 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001899 if (CS.isCall()) {
1900 // For call safepoints insert dummy calls right after safepoint
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001901 Holders.push_back(CallInst::Create(Func, Values, "",
1902 &*++CS.getInstruction()->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001903 return;
1904 }
1905 // For invoke safepooints insert dummy calls both in normal and
1906 // exceptional destination blocks
1907 auto *II = cast<InvokeInst>(CS.getInstruction());
1908 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001909 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001910 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001911 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001912}
1913
1914static void findLiveReferences(
Justin Bogner843fb202015-12-15 19:40:57 +00001915 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001916 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001917 GCPtrLivenessData OriginalLivenessData;
1918 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001919 for (size_t i = 0; i < records.size(); i++) {
1920 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001921 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001922 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001923 }
1924}
1925
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001926/// Remove any vector of pointers from the live set by scalarizing them over the
1927/// statepoint instruction. Adds the scalarized pieces to the live set. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001928/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001929/// the lowering code currently does not handle that. Extending it would be
1930/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001931/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001932static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001933 StatepointLiveSetTy &LiveSet,
1934 DenseMap<Value *, Value *>& PointerToBase,
1935 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001936 SmallVector<Value *, 16> ToSplit;
1937 for (Value *V : LiveSet)
1938 if (isa<VectorType>(V->getType()))
1939 ToSplit.push_back(V);
1940
1941 if (ToSplit.empty())
1942 return;
1943
Philip Reames8fe7f132015-06-26 22:47:37 +00001944 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1945
Philip Reames8531d8c2015-04-10 21:48:25 +00001946 Function &F = *(StatepointInst->getParent()->getParent());
1947
Philip Reames704e78b2015-04-10 22:34:56 +00001948 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001949 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001950 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001951 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001952 AllocaInst *Alloca =
1953 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001954 AllocaMap[V] = Alloca;
1955
1956 VectorType *VT = cast<VectorType>(V->getType());
1957 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001958 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001959 for (unsigned i = 0; i < VT->getNumElements(); i++)
1960 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001961 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001962
1963 auto InsertVectorReform = [&](Instruction *IP) {
1964 Builder.SetInsertPoint(IP);
1965 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1966 Value *ResultVec = UndefValue::get(VT);
1967 for (unsigned i = 0; i < VT->getNumElements(); i++)
1968 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1969 Builder.getInt32(i));
1970 return ResultVec;
1971 };
1972
1973 if (isa<CallInst>(StatepointInst)) {
1974 BasicBlock::iterator Next(StatepointInst);
1975 Next++;
1976 Instruction *IP = &*(Next);
1977 Replacements[V].first = InsertVectorReform(IP);
1978 Replacements[V].second = nullptr;
1979 } else {
1980 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1981 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001982 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001983 BasicBlock *NormalDest = Invoke->getNormalDest();
1984 assert(!isa<PHINode>(NormalDest->begin()));
1985 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1986 assert(!isa<PHINode>(UnwindDest->begin()));
1987 // Insert insert element sequences in both successors
1988 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1989 Replacements[V].first = InsertVectorReform(IP);
1990 IP = &*(UnwindDest->getFirstInsertionPt());
1991 Replacements[V].second = InsertVectorReform(IP);
1992 }
1993 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001994
Philip Reames8531d8c2015-04-10 21:48:25 +00001995 for (Value *V : ToSplit) {
1996 AllocaInst *Alloca = AllocaMap[V];
1997
1998 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001999 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00002000 for (User *U : V->users())
2001 Users.push_back(cast<Instruction>(U));
2002
2003 for (Instruction *I : Users) {
2004 if (auto Phi = dyn_cast<PHINode>(I)) {
2005 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
2006 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00002007 LoadInst *Load = new LoadInst(
2008 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00002009 Phi->setIncomingValue(i, Load);
2010 }
2011 } else {
2012 LoadInst *Load = new LoadInst(Alloca, "", I);
2013 I->replaceUsesOfWith(V, Load);
2014 }
2015 }
2016
2017 // Store the original value and the replacement value into the alloca
2018 StoreInst *Store = new StoreInst(V, Alloca);
2019 if (auto I = dyn_cast<Instruction>(V))
2020 Store->insertAfter(I);
2021 else
2022 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00002023
Philip Reames8531d8c2015-04-10 21:48:25 +00002024 // Normal return for invoke, or call return
2025 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
2026 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2027 // Unwind return for invoke only
2028 Replacement = cast_or_null<Instruction>(Replacements[V].second);
2029 if (Replacement)
2030 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2031 }
2032
2033 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00002034 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00002035 for (Value *V : ToSplit)
2036 Allocas.push_back(AllocaMap[V]);
2037 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00002038
2039 // Update our tracking of live pointers and base mappings to account for the
2040 // changes we just made.
2041 for (Value *V : ToSplit) {
2042 auto &Elements = ElementMapping[V];
2043
2044 LiveSet.erase(V);
2045 LiveSet.insert(Elements.begin(), Elements.end());
2046 // We need to update the base mapping as well.
2047 assert(PointerToBase.count(V));
2048 Value *OldBase = PointerToBase[V];
2049 auto &BaseElements = ElementMapping[OldBase];
2050 PointerToBase.erase(V);
2051 assert(Elements.size() == BaseElements.size());
2052 for (unsigned i = 0; i < Elements.size(); i++) {
2053 Value *Elem = Elements[i];
2054 PointerToBase[Elem] = BaseElements[i];
2055 }
2056 }
Philip Reames8531d8c2015-04-10 21:48:25 +00002057}
2058
Igor Laevskye0317182015-05-19 15:59:05 +00002059// Helper function for the "rematerializeLiveValues". It walks use chain
2060// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2061// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002062// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00002063// Fills "ChainToBase" array with all visited values. "BaseValue" is not
2064// recorded.
2065static bool findRematerializableChainToBasePointer(
2066 SmallVectorImpl<Instruction*> &ChainToBase,
2067 Value *CurrentValue, Value *BaseValue) {
2068
2069 // We have found a base value
2070 if (CurrentValue == BaseValue) {
2071 return true;
2072 }
2073
2074 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2075 ChainToBase.push_back(GEP);
2076 return findRematerializableChainToBasePointer(ChainToBase,
2077 GEP->getPointerOperand(),
2078 BaseValue);
2079 }
2080
2081 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
Igor Laevskye0317182015-05-19 15:59:05 +00002082 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2083 return false;
2084
2085 ChainToBase.push_back(CI);
Manuel Jacob9db5b932015-12-28 20:14:05 +00002086 return findRematerializableChainToBasePointer(ChainToBase,
2087 CI->getOperand(0), BaseValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002088 }
2089
2090 // Not supported instruction in the chain
2091 return false;
2092}
2093
2094// Helper function for the "rematerializeLiveValues". Compute cost of the use
2095// chain we are going to rematerialize.
2096static unsigned
2097chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2098 TargetTransformInfo &TTI) {
2099 unsigned Cost = 0;
2100
2101 for (Instruction *Instr : Chain) {
2102 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2103 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2104 "non noop cast is found during rematerialization");
2105
2106 Type *SrcTy = CI->getOperand(0)->getType();
2107 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2108
2109 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2110 // Cost of the address calculation
2111 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2112 Cost += TTI.getAddressComputationCost(ValTy);
2113
2114 // And cost of the GEP itself
2115 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2116 // allowed for the external usage)
2117 if (!GEP->hasAllConstantIndices())
2118 Cost += 2;
2119
2120 } else {
2121 llvm_unreachable("unsupported instruciton type during rematerialization");
2122 }
2123 }
2124
2125 return Cost;
2126}
2127
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002128// From the statepoint live set pick values that are cheaper to recompute then
2129// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00002130// statepoint and record them in "Info" structure. Note that similar to
2131// relocated values we don't do any user adjustments here.
2132static void rematerializeLiveValues(CallSite CS,
2133 PartiallyConstructedSafepointRecord &Info,
2134 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002135 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002136
Igor Laevskye0317182015-05-19 15:59:05 +00002137 // Record values we are going to delete from this statepoint live set.
2138 // We can not di this in following loop due to iterator invalidation.
2139 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2140
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002141 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00002142 // For each live pointer find it's defining chain
2143 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002144 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002145 bool FoundChain =
2146 findRematerializableChainToBasePointer(ChainToBase,
2147 LiveValue,
2148 Info.PointerToBase[LiveValue]);
2149 // Nothing to do, or chain is too long
2150 if (!FoundChain ||
2151 ChainToBase.size() == 0 ||
2152 ChainToBase.size() > ChainLengthThreshold)
2153 continue;
2154
2155 // Compute cost of this chain
2156 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2157 // TODO: We can also account for cases when we will be able to remove some
2158 // of the rematerialized values by later optimization passes. I.e if
2159 // we rematerialized several intersecting chains. Or if original values
2160 // don't have any uses besides this statepoint.
2161
2162 // For invokes we need to rematerialize each chain twice - for normal and
2163 // for unwind basic blocks. Model this by multiplying cost by two.
2164 if (CS.isInvoke()) {
2165 Cost *= 2;
2166 }
2167 // If it's too expensive - skip it
2168 if (Cost >= RematerializationThreshold)
2169 continue;
2170
2171 // Remove value from the live set
2172 LiveValuesToBeDeleted.push_back(LiveValue);
2173
2174 // Clone instructions and record them inside "Info" structure
2175
2176 // Walk backwards to visit top-most instructions first
2177 std::reverse(ChainToBase.begin(), ChainToBase.end());
2178
2179 // Utility function which clones all instructions from "ChainToBase"
2180 // and inserts them before "InsertBefore". Returns rematerialized value
2181 // which should be used after statepoint.
2182 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2183 Instruction *LastClonedValue = nullptr;
2184 Instruction *LastValue = nullptr;
2185 for (Instruction *Instr: ChainToBase) {
2186 // Only GEP's and casts are suported as we need to be careful to not
2187 // introduce any new uses of pointers not in the liveset.
2188 // Note that it's fine to introduce new uses of pointers which were
2189 // otherwise not used after this statepoint.
2190 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2191
2192 Instruction *ClonedValue = Instr->clone();
2193 ClonedValue->insertBefore(InsertBefore);
2194 ClonedValue->setName(Instr->getName() + ".remat");
2195
2196 // If it is not first instruction in the chain then it uses previously
2197 // cloned value. We should update it to use cloned value.
2198 if (LastClonedValue) {
2199 assert(LastValue);
2200 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2201#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002202 // Assert that cloned instruction does not use any instructions from
2203 // this chain other than LastClonedValue
2204 for (auto OpValue : ClonedValue->operand_values()) {
2205 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2206 ChainToBase.end() &&
2207 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002208 }
2209#endif
2210 }
2211
2212 LastClonedValue = ClonedValue;
2213 LastValue = Instr;
2214 }
2215 assert(LastClonedValue);
2216 return LastClonedValue;
2217 };
2218
2219 // Different cases for calls and invokes. For invokes we need to clone
2220 // instructions both on normal and unwind path.
2221 if (CS.isCall()) {
2222 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2223 assert(InsertBefore);
2224 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2225 Info.RematerializedValues[RematerializedValue] = LiveValue;
2226 } else {
2227 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2228
2229 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002230 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002231 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002232 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002233
2234 Instruction *NormalRematerializedValue =
2235 rematerializeChain(NormalInsertBefore);
2236 Instruction *UnwindRematerializedValue =
2237 rematerializeChain(UnwindInsertBefore);
2238
2239 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2240 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2241 }
2242 }
2243
2244 // Remove rematerializaed values from the live set
2245 for (auto LiveValue: LiveValuesToBeDeleted) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002246 Info.LiveSet.erase(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002247 }
2248}
2249
Justin Bogner843fb202015-12-15 19:40:57 +00002250static bool insertParsePoints(Function &F, DominatorTree &DT,
2251 TargetTransformInfo &TTI,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002252 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002253#ifndef NDEBUG
2254 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002255 std::set<CallSite> Uniqued;
2256 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2257 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002258
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002259 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002260 assert(CS.getInstruction()->getParent()->getParent() == &F);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002261 assert((UseDeoptBundles || isStatepoint(CS)) &&
2262 "expected to already be a deopt statepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002263 }
2264#endif
2265
Philip Reames69e51ca2015-04-13 18:07:21 +00002266 // When inserting gc.relocates for invokes, we need to be able to insert at
2267 // the top of the successor blocks. See the comment on
2268 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002269 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002270 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002271 if (!CS.isInvoke())
2272 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002273 auto *II = cast<InvokeInst>(CS.getInstruction());
2274 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2275 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002276 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002277
Philip Reamesd16a9b12015-02-20 01:06:44 +00002278 // A list of dummy calls added to the IR to keep various values obviously
2279 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002280 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002281
2282 // Insert a dummy call with all of the arguments to the vm_state we'll need
2283 // for the actual safepoint insertion. This ensures reference arguments in
2284 // the deopt argument list are considered live through the safepoint (and
2285 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002286 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002287 SmallVector<Value *, 64> DeoptValues;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002288
2289 iterator_range<const Use *> DeoptStateRange =
2290 UseDeoptBundles
2291 ? iterator_range<const Use *>(GetDeoptBundleOperands(CS))
2292 : iterator_range<const Use *>(Statepoint(CS).vm_state_args());
2293
2294 for (Value *Arg : DeoptStateRange) {
Philip Reames8531d8c2015-04-10 21:48:25 +00002295 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2296 "support for FCA unimplemented");
2297 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002298 DeoptValues.push_back(Arg);
2299 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002300
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002301 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002302 }
2303
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002304 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002305
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002306 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002307 // site.
Justin Bogner843fb202015-12-15 19:40:57 +00002308 findLiveReferences(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002309
2310 // B) Find the base pointers for each live pointer
2311 /* scope for caching */ {
2312 // Cache the 'defining value' relation used in the computation and
2313 // insertion of base phis and selects. This ensures that we don't insert
2314 // large numbers of duplicate base_phis.
2315 DefiningValueMapTy DVCache;
2316
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002317 for (size_t i = 0; i < Records.size(); i++) {
2318 PartiallyConstructedSafepointRecord &info = Records[i];
2319 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002320 }
2321 } // end of cache scope
2322
2323 // The base phi insertion logic (for any safepoint) may have inserted new
2324 // instructions which are now live at some safepoint. The simplest such
2325 // example is:
2326 // loop:
2327 // phi a <-- will be a new base_phi here
2328 // safepoint 1 <-- that needs to be live here
2329 // gep a + 1
2330 // safepoint 2
2331 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002332 // We insert some dummy calls after each safepoint to definitely hold live
2333 // the base pointers which were identified for that safepoint. We'll then
2334 // ask liveness for _every_ base inserted to see what is now live. Then we
2335 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002336 Holders.reserve(Holders.size() + Records.size());
2337 for (size_t i = 0; i < Records.size(); i++) {
2338 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002339
2340 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002341 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002342 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002343
2344 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002345 }
2346
Philip Reamesdf1ef082015-04-10 22:53:14 +00002347 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2348 // need to rerun liveness. We may *also* have inserted new defs, but that's
2349 // not the key issue.
Justin Bogner843fb202015-12-15 19:40:57 +00002350 recomputeLiveInValues(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002351
Philip Reamesd16a9b12015-02-20 01:06:44 +00002352 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002353 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002354 errs() << "Base Pairs: (w/Relocation)\n";
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00002355 for (auto Pair : Info.PointerToBase) {
2356 errs() << " derived ";
2357 Pair.first->printAsOperand(errs(), false);
2358 errs() << " base ";
2359 Pair.second->printAsOperand(errs(), false);
2360 errs() << "\n";
2361 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002362 }
2363 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002364
Manuel Jacob990dfa62015-12-22 16:50:44 +00002365 // It is possible that non-constant live variables have a constant base. For
2366 // example, a GEP with a variable offset from a global. In this case we can
2367 // remove it from the liveset. We already don't add constants to the liveset
2368 // because we assume they won't move at runtime and the GC doesn't need to be
2369 // informed about them. The same reasoning applies if the base is constant.
2370 // Note that the relocation placement code relies on this filtering for
2371 // correctness as it expects the base to be in the liveset, which isn't true
2372 // if the base is constant.
2373 for (auto &Info : Records)
2374 for (auto &BasePair : Info.PointerToBase)
2375 if (isa<Constant>(BasePair.second))
2376 Info.LiveSet.erase(BasePair.first);
2377
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002378 for (CallInst *CI : Holders)
2379 CI->eraseFromParent();
2380
2381 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002382
Philip Reames8fe7f132015-06-26 22:47:37 +00002383 // Do a limited scalarization of any live at safepoint vector values which
2384 // contain pointers. This enables this pass to run after vectorization at
Philip Reames103d2382016-01-07 02:20:11 +00002385 // the cost of some possible performance loss. Note: This is known to not
2386 // handle updating of the side tables correctly which can lead to relocation
2387 // bugs when the same vector is live at multiple statepoints. We're in the
2388 // process of implementing the alternate lowering - relocating the
2389 // vector-of-pointers as first class item and updating the backend to
2390 // understand that - but that's not yet complete.
2391 if (UseVectorSplit)
2392 for (size_t i = 0; i < Records.size(); i++) {
2393 PartiallyConstructedSafepointRecord &Info = Records[i];
2394 Instruction *Statepoint = ToUpdate[i].getInstruction();
2395 splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
2396 Info.PointerToBase, DT);
2397 }
Philip Reames8fe7f132015-06-26 22:47:37 +00002398
Igor Laevskye0317182015-05-19 15:59:05 +00002399 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002400 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002401 // does not influence correctness.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002402 for (size_t i = 0; i < Records.size(); i++)
2403 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002404
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002405 // We need this to safely RAUW and delete call or invoke return values that
2406 // may themselves be live over a statepoint. For details, please see usage in
2407 // makeStatepointExplicitImpl.
2408 std::vector<DeferredReplacement> Replacements;
2409
Philip Reamesd16a9b12015-02-20 01:06:44 +00002410 // Now run through and replace the existing statepoints with new ones with
2411 // the live variables listed. We do not yet update uses of the values being
2412 // relocated. We have references to live variables that need to
2413 // survive to the last iteration of this loop. (By construction, the
2414 // previous statepoint can not be a live variable, thus we can and remove
2415 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002416 for (size_t i = 0; i < Records.size(); i++)
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002417 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002418
2419 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002420
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002421 for (auto &PR : Replacements)
2422 PR.doReplacement();
2423
2424 Replacements.clear();
2425
2426 for (auto &Info : Records) {
2427 // These live sets may contain state Value pointers, since we replaced calls
2428 // with operand bundles with calls wrapped in gc.statepoint, and some of
2429 // those calls may have been def'ing live gc pointers. Clear these out to
2430 // avoid accidentally using them.
2431 //
2432 // TODO: We should create a separate data structure that does not contain
2433 // these live sets, and migrate to using that data structure from this point
2434 // onward.
2435 Info.LiveSet.clear();
2436 Info.PointerToBase.clear();
2437 }
2438
Philip Reamesd16a9b12015-02-20 01:06:44 +00002439 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002440 SmallVector<Value *, 128> Live;
2441 for (size_t i = 0; i < Records.size(); i++) {
2442 PartiallyConstructedSafepointRecord &Info = Records[i];
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002443
Philip Reamesd16a9b12015-02-20 01:06:44 +00002444 // We can't simply save the live set from the original insertion. One of
2445 // the live values might be the result of a call which needs a safepoint.
2446 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002447 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002448 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002449 Statepoint Statepoint(Info.StatepointToken);
2450 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2451 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002452#ifndef NDEBUG
2453 // Do some basic sanity checks on our liveness results before performing
2454 // relocation. Relocation can and will turn mistakes in liveness results
2455 // into non-sensical code which is must harder to debug.
2456 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002457 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002458 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002459 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002460 if (!isa<Instruction>(V))
2461 // Non-instruction values trivial dominate all possible uses
2462 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002463 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002464 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2465 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002466 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002467 "basic SSA liveness expectation violated by liveness analysis");
2468 }
2469#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002470 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002471 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002472
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002473#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002474 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002475 for (auto *Ptr : Live)
Philip Reames5715f572016-01-09 01:31:13 +00002476 assert(isHandledGCPointerType(Ptr->getType()) &&
2477 "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002478#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002479
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002480 relocationViaAlloca(F, DT, Live, Records);
2481 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002482}
2483
Sanjoy Das353a19e2015-06-02 22:33:37 +00002484// Handles both return values and arguments for Functions and CallSites.
2485template <typename AttrHolder>
Igor Laevskydde00292015-10-23 22:42:44 +00002486static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2487 unsigned Index) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002488 AttrBuilder R;
2489 if (AH.getDereferenceableBytes(Index))
2490 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2491 AH.getDereferenceableBytes(Index)));
2492 if (AH.getDereferenceableOrNullBytes(Index))
2493 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2494 AH.getDereferenceableOrNullBytes(Index)));
Igor Laevsky1ef06552015-10-26 19:06:01 +00002495 if (AH.doesNotAlias(Index))
2496 R.addAttribute(Attribute::NoAlias);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002497
2498 if (!R.empty())
2499 AH.setAttributes(AH.getAttributes().removeAttributes(
2500 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002501}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002502
2503void
Igor Laevskydde00292015-10-23 22:42:44 +00002504RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002505 LLVMContext &Ctx = F.getContext();
2506
2507 for (Argument &A : F.args())
2508 if (isa<PointerType>(A.getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002509 RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002510
2511 if (isa<PointerType>(F.getReturnType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002512 RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002513}
2514
Igor Laevskydde00292015-10-23 22:42:44 +00002515void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002516 if (F.empty())
2517 return;
2518
2519 LLVMContext &Ctx = F.getContext();
2520 MDBuilder Builder(Ctx);
2521
Nico Rieck78199512015-08-06 19:10:45 +00002522 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002523 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2524 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2525 bool IsImmutableTBAA =
2526 MD->getNumOperands() == 4 &&
2527 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2528
2529 if (!IsImmutableTBAA)
2530 continue; // no work to do, MD_tbaa is already marked mutable
2531
2532 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2533 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2534 uint64_t Offset =
2535 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2536
2537 MDNode *MutableTBAA =
2538 Builder.createTBAAStructTagNode(Base, Access, Offset);
2539 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2540 }
2541
2542 if (CallSite CS = CallSite(&I)) {
2543 for (int i = 0, e = CS.arg_size(); i != e; i++)
2544 if (isa<PointerType>(CS.getArgument(i)->getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002545 RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002546 if (isa<PointerType>(CS.getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002547 RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002548 }
2549 }
2550}
2551
Philip Reamesd16a9b12015-02-20 01:06:44 +00002552/// Returns true if this function should be rewritten by this pass. The main
2553/// point of this function is as an extension point for custom logic.
2554static bool shouldRewriteStatepointsIn(Function &F) {
2555 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002556 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +00002557 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002558 const StringRef StatepointExampleName("statepoint-example");
2559 const StringRef CoreCLRName("coreclr");
2560 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002561 (CoreCLRName == FunctionGCName);
2562 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002563 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002564}
2565
Igor Laevskydde00292015-10-23 22:42:44 +00002566void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002567#ifndef NDEBUG
2568 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2569 "precondition!");
2570#endif
2571
2572 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002573 stripNonValidAttributesFromPrototype(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002574
2575 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002576 stripNonValidAttributesFromBody(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002577}
2578
Philip Reamesd16a9b12015-02-20 01:06:44 +00002579bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2580 // Nothing to do for declarations.
2581 if (F.isDeclaration() || F.empty())
2582 return false;
2583
2584 // Policy choice says not to rewrite - the most common reason is that we're
2585 // compiling code without a GCStrategy.
2586 if (!shouldRewriteStatepointsIn(F))
2587 return false;
2588
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002589 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00002590 TargetTransformInfo &TTI =
2591 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Philip Reames704e78b2015-04-10 22:34:56 +00002592
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002593 auto NeedsRewrite = [](Instruction &I) {
2594 if (UseDeoptBundles) {
2595 if (ImmutableCallSite CS = ImmutableCallSite(&I))
2596 return !callsGCLeafFunction(CS);
2597 return false;
2598 }
2599
2600 return isStatepoint(I);
2601 };
2602
Philip Reames85b36a82015-04-10 22:07:04 +00002603 // Gather all the statepoints which need rewritten. Be careful to only
2604 // consider those in reachable code since we need to ask dominance queries
2605 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002606 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002607 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002608 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002609 // TODO: only the ones with the flag set!
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002610 if (NeedsRewrite(I)) {
Philip Reames85b36a82015-04-10 22:07:04 +00002611 if (DT.isReachableFromEntry(I.getParent()))
2612 ParsePointNeeded.push_back(CallSite(&I));
2613 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002614 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002615 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002616 }
2617
Philip Reames85b36a82015-04-10 22:07:04 +00002618 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002619
Philip Reames85b36a82015-04-10 22:07:04 +00002620 // Delete any unreachable statepoints so that we don't have unrewritten
2621 // statepoints surviving this pass. This makes testing easier and the
2622 // resulting IR less confusing to human readers. Rather than be fancy, we
2623 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002624 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002625 MadeChange |= removeUnreachableBlocks(F);
2626
Philip Reamesd16a9b12015-02-20 01:06:44 +00002627 // Return early if no work to do.
2628 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002629 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002630
Philip Reames85b36a82015-04-10 22:07:04 +00002631 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2632 // These are created by LCSSA. They have the effect of increasing the size
2633 // of liveness sets for no good reason. It may be harder to do this post
2634 // insertion since relocations and base phis can confuse things.
2635 for (BasicBlock &BB : F)
2636 if (BB.getUniquePredecessor()) {
2637 MadeChange = true;
2638 FoldSingleEntryPHINodes(&BB);
2639 }
2640
Philip Reames971dc3a2015-08-12 22:11:45 +00002641 // Before we start introducing relocations, we want to tweak the IR a bit to
2642 // avoid unfortunate code generation effects. The main example is that we
2643 // want to try to make sure the comparison feeding a branch is after any
2644 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2645 // values feeding a branch after relocation. This is semantically correct,
2646 // but results in extra register pressure since both the pre-relocation and
2647 // post-relocation copies must be available in registers. For code without
2648 // relocations this is handled elsewhere, but teaching the scheduler to
2649 // reverse the transform we're about to do would be slightly complex.
2650 // Note: This may extend the live range of the inputs to the icmp and thus
2651 // increase the liveset of any statepoint we move over. This is profitable
2652 // as long as all statepoints are in rare blocks. If we had in-register
2653 // lowering for live values this would be a much safer transform.
2654 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2655 if (auto *BI = dyn_cast<BranchInst>(TI))
2656 if (BI->isConditional())
2657 return dyn_cast<Instruction>(BI->getCondition());
2658 // TODO: Extend this to handle switches
2659 return nullptr;
2660 };
2661 for (BasicBlock &BB : F) {
2662 TerminatorInst *TI = BB.getTerminator();
2663 if (auto *Cond = getConditionInst(TI))
2664 // TODO: Handle more than just ICmps here. We should be able to move
2665 // most instructions without side effects or memory access.
2666 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2667 MadeChange = true;
2668 Cond->moveBefore(TI);
2669 }
2670 }
2671
Justin Bogner843fb202015-12-15 19:40:57 +00002672 MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
Philip Reames85b36a82015-04-10 22:07:04 +00002673 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002674}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002675
2676// liveness computation via standard dataflow
2677// -------------------------------------------------------------------
2678
2679// TODO: Consider using bitvectors for liveness, the set of potentially
2680// interesting values should be small and easy to pre-compute.
2681
Philip Reamesdf1ef082015-04-10 22:53:14 +00002682/// Compute the live-in set for the location rbegin starting from
2683/// the live-out set of the basic block
2684static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2685 BasicBlock::reverse_iterator rend,
2686 DenseSet<Value *> &LiveTmp) {
2687
2688 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2689 Instruction *I = &*ritr;
2690
2691 // KILL/Def - Remove this definition from LiveIn
2692 LiveTmp.erase(I);
2693
2694 // Don't consider *uses* in PHI nodes, we handle their contribution to
2695 // predecessor blocks when we seed the LiveOut sets
2696 if (isa<PHINode>(I))
2697 continue;
2698
2699 // USE - Add to the LiveIn set for this instruction
2700 for (Value *V : I->operands()) {
2701 assert(!isUnhandledGCPointerType(V->getType()) &&
2702 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002703 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2704 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002705 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002706 // - We assume that things which are constant (from LLVM's definition)
2707 // do not move at runtime. For example, the address of a global
2708 // variable is fixed, even though it's contents may not be.
2709 // - Second, we can't disallow arbitrary inttoptr constants even
2710 // if the language frontend does. Optimization passes are free to
2711 // locally exploit facts without respect to global reachability. This
2712 // can create sections of code which are dynamically unreachable and
2713 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002714 LiveTmp.insert(V);
2715 }
2716 }
2717 }
2718}
2719
2720static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2721
2722 for (BasicBlock *Succ : successors(BB)) {
2723 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2724 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2725 PHINode *Phi = cast<PHINode>(&*I);
2726 Value *V = Phi->getIncomingValueForBlock(BB);
2727 assert(!isUnhandledGCPointerType(V->getType()) &&
2728 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002729 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002730 LiveTmp.insert(V);
2731 }
2732 }
2733 }
2734}
2735
2736static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2737 DenseSet<Value *> KillSet;
2738 for (Instruction &I : *BB)
2739 if (isHandledGCPointerType(I.getType()))
2740 KillSet.insert(&I);
2741 return KillSet;
2742}
2743
Philip Reames9638ff92015-04-11 00:06:47 +00002744#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002745/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2746/// sanity check for the liveness computation.
2747static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2748 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002749 for (Value *V : Live) {
2750 if (auto *I = dyn_cast<Instruction>(V)) {
2751 // The terminator can be a member of the LiveOut set. LLVM's definition
2752 // of instruction dominance states that V does not dominate itself. As
2753 // such, we need to special case this to allow it.
2754 if (TermOkay && TI == I)
2755 continue;
2756 assert(DT.dominates(I, TI) &&
2757 "basic SSA liveness expectation violated by liveness analysis");
2758 }
2759 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002760}
2761
2762/// Check that all the liveness sets used during the computation of liveness
2763/// obey basic SSA properties. This is useful for finding cases where we miss
2764/// a def.
2765static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2766 BasicBlock &BB) {
2767 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2768 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2769 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2770}
Philip Reames9638ff92015-04-11 00:06:47 +00002771#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002772
2773static void computeLiveInValues(DominatorTree &DT, Function &F,
2774 GCPtrLivenessData &Data) {
2775
Philip Reames4d80ede2015-04-10 23:11:26 +00002776 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002777 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002778 // We use a SetVector so that we don't have duplicates in the worklist.
2779 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002780 };
2781 auto NextItem = [&]() {
2782 BasicBlock *BB = Worklist.back();
2783 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002784 return BB;
2785 };
2786
2787 // Seed the liveness for each individual block
2788 for (BasicBlock &BB : F) {
2789 Data.KillSet[&BB] = computeKillSet(&BB);
2790 Data.LiveSet[&BB].clear();
2791 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2792
2793#ifndef NDEBUG
2794 for (Value *Kill : Data.KillSet[&BB])
2795 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2796#endif
2797
2798 Data.LiveOut[&BB] = DenseSet<Value *>();
2799 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2800 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2801 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2802 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2803 if (!Data.LiveIn[&BB].empty())
2804 AddPredsToWorklist(&BB);
2805 }
2806
2807 // Propagate that liveness until stable
2808 while (!Worklist.empty()) {
2809 BasicBlock *BB = NextItem();
2810
2811 // Compute our new liveout set, then exit early if it hasn't changed
2812 // despite the contribution of our successor.
2813 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2814 const auto OldLiveOutSize = LiveOut.size();
2815 for (BasicBlock *Succ : successors(BB)) {
2816 assert(Data.LiveIn.count(Succ));
2817 set_union(LiveOut, Data.LiveIn[Succ]);
2818 }
2819 // assert OutLiveOut is a subset of LiveOut
2820 if (OldLiveOutSize == LiveOut.size()) {
2821 // If the sets are the same size, then we didn't actually add anything
2822 // when unioning our successors LiveIn Thus, the LiveIn of this block
2823 // hasn't changed.
2824 continue;
2825 }
2826 Data.LiveOut[BB] = LiveOut;
2827
2828 // Apply the effects of this basic block
2829 DenseSet<Value *> LiveTmp = LiveOut;
2830 set_union(LiveTmp, Data.LiveSet[BB]);
2831 set_subtract(LiveTmp, Data.KillSet[BB]);
2832
2833 assert(Data.LiveIn.count(BB));
2834 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2835 // assert: OldLiveIn is a subset of LiveTmp
2836 if (OldLiveIn.size() != LiveTmp.size()) {
2837 Data.LiveIn[BB] = LiveTmp;
2838 AddPredsToWorklist(BB);
2839 }
2840 } // while( !worklist.empty() )
2841
2842#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002843 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002844 // missing kills during the above iteration.
2845 for (BasicBlock &BB : F) {
2846 checkBasicSSA(DT, Data, BB);
2847 }
2848#endif
2849}
2850
2851static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2852 StatepointLiveSetTy &Out) {
2853
2854 BasicBlock *BB = Inst->getParent();
2855
2856 // Note: The copy is intentional and required
2857 assert(Data.LiveOut.count(BB));
2858 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2859
2860 // We want to handle the statepoint itself oddly. It's
2861 // call result is not live (normal), nor are it's arguments
2862 // (unless they're used again later). This adjustment is
2863 // specifically what we need to relocate
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002864 BasicBlock::reverse_iterator rend(Inst->getIterator());
Philip Reamesdf1ef082015-04-10 22:53:14 +00002865 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2866 LiveOut.erase(Inst);
2867 Out.insert(LiveOut.begin(), LiveOut.end());
2868}
2869
2870static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2871 const CallSite &CS,
2872 PartiallyConstructedSafepointRecord &Info) {
2873 Instruction *Inst = CS.getInstruction();
2874 StatepointLiveSetTy Updated;
2875 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2876
2877#ifndef NDEBUG
2878 DenseSet<Value *> Bases;
2879 for (auto KVPair : Info.PointerToBase) {
2880 Bases.insert(KVPair.second);
2881 }
2882#endif
2883 // We may have base pointers which are now live that weren't before. We need
2884 // to update the PointerToBase structure to reflect this.
2885 for (auto V : Updated)
2886 if (!Info.PointerToBase.count(V)) {
2887 assert(Bases.count(V) && "can't find base for unexpected live value");
2888 Info.PointerToBase[V] = V;
2889 continue;
2890 }
2891
2892#ifndef NDEBUG
2893 for (auto V : Updated) {
2894 assert(Info.PointerToBase.count(V) &&
2895 "must be able to find base for live value");
2896 }
2897#endif
2898
2899 // Remove any stale base mappings - this can happen since our liveness is
2900 // more precise then the one inherent in the base pointer analysis
2901 DenseSet<Value *> ToErase;
2902 for (auto KVPair : Info.PointerToBase)
2903 if (!Updated.count(KVPair.first))
2904 ToErase.insert(KVPair.first);
2905 for (auto V : ToErase)
2906 Info.PointerToBase.erase(V);
2907
2908#ifndef NDEBUG
2909 for (auto KVPair : Info.PointerToBase)
2910 assert(Updated.count(KVPair.first) && "record for non-live value");
2911#endif
2912
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002913 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002914}