blob: 36827f89c39c7c6a5fd28d6f5bfbb4eb8d3ebe17 [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 Das04071082016-01-29 00:28:57 +000075static const bool UseDeoptBundles = true;
76
Sanjoy Das25ec1a32015-10-16 02:41:00 +000077static 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,
Philip Reamesb336bca2016-01-19 04:18:24 +000086 cl::init(false));
Philip Reames103d2382016-01-07 02:20:11 +000087
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
Sanjoy Dasacc43d12016-01-22 19:20:40 +0000204 Optional<OperandBundleUse> DeoptBundle =
205 CS.getOperandBundle(LLVMContext::OB_deopt);
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000206
207 if (!DeoptBundle.hasValue()) {
208 assert(AllowStatepointWithNoDeoptInfo &&
209 "Found non-leaf call without deopt info!");
210 return None;
211 }
212
213 return DeoptBundle.getValue().Inputs;
214}
215
Philip Reamesdf1ef082015-04-10 22:53:14 +0000216/// Compute the live-in set for every basic block in the function
217static void computeLiveInValues(DominatorTree &DT, Function &F,
218 GCPtrLivenessData &Data);
219
220/// Given results from the dataflow liveness computation, find the set of live
221/// Values at a particular instruction.
222static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
223 StatepointLiveSetTy &out);
224
Philip Reamesd16a9b12015-02-20 01:06:44 +0000225// TODO: Once we can get to the GCStrategy, this becomes
Philip Reamesee8f0552015-12-23 01:42:15 +0000226// Optional<bool> isGCManagedPointer(const Type *Ty) const override {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000227
Craig Toppere3dcce92015-08-01 22:20:21 +0000228static bool isGCPointerType(Type *T) {
229 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000230 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
231 // GC managed heap. We know that a pointer into this heap needs to be
232 // updated and that no other pointer does.
233 return (1 == PT->getAddressSpace());
234 return false;
235}
236
Philip Reames8531d8c2015-04-10 21:48:25 +0000237// Return true if this type is one which a) is a gc pointer or contains a GC
238// pointer and b) is of a type this code expects to encounter as a live value.
239// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000240// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000241static bool isHandledGCPointerType(Type *T) {
242 // We fully support gc pointers
243 if (isGCPointerType(T))
244 return true;
245 // We partially support vectors of gc pointers. The code will assert if it
246 // can't handle something.
247 if (auto VT = dyn_cast<VectorType>(T))
248 if (isGCPointerType(VT->getElementType()))
249 return true;
250 return false;
251}
252
253#ifndef NDEBUG
254/// Returns true if this type contains a gc pointer whether we know how to
255/// handle that type or not.
256static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000257 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000258 return true;
259 if (VectorType *VT = dyn_cast<VectorType>(Ty))
260 return isGCPointerType(VT->getScalarType());
261 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
262 return containsGCPtrType(AT->getElementType());
263 if (StructType *ST = dyn_cast<StructType>(Ty))
Craig Topperd896b032015-11-29 05:38:08 +0000264 return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
265 containsGCPtrType);
Philip Reames8531d8c2015-04-10 21:48:25 +0000266 return false;
267}
268
269// Returns true if this is a type which a) is a gc pointer or contains a GC
270// pointer and b) is of a type which the code doesn't expect (i.e. first class
271// aggregates). Used to trip assertions.
272static bool isUnhandledGCPointerType(Type *Ty) {
273 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
274}
275#endif
276
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000277static bool order_by_name(Value *a, Value *b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000278 if (a->hasName() && b->hasName()) {
279 return -1 == a->getName().compare(b->getName());
280 } else if (a->hasName() && !b->hasName()) {
281 return true;
282 } else if (!a->hasName() && b->hasName()) {
283 return false;
284 } else {
285 // Better than nothing, but not stable
286 return a < b;
287 }
288}
289
Philip Reamesece70b82015-09-09 23:57:18 +0000290// Return the name of the value suffixed with the provided value, or if the
291// value didn't have a name, the default value specified.
292static std::string suffixed_name_or(Value *V, StringRef Suffix,
293 StringRef DefaultName) {
294 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
295}
296
Philip Reamesdf1ef082015-04-10 22:53:14 +0000297// Conservatively identifies any definitions which might be live at the
298// given instruction. The analysis is performed immediately before the
299// given instruction. Values defined by that instruction are not considered
300// live. Values used by that instruction are considered live.
301static void analyzeParsePointLiveness(
302 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
303 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000304 Instruction *inst = CS.getInstruction();
305
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000306 StatepointLiveSetTy LiveSet;
307 findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000308
309 if (PrintLiveSet) {
310 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000311 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000312 // by name
Philip Reamesdab35f32015-09-02 21:11:44 +0000313 SmallVector<Value *, 64> Temp;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000314 Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
Philip Reamesdab35f32015-09-02 21:11:44 +0000315 std::sort(Temp.begin(), Temp.end(), order_by_name);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000316 errs() << "Live Variables:\n";
Philip Reamesdab35f32015-09-02 21:11:44 +0000317 for (Value *V : Temp)
318 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000319 }
320 if (PrintLiveSetSize) {
321 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000322 errs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000323 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000324 result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000325}
326
Philip Reamesf5b8e472015-09-03 21:34:30 +0000327static bool isKnownBaseResult(Value *V);
328namespace {
329/// A single base defining value - An immediate base defining value for an
330/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
331/// For instructions which have multiple pointer [vector] inputs or that
332/// transition between vector and scalar types, there is no immediate base
333/// defining value. The 'base defining value' for 'Def' is the transitive
334/// closure of this relation stopping at the first instruction which has no
335/// immediate base defining value. The b.d.v. might itself be a base pointer,
336/// but it can also be an arbitrary derived pointer.
337struct BaseDefiningValueResult {
338 /// Contains the value which is the base defining value.
339 Value * const BDV;
340 /// True if the base defining value is also known to be an actual base
341 /// pointer.
342 const bool IsKnownBase;
343 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
344 : BDV(BDV), IsKnownBase(IsKnownBase) {
345#ifndef NDEBUG
346 // Check consistency between new and old means of checking whether a BDV is
347 // a base.
348 bool MustBeBase = isKnownBaseResult(BDV);
349 assert(!MustBeBase || MustBeBase == IsKnownBase);
350#endif
351 }
352};
353}
354
355static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000356
Philip Reames8fe7f132015-06-26 22:47:37 +0000357/// Return a base defining value for the 'Index' element of the given vector
358/// instruction 'I'. If Index is null, returns a BDV for the entire vector
359/// 'I'. As an optimization, this method will try to determine when the
360/// element is known to already be a base pointer. If this can be established,
361/// the second value in the returned pair will be true. Note that either a
362/// vector or a pointer typed value can be returned. For the former, the
363/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
364/// If the later, the return pointer is a BDV (or possibly a base) for the
365/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000366static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000367findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000368 // Each case parallels findBaseDefiningValue below, see that code for
369 // detailed motivation.
370
371 if (isa<Argument>(I))
372 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000373 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000374
Manuel Jacob734e7332016-01-09 04:02:16 +0000375 if (isa<Constant>(I))
376 // Constant vectors consist only of constant pointers.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000377 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000378
Philip Reames8531d8c2015-04-10 21:48:25 +0000379 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000380 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000381
Philip Reames66287132015-09-09 23:40:12 +0000382 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000383 // We don't know whether this vector contains entirely base pointers or
384 // not. To be conservatively correct, we treat it as a BDV and will
385 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000386 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000387
Philip Reames8fe7f132015-06-26 22:47:37 +0000388 if (isa<ShuffleVectorInst>(I))
389 // We don't know whether this vector contains entirely base pointers or
390 // not. To be conservatively correct, we treat it as a BDV and will
391 // duplicate code as needed to construct a parallel vector of bases.
392 // TODO: There a number of local optimizations which could be applied here
393 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000394 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000395
396 // A PHI or Select is a base defining value. The outer findBasePointer
397 // algorithm is responsible for constructing a base value for this BDV.
398 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
399 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000400 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000401}
402
Philip Reamesd16a9b12015-02-20 01:06:44 +0000403/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000404/// defines the base pointer for the input, b) blocks the simple search
405/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
406/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000407static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Manuel Jacob0593cfd2016-01-09 03:08:49 +0000408 assert(I->getType()->isPtrOrPtrVectorTy() &&
409 "Illegal to ask for the base pointer of a non-pointer type");
410
Philip Reames8fe7f132015-06-26 22:47:37 +0000411 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000412 return findBaseDefiningValueOfVector(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000413
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000414 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000415 // An incoming argument to the function is a base pointer
416 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000417 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000418
Manuel Jacob75cbfdc2016-01-05 04:06:21 +0000419 if (isa<Constant>(I))
420 // We assume that objects with a constant base (e.g. a global) can't move
421 // and don't need to be reported to the collector because they are always
422 // live. All constants have constant bases. Besides global references, all
423 // kinds of constants (e.g. undef, constant expressions, null pointers) can
424 // be introduced by the inliner or the optimizer, especially on dynamically
425 // dead paths. See e.g. test4 in constants.ll.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000426 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000427
Philip Reamesd16a9b12015-02-20 01:06:44 +0000428 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000429 Value *Def = CI->stripPointerCasts();
Manuel Jacob8050a492015-12-21 01:26:46 +0000430 // If stripping pointer casts changes the address space there is an
431 // addrspacecast in between.
432 assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
433 cast<PointerType>(CI->getType())->getAddressSpace() &&
434 "unsupported addrspacecast");
David Blaikie82ad7872015-02-20 23:44:24 +0000435 // If we find a cast instruction here, it means we've found a cast which is
436 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
437 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000438 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
439 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000440 }
441
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000442 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000443 // The value loaded is an gc base itself
444 return BaseDefiningValueResult(I, true);
445
Philip Reamesd16a9b12015-02-20 01:06:44 +0000446
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000447 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
448 // The base of this GEP is the base
449 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000450
451 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
452 switch (II->getIntrinsicID()) {
453 default:
454 // fall through to general call handling
455 break;
456 case Intrinsic::experimental_gc_statepoint:
Manuel Jacob4e4f60d2015-12-22 18:44:45 +0000457 llvm_unreachable("statepoints don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000458 case Intrinsic::experimental_gc_relocate: {
459 // Rerunning safepoint insertion after safepoints are already
460 // inserted is not supported. It could probably be made to work,
461 // but why are you doing this? There's no good reason.
462 llvm_unreachable("repeat safepoint insertion is not supported");
463 }
464 case Intrinsic::gcroot:
465 // Currently, this mechanism hasn't been extended to work with gcroot.
466 // There's no reason it couldn't be, but I haven't thought about the
467 // implications much.
468 llvm_unreachable(
469 "interaction with the gcroot mechanism is not supported");
470 }
471 }
472 // We assume that functions in the source language only return base
473 // pointers. This should probably be generalized via attributes to support
474 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000475 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000476 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000477
478 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000479 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000480 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
481
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000482 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000483 // A CAS is effectively a atomic store and load combined under a
484 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000485 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000486 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000487
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000488 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000489 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000490
491 // The aggregate ops. Aggregates can either be in the heap or on the
492 // stack, but in either case, this is simply a field load. As a result,
493 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000494 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000495 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000496
497 // We should never see an insert vector since that would require we be
498 // tracing back a struct value not a pointer value.
499 assert(!isa<InsertValueInst>(I) &&
500 "Base pointer for a struct is meaningless");
501
Philip Reames9ac4e382015-08-12 21:00:20 +0000502 // An extractelement produces a base result exactly when it's input does.
503 // We may need to insert a parallel instruction to extract the appropriate
504 // element out of the base vector corresponding to the input. Given this,
505 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000506 if (isa<ExtractElementInst>(I))
507 // Note: There a lot of obvious peephole cases here. This are deliberately
508 // handled after the main base pointer inference algorithm to make writing
509 // test cases to exercise that code easier.
510 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000511
Philip Reamesd16a9b12015-02-20 01:06:44 +0000512 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000513 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000514 // derived pointers (each with it's own base potentially). It's the job of
515 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000516 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000517 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000518 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000519}
520
521/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000522static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
523 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000524 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000525 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000526 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
527 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000528 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000529 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000530 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000531}
532
533/// Return a base pointer for this value if known. Otherwise, return it's
534/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000535static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
536 Value *Def = findBaseDefiningValueCached(I, Cache);
537 auto Found = Cache.find(Def);
538 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000539 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000540 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000541 }
542 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000543 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000544}
545
546/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
547/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000548static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000549 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
550 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
551 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000552 // no recursion possible
553 return true;
554 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000555 if (isa<Instruction>(V) &&
556 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000557 // This is a previously inserted base phi or select. We know
558 // that this is a base value.
559 return true;
560 }
561
562 // We need to keep searching
563 return false;
564}
565
Philip Reamesd16a9b12015-02-20 01:06:44 +0000566namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000567/// Models the state of a single base defining value in the findBasePointer
568/// algorithm for determining where a new instruction is needed to propagate
569/// the base of this BDV.
570class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000571public:
572 enum Status { Unknown, Base, Conflict };
573
Philip Reames9b141ed2015-07-23 22:49:14 +0000574 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000575 assert(status != Base || b);
576 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000577 explicit BDVState(Value *b) : status(Base), base(b) {}
578 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000579
580 Status getStatus() const { return status; }
581 Value *getBase() const { return base; }
582
583 bool isBase() const { return getStatus() == Base; }
584 bool isUnknown() const { return getStatus() == Unknown; }
585 bool isConflict() const { return getStatus() == Conflict; }
586
Philip Reames9b141ed2015-07-23 22:49:14 +0000587 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000588 return base == other.base && status == other.status;
589 }
590
Philip Reames9b141ed2015-07-23 22:49:14 +0000591 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000592
Philip Reames2a892a62015-07-23 22:25:26 +0000593 LLVM_DUMP_METHOD
594 void dump() const { print(dbgs()); dbgs() << '\n'; }
595
596 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000597 switch (status) {
598 case Unknown:
599 OS << "U";
600 break;
601 case Base:
602 OS << "B";
603 break;
604 case Conflict:
605 OS << "C";
606 break;
607 };
608 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000609 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000610 }
611
612private:
613 Status status;
Philip Reamesdd0948a2015-12-18 03:53:28 +0000614 AssertingVH<Value> base; // non null only if status == base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000615};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000616}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000617
Philip Reames6906e922015-09-02 21:57:17 +0000618#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000619static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000620 State.print(OS);
621 return OS;
622}
Philip Reames6906e922015-09-02 21:57:17 +0000623#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000624
Philip Reamesb3967cd2015-09-02 22:30:53 +0000625namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000626// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000627// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000628// operation is implemented in MeetBDVStates::pureMeet
629class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000630public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000631 /// Initializes the currentResult to the TOP state so that if can be met with
632 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000633 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000634
Philip Reames9b141ed2015-07-23 22:49:14 +0000635 // Destructively meet the current result with the given BDVState
636 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000637 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000638 }
639
Philip Reames9b141ed2015-07-23 22:49:14 +0000640 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000641
642private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000643 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000644
Philip Reames9b141ed2015-07-23 22:49:14 +0000645 /// Perform a meet operation on two elements of the BDVState lattice.
646 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000647 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
648 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000649 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000650 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
651 << " produced " << Result << "\n");
652 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000653 }
654
Philip Reames9b141ed2015-07-23 22:49:14 +0000655 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000656 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000657 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000658 return stateB;
659
Philip Reames9b141ed2015-07-23 22:49:14 +0000660 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000661 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000662 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000663 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000664
665 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000666 if (stateA.getBase() == stateB.getBase()) {
667 assert(stateA == stateB && "equality broken!");
668 return stateA;
669 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000670 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000671 }
David Blaikie82ad7872015-02-20 23:44:24 +0000672 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000673 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000674
Philip Reames9b141ed2015-07-23 22:49:14 +0000675 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000676 return stateA;
677 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000678 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000679 }
680};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000681}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000682
683
Philip Reamesd16a9b12015-02-20 01:06:44 +0000684/// For a given value or instruction, figure out what base ptr it's derived
685/// from. For gc objects, this is simply itself. On success, returns a value
686/// which is the base pointer. (This is reliable and can be used for
687/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000688static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000689 Value *def = findBaseOrBDV(I, cache);
690
691 if (isKnownBaseResult(def)) {
692 return def;
693 }
694
695 // Here's the rough algorithm:
696 // - For every SSA value, construct a mapping to either an actual base
697 // pointer or a PHI which obscures the base pointer.
698 // - Construct a mapping from PHI to unknown TOP state. Use an
699 // optimistic algorithm to propagate base pointer information. Lattice
700 // looks like:
701 // UNKNOWN
702 // b1 b2 b3 b4
703 // CONFLICT
704 // When algorithm terminates, all PHIs will either have a single concrete
705 // base or be in a conflict state.
706 // - For every conflict, insert a dummy PHI node without arguments. Add
707 // these to the base[Instruction] = BasePtr mapping. For every
708 // non-conflict, add the actual base.
709 // - For every conflict, add arguments for the base[a] of each input
710 // arguments.
711 //
712 // Note: A simpler form of this would be to add the conflict form of all
713 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000714 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000715 // overall worse solution.
716
Philip Reames29e9ae72015-07-24 00:42:55 +0000717#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000718 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000719 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
720 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000721 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000722#endif
Philip Reames88958b22015-07-24 00:02:11 +0000723
724 // Once populated, will contain a mapping from each potentially non-base BDV
725 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000726 // We use the order of insertion (DFS over the def/use graph) to provide a
727 // stable deterministic ordering for visiting DenseMaps (which are unordered)
728 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000729 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000730
731 // Recursively fill in all base defining values reachable from the initial
732 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000733 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000734 SmallVector<Value*, 16> Worklist;
735 Worklist.push_back(def);
Philip Reames34d7a742015-09-10 00:22:49 +0000736 States.insert(std::make_pair(def, BDVState()));
Philip Reames88958b22015-07-24 00:02:11 +0000737 while (!Worklist.empty()) {
738 Value *Current = Worklist.pop_back_val();
739 assert(!isKnownBaseResult(Current) && "why did it get added?");
740
741 auto visitIncomingValue = [&](Value *InVal) {
742 Value *Base = findBaseOrBDV(InVal, cache);
743 if (isKnownBaseResult(Base))
744 // Known bases won't need new instructions introduced and can be
745 // ignored safely
746 return;
747 assert(isExpectedBDVType(Base) && "the only non-base values "
748 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000749 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000750 Worklist.push_back(Base);
751 };
752 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
753 for (Value *InVal : Phi->incoming_values())
754 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000755 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000756 visitIncomingValue(Sel->getTrueValue());
757 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000758 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
759 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000760 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
761 visitIncomingValue(IE->getOperand(0)); // vector operand
762 visitIncomingValue(IE->getOperand(1)); // scalar operand
Philip Reames9ac4e382015-08-12 21:00:20 +0000763 } else {
Philip Reames66287132015-09-09 23:40:12 +0000764 // There is one known class of instructions we know we don't handle.
765 assert(isa<ShuffleVectorInst>(Current));
Philip Reames9ac4e382015-08-12 21:00:20 +0000766 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000767 }
768 }
769 }
770
Philip Reamesdab35f32015-09-02 21:11:44 +0000771#ifndef NDEBUG
772 DEBUG(dbgs() << "States after initialization:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000773 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000774 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000775 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000776#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000777
Philip Reames273e6bb2015-07-23 21:41:27 +0000778 // Return a phi state for a base defining value. We'll generate a new
779 // base state for known bases and expect to find a cached state otherwise.
780 auto getStateForBDV = [&](Value *baseValue) {
781 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000782 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000783 auto I = States.find(baseValue);
784 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000785 return I->second;
786 };
787
Philip Reamesd16a9b12015-02-20 01:06:44 +0000788 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000789 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000790#ifndef NDEBUG
Philip Reamesb4e55f32015-09-10 00:32:56 +0000791 const size_t oldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000792#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000793 progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000794 // We're only changing values in this loop, thus safe to keep iterators.
795 // Since this is computing a fixed point, the order of visit does not
796 // effect the result. TODO: We could use a worklist here and make this run
797 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000798 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000799 Value *BDV = Pair.first;
800 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000801
Philip Reames9b141ed2015-07-23 22:49:14 +0000802 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000803 // instance which represents the BDV of that value.
804 auto getStateForInput = [&](Value *V) mutable {
805 Value *BDV = findBaseOrBDV(V, cache);
806 return getStateForBDV(BDV);
807 };
808
Philip Reames9b141ed2015-07-23 22:49:14 +0000809 MeetBDVStates calculateMeet;
Philip Reamesece70b82015-09-09 23:57:18 +0000810 if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000811 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
812 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reamesece70b82015-09-09 23:57:18 +0000813 } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000814 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000815 calculateMeet.meetWith(getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000816 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000817 // The 'meet' for an extractelement is slightly trivial, but it's still
818 // useful in that it drives us to conflict if our input is.
Philip Reames9ac4e382015-08-12 21:00:20 +0000819 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
Philip Reames66287132015-09-09 23:40:12 +0000820 } else {
821 // Given there's a inherent type mismatch between the operands, will
822 // *always* produce Conflict.
Philip Reamesece70b82015-09-09 23:57:18 +0000823 auto *IE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +0000824 calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
825 calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000826 }
827
Philip Reames34d7a742015-09-10 00:22:49 +0000828 BDVState oldState = States[BDV];
Philip Reames9b141ed2015-07-23 22:49:14 +0000829 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000830 if (oldState != newState) {
831 progress = true;
Philip Reames34d7a742015-09-10 00:22:49 +0000832 States[BDV] = newState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000833 }
834 }
835
Philip Reamesb4e55f32015-09-10 00:32:56 +0000836 assert(oldSize == States.size() &&
837 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000838 }
839
Philip Reamesdab35f32015-09-02 21:11:44 +0000840#ifndef NDEBUG
841 DEBUG(dbgs() << "States after meet iteration:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000842 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000843 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000844 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000845#endif
846
Philip Reamesd16a9b12015-02-20 01:06:44 +0000847 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000848 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000849 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000850 Instruction *I = cast<Instruction>(Pair.first);
851 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000852 assert(!isKnownBaseResult(I) && "why did it get added?");
853 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000854
855 // extractelement instructions are a bit special in that we may need to
856 // insert an extract even when we know an exact base for the instruction.
857 // The problem is that we need to convert from a vector base to a scalar
858 // base for the particular indice we're interested in.
859 if (State.isBase() && isa<ExtractElementInst>(I) &&
860 isa<VectorType>(State.getBase()->getType())) {
861 auto *EE = cast<ExtractElementInst>(I);
862 // TODO: In many cases, the new instruction is just EE itself. We should
863 // exploit this, but can't do it here since it would break the invariant
864 // about the BDV not being known to be a base.
865 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
866 EE->getIndexOperand(),
867 "base_ee", EE);
868 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000869 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000870 }
Philip Reames66287132015-09-09 23:40:12 +0000871
872 // Since we're joining a vector and scalar base, they can never be the
873 // same. As a result, we should always see insert element having reached
874 // the conflict state.
875 if (isa<InsertElementInst>(I)) {
876 assert(State.isConflict());
877 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000878
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000879 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000880 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000881
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000882 /// Create and insert a new instruction which will represent the base of
883 /// the given instruction 'I'.
884 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
885 if (isa<PHINode>(I)) {
886 BasicBlock *BB = I->getParent();
887 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
888 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000889 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000890 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000891 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
892 // The undef will be replaced later
893 UndefValue *Undef = UndefValue::get(Sel->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000894 std::string Name = suffixed_name_or(I, ".base", "base_select");
Philip Reames9ac4e382015-08-12 21:00:20 +0000895 return SelectInst::Create(Sel->getCondition(), Undef,
896 Undef, Name, Sel);
Philip Reames66287132015-09-09 23:40:12 +0000897 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000898 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000899 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000900 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
901 EE);
Philip Reames66287132015-09-09 23:40:12 +0000902 } else {
903 auto *IE = cast<InsertElementInst>(I);
904 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
905 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000906 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000907 return InsertElementInst::Create(VecUndef, ScalarUndef,
908 IE->getOperand(2), Name, IE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000909 }
Philip Reames66287132015-09-09 23:40:12 +0000910
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000911 };
912 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
913 // Add metadata marking this as a base value
914 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000915 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000916 }
917
Philip Reames3ea15892015-09-03 21:57:40 +0000918 // Returns a instruction which produces the base pointer for a given
919 // instruction. The instruction is assumed to be an input to one of the BDVs
920 // seen in the inference algorithm above. As such, we must either already
921 // know it's base defining value is a base, or have inserted a new
922 // instruction to propagate the base of it's BDV and have entered that newly
923 // introduced instruction into the state table. In either case, we are
924 // assured to be able to determine an instruction which produces it's base
925 // pointer.
926 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
927 Value *BDV = findBaseOrBDV(Input, cache);
928 Value *Base = nullptr;
929 if (isKnownBaseResult(BDV)) {
930 Base = BDV;
931 } else {
932 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000933 assert(States.count(BDV));
934 Base = States[BDV].getBase();
Philip Reames3ea15892015-09-03 21:57:40 +0000935 }
936 assert(Base && "can't be null");
937 // The cast is needed since base traversal may strip away bitcasts
938 if (Base->getType() != Input->getType() &&
939 InsertPt) {
940 Base = new BitCastInst(Base, Input->getType(), "cast",
941 InsertPt);
942 }
943 return Base;
944 };
945
Philip Reames15d55632015-09-09 23:26:08 +0000946 // Fixup all the inputs of the new PHIs. Visit order needs to be
947 // deterministic and predictable because we're naming newly created
948 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000949 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000950 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000951 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000952
Philip Reames7540e3a2015-09-10 00:01:53 +0000953 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000954 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
955 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000956 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000957
Philip Reamesc8ded462015-09-10 00:27:50 +0000958 if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000959 PHINode *phi = cast<PHINode>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +0000960 unsigned NumPHIValues = phi->getNumIncomingValues();
961 for (unsigned i = 0; i < NumPHIValues; i++) {
962 Value *InVal = phi->getIncomingValue(i);
963 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000964
Philip Reames28e61ce2015-02-28 01:57:44 +0000965 // If we've already seen InBB, add the same incoming value
966 // we added for it earlier. The IR verifier requires phi
967 // nodes with multiple entries from the same basic block
968 // to have the same incoming value for each of those
969 // entries. If we don't do this check here and basephi
970 // has a different type than base, we'll end up adding two
971 // bitcasts (and hence two distinct values) as incoming
972 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000973
Philip Reames28e61ce2015-02-28 01:57:44 +0000974 int blockIndex = basephi->getBasicBlockIndex(InBB);
975 if (blockIndex != -1) {
976 Value *oldBase = basephi->getIncomingValue(blockIndex);
977 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +0000978
Philip Reamesd16a9b12015-02-20 01:06:44 +0000979#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +0000980 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000981 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +0000982 // values incoming from the same basic block may be
983 // different is by being different bitcasts of the same
984 // value. A cleanup that remains TODO is changing
985 // findBaseOrBDV to return an llvm::Value of the correct
986 // type (and still remain pure). This will remove the
987 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +0000988 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +0000989 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000990#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000991 continue;
992 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000993
Philip Reames3ea15892015-09-03 21:57:40 +0000994 // Find the instruction which produces the base for each input. We may
995 // need to insert a bitcast in the incoming block.
996 // TODO: Need to split critical edges if insertion is needed
997 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
998 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +0000999 }
1000 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reamesc8ded462015-09-10 00:27:50 +00001001 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001002 SelectInst *Sel = cast<SelectInst>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +00001003 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1004 // something more safe and less hacky.
1005 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001006 Value *InVal = Sel->getOperand(i);
1007 // Find the instruction which produces the base for each input. We may
1008 // need to insert a bitcast.
1009 Value *Base = getBaseForInput(InVal, BaseSel);
1010 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001011 }
Philip Reamesc8ded462015-09-10 00:27:50 +00001012 } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001013 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001014 // Find the instruction which produces the base for each input. We may
1015 // need to insert a bitcast.
1016 Value *Base = getBaseForInput(InVal, BaseEE);
Philip Reames9ac4e382015-08-12 21:00:20 +00001017 BaseEE->setOperand(0, Base);
Philip Reames66287132015-09-09 23:40:12 +00001018 } else {
Philip Reamesc8ded462015-09-10 00:27:50 +00001019 auto *BaseIE = cast<InsertElementInst>(State.getBase());
Philip Reames7540e3a2015-09-10 00:01:53 +00001020 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001021 auto UpdateOperand = [&](int OperandIdx) {
1022 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001023 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001024 BaseIE->setOperand(OperandIdx, Base);
1025 };
1026 UpdateOperand(0); // vector operand
1027 UpdateOperand(1); // scalar operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001028 }
Philip Reames66287132015-09-09 23:40:12 +00001029
Philip Reamesd16a9b12015-02-20 01:06:44 +00001030 }
1031
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001032 // Now that we're done with the algorithm, see if we can optimize the
1033 // results slightly by reducing the number of new instructions needed.
1034 // Arguably, this should be integrated into the algorithm above, but
1035 // doing as a post process step is easier to reason about for the moment.
1036 DenseMap<Value *, Value *> ReverseMap;
1037 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001038 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001039 // Note: We need to visit the states in a deterministic order. We uses the
1040 // Keys we sorted above for this purpose. Note that we are papering over a
1041 // bigger problem with the algorithm above - it's visit order is not
1042 // deterministic. A larger change is needed to fix this.
Philip Reames34d7a742015-09-10 00:22:49 +00001043 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001044 auto *BDV = Pair.first;
1045 auto State = Pair.second;
Philip Reames246e6182015-09-03 20:24:29 +00001046 Value *Base = State.getBase();
Philip Reames15d55632015-09-09 23:26:08 +00001047 assert(BDV && Base);
1048 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001049 assert(isKnownBaseResult(Base) &&
1050 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001051 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001052 continue;
1053
Philip Reames15d55632015-09-09 23:26:08 +00001054 ReverseMap[Base] = BDV;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001055 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1056 NewInsts.insert(BaseI);
1057 Worklist.insert(BaseI);
1058 }
1059 }
Philip Reames9546f362015-09-02 22:25:07 +00001060 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1061 Value *Replacement) {
1062 // Add users which are new instructions (excluding self references)
1063 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001064 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001065 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001066 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001067 // Then do the actual replacement
1068 NewInsts.erase(BaseI);
1069 ReverseMap.erase(BaseI);
1070 BaseI->replaceAllUsesWith(Replacement);
Philip Reames34d7a742015-09-10 00:22:49 +00001071 assert(States.count(BDV));
1072 assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
1073 States[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesdd0948a2015-12-18 03:53:28 +00001074 BaseI->eraseFromParent();
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001075 };
1076 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1077 while (!Worklist.empty()) {
1078 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001079 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001080 Value *Bdv = ReverseMap[BaseI];
1081 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1082 if (BaseI->isIdenticalTo(BdvI)) {
1083 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001084 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001085 continue;
1086 }
1087 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1088 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001089 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001090 continue;
1091 }
1092 }
1093
Philip Reamesd16a9b12015-02-20 01:06:44 +00001094 // Cache all of our results so we can cheaply reuse them
1095 // NOTE: This is actually two caches: one of the base defining value
1096 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001097 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001098 auto *BDV = Pair.first;
1099 Value *base = Pair.second.getBase();
1100 assert(BDV && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001101
Philip Reamesece70b82015-09-09 23:57:18 +00001102 std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
Philip Reamesdab35f32015-09-02 21:11:44 +00001103 DEBUG(dbgs() << "Updating base value cache"
Philip Reamesece70b82015-09-09 23:57:18 +00001104 << " for: " << BDV->getName()
Philip Reamesdab35f32015-09-02 21:11:44 +00001105 << " from: " << fromstr
Philip Reamesece70b82015-09-09 23:57:18 +00001106 << " to: " << base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001107
Philip Reames15d55632015-09-09 23:26:08 +00001108 if (cache.count(BDV)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001109 // Once we transition from the BDV relation being store in the cache to
1110 // the base relation being stored, it must be stable
Philip Reames15d55632015-09-09 23:26:08 +00001111 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001112 "base relation should be stable");
1113 }
Philip Reames15d55632015-09-09 23:26:08 +00001114 cache[BDV] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001115 }
Manuel Jacob67f1d3a2015-12-29 22:16:41 +00001116 assert(cache.count(def));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001117 return cache[def];
1118}
1119
1120// For a set of live pointers (base and/or derived), identify the base
1121// pointer of the object which they are derived from. This routine will
1122// mutate the IR graph as needed to make the 'base' pointer live at the
1123// definition site of 'derived'. This ensures that any use of 'derived' can
1124// also use 'base'. This may involve the insertion of a number of
1125// additional PHI nodes.
1126//
1127// preconditions: live is a set of pointer type Values
1128//
1129// side effects: may insert PHI nodes into the existing CFG, will preserve
1130// CFG, will not remove or mutate any existing nodes
1131//
Philip Reamesf2041322015-02-20 19:26:04 +00001132// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001133// pointer in live. Note that derived can be equal to base if the original
1134// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001135static void
1136findBasePointers(const StatepointLiveSetTy &live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001137 DenseMap<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001138 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001139 // For the naming of values inserted to be deterministic - which makes for
1140 // much cleaner and more stable tests - we need to assign an order to the
1141 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001142 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001143 Temp.insert(Temp.end(), live.begin(), live.end());
1144 std::sort(Temp.begin(), Temp.end(), order_by_name);
1145 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001146 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001147 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001148 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001149 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1150 DT->dominates(cast<Instruction>(base)->getParent(),
1151 cast<Instruction>(ptr)->getParent())) &&
1152 "The base we found better dominate the derived pointer");
1153
David Blaikie82ad7872015-02-20 23:44:24 +00001154 // If you see this trip and like to live really dangerously, the code should
1155 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001156 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001157 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001158 "the relocation code needs adjustment to handle the relocation of "
1159 "a null pointer constant without causing false positives in the "
1160 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001161 }
1162}
1163
1164/// Find the required based pointers (and adjust the live set) for the given
1165/// parse point.
1166static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1167 const CallSite &CS,
1168 PartiallyConstructedSafepointRecord &result) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001169 DenseMap<Value *, Value *> PointerToBase;
1170 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001171
1172 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001173 // Note: Need to print these in a stable order since this is checked in
1174 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001175 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001176 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001177 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001178 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001179 Temp.push_back(Pair.first);
1180 }
1181 std::sort(Temp.begin(), Temp.end(), order_by_name);
1182 for (Value *Ptr : Temp) {
1183 Value *Base = PointerToBase[Ptr];
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001184 errs() << " derived ";
1185 Ptr->printAsOperand(errs(), false);
1186 errs() << " base ";
1187 Base->printAsOperand(errs(), false);
1188 errs() << "\n";;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001189 }
1190 }
1191
Philip Reamesf2041322015-02-20 19:26:04 +00001192 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001193}
1194
Philip Reamesdf1ef082015-04-10 22:53:14 +00001195/// Given an updated version of the dataflow liveness results, update the
1196/// liveset and base pointer maps for the call site CS.
1197static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1198 const CallSite &CS,
1199 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001200
Philip Reamesdf1ef082015-04-10 22:53:14 +00001201static void recomputeLiveInValues(
Justin Bogner843fb202015-12-15 19:40:57 +00001202 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001203 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001204 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001205 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001206 GCPtrLivenessData RevisedLivenessData;
1207 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001208 for (size_t i = 0; i < records.size(); i++) {
1209 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001210 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001211 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001212 }
1213}
1214
Sanjoy Das7ad67642015-10-20 01:06:24 +00001215// When inserting gc.relocate and gc.result calls, we need to ensure there are
1216// no uses of the original value / return value between the gc.statepoint and
1217// the gc.relocate / gc.result call. One case which can arise is a phi node
1218// starting one of the successor blocks. We also need to be able to insert the
1219// gc.relocates only on the path which goes through the statepoint. We might
1220// need to split an edge to make this possible.
Philip Reamesf209a152015-04-13 20:00:30 +00001221static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001222normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1223 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001224 BasicBlock *Ret = BB;
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001225 if (!BB->getUniquePredecessor())
Chandler Carruth96ada252015-07-22 09:52:54 +00001226 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001227
Sanjoy Das7ad67642015-10-20 01:06:24 +00001228 // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
Philip Reames69e51ca2015-04-13 18:07:21 +00001229 // from it
1230 FoldSingleEntryPHINodes(Ret);
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001231 assert(!isa<PHINode>(Ret->begin()) &&
1232 "All PHI nodes should have been removed!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001233
Sanjoy Das7ad67642015-10-20 01:06:24 +00001234 // At this point, we can safely insert a gc.relocate or gc.result as the first
1235 // instruction in Ret if needed.
Philip Reames69e51ca2015-04-13 18:07:21 +00001236 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001237}
1238
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001239// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001240// from original call to the safepoint.
1241static AttributeSet legalizeCallAttributes(AttributeSet AS) {
Sanjoy Das810a59d2015-10-16 02:41:11 +00001242 AttributeSet Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001243
1244 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
Sanjoy Das810a59d2015-10-16 02:41:11 +00001245 unsigned Index = AS.getSlotIndex(Slot);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001246
Sanjoy Das810a59d2015-10-16 02:41:11 +00001247 if (Index == AttributeSet::ReturnIndex ||
1248 Index == AttributeSet::FunctionIndex) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001249
Sanjoy Das810a59d2015-10-16 02:41:11 +00001250 for (Attribute Attr : make_range(AS.begin(Slot), AS.end(Slot))) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001251
1252 // Do not allow certain attributes - just skip them
1253 // Safepoint can not be read only or read none.
Sanjoy Das810a59d2015-10-16 02:41:11 +00001254 if (Attr.hasAttribute(Attribute::ReadNone) ||
1255 Attr.hasAttribute(Attribute::ReadOnly))
Philip Reamesd16a9b12015-02-20 01:06:44 +00001256 continue;
1257
Sanjoy Das58fae7c2015-10-16 02:41:23 +00001258 // These attributes control the generation of the gc.statepoint call /
1259 // invoke itself; and once the gc.statepoint is in place, they're of no
1260 // use.
1261 if (Attr.hasAttribute("statepoint-num-patch-bytes") ||
1262 Attr.hasAttribute("statepoint-id"))
1263 continue;
1264
Sanjoy Das810a59d2015-10-16 02:41:11 +00001265 Ret = Ret.addAttributes(
1266 AS.getContext(), Index,
1267 AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001268 }
1269 }
1270
1271 // Just skip parameter attributes for now
1272 }
1273
Sanjoy Das810a59d2015-10-16 02:41:11 +00001274 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001275}
1276
1277/// Helper function to place all gc relocates necessary for the given
1278/// statepoint.
1279/// Inputs:
1280/// liveVariables - list of variables to be relocated.
1281/// liveStart - index of the first live variable.
1282/// basePtrs - base pointers.
1283/// statepointToken - statepoint instruction to which relocates should be
1284/// bound.
1285/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001286static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001287 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001288 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001289 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001290 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001291 if (LiveVariables.empty())
1292 return;
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001293
1294 auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1295 auto ValIt = std::find(LiveVec.begin(), LiveVec.end(), Val);
1296 assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1297 size_t Index = std::distance(LiveVec.begin(), ValIt);
1298 assert(Index < LiveVec.size() && "Bug in std::find?");
1299 return Index;
1300 };
Philip Reames74ce2e72015-07-21 16:51:17 +00001301 Module *M = StatepointToken->getModule();
Philip Reames5715f572016-01-09 01:31:13 +00001302
1303 // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1304 // element type is i8 addrspace(1)*). We originally generated unique
1305 // declarations for each pointer type, but this proved problematic because
1306 // the intrinsic mangling code is incomplete and fragile. Since we're moving
1307 // towards a single unified pointer type anyways, we can just cast everything
1308 // to an i8* of the right address space. A bitcast is added later to convert
1309 // gc_relocate to the actual value's type.
1310 auto getGCRelocateDecl = [&] (Type *Ty) {
1311 assert(isHandledGCPointerType(Ty));
1312 auto AS = Ty->getScalarType()->getPointerAddressSpace();
1313 Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1314 if (auto *VT = dyn_cast<VectorType>(Ty))
1315 NewTy = VectorType::get(NewTy, VT->getNumElements());
1316 return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1317 {NewTy});
1318 };
1319
1320 // Lazily populated map from input types to the canonicalized form mentioned
1321 // in the comment above. This should probably be cached somewhere more
1322 // broadly.
1323 DenseMap<Type*, Value*> TypeToDeclMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001324
Sanjoy Das5665c992015-05-11 23:47:27 +00001325 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001326 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001327 Value *BaseIdx =
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001328 Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
Sanjoy Das3020b1b2015-10-20 01:06:31 +00001329 Value *LiveIdx = Builder.getInt32(LiveStart + i);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001330
Philip Reames5715f572016-01-09 01:31:13 +00001331 Type *Ty = LiveVariables[i]->getType();
1332 if (!TypeToDeclMap.count(Ty))
1333 TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1334 Value *GCRelocateDecl = TypeToDeclMap[Ty];
1335
Philip Reamesd16a9b12015-02-20 01:06:44 +00001336 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001337 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001338 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001339 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001340 // Trick CodeGen into thinking there are lots of free registers at this
1341 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001342 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001343 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001344}
1345
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001346namespace {
1347
1348/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1349/// avoids having to worry about keeping around dangling pointers to Values.
1350class DeferredReplacement {
1351 AssertingVH<Instruction> Old;
1352 AssertingVH<Instruction> New;
1353
1354public:
1355 explicit DeferredReplacement(Instruction *Old, Instruction *New) :
1356 Old(Old), New(New) {
1357 assert(Old != New && "Not allowed!");
1358 }
1359
1360 /// Does the task represented by this instance.
1361 void doReplacement() {
1362 Instruction *OldI = Old;
1363 Instruction *NewI = New;
1364
1365 assert(OldI != NewI && "Disallowed at construction?!");
1366
1367 Old = nullptr;
1368 New = nullptr;
1369
1370 if (NewI)
1371 OldI->replaceAllUsesWith(NewI);
1372 OldI->eraseFromParent();
1373 }
1374};
1375}
1376
Philip Reamesd16a9b12015-02-20 01:06:44 +00001377static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001378makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1379 const SmallVectorImpl<Value *> &BasePtrs,
1380 const SmallVectorImpl<Value *> &LiveVariables,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001381 PartiallyConstructedSafepointRecord &Result,
1382 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001383 assert(BasePtrs.size() == LiveVariables.size());
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001384 assert((UseDeoptBundles || isStatepoint(CS)) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001385 "This method expects to be rewriting a statepoint");
1386
Philip Reamesd16a9b12015-02-20 01:06:44 +00001387 // Then go ahead and use the builder do actually do the inserts. We insert
1388 // immediately before the previous instruction under the assumption that all
1389 // arguments will be available here. We can't insert afterwards since we may
1390 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001391 Instruction *InsertBefore = CS.getInstruction();
1392 IRBuilder<> Builder(InsertBefore);
1393
Sanjoy Das3c520a12015-10-08 23:18:38 +00001394 ArrayRef<Value *> GCArgs(LiveVariables);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001395 uint64_t StatepointID = 0xABCDEF00;
1396 uint32_t NumPatchBytes = 0;
1397 uint32_t Flags = uint32_t(StatepointFlags::None);
Sanjoy Das3c520a12015-10-08 23:18:38 +00001398
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001399 ArrayRef<Use> CallArgs;
1400 ArrayRef<Use> DeoptArgs;
1401 ArrayRef<Use> TransitionArgs;
1402
1403 Value *CallTarget = nullptr;
1404
1405 if (UseDeoptBundles) {
1406 CallArgs = {CS.arg_begin(), CS.arg_end()};
1407 DeoptArgs = GetDeoptBundleOperands(CS);
Sanjoy Dasa34ce952016-01-20 19:50:25 +00001408 if (auto TransitionBundle =
1409 CS.getOperandBundle(LLVMContext::OB_gc_transition)) {
1410 Flags |= uint32_t(StatepointFlags::GCTransition);
1411 TransitionArgs = TransitionBundle->Inputs;
1412 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001413 AttributeSet OriginalAttrs = CS.getAttributes();
1414
1415 Attribute AttrID = OriginalAttrs.getAttribute(AttributeSet::FunctionIndex,
1416 "statepoint-id");
1417 if (AttrID.isStringAttribute())
1418 AttrID.getValueAsString().getAsInteger(10, StatepointID);
1419
1420 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
1421 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
1422 if (AttrNumPatchBytes.isStringAttribute())
1423 AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
1424
1425 CallTarget = CS.getCalledValue();
1426 } else {
1427 // This branch will be gone soon, and we will soon only support the
1428 // UseDeoptBundles == true configuration.
1429 Statepoint OldSP(CS);
1430 StatepointID = OldSP.getID();
1431 NumPatchBytes = OldSP.getNumPatchBytes();
1432 Flags = OldSP.getFlags();
1433
1434 CallArgs = {OldSP.arg_begin(), OldSP.arg_end()};
1435 DeoptArgs = {OldSP.vm_state_begin(), OldSP.vm_state_end()};
1436 TransitionArgs = {OldSP.gc_transition_args_begin(),
1437 OldSP.gc_transition_args_end()};
1438 CallTarget = OldSP.getCalledValue();
1439 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001440
1441 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001442 Instruction *Token = nullptr;
1443 AttributeSet ReturnAttrs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001444 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001445 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Das3c520a12015-10-08 23:18:38 +00001446 CallInst *Call = Builder.CreateGCStatepointCall(
1447 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1448 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1449
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001450 Call->setTailCall(ToReplace->isTailCall());
1451 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001452
1453 // Currently we will fail on parameter attributes and on certain
1454 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001455 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001456 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001457 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001458 Call->setAttributes(NewAttrs.getFnAttributes());
1459 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001460
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001461 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001462
1463 // Put the following gc_result and gc_relocate calls immediately after the
1464 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001465 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1466 Builder.SetInsertPoint(ToReplace->getNextNode());
1467 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001468 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001469 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001470
1471 // Insert the new invoke into the old block. We'll remove the old one in a
1472 // moment at which point this will become the new terminator for the
1473 // original block.
Sanjoy Das3c520a12015-10-08 23:18:38 +00001474 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1475 StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1476 ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1477 GCArgs, "statepoint_token");
1478
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001479 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001480
1481 // Currently we will fail on parameter attributes and on certain
1482 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001483 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001484 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001485 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001486 Invoke->setAttributes(NewAttrs.getFnAttributes());
1487 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001488
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001489 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001490
1491 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001492 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1493 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1494 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001495 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001496
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001497 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001498 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001499
Chen Lid71999e2015-12-26 07:54:32 +00001500 // Attach exceptional gc relocates to the landingpad.
1501 Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001502 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001503
Sanjoy Das3c520a12015-10-08 23:18:38 +00001504 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001505 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1506 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001507
1508 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001509 BasicBlock *NormalDest = ToReplace->getNormalDest();
1510 assert(!isa<PHINode>(NormalDest->begin()) &&
1511 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001512 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001513
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001514 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001515
1516 // gc relocates will be generated later as if it were regular call
1517 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001518 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001519 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001520
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001521 if (UseDeoptBundles) {
1522 Token->setName("statepoint_token");
1523 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1524 StringRef Name =
1525 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1526 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
1527 GCResult->setAttributes(CS.getAttributes().getRetAttributes());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001528
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001529 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1530 // live set of some other safepoint, in which case that safepoint's
1531 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1532 // llvm::Instruction. Instead, we defer the replacement and deletion to
1533 // after the live sets have been made explicit in the IR, and we no longer
1534 // have raw pointers to worry about.
1535 Replacements.emplace_back(CS.getInstruction(), GCResult);
1536 } else {
1537 Replacements.emplace_back(CS.getInstruction(), nullptr);
1538 }
1539 } else {
1540 assert(!CS.getInstruction()->hasNUsesOrMore(2) &&
1541 "only valid use before rewrite is gc.result");
1542 assert(!CS.getInstruction()->hasOneUse() ||
1543 isGCResult(cast<Instruction>(*CS.getInstruction()->user_begin())));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001544
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001545 // Take the name of the original statepoint token if there was one.
1546 Token->takeName(CS.getInstruction());
1547
1548 // Update the gc.result of the original statepoint (if any) to use the newly
1549 // inserted statepoint. This is safe to do here since the token can't be
1550 // considered a live reference.
1551 CS.getInstruction()->replaceAllUsesWith(Token);
1552 CS.getInstruction()->eraseFromParent();
1553 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001554
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001555 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001556
Philip Reamesd16a9b12015-02-20 01:06:44 +00001557 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001558 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001559 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001560}
1561
1562namespace {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001563struct NameOrdering {
1564 Value *Base;
1565 Value *Derived;
1566
1567 bool operator()(NameOrdering const &a, NameOrdering const &b) {
1568 return -1 == a.Derived->getName().compare(b.Derived->getName());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001569 }
1570};
1571}
Philip Reamesd16a9b12015-02-20 01:06:44 +00001572
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001573static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
1574 SmallVectorImpl<Value *> &LiveVec) {
1575 assert(BaseVec.size() == LiveVec.size());
1576
1577 SmallVector<NameOrdering, 64> Temp;
1578 for (size_t i = 0; i < BaseVec.size(); i++) {
1579 NameOrdering v;
1580 v.Base = BaseVec[i];
1581 v.Derived = LiveVec[i];
1582 Temp.push_back(v);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001583 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001584
1585 std::sort(Temp.begin(), Temp.end(), NameOrdering());
1586 for (size_t i = 0; i < BaseVec.size(); i++) {
1587 BaseVec[i] = Temp[i].Base;
1588 LiveVec[i] = Temp[i].Derived;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001589 }
1590}
1591
1592// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1593// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001594//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001595// WARNING: Does not do any fixup to adjust users of the original live
1596// values. That's the callers responsibility.
1597static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001598makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001599 PartiallyConstructedSafepointRecord &Result,
1600 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001601 const auto &LiveSet = Result.LiveSet;
1602 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001603
1604 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001605 SmallVector<Value *, 64> BaseVec, LiveVec;
1606 LiveVec.reserve(LiveSet.size());
1607 BaseVec.reserve(LiveSet.size());
1608 for (Value *L : LiveSet) {
1609 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001610 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001611 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001612 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001613 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001614 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001615
1616 // To make the output IR slightly more stable (for use in diffs), ensure a
1617 // fixed order of the values in the safepoint (by sorting the value name).
1618 // The order is otherwise meaningless.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001619 StabilizeOrder(BaseVec, LiveVec);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001620
1621 // Do the actual rewriting and delete the old statepoint
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001622 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001623}
1624
1625// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001626//
1627// It receives iterator to the statepoint gc relocates and emits a store to the
1628// assigned location (via allocaMap) for the each one of them. It adds the
1629// visited values into the visitedLiveValues set, which we will later use them
1630// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001631static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001632insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1633 DenseMap<Value *, Value *> &AllocaMap,
1634 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001635
Sanjoy Das5665c992015-05-11 23:47:27 +00001636 for (User *U : GCRelocs) {
Manuel Jacob83eefa62016-01-05 04:03:00 +00001637 GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1638 if (!Relocate)
Philip Reamesd16a9b12015-02-20 01:06:44 +00001639 continue;
1640
Manuel Jacob83eefa62016-01-05 04:03:00 +00001641 Value *OriginalValue = const_cast<Value *>(Relocate->getDerivedPtr());
Sanjoy Das5665c992015-05-11 23:47:27 +00001642 assert(AllocaMap.count(OriginalValue));
1643 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001644
1645 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001646 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001647 // the correct type according to alloca.
Manuel Jacob83eefa62016-01-05 04:03:00 +00001648 assert(Relocate->getNextNode() &&
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001649 "Should always have one since it's not a terminator");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001650 IRBuilder<> Builder(Relocate->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001651 Value *CastedRelocatedValue =
Manuel Jacob83eefa62016-01-05 04:03:00 +00001652 Builder.CreateBitCast(Relocate,
Philip Reamesece70b82015-09-09 23:57:18 +00001653 cast<AllocaInst>(Alloca)->getAllocatedType(),
Manuel Jacob83eefa62016-01-05 04:03:00 +00001654 suffixed_name_or(Relocate, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001655
Sanjoy Das5665c992015-05-11 23:47:27 +00001656 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1657 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001658
1659#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001660 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001661#endif
1662 }
1663}
1664
Igor Laevskye0317182015-05-19 15:59:05 +00001665// Helper function for the "relocationViaAlloca". Similar to the
1666// "insertRelocationStores" but works for rematerialized values.
1667static void
1668insertRematerializationStores(
1669 RematerializedValueMapTy RematerializedValues,
1670 DenseMap<Value *, Value *> &AllocaMap,
1671 DenseSet<Value *> &VisitedLiveValues) {
1672
1673 for (auto RematerializedValuePair: RematerializedValues) {
1674 Instruction *RematerializedValue = RematerializedValuePair.first;
1675 Value *OriginalValue = RematerializedValuePair.second;
1676
1677 assert(AllocaMap.count(OriginalValue) &&
1678 "Can not find alloca for rematerialized value");
1679 Value *Alloca = AllocaMap[OriginalValue];
1680
1681 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1682 Store->insertAfter(RematerializedValue);
1683
1684#ifndef NDEBUG
1685 VisitedLiveValues.insert(OriginalValue);
1686#endif
1687 }
1688}
1689
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001690/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001691static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001692 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001693 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001694#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001695 // record initial number of (static) allocas; we'll check we have the same
1696 // number when we get done.
1697 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001698 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1699 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001700 if (isa<AllocaInst>(*I))
1701 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001702#endif
1703
1704 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001705 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001706 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001707 // Used later to chack that we have enough allocas to store all values
1708 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001709 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001710
Igor Laevskye0317182015-05-19 15:59:05 +00001711 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1712 // "PromotableAllocas"
1713 auto emitAllocaFor = [&](Value *LiveValue) {
1714 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1715 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001716 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001717 PromotableAllocas.push_back(Alloca);
1718 };
1719
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001720 // Emit alloca for each live gc pointer
1721 for (Value *V : Live)
1722 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001723
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001724 // Emit allocas for rematerialized values
1725 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001726 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001727 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001728 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001729 continue;
1730
1731 emitAllocaFor(OriginalValue);
1732 ++NumRematerializedValues;
1733 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001734
Philip Reamesd16a9b12015-02-20 01:06:44 +00001735 // The next two loops are part of the same conceptual operation. We need to
1736 // insert a store to the alloca after the original def and at each
1737 // redefinition. We need to insert a load before each use. These are split
1738 // into distinct loops for performance reasons.
1739
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001740 // Update gc pointer after each statepoint: either store a relocated value or
1741 // null (if no relocated value was found for this gc pointer and it is not a
1742 // gc_result). This must happen before we update the statepoint with load of
1743 // alloca otherwise we lose the link between statepoint and old def.
1744 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001745 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001746
1747 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001748 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001749
1750 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001751 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001752
1753 // In case if it was invoke statepoint
1754 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001755 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001756 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1757 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001758 }
1759
Igor Laevskye0317182015-05-19 15:59:05 +00001760 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001761 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1762 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001763
Philip Reamese73300b2015-04-13 16:41:32 +00001764 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001765 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001766 // the gc.statepoint. This will turn some subtle GC problems into
1767 // slightly easier to debug SEGVs. Note that on large IR files with
1768 // lots of gc.statepoints this is extremely costly both memory and time
1769 // wise.
1770 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001771 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001772 Value *Def = Pair.first;
1773 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001774
Philip Reamese73300b2015-04-13 16:41:32 +00001775 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001776 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001777 continue;
1778 }
1779 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001780 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001781
Philip Reamese73300b2015-04-13 16:41:32 +00001782 auto InsertClobbersAt = [&](Instruction *IP) {
1783 for (auto *AI : ToClobber) {
Eduard Burtescu90c44492016-01-18 00:10:01 +00001784 auto PT = cast<PointerType>(AI->getAllocatedType());
Philip Reamese73300b2015-04-13 16:41:32 +00001785 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001786 StoreInst *Store = new StoreInst(CPN, AI);
1787 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001788 }
1789 };
1790
1791 // Insert the clobbering stores. These may get intermixed with the
1792 // gc.results and gc.relocates, but that's fine.
1793 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001794 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1795 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001796 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001797 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001798 }
David Blaikie82ad7872015-02-20 23:44:24 +00001799 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001800 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001801
1802 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001803 for (auto Pair : AllocaMap) {
1804 Value *Def = Pair.first;
1805 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001806
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001807 // We pre-record the uses of allocas so that we dont have to worry about
1808 // later update that changes the user information..
1809
Igor Laevsky285fe842015-05-19 16:29:43 +00001810 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001811 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001812 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1813 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001814 if (!isa<ConstantExpr>(U)) {
1815 // If the def has a ConstantExpr use, then the def is either a
1816 // ConstantExpr use itself or null. In either case
1817 // (recursively in the first, directly in the second), the oop
1818 // it is ultimately dependent on is null and this particular
1819 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001820 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001821 }
1822 }
1823
Igor Laevsky285fe842015-05-19 16:29:43 +00001824 std::sort(Uses.begin(), Uses.end());
1825 auto Last = std::unique(Uses.begin(), Uses.end());
1826 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001827
Igor Laevsky285fe842015-05-19 16:29:43 +00001828 for (Instruction *Use : Uses) {
1829 if (isa<PHINode>(Use)) {
1830 PHINode *Phi = cast<PHINode>(Use);
1831 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1832 if (Def == Phi->getIncomingValue(i)) {
1833 LoadInst *Load = new LoadInst(
1834 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1835 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001836 }
1837 }
1838 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001839 LoadInst *Load = new LoadInst(Alloca, "", Use);
1840 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001841 }
1842 }
1843
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001844 // Emit store for the initial gc value. Store must be inserted after load,
1845 // otherwise store will be in alloca's use list and an extra load will be
1846 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001847 StoreInst *Store = new StoreInst(Def, Alloca);
1848 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1849 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001850 // InvokeInst is a TerminatorInst so the store need to be inserted
1851 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001852 BasicBlock *NormalDest = Invoke->getNormalDest();
1853 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001854 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001855 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001856 "The only TerminatorInst that can produce a value is "
1857 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001858 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001859 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001860 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001861 assert(isa<Argument>(Def));
1862 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001863 }
1864 }
1865
Igor Laevsky285fe842015-05-19 16:29:43 +00001866 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001867 "we must have the same allocas with lives");
1868 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001869 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001870 PromoteMemToReg(PromotableAllocas, DT);
1871 }
1872
1873#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001874 for (auto &I : F.getEntryBlock())
1875 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001876 InitialAllocaNum--;
1877 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001878#endif
1879}
1880
1881/// Implement a unique function which doesn't require we sort the input
1882/// vector. Doing so has the effect of changing the output of a couple of
1883/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001884template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001885 SmallSet<T, 8> Seen;
1886 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1887 return !Seen.insert(V).second;
1888 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001889}
1890
Philip Reamesd16a9b12015-02-20 01:06:44 +00001891/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001892/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001893static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001894 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001895 if (Values.empty())
1896 // No values to hold live, might as well not insert the empty holder
1897 return;
1898
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001899 Module *M = CS.getInstruction()->getModule();
Philip Reamesf209a152015-04-13 20:00:30 +00001900 // Use a dummy vararg function to actually hold the values live
1901 Function *Func = cast<Function>(M->getOrInsertFunction(
1902 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001903 if (CS.isCall()) {
1904 // For call safepoints insert dummy calls right after safepoint
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001905 Holders.push_back(CallInst::Create(Func, Values, "",
1906 &*++CS.getInstruction()->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001907 return;
1908 }
1909 // For invoke safepooints insert dummy calls both in normal and
1910 // exceptional destination blocks
1911 auto *II = cast<InvokeInst>(CS.getInstruction());
1912 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001913 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001914 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001915 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001916}
1917
1918static void findLiveReferences(
Justin Bogner843fb202015-12-15 19:40:57 +00001919 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001920 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001921 GCPtrLivenessData OriginalLivenessData;
1922 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001923 for (size_t i = 0; i < records.size(); i++) {
1924 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001925 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001926 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001927 }
1928}
1929
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001930/// Remove any vector of pointers from the live set by scalarizing them over the
1931/// statepoint instruction. Adds the scalarized pieces to the live set. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001932/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001933/// the lowering code currently does not handle that. Extending it would be
1934/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001935/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001936static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001937 StatepointLiveSetTy &LiveSet,
1938 DenseMap<Value *, Value *>& PointerToBase,
1939 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001940 SmallVector<Value *, 16> ToSplit;
1941 for (Value *V : LiveSet)
1942 if (isa<VectorType>(V->getType()))
1943 ToSplit.push_back(V);
1944
1945 if (ToSplit.empty())
1946 return;
1947
Philip Reames8fe7f132015-06-26 22:47:37 +00001948 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1949
Philip Reames8531d8c2015-04-10 21:48:25 +00001950 Function &F = *(StatepointInst->getParent()->getParent());
1951
Philip Reames704e78b2015-04-10 22:34:56 +00001952 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001953 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001954 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001955 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001956 AllocaInst *Alloca =
1957 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001958 AllocaMap[V] = Alloca;
1959
1960 VectorType *VT = cast<VectorType>(V->getType());
1961 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001962 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001963 for (unsigned i = 0; i < VT->getNumElements(); i++)
1964 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001965 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001966
1967 auto InsertVectorReform = [&](Instruction *IP) {
1968 Builder.SetInsertPoint(IP);
1969 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1970 Value *ResultVec = UndefValue::get(VT);
1971 for (unsigned i = 0; i < VT->getNumElements(); i++)
1972 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1973 Builder.getInt32(i));
1974 return ResultVec;
1975 };
1976
1977 if (isa<CallInst>(StatepointInst)) {
1978 BasicBlock::iterator Next(StatepointInst);
1979 Next++;
1980 Instruction *IP = &*(Next);
1981 Replacements[V].first = InsertVectorReform(IP);
1982 Replacements[V].second = nullptr;
1983 } else {
1984 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1985 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001986 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001987 BasicBlock *NormalDest = Invoke->getNormalDest();
1988 assert(!isa<PHINode>(NormalDest->begin()));
1989 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1990 assert(!isa<PHINode>(UnwindDest->begin()));
1991 // Insert insert element sequences in both successors
1992 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1993 Replacements[V].first = InsertVectorReform(IP);
1994 IP = &*(UnwindDest->getFirstInsertionPt());
1995 Replacements[V].second = InsertVectorReform(IP);
1996 }
1997 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001998
Philip Reames8531d8c2015-04-10 21:48:25 +00001999 for (Value *V : ToSplit) {
2000 AllocaInst *Alloca = AllocaMap[V];
2001
2002 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00002003 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00002004 for (User *U : V->users())
2005 Users.push_back(cast<Instruction>(U));
2006
2007 for (Instruction *I : Users) {
2008 if (auto Phi = dyn_cast<PHINode>(I)) {
2009 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
2010 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00002011 LoadInst *Load = new LoadInst(
2012 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00002013 Phi->setIncomingValue(i, Load);
2014 }
2015 } else {
2016 LoadInst *Load = new LoadInst(Alloca, "", I);
2017 I->replaceUsesOfWith(V, Load);
2018 }
2019 }
2020
2021 // Store the original value and the replacement value into the alloca
2022 StoreInst *Store = new StoreInst(V, Alloca);
2023 if (auto I = dyn_cast<Instruction>(V))
2024 Store->insertAfter(I);
2025 else
2026 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00002027
Philip Reames8531d8c2015-04-10 21:48:25 +00002028 // Normal return for invoke, or call return
2029 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
2030 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2031 // Unwind return for invoke only
2032 Replacement = cast_or_null<Instruction>(Replacements[V].second);
2033 if (Replacement)
2034 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2035 }
2036
2037 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00002038 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00002039 for (Value *V : ToSplit)
2040 Allocas.push_back(AllocaMap[V]);
2041 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00002042
2043 // Update our tracking of live pointers and base mappings to account for the
2044 // changes we just made.
2045 for (Value *V : ToSplit) {
2046 auto &Elements = ElementMapping[V];
2047
2048 LiveSet.erase(V);
2049 LiveSet.insert(Elements.begin(), Elements.end());
2050 // We need to update the base mapping as well.
2051 assert(PointerToBase.count(V));
2052 Value *OldBase = PointerToBase[V];
2053 auto &BaseElements = ElementMapping[OldBase];
2054 PointerToBase.erase(V);
2055 assert(Elements.size() == BaseElements.size());
2056 for (unsigned i = 0; i < Elements.size(); i++) {
2057 Value *Elem = Elements[i];
2058 PointerToBase[Elem] = BaseElements[i];
2059 }
2060 }
Philip Reames8531d8c2015-04-10 21:48:25 +00002061}
2062
Igor Laevskye0317182015-05-19 15:59:05 +00002063// Helper function for the "rematerializeLiveValues". It walks use chain
2064// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2065// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002066// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00002067// Fills "ChainToBase" array with all visited values. "BaseValue" is not
2068// recorded.
2069static bool findRematerializableChainToBasePointer(
2070 SmallVectorImpl<Instruction*> &ChainToBase,
2071 Value *CurrentValue, Value *BaseValue) {
2072
2073 // We have found a base value
2074 if (CurrentValue == BaseValue) {
2075 return true;
2076 }
2077
2078 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2079 ChainToBase.push_back(GEP);
2080 return findRematerializableChainToBasePointer(ChainToBase,
2081 GEP->getPointerOperand(),
2082 BaseValue);
2083 }
2084
2085 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
Igor Laevskye0317182015-05-19 15:59:05 +00002086 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2087 return false;
2088
2089 ChainToBase.push_back(CI);
Manuel Jacob9db5b932015-12-28 20:14:05 +00002090 return findRematerializableChainToBasePointer(ChainToBase,
2091 CI->getOperand(0), BaseValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002092 }
2093
2094 // Not supported instruction in the chain
2095 return false;
2096}
2097
2098// Helper function for the "rematerializeLiveValues". Compute cost of the use
2099// chain we are going to rematerialize.
2100static unsigned
2101chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2102 TargetTransformInfo &TTI) {
2103 unsigned Cost = 0;
2104
2105 for (Instruction *Instr : Chain) {
2106 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2107 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2108 "non noop cast is found during rematerialization");
2109
2110 Type *SrcTy = CI->getOperand(0)->getType();
2111 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2112
2113 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2114 // Cost of the address calculation
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002115 Type *ValTy = GEP->getSourceElementType();
Igor Laevskye0317182015-05-19 15:59:05 +00002116 Cost += TTI.getAddressComputationCost(ValTy);
2117
2118 // And cost of the GEP itself
2119 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2120 // allowed for the external usage)
2121 if (!GEP->hasAllConstantIndices())
2122 Cost += 2;
2123
2124 } else {
2125 llvm_unreachable("unsupported instruciton type during rematerialization");
2126 }
2127 }
2128
2129 return Cost;
2130}
2131
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002132// From the statepoint live set pick values that are cheaper to recompute then
2133// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00002134// statepoint and record them in "Info" structure. Note that similar to
2135// relocated values we don't do any user adjustments here.
2136static void rematerializeLiveValues(CallSite CS,
2137 PartiallyConstructedSafepointRecord &Info,
2138 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002139 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002140
Igor Laevskye0317182015-05-19 15:59:05 +00002141 // Record values we are going to delete from this statepoint live set.
2142 // We can not di this in following loop due to iterator invalidation.
2143 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2144
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002145 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00002146 // For each live pointer find it's defining chain
2147 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002148 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002149 bool FoundChain =
2150 findRematerializableChainToBasePointer(ChainToBase,
2151 LiveValue,
2152 Info.PointerToBase[LiveValue]);
2153 // Nothing to do, or chain is too long
2154 if (!FoundChain ||
2155 ChainToBase.size() == 0 ||
2156 ChainToBase.size() > ChainLengthThreshold)
2157 continue;
2158
2159 // Compute cost of this chain
2160 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2161 // TODO: We can also account for cases when we will be able to remove some
2162 // of the rematerialized values by later optimization passes. I.e if
2163 // we rematerialized several intersecting chains. Or if original values
2164 // don't have any uses besides this statepoint.
2165
2166 // For invokes we need to rematerialize each chain twice - for normal and
2167 // for unwind basic blocks. Model this by multiplying cost by two.
2168 if (CS.isInvoke()) {
2169 Cost *= 2;
2170 }
2171 // If it's too expensive - skip it
2172 if (Cost >= RematerializationThreshold)
2173 continue;
2174
2175 // Remove value from the live set
2176 LiveValuesToBeDeleted.push_back(LiveValue);
2177
2178 // Clone instructions and record them inside "Info" structure
2179
2180 // Walk backwards to visit top-most instructions first
2181 std::reverse(ChainToBase.begin(), ChainToBase.end());
2182
2183 // Utility function which clones all instructions from "ChainToBase"
2184 // and inserts them before "InsertBefore". Returns rematerialized value
2185 // which should be used after statepoint.
2186 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2187 Instruction *LastClonedValue = nullptr;
2188 Instruction *LastValue = nullptr;
2189 for (Instruction *Instr: ChainToBase) {
2190 // Only GEP's and casts are suported as we need to be careful to not
2191 // introduce any new uses of pointers not in the liveset.
2192 // Note that it's fine to introduce new uses of pointers which were
2193 // otherwise not used after this statepoint.
2194 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2195
2196 Instruction *ClonedValue = Instr->clone();
2197 ClonedValue->insertBefore(InsertBefore);
2198 ClonedValue->setName(Instr->getName() + ".remat");
2199
2200 // If it is not first instruction in the chain then it uses previously
2201 // cloned value. We should update it to use cloned value.
2202 if (LastClonedValue) {
2203 assert(LastValue);
2204 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2205#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002206 // Assert that cloned instruction does not use any instructions from
2207 // this chain other than LastClonedValue
2208 for (auto OpValue : ClonedValue->operand_values()) {
2209 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2210 ChainToBase.end() &&
2211 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002212 }
2213#endif
2214 }
2215
2216 LastClonedValue = ClonedValue;
2217 LastValue = Instr;
2218 }
2219 assert(LastClonedValue);
2220 return LastClonedValue;
2221 };
2222
2223 // Different cases for calls and invokes. For invokes we need to clone
2224 // instructions both on normal and unwind path.
2225 if (CS.isCall()) {
2226 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2227 assert(InsertBefore);
2228 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2229 Info.RematerializedValues[RematerializedValue] = LiveValue;
2230 } else {
2231 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2232
2233 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002234 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002235 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002236 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002237
2238 Instruction *NormalRematerializedValue =
2239 rematerializeChain(NormalInsertBefore);
2240 Instruction *UnwindRematerializedValue =
2241 rematerializeChain(UnwindInsertBefore);
2242
2243 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2244 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2245 }
2246 }
2247
2248 // Remove rematerializaed values from the live set
2249 for (auto LiveValue: LiveValuesToBeDeleted) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002250 Info.LiveSet.erase(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002251 }
2252}
2253
Justin Bogner843fb202015-12-15 19:40:57 +00002254static bool insertParsePoints(Function &F, DominatorTree &DT,
2255 TargetTransformInfo &TTI,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002256 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002257#ifndef NDEBUG
2258 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002259 std::set<CallSite> Uniqued;
2260 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2261 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002262
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002263 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002264 assert(CS.getInstruction()->getParent()->getParent() == &F);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002265 assert((UseDeoptBundles || isStatepoint(CS)) &&
2266 "expected to already be a deopt statepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002267 }
2268#endif
2269
Philip Reames69e51ca2015-04-13 18:07:21 +00002270 // When inserting gc.relocates for invokes, we need to be able to insert at
2271 // the top of the successor blocks. See the comment on
2272 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002273 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002274 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002275 if (!CS.isInvoke())
2276 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002277 auto *II = cast<InvokeInst>(CS.getInstruction());
2278 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2279 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002280 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002281
Philip Reamesd16a9b12015-02-20 01:06:44 +00002282 // A list of dummy calls added to the IR to keep various values obviously
2283 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002284 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002285
2286 // Insert a dummy call with all of the arguments to the vm_state we'll need
2287 // for the actual safepoint insertion. This ensures reference arguments in
2288 // the deopt argument list are considered live through the safepoint (and
2289 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002290 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002291 SmallVector<Value *, 64> DeoptValues;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002292
2293 iterator_range<const Use *> DeoptStateRange =
2294 UseDeoptBundles
2295 ? iterator_range<const Use *>(GetDeoptBundleOperands(CS))
2296 : iterator_range<const Use *>(Statepoint(CS).vm_state_args());
2297
2298 for (Value *Arg : DeoptStateRange) {
Philip Reames8531d8c2015-04-10 21:48:25 +00002299 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2300 "support for FCA unimplemented");
2301 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002302 DeoptValues.push_back(Arg);
2303 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002304
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002305 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002306 }
2307
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002308 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002309
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002310 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002311 // site.
Justin Bogner843fb202015-12-15 19:40:57 +00002312 findLiveReferences(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002313
2314 // B) Find the base pointers for each live pointer
2315 /* scope for caching */ {
2316 // Cache the 'defining value' relation used in the computation and
2317 // insertion of base phis and selects. This ensures that we don't insert
2318 // large numbers of duplicate base_phis.
2319 DefiningValueMapTy DVCache;
2320
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002321 for (size_t i = 0; i < Records.size(); i++) {
2322 PartiallyConstructedSafepointRecord &info = Records[i];
2323 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002324 }
2325 } // end of cache scope
2326
2327 // The base phi insertion logic (for any safepoint) may have inserted new
2328 // instructions which are now live at some safepoint. The simplest such
2329 // example is:
2330 // loop:
2331 // phi a <-- will be a new base_phi here
2332 // safepoint 1 <-- that needs to be live here
2333 // gep a + 1
2334 // safepoint 2
2335 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002336 // We insert some dummy calls after each safepoint to definitely hold live
2337 // the base pointers which were identified for that safepoint. We'll then
2338 // ask liveness for _every_ base inserted to see what is now live. Then we
2339 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002340 Holders.reserve(Holders.size() + Records.size());
2341 for (size_t i = 0; i < Records.size(); i++) {
2342 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002343
2344 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002345 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002346 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002347
2348 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002349 }
2350
Philip Reamesdf1ef082015-04-10 22:53:14 +00002351 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2352 // need to rerun liveness. We may *also* have inserted new defs, but that's
2353 // not the key issue.
Justin Bogner843fb202015-12-15 19:40:57 +00002354 recomputeLiveInValues(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002355
Philip Reamesd16a9b12015-02-20 01:06:44 +00002356 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002357 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002358 errs() << "Base Pairs: (w/Relocation)\n";
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00002359 for (auto Pair : Info.PointerToBase) {
2360 errs() << " derived ";
2361 Pair.first->printAsOperand(errs(), false);
2362 errs() << " base ";
2363 Pair.second->printAsOperand(errs(), false);
2364 errs() << "\n";
2365 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002366 }
2367 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002368
Manuel Jacob990dfa62015-12-22 16:50:44 +00002369 // It is possible that non-constant live variables have a constant base. For
2370 // example, a GEP with a variable offset from a global. In this case we can
2371 // remove it from the liveset. We already don't add constants to the liveset
2372 // because we assume they won't move at runtime and the GC doesn't need to be
2373 // informed about them. The same reasoning applies if the base is constant.
2374 // Note that the relocation placement code relies on this filtering for
2375 // correctness as it expects the base to be in the liveset, which isn't true
2376 // if the base is constant.
2377 for (auto &Info : Records)
2378 for (auto &BasePair : Info.PointerToBase)
2379 if (isa<Constant>(BasePair.second))
2380 Info.LiveSet.erase(BasePair.first);
2381
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002382 for (CallInst *CI : Holders)
2383 CI->eraseFromParent();
2384
2385 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002386
Philip Reames8fe7f132015-06-26 22:47:37 +00002387 // Do a limited scalarization of any live at safepoint vector values which
2388 // contain pointers. This enables this pass to run after vectorization at
Philip Reames103d2382016-01-07 02:20:11 +00002389 // the cost of some possible performance loss. Note: This is known to not
2390 // handle updating of the side tables correctly which can lead to relocation
2391 // bugs when the same vector is live at multiple statepoints. We're in the
2392 // process of implementing the alternate lowering - relocating the
2393 // vector-of-pointers as first class item and updating the backend to
2394 // understand that - but that's not yet complete.
2395 if (UseVectorSplit)
2396 for (size_t i = 0; i < Records.size(); i++) {
2397 PartiallyConstructedSafepointRecord &Info = Records[i];
2398 Instruction *Statepoint = ToUpdate[i].getInstruction();
2399 splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
2400 Info.PointerToBase, DT);
2401 }
Philip Reames8fe7f132015-06-26 22:47:37 +00002402
Igor Laevskye0317182015-05-19 15:59:05 +00002403 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002404 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002405 // does not influence correctness.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002406 for (size_t i = 0; i < Records.size(); i++)
2407 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002408
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002409 // We need this to safely RAUW and delete call or invoke return values that
2410 // may themselves be live over a statepoint. For details, please see usage in
2411 // makeStatepointExplicitImpl.
2412 std::vector<DeferredReplacement> Replacements;
2413
Philip Reamesd16a9b12015-02-20 01:06:44 +00002414 // Now run through and replace the existing statepoints with new ones with
2415 // the live variables listed. We do not yet update uses of the values being
2416 // relocated. We have references to live variables that need to
2417 // survive to the last iteration of this loop. (By construction, the
2418 // previous statepoint can not be a live variable, thus we can and remove
2419 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002420 for (size_t i = 0; i < Records.size(); i++)
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002421 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002422
2423 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002424
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002425 for (auto &PR : Replacements)
2426 PR.doReplacement();
2427
2428 Replacements.clear();
2429
2430 for (auto &Info : Records) {
2431 // These live sets may contain state Value pointers, since we replaced calls
2432 // with operand bundles with calls wrapped in gc.statepoint, and some of
2433 // those calls may have been def'ing live gc pointers. Clear these out to
2434 // avoid accidentally using them.
2435 //
2436 // TODO: We should create a separate data structure that does not contain
2437 // these live sets, and migrate to using that data structure from this point
2438 // onward.
2439 Info.LiveSet.clear();
2440 Info.PointerToBase.clear();
2441 }
2442
Philip Reamesd16a9b12015-02-20 01:06:44 +00002443 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002444 SmallVector<Value *, 128> Live;
2445 for (size_t i = 0; i < Records.size(); i++) {
2446 PartiallyConstructedSafepointRecord &Info = Records[i];
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002447
Philip Reamesd16a9b12015-02-20 01:06:44 +00002448 // We can't simply save the live set from the original insertion. One of
2449 // the live values might be the result of a call which needs a safepoint.
2450 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002451 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002452 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002453 Statepoint Statepoint(Info.StatepointToken);
2454 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2455 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002456#ifndef NDEBUG
2457 // Do some basic sanity checks on our liveness results before performing
2458 // relocation. Relocation can and will turn mistakes in liveness results
2459 // into non-sensical code which is must harder to debug.
2460 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002461 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002462 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002463 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002464 if (!isa<Instruction>(V))
2465 // Non-instruction values trivial dominate all possible uses
2466 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002467 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002468 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2469 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002470 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002471 "basic SSA liveness expectation violated by liveness analysis");
2472 }
2473#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002474 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002475 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002476
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002477#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002478 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002479 for (auto *Ptr : Live)
Philip Reames5715f572016-01-09 01:31:13 +00002480 assert(isHandledGCPointerType(Ptr->getType()) &&
2481 "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002482#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002483
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002484 relocationViaAlloca(F, DT, Live, Records);
2485 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002486}
2487
Sanjoy Das353a19e2015-06-02 22:33:37 +00002488// Handles both return values and arguments for Functions and CallSites.
2489template <typename AttrHolder>
Igor Laevskydde00292015-10-23 22:42:44 +00002490static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2491 unsigned Index) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002492 AttrBuilder R;
2493 if (AH.getDereferenceableBytes(Index))
2494 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2495 AH.getDereferenceableBytes(Index)));
2496 if (AH.getDereferenceableOrNullBytes(Index))
2497 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2498 AH.getDereferenceableOrNullBytes(Index)));
Igor Laevsky1ef06552015-10-26 19:06:01 +00002499 if (AH.doesNotAlias(Index))
2500 R.addAttribute(Attribute::NoAlias);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002501
2502 if (!R.empty())
2503 AH.setAttributes(AH.getAttributes().removeAttributes(
2504 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002505}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002506
2507void
Igor Laevskydde00292015-10-23 22:42:44 +00002508RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002509 LLVMContext &Ctx = F.getContext();
2510
2511 for (Argument &A : F.args())
2512 if (isa<PointerType>(A.getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002513 RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002514
2515 if (isa<PointerType>(F.getReturnType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002516 RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002517}
2518
Igor Laevskydde00292015-10-23 22:42:44 +00002519void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002520 if (F.empty())
2521 return;
2522
2523 LLVMContext &Ctx = F.getContext();
2524 MDBuilder Builder(Ctx);
2525
Nico Rieck78199512015-08-06 19:10:45 +00002526 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002527 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2528 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2529 bool IsImmutableTBAA =
2530 MD->getNumOperands() == 4 &&
2531 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2532
2533 if (!IsImmutableTBAA)
2534 continue; // no work to do, MD_tbaa is already marked mutable
2535
2536 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2537 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2538 uint64_t Offset =
2539 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2540
2541 MDNode *MutableTBAA =
2542 Builder.createTBAAStructTagNode(Base, Access, Offset);
2543 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2544 }
2545
2546 if (CallSite CS = CallSite(&I)) {
2547 for (int i = 0, e = CS.arg_size(); i != e; i++)
2548 if (isa<PointerType>(CS.getArgument(i)->getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002549 RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002550 if (isa<PointerType>(CS.getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002551 RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002552 }
2553 }
2554}
2555
Philip Reamesd16a9b12015-02-20 01:06:44 +00002556/// Returns true if this function should be rewritten by this pass. The main
2557/// point of this function is as an extension point for custom logic.
2558static bool shouldRewriteStatepointsIn(Function &F) {
2559 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002560 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +00002561 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002562 const StringRef StatepointExampleName("statepoint-example");
2563 const StringRef CoreCLRName("coreclr");
2564 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002565 (CoreCLRName == FunctionGCName);
2566 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002567 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002568}
2569
Igor Laevskydde00292015-10-23 22:42:44 +00002570void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002571#ifndef NDEBUG
2572 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2573 "precondition!");
2574#endif
2575
2576 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002577 stripNonValidAttributesFromPrototype(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002578
2579 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002580 stripNonValidAttributesFromBody(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002581}
2582
Philip Reamesd16a9b12015-02-20 01:06:44 +00002583bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2584 // Nothing to do for declarations.
2585 if (F.isDeclaration() || F.empty())
2586 return false;
2587
2588 // Policy choice says not to rewrite - the most common reason is that we're
2589 // compiling code without a GCStrategy.
2590 if (!shouldRewriteStatepointsIn(F))
2591 return false;
2592
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002593 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00002594 TargetTransformInfo &TTI =
2595 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Philip Reames704e78b2015-04-10 22:34:56 +00002596
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002597 auto NeedsRewrite = [](Instruction &I) {
2598 if (UseDeoptBundles) {
2599 if (ImmutableCallSite CS = ImmutableCallSite(&I))
2600 return !callsGCLeafFunction(CS);
2601 return false;
2602 }
2603
2604 return isStatepoint(I);
2605 };
2606
Philip Reames85b36a82015-04-10 22:07:04 +00002607 // Gather all the statepoints which need rewritten. Be careful to only
2608 // consider those in reachable code since we need to ask dominance queries
2609 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002610 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002611 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002612 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002613 // TODO: only the ones with the flag set!
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002614 if (NeedsRewrite(I)) {
Philip Reames85b36a82015-04-10 22:07:04 +00002615 if (DT.isReachableFromEntry(I.getParent()))
2616 ParsePointNeeded.push_back(CallSite(&I));
2617 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002618 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002619 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002620 }
2621
Philip Reames85b36a82015-04-10 22:07:04 +00002622 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002623
Philip Reames85b36a82015-04-10 22:07:04 +00002624 // Delete any unreachable statepoints so that we don't have unrewritten
2625 // statepoints surviving this pass. This makes testing easier and the
2626 // resulting IR less confusing to human readers. Rather than be fancy, we
2627 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002628 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002629 MadeChange |= removeUnreachableBlocks(F);
2630
Philip Reamesd16a9b12015-02-20 01:06:44 +00002631 // Return early if no work to do.
2632 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002633 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002634
Philip Reames85b36a82015-04-10 22:07:04 +00002635 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2636 // These are created by LCSSA. They have the effect of increasing the size
2637 // of liveness sets for no good reason. It may be harder to do this post
2638 // insertion since relocations and base phis can confuse things.
2639 for (BasicBlock &BB : F)
2640 if (BB.getUniquePredecessor()) {
2641 MadeChange = true;
2642 FoldSingleEntryPHINodes(&BB);
2643 }
2644
Philip Reames971dc3a2015-08-12 22:11:45 +00002645 // Before we start introducing relocations, we want to tweak the IR a bit to
2646 // avoid unfortunate code generation effects. The main example is that we
2647 // want to try to make sure the comparison feeding a branch is after any
2648 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2649 // values feeding a branch after relocation. This is semantically correct,
2650 // but results in extra register pressure since both the pre-relocation and
2651 // post-relocation copies must be available in registers. For code without
2652 // relocations this is handled elsewhere, but teaching the scheduler to
2653 // reverse the transform we're about to do would be slightly complex.
2654 // Note: This may extend the live range of the inputs to the icmp and thus
2655 // increase the liveset of any statepoint we move over. This is profitable
2656 // as long as all statepoints are in rare blocks. If we had in-register
2657 // lowering for live values this would be a much safer transform.
2658 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2659 if (auto *BI = dyn_cast<BranchInst>(TI))
2660 if (BI->isConditional())
2661 return dyn_cast<Instruction>(BI->getCondition());
2662 // TODO: Extend this to handle switches
2663 return nullptr;
2664 };
2665 for (BasicBlock &BB : F) {
2666 TerminatorInst *TI = BB.getTerminator();
2667 if (auto *Cond = getConditionInst(TI))
2668 // TODO: Handle more than just ICmps here. We should be able to move
2669 // most instructions without side effects or memory access.
2670 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2671 MadeChange = true;
2672 Cond->moveBefore(TI);
2673 }
2674 }
2675
Justin Bogner843fb202015-12-15 19:40:57 +00002676 MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
Philip Reames85b36a82015-04-10 22:07:04 +00002677 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002678}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002679
2680// liveness computation via standard dataflow
2681// -------------------------------------------------------------------
2682
2683// TODO: Consider using bitvectors for liveness, the set of potentially
2684// interesting values should be small and easy to pre-compute.
2685
Philip Reamesdf1ef082015-04-10 22:53:14 +00002686/// Compute the live-in set for the location rbegin starting from
2687/// the live-out set of the basic block
2688static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2689 BasicBlock::reverse_iterator rend,
2690 DenseSet<Value *> &LiveTmp) {
2691
2692 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2693 Instruction *I = &*ritr;
2694
2695 // KILL/Def - Remove this definition from LiveIn
2696 LiveTmp.erase(I);
2697
2698 // Don't consider *uses* in PHI nodes, we handle their contribution to
2699 // predecessor blocks when we seed the LiveOut sets
2700 if (isa<PHINode>(I))
2701 continue;
2702
2703 // USE - Add to the LiveIn set for this instruction
2704 for (Value *V : I->operands()) {
2705 assert(!isUnhandledGCPointerType(V->getType()) &&
2706 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002707 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2708 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002709 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002710 // - We assume that things which are constant (from LLVM's definition)
2711 // do not move at runtime. For example, the address of a global
2712 // variable is fixed, even though it's contents may not be.
2713 // - Second, we can't disallow arbitrary inttoptr constants even
2714 // if the language frontend does. Optimization passes are free to
2715 // locally exploit facts without respect to global reachability. This
2716 // can create sections of code which are dynamically unreachable and
2717 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002718 LiveTmp.insert(V);
2719 }
2720 }
2721 }
2722}
2723
2724static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2725
2726 for (BasicBlock *Succ : successors(BB)) {
2727 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2728 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2729 PHINode *Phi = cast<PHINode>(&*I);
2730 Value *V = Phi->getIncomingValueForBlock(BB);
2731 assert(!isUnhandledGCPointerType(V->getType()) &&
2732 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002733 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002734 LiveTmp.insert(V);
2735 }
2736 }
2737 }
2738}
2739
2740static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2741 DenseSet<Value *> KillSet;
2742 for (Instruction &I : *BB)
2743 if (isHandledGCPointerType(I.getType()))
2744 KillSet.insert(&I);
2745 return KillSet;
2746}
2747
Philip Reames9638ff92015-04-11 00:06:47 +00002748#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002749/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2750/// sanity check for the liveness computation.
2751static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2752 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002753 for (Value *V : Live) {
2754 if (auto *I = dyn_cast<Instruction>(V)) {
2755 // The terminator can be a member of the LiveOut set. LLVM's definition
2756 // of instruction dominance states that V does not dominate itself. As
2757 // such, we need to special case this to allow it.
2758 if (TermOkay && TI == I)
2759 continue;
2760 assert(DT.dominates(I, TI) &&
2761 "basic SSA liveness expectation violated by liveness analysis");
2762 }
2763 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002764}
2765
2766/// Check that all the liveness sets used during the computation of liveness
2767/// obey basic SSA properties. This is useful for finding cases where we miss
2768/// a def.
2769static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2770 BasicBlock &BB) {
2771 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2772 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2773 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2774}
Philip Reames9638ff92015-04-11 00:06:47 +00002775#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002776
2777static void computeLiveInValues(DominatorTree &DT, Function &F,
2778 GCPtrLivenessData &Data) {
2779
Philip Reames4d80ede2015-04-10 23:11:26 +00002780 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002781 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002782 // We use a SetVector so that we don't have duplicates in the worklist.
2783 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002784 };
2785 auto NextItem = [&]() {
2786 BasicBlock *BB = Worklist.back();
2787 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002788 return BB;
2789 };
2790
2791 // Seed the liveness for each individual block
2792 for (BasicBlock &BB : F) {
2793 Data.KillSet[&BB] = computeKillSet(&BB);
2794 Data.LiveSet[&BB].clear();
2795 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2796
2797#ifndef NDEBUG
2798 for (Value *Kill : Data.KillSet[&BB])
2799 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2800#endif
2801
2802 Data.LiveOut[&BB] = DenseSet<Value *>();
2803 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2804 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2805 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2806 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2807 if (!Data.LiveIn[&BB].empty())
2808 AddPredsToWorklist(&BB);
2809 }
2810
2811 // Propagate that liveness until stable
2812 while (!Worklist.empty()) {
2813 BasicBlock *BB = NextItem();
2814
2815 // Compute our new liveout set, then exit early if it hasn't changed
2816 // despite the contribution of our successor.
2817 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2818 const auto OldLiveOutSize = LiveOut.size();
2819 for (BasicBlock *Succ : successors(BB)) {
2820 assert(Data.LiveIn.count(Succ));
2821 set_union(LiveOut, Data.LiveIn[Succ]);
2822 }
2823 // assert OutLiveOut is a subset of LiveOut
2824 if (OldLiveOutSize == LiveOut.size()) {
2825 // If the sets are the same size, then we didn't actually add anything
2826 // when unioning our successors LiveIn Thus, the LiveIn of this block
2827 // hasn't changed.
2828 continue;
2829 }
2830 Data.LiveOut[BB] = LiveOut;
2831
2832 // Apply the effects of this basic block
2833 DenseSet<Value *> LiveTmp = LiveOut;
2834 set_union(LiveTmp, Data.LiveSet[BB]);
2835 set_subtract(LiveTmp, Data.KillSet[BB]);
2836
2837 assert(Data.LiveIn.count(BB));
2838 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2839 // assert: OldLiveIn is a subset of LiveTmp
2840 if (OldLiveIn.size() != LiveTmp.size()) {
2841 Data.LiveIn[BB] = LiveTmp;
2842 AddPredsToWorklist(BB);
2843 }
2844 } // while( !worklist.empty() )
2845
2846#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002847 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002848 // missing kills during the above iteration.
2849 for (BasicBlock &BB : F) {
2850 checkBasicSSA(DT, Data, BB);
2851 }
2852#endif
2853}
2854
2855static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2856 StatepointLiveSetTy &Out) {
2857
2858 BasicBlock *BB = Inst->getParent();
2859
2860 // Note: The copy is intentional and required
2861 assert(Data.LiveOut.count(BB));
2862 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2863
2864 // We want to handle the statepoint itself oddly. It's
2865 // call result is not live (normal), nor are it's arguments
2866 // (unless they're used again later). This adjustment is
2867 // specifically what we need to relocate
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002868 BasicBlock::reverse_iterator rend(Inst->getIterator());
Philip Reamesdf1ef082015-04-10 22:53:14 +00002869 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2870 LiveOut.erase(Inst);
2871 Out.insert(LiveOut.begin(), LiveOut.end());
2872}
2873
2874static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2875 const CallSite &CS,
2876 PartiallyConstructedSafepointRecord &Info) {
2877 Instruction *Inst = CS.getInstruction();
2878 StatepointLiveSetTy Updated;
2879 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2880
2881#ifndef NDEBUG
2882 DenseSet<Value *> Bases;
2883 for (auto KVPair : Info.PointerToBase) {
2884 Bases.insert(KVPair.second);
2885 }
2886#endif
2887 // We may have base pointers which are now live that weren't before. We need
2888 // to update the PointerToBase structure to reflect this.
2889 for (auto V : Updated)
2890 if (!Info.PointerToBase.count(V)) {
2891 assert(Bases.count(V) && "can't find base for unexpected live value");
2892 Info.PointerToBase[V] = V;
2893 continue;
2894 }
2895
2896#ifndef NDEBUG
2897 for (auto V : Updated) {
2898 assert(Info.PointerToBase.count(V) &&
2899 "must be able to find base for live value");
2900 }
2901#endif
2902
2903 // Remove any stale base mappings - this can happen since our liveness is
2904 // more precise then the one inherent in the base pointer analysis
2905 DenseSet<Value *> ToErase;
2906 for (auto KVPair : Info.PointerToBase)
2907 if (!Updated.count(KVPair.first))
2908 ToErase.insert(KVPair.first);
2909 for (auto V : ToErase)
2910 Info.PointerToBase.erase(V);
2911
2912#ifndef NDEBUG
2913 for (auto KVPair : Info.PointerToBase)
2914 assert(Updated.count(KVPair.first) && "record for non-live value");
2915#endif
2916
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002917 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002918}