blob: cc89149f2def190499f2704bc9ef136c4ac61ce0 [file] [log] [blame]
Philip Reamesd16a9b12015-02-20 01:06:44 +00001//===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Rewrite an existing set of gc.statepoints such that they make potential
11// relocations performed by the garbage collector explicit in the IR.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Pass.h"
16#include "llvm/Analysis/CFG.h"
Philip Reamesabcdc5e2015-08-27 01:02:28 +000017#include "llvm/Analysis/InstructionSimplify.h"
Igor Laevskye0317182015-05-19 15:59:05 +000018#include "llvm/Analysis/TargetTransformInfo.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000019#include "llvm/ADT/SetOperations.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/DenseSet.h"
Philip Reames4d80ede2015-04-10 23:11:26 +000022#include "llvm/ADT/SetVector.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000023#include "llvm/ADT/StringRef.h"
Philip Reames15d55632015-09-09 23:26:08 +000024#include "llvm/ADT/MapVector.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000025#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallSite.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InstIterator.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Module.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000035#include "llvm/IR/MDBuilder.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000036#include "llvm/IR/Statepoint.h"
37#include "llvm/IR/Value.h"
38#include "llvm/IR/Verifier.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43#include "llvm/Transforms/Utils/Cloning.h"
44#include "llvm/Transforms/Utils/Local.h"
45#include "llvm/Transforms/Utils/PromoteMemToReg.h"
46
47#define DEBUG_TYPE "rewrite-statepoints-for-gc"
48
49using namespace llvm;
50
Philip Reamesd16a9b12015-02-20 01:06:44 +000051// Print the liveset found at the insert location
52static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
53 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000054static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
55 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000056// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000057static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
58 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000059
Igor Laevskye0317182015-05-19 15:59:05 +000060// Cost threshold measuring when it is profitable to rematerialize value instead
61// of relocating it
62static cl::opt<unsigned>
63RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
64 cl::init(6));
65
Philip Reamese73300b2015-04-13 16:41:32 +000066#ifdef XDEBUG
67static bool ClobberNonLive = true;
68#else
69static bool ClobberNonLive = false;
70#endif
71static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
72 cl::location(ClobberNonLive),
73 cl::Hidden);
74
Sanjoy Das25ec1a32015-10-16 02:41:00 +000075static cl::opt<bool>
76 AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
77 cl::Hidden, cl::init(true));
78
Philip Reames103d2382016-01-07 02:20:11 +000079/// Should we split vectors of pointers into their individual elements? This
80/// is known to be buggy, but the alternate implementation isn't yet ready.
81/// This is purely to provide a debugging and dianostic hook until the vector
82/// split is replaced with vector relocations.
83static cl::opt<bool> UseVectorSplit("rs4gc-split-vector-values", cl::Hidden,
Philip Reamesb336bca2016-01-19 04:18:24 +000084 cl::init(false));
Philip Reames103d2382016-01-07 02:20:11 +000085
Benjamin Kramer6f665452015-02-20 14:00:58 +000086namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000087struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000088 static char ID; // Pass identification, replacement for typeid
89
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000090 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000091 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
92 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000093 bool runOnFunction(Function &F);
94 bool runOnModule(Module &M) override {
95 bool Changed = false;
96 for (Function &F : M)
97 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000098
99 if (Changed) {
Igor Laevskydde00292015-10-23 22:42:44 +0000100 // stripNonValidAttributes asserts that shouldRewriteStatepointsIn
Sanjoy Das353a19e2015-06-02 22:33:37 +0000101 // returns true for at least one function in the module. Since at least
102 // one function changed, we know that the precondition is satisfied.
Igor Laevskydde00292015-10-23 22:42:44 +0000103 stripNonValidAttributes(M);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000104 }
105
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000106 return Changed;
107 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000108
109 void getAnalysisUsage(AnalysisUsage &AU) const override {
110 // We add and rewrite a bunch of instructions, but don't really do much
111 // else. We could in theory preserve a lot more analyses here.
112 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000113 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000114 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000115
116 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
117 /// dereferenceability that are no longer valid/correct after
118 /// RewriteStatepointsForGC has run. This is because semantically, after
119 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
Igor Laevskydde00292015-10-23 22:42:44 +0000120 /// heap. stripNonValidAttributes (conservatively) restores correctness
Sanjoy Das353a19e2015-06-02 22:33:37 +0000121 /// by erasing all attributes in the module that externally imply
122 /// dereferenceability.
Igor Laevsky1ef06552015-10-26 19:06:01 +0000123 /// Similar reasoning also applies to the noalias attributes. gc.statepoint
124 /// can touch the entire heap including noalias objects.
Igor Laevskydde00292015-10-23 22:42:44 +0000125 void stripNonValidAttributes(Module &M);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000126
Igor Laevskydde00292015-10-23 22:42:44 +0000127 // Helpers for stripNonValidAttributes
128 void stripNonValidAttributesFromBody(Function &F);
129 void stripNonValidAttributesFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000130};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000131} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000132
133char RewriteStatepointsForGC::ID = 0;
134
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000135ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000136 return new RewriteStatepointsForGC();
137}
138
139INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
140 "Make relocations explicit at statepoints", false, false)
141INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
142INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
143 "Make relocations explicit at statepoints", false, false)
144
145namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000146struct GCPtrLivenessData {
147 /// Values defined in this block.
148 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
149 /// Values used in this block (and thus live); does not included values
150 /// killed within this block.
151 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
152
153 /// Values live into this basic block (i.e. used by any
154 /// instruction in this basic block or ones reachable from here)
155 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
156
157 /// Values live out of this basic block (i.e. live into
158 /// any successor block)
159 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
160};
161
Philip Reamesd16a9b12015-02-20 01:06:44 +0000162// The type of the internal cache used inside the findBasePointers family
163// of functions. From the callers perspective, this is an opaque type and
164// should not be inspected.
165//
166// In the actual implementation this caches two relations:
167// - The base relation itself (i.e. this pointer is based on that one)
168// - The base defining value relation (i.e. before base_phi insertion)
169// Generally, after the execution of a full findBasePointer call, only the
170// base relation will remain. Internally, we add a mixture of the two
171// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000172typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000173typedef DenseSet<Value *> StatepointLiveSetTy;
Sanjoy Das40bdd042015-10-07 21:32:35 +0000174typedef DenseMap<AssertingVH<Instruction>, AssertingVH<Value>>
175 RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000176
Philip Reamesd16a9b12015-02-20 01:06:44 +0000177struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000178 /// The set of values known to be live across this safepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000179 StatepointLiveSetTy LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000180
181 /// Mapping from live pointers to a base-defining-value
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000182 DenseMap<Value *, Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000183
Philip Reames0a3240f2015-02-20 21:34:11 +0000184 /// The *new* gc.statepoint instruction itself. This produces the token
185 /// that normal path gc.relocates and the gc.result are tied to.
186 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000187
Philip Reamesf2041322015-02-20 19:26:04 +0000188 /// Instruction to which exceptional gc relocates are attached
189 /// Makes it easier to iterate through them during relocationViaAlloca.
190 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000191
192 /// Record live values we are rematerialized instead of relocating.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000193 /// They are not included into 'LiveSet' field.
Igor Laevskye0317182015-05-19 15:59:05 +0000194 /// Maps rematerialized copy to it's original value.
195 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000196};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000197}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000198
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000199static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
Sanjoy Dasacc43d12016-01-22 19:20:40 +0000200 Optional<OperandBundleUse> DeoptBundle =
201 CS.getOperandBundle(LLVMContext::OB_deopt);
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000202
203 if (!DeoptBundle.hasValue()) {
204 assert(AllowStatepointWithNoDeoptInfo &&
205 "Found non-leaf call without deopt info!");
206 return None;
207 }
208
209 return DeoptBundle.getValue().Inputs;
210}
211
Philip Reamesdf1ef082015-04-10 22:53:14 +0000212/// Compute the live-in set for every basic block in the function
213static void computeLiveInValues(DominatorTree &DT, Function &F,
214 GCPtrLivenessData &Data);
215
216/// Given results from the dataflow liveness computation, find the set of live
217/// Values at a particular instruction.
218static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
219 StatepointLiveSetTy &out);
220
Philip Reamesd16a9b12015-02-20 01:06:44 +0000221// TODO: Once we can get to the GCStrategy, this becomes
Philip Reamesee8f0552015-12-23 01:42:15 +0000222// Optional<bool> isGCManagedPointer(const Type *Ty) const override {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000223
Craig Toppere3dcce92015-08-01 22:20:21 +0000224static bool isGCPointerType(Type *T) {
225 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000226 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
227 // GC managed heap. We know that a pointer into this heap needs to be
228 // updated and that no other pointer does.
229 return (1 == PT->getAddressSpace());
230 return false;
231}
232
Philip Reames8531d8c2015-04-10 21:48:25 +0000233// Return true if this type is one which a) is a gc pointer or contains a GC
234// pointer and b) is of a type this code expects to encounter as a live value.
235// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000236// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000237static bool isHandledGCPointerType(Type *T) {
238 // We fully support gc pointers
239 if (isGCPointerType(T))
240 return true;
241 // We partially support vectors of gc pointers. The code will assert if it
242 // can't handle something.
243 if (auto VT = dyn_cast<VectorType>(T))
244 if (isGCPointerType(VT->getElementType()))
245 return true;
246 return false;
247}
248
249#ifndef NDEBUG
250/// Returns true if this type contains a gc pointer whether we know how to
251/// handle that type or not.
252static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000253 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000254 return true;
255 if (VectorType *VT = dyn_cast<VectorType>(Ty))
256 return isGCPointerType(VT->getScalarType());
257 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
258 return containsGCPtrType(AT->getElementType());
259 if (StructType *ST = dyn_cast<StructType>(Ty))
Craig Topperd896b032015-11-29 05:38:08 +0000260 return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
261 containsGCPtrType);
Philip Reames8531d8c2015-04-10 21:48:25 +0000262 return false;
263}
264
265// Returns true if this is a type which a) is a gc pointer or contains a GC
266// pointer and b) is of a type which the code doesn't expect (i.e. first class
267// aggregates). Used to trip assertions.
268static bool isUnhandledGCPointerType(Type *Ty) {
269 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
270}
271#endif
272
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000273static bool order_by_name(Value *a, Value *b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000274 if (a->hasName() && b->hasName()) {
275 return -1 == a->getName().compare(b->getName());
276 } else if (a->hasName() && !b->hasName()) {
277 return true;
278 } else if (!a->hasName() && b->hasName()) {
279 return false;
280 } else {
281 // Better than nothing, but not stable
282 return a < b;
283 }
284}
285
Philip Reamesece70b82015-09-09 23:57:18 +0000286// Return the name of the value suffixed with the provided value, or if the
287// value didn't have a name, the default value specified.
288static std::string suffixed_name_or(Value *V, StringRef Suffix,
289 StringRef DefaultName) {
290 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
291}
292
Philip Reamesdf1ef082015-04-10 22:53:14 +0000293// Conservatively identifies any definitions which might be live at the
294// given instruction. The analysis is performed immediately before the
295// given instruction. Values defined by that instruction are not considered
296// live. Values used by that instruction are considered live.
297static void analyzeParsePointLiveness(
298 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
299 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000300 Instruction *inst = CS.getInstruction();
301
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000302 StatepointLiveSetTy LiveSet;
303 findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000304
305 if (PrintLiveSet) {
306 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000307 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000308 // by name
Philip Reamesdab35f32015-09-02 21:11:44 +0000309 SmallVector<Value *, 64> Temp;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000310 Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
Philip Reamesdab35f32015-09-02 21:11:44 +0000311 std::sort(Temp.begin(), Temp.end(), order_by_name);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000312 errs() << "Live Variables:\n";
Philip Reamesdab35f32015-09-02 21:11:44 +0000313 for (Value *V : Temp)
314 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000315 }
316 if (PrintLiveSetSize) {
317 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000318 errs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000319 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000320 result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000321}
322
Philip Reamesf5b8e472015-09-03 21:34:30 +0000323static bool isKnownBaseResult(Value *V);
324namespace {
325/// A single base defining value - An immediate base defining value for an
326/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
327/// For instructions which have multiple pointer [vector] inputs or that
328/// transition between vector and scalar types, there is no immediate base
329/// defining value. The 'base defining value' for 'Def' is the transitive
330/// closure of this relation stopping at the first instruction which has no
331/// immediate base defining value. The b.d.v. might itself be a base pointer,
332/// but it can also be an arbitrary derived pointer.
333struct BaseDefiningValueResult {
334 /// Contains the value which is the base defining value.
335 Value * const BDV;
336 /// True if the base defining value is also known to be an actual base
337 /// pointer.
338 const bool IsKnownBase;
339 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
340 : BDV(BDV), IsKnownBase(IsKnownBase) {
341#ifndef NDEBUG
342 // Check consistency between new and old means of checking whether a BDV is
343 // a base.
344 bool MustBeBase = isKnownBaseResult(BDV);
345 assert(!MustBeBase || MustBeBase == IsKnownBase);
346#endif
347 }
348};
349}
350
351static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000352
Philip Reames8fe7f132015-06-26 22:47:37 +0000353/// Return a base defining value for the 'Index' element of the given vector
354/// instruction 'I'. If Index is null, returns a BDV for the entire vector
355/// 'I'. As an optimization, this method will try to determine when the
356/// element is known to already be a base pointer. If this can be established,
357/// the second value in the returned pair will be true. Note that either a
358/// vector or a pointer typed value can be returned. For the former, the
359/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
360/// If the later, the return pointer is a BDV (or possibly a base) for the
361/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000362static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000363findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000364 // Each case parallels findBaseDefiningValue below, see that code for
365 // detailed motivation.
366
367 if (isa<Argument>(I))
368 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000369 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000370
Manuel Jacob734e7332016-01-09 04:02:16 +0000371 if (isa<Constant>(I))
372 // Constant vectors consist only of constant pointers.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000373 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000374
Philip Reames8531d8c2015-04-10 21:48:25 +0000375 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000376 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000377
Philip Reames66287132015-09-09 23:40:12 +0000378 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000379 // We don't know whether this vector contains entirely base pointers or
380 // not. To be conservatively correct, we treat it as a BDV and will
381 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000382 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000383
Philip Reames8fe7f132015-06-26 22:47:37 +0000384 if (isa<ShuffleVectorInst>(I))
385 // We don't know whether this vector contains entirely base pointers or
386 // not. To be conservatively correct, we treat it as a BDV and will
387 // duplicate code as needed to construct a parallel vector of bases.
388 // TODO: There a number of local optimizations which could be applied here
389 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000390 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000391
392 // A PHI or Select is a base defining value. The outer findBasePointer
393 // algorithm is responsible for constructing a base value for this BDV.
394 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
395 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000396 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000397}
398
Philip Reamesd16a9b12015-02-20 01:06:44 +0000399/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000400/// defines the base pointer for the input, b) blocks the simple search
401/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
402/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000403static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Manuel Jacob0593cfd2016-01-09 03:08:49 +0000404 assert(I->getType()->isPtrOrPtrVectorTy() &&
405 "Illegal to ask for the base pointer of a non-pointer type");
406
Philip Reames8fe7f132015-06-26 22:47:37 +0000407 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000408 return findBaseDefiningValueOfVector(I);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000409
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000410 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000411 // An incoming argument to the function is a base pointer
412 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000413 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000414
Manuel Jacob75cbfdc2016-01-05 04:06:21 +0000415 if (isa<Constant>(I))
416 // We assume that objects with a constant base (e.g. a global) can't move
417 // and don't need to be reported to the collector because they are always
418 // live. All constants have constant bases. Besides global references, all
419 // kinds of constants (e.g. undef, constant expressions, null pointers) can
420 // be introduced by the inliner or the optimizer, especially on dynamically
421 // dead paths. See e.g. test4 in constants.ll.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000422 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000423
Philip Reamesd16a9b12015-02-20 01:06:44 +0000424 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000425 Value *Def = CI->stripPointerCasts();
Manuel Jacob8050a492015-12-21 01:26:46 +0000426 // If stripping pointer casts changes the address space there is an
427 // addrspacecast in between.
428 assert(cast<PointerType>(Def->getType())->getAddressSpace() ==
429 cast<PointerType>(CI->getType())->getAddressSpace() &&
430 "unsupported addrspacecast");
David Blaikie82ad7872015-02-20 23:44:24 +0000431 // If we find a cast instruction here, it means we've found a cast which is
432 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
433 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000434 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
435 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000436 }
437
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000438 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000439 // The value loaded is an gc base itself
440 return BaseDefiningValueResult(I, true);
441
Philip Reamesd16a9b12015-02-20 01:06:44 +0000442
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000443 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
444 // The base of this GEP is the base
445 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000446
447 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
448 switch (II->getIntrinsicID()) {
449 default:
450 // fall through to general call handling
451 break;
452 case Intrinsic::experimental_gc_statepoint:
Manuel Jacob4e4f60d2015-12-22 18:44:45 +0000453 llvm_unreachable("statepoints don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000454 case Intrinsic::experimental_gc_relocate: {
455 // Rerunning safepoint insertion after safepoints are already
456 // inserted is not supported. It could probably be made to work,
457 // but why are you doing this? There's no good reason.
458 llvm_unreachable("repeat safepoint insertion is not supported");
459 }
460 case Intrinsic::gcroot:
461 // Currently, this mechanism hasn't been extended to work with gcroot.
462 // There's no reason it couldn't be, but I haven't thought about the
463 // implications much.
464 llvm_unreachable(
465 "interaction with the gcroot mechanism is not supported");
466 }
467 }
468 // We assume that functions in the source language only return base
469 // pointers. This should probably be generalized via attributes to support
470 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000471 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000472 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000473
474 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000475 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000476 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
477
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000478 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000479 // A CAS is effectively a atomic store and load combined under a
480 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000481 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000482 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000483
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000484 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000485 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000486
487 // The aggregate ops. Aggregates can either be in the heap or on the
488 // stack, but in either case, this is simply a field load. As a result,
489 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000490 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000491 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000492
493 // We should never see an insert vector since that would require we be
494 // tracing back a struct value not a pointer value.
495 assert(!isa<InsertValueInst>(I) &&
496 "Base pointer for a struct is meaningless");
497
Philip Reames9ac4e382015-08-12 21:00:20 +0000498 // An extractelement produces a base result exactly when it's input does.
499 // We may need to insert a parallel instruction to extract the appropriate
500 // element out of the base vector corresponding to the input. Given this,
501 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000502 if (isa<ExtractElementInst>(I))
503 // Note: There a lot of obvious peephole cases here. This are deliberately
504 // handled after the main base pointer inference algorithm to make writing
505 // test cases to exercise that code easier.
506 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000507
Philip Reamesd16a9b12015-02-20 01:06:44 +0000508 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000509 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000510 // derived pointers (each with it's own base potentially). It's the job of
511 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000512 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000513 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000514 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000515}
516
517/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000518static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
519 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000520 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000521 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000522 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
523 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000524 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000525 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000526 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000527}
528
529/// Return a base pointer for this value if known. Otherwise, return it's
530/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000531static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
532 Value *Def = findBaseDefiningValueCached(I, Cache);
533 auto Found = Cache.find(Def);
534 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000535 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000536 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000537 }
538 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000539 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000540}
541
542/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
543/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000544static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000545 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
546 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
547 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000548 // no recursion possible
549 return true;
550 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000551 if (isa<Instruction>(V) &&
552 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000553 // This is a previously inserted base phi or select. We know
554 // that this is a base value.
555 return true;
556 }
557
558 // We need to keep searching
559 return false;
560}
561
Philip Reamesd16a9b12015-02-20 01:06:44 +0000562namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000563/// Models the state of a single base defining value in the findBasePointer
564/// algorithm for determining where a new instruction is needed to propagate
565/// the base of this BDV.
566class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000567public:
568 enum Status { Unknown, Base, Conflict };
569
Philip Reames9b141ed2015-07-23 22:49:14 +0000570 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000571 assert(status != Base || b);
572 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000573 explicit BDVState(Value *b) : status(Base), base(b) {}
574 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000575
576 Status getStatus() const { return status; }
577 Value *getBase() const { return base; }
578
579 bool isBase() const { return getStatus() == Base; }
580 bool isUnknown() const { return getStatus() == Unknown; }
581 bool isConflict() const { return getStatus() == Conflict; }
582
Philip Reames9b141ed2015-07-23 22:49:14 +0000583 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000584 return base == other.base && status == other.status;
585 }
586
Philip Reames9b141ed2015-07-23 22:49:14 +0000587 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000588
Philip Reames2a892a62015-07-23 22:25:26 +0000589 LLVM_DUMP_METHOD
590 void dump() const { print(dbgs()); dbgs() << '\n'; }
591
592 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000593 switch (status) {
594 case Unknown:
595 OS << "U";
596 break;
597 case Base:
598 OS << "B";
599 break;
600 case Conflict:
601 OS << "C";
602 break;
603 };
604 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000605 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000606 }
607
608private:
609 Status status;
Philip Reamesdd0948a2015-12-18 03:53:28 +0000610 AssertingVH<Value> base; // non null only if status == base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000611};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000612}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000613
Philip Reames6906e922015-09-02 21:57:17 +0000614#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000615static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000616 State.print(OS);
617 return OS;
618}
Philip Reames6906e922015-09-02 21:57:17 +0000619#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000620
Philip Reamesb3967cd2015-09-02 22:30:53 +0000621namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000622// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000623// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000624// operation is implemented in MeetBDVStates::pureMeet
625class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000626public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000627 /// Initializes the currentResult to the TOP state so that if can be met with
628 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000629 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000630
Philip Reames9b141ed2015-07-23 22:49:14 +0000631 // Destructively meet the current result with the given BDVState
632 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000633 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000634 }
635
Philip Reames9b141ed2015-07-23 22:49:14 +0000636 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000637
638private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000639 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000640
Philip Reames9b141ed2015-07-23 22:49:14 +0000641 /// Perform a meet operation on two elements of the BDVState lattice.
642 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000643 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
644 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000645 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000646 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
647 << " produced " << Result << "\n");
648 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000649 }
650
Philip Reames9b141ed2015-07-23 22:49:14 +0000651 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000652 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000653 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000654 return stateB;
655
Philip Reames9b141ed2015-07-23 22:49:14 +0000656 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000657 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000658 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000659 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000660
661 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000662 if (stateA.getBase() == stateB.getBase()) {
663 assert(stateA == stateB && "equality broken!");
664 return stateA;
665 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000666 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000667 }
David Blaikie82ad7872015-02-20 23:44:24 +0000668 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000669 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000670
Philip Reames9b141ed2015-07-23 22:49:14 +0000671 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000672 return stateA;
673 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000674 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000675 }
676};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000677}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000678
679
Philip Reamesd16a9b12015-02-20 01:06:44 +0000680/// For a given value or instruction, figure out what base ptr it's derived
681/// from. For gc objects, this is simply itself. On success, returns a value
682/// which is the base pointer. (This is reliable and can be used for
683/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000684static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000685 Value *def = findBaseOrBDV(I, cache);
686
687 if (isKnownBaseResult(def)) {
688 return def;
689 }
690
691 // Here's the rough algorithm:
692 // - For every SSA value, construct a mapping to either an actual base
693 // pointer or a PHI which obscures the base pointer.
694 // - Construct a mapping from PHI to unknown TOP state. Use an
695 // optimistic algorithm to propagate base pointer information. Lattice
696 // looks like:
697 // UNKNOWN
698 // b1 b2 b3 b4
699 // CONFLICT
700 // When algorithm terminates, all PHIs will either have a single concrete
701 // base or be in a conflict state.
702 // - For every conflict, insert a dummy PHI node without arguments. Add
703 // these to the base[Instruction] = BasePtr mapping. For every
704 // non-conflict, add the actual base.
705 // - For every conflict, add arguments for the base[a] of each input
706 // arguments.
707 //
708 // Note: A simpler form of this would be to add the conflict form of all
709 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000710 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000711 // overall worse solution.
712
Philip Reames29e9ae72015-07-24 00:42:55 +0000713#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000714 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000715 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
716 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000717 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000718#endif
Philip Reames88958b22015-07-24 00:02:11 +0000719
720 // Once populated, will contain a mapping from each potentially non-base BDV
721 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000722 // We use the order of insertion (DFS over the def/use graph) to provide a
723 // stable deterministic ordering for visiting DenseMaps (which are unordered)
724 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000725 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000726
727 // Recursively fill in all base defining values reachable from the initial
728 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000729 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000730 SmallVector<Value*, 16> Worklist;
731 Worklist.push_back(def);
Philip Reames34d7a742015-09-10 00:22:49 +0000732 States.insert(std::make_pair(def, BDVState()));
Philip Reames88958b22015-07-24 00:02:11 +0000733 while (!Worklist.empty()) {
734 Value *Current = Worklist.pop_back_val();
735 assert(!isKnownBaseResult(Current) && "why did it get added?");
736
737 auto visitIncomingValue = [&](Value *InVal) {
738 Value *Base = findBaseOrBDV(InVal, cache);
739 if (isKnownBaseResult(Base))
740 // Known bases won't need new instructions introduced and can be
741 // ignored safely
742 return;
743 assert(isExpectedBDVType(Base) && "the only non-base values "
744 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000745 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000746 Worklist.push_back(Base);
747 };
748 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
749 for (Value *InVal : Phi->incoming_values())
750 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000751 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000752 visitIncomingValue(Sel->getTrueValue());
753 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000754 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
755 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000756 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
757 visitIncomingValue(IE->getOperand(0)); // vector operand
758 visitIncomingValue(IE->getOperand(1)); // scalar operand
Philip Reames9ac4e382015-08-12 21:00:20 +0000759 } else {
Philip Reames66287132015-09-09 23:40:12 +0000760 // There is one known class of instructions we know we don't handle.
761 assert(isa<ShuffleVectorInst>(Current));
Philip Reames9ac4e382015-08-12 21:00:20 +0000762 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000763 }
764 }
765 }
766
Philip Reamesdab35f32015-09-02 21:11:44 +0000767#ifndef NDEBUG
768 DEBUG(dbgs() << "States after initialization:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000769 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000770 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000771 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000772#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000773
Philip Reames273e6bb2015-07-23 21:41:27 +0000774 // Return a phi state for a base defining value. We'll generate a new
775 // base state for known bases and expect to find a cached state otherwise.
776 auto getStateForBDV = [&](Value *baseValue) {
777 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000778 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000779 auto I = States.find(baseValue);
780 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000781 return I->second;
782 };
783
Philip Reamesd16a9b12015-02-20 01:06:44 +0000784 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000785 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000786#ifndef NDEBUG
Philip Reamesb4e55f32015-09-10 00:32:56 +0000787 const size_t oldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000788#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000789 progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000790 // We're only changing values in this loop, thus safe to keep iterators.
791 // Since this is computing a fixed point, the order of visit does not
792 // effect the result. TODO: We could use a worklist here and make this run
793 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000794 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000795 Value *BDV = Pair.first;
796 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000797
Philip Reames9b141ed2015-07-23 22:49:14 +0000798 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000799 // instance which represents the BDV of that value.
800 auto getStateForInput = [&](Value *V) mutable {
801 Value *BDV = findBaseOrBDV(V, cache);
802 return getStateForBDV(BDV);
803 };
804
Philip Reames9b141ed2015-07-23 22:49:14 +0000805 MeetBDVStates calculateMeet;
Philip Reamesece70b82015-09-09 23:57:18 +0000806 if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000807 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
808 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reamesece70b82015-09-09 23:57:18 +0000809 } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000810 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000811 calculateMeet.meetWith(getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000812 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000813 // The 'meet' for an extractelement is slightly trivial, but it's still
814 // useful in that it drives us to conflict if our input is.
Philip Reames9ac4e382015-08-12 21:00:20 +0000815 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
Philip Reames66287132015-09-09 23:40:12 +0000816 } else {
817 // Given there's a inherent type mismatch between the operands, will
818 // *always* produce Conflict.
Philip Reamesece70b82015-09-09 23:57:18 +0000819 auto *IE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +0000820 calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
821 calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000822 }
823
Philip Reames34d7a742015-09-10 00:22:49 +0000824 BDVState oldState = States[BDV];
Philip Reames9b141ed2015-07-23 22:49:14 +0000825 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000826 if (oldState != newState) {
827 progress = true;
Philip Reames34d7a742015-09-10 00:22:49 +0000828 States[BDV] = newState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000829 }
830 }
831
Philip Reamesb4e55f32015-09-10 00:32:56 +0000832 assert(oldSize == States.size() &&
833 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000834 }
835
Philip Reamesdab35f32015-09-02 21:11:44 +0000836#ifndef NDEBUG
837 DEBUG(dbgs() << "States after meet iteration:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000838 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000839 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000840 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000841#endif
842
Philip Reamesd16a9b12015-02-20 01:06:44 +0000843 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000844 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000845 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000846 Instruction *I = cast<Instruction>(Pair.first);
847 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000848 assert(!isKnownBaseResult(I) && "why did it get added?");
849 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000850
851 // extractelement instructions are a bit special in that we may need to
852 // insert an extract even when we know an exact base for the instruction.
853 // The problem is that we need to convert from a vector base to a scalar
854 // base for the particular indice we're interested in.
855 if (State.isBase() && isa<ExtractElementInst>(I) &&
856 isa<VectorType>(State.getBase()->getType())) {
857 auto *EE = cast<ExtractElementInst>(I);
858 // TODO: In many cases, the new instruction is just EE itself. We should
859 // exploit this, but can't do it here since it would break the invariant
860 // about the BDV not being known to be a base.
861 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
862 EE->getIndexOperand(),
863 "base_ee", EE);
864 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000865 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000866 }
Philip Reames66287132015-09-09 23:40:12 +0000867
868 // Since we're joining a vector and scalar base, they can never be the
869 // same. As a result, we should always see insert element having reached
870 // the conflict state.
871 if (isa<InsertElementInst>(I)) {
872 assert(State.isConflict());
873 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000874
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000875 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000876 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000877
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000878 /// Create and insert a new instruction which will represent the base of
879 /// the given instruction 'I'.
880 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
881 if (isa<PHINode>(I)) {
882 BasicBlock *BB = I->getParent();
883 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
884 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000885 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000886 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000887 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
888 // The undef will be replaced later
889 UndefValue *Undef = UndefValue::get(Sel->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000890 std::string Name = suffixed_name_or(I, ".base", "base_select");
Philip Reames9ac4e382015-08-12 21:00:20 +0000891 return SelectInst::Create(Sel->getCondition(), Undef,
892 Undef, Name, Sel);
Philip Reames66287132015-09-09 23:40:12 +0000893 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000894 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000895 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000896 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
897 EE);
Philip Reames66287132015-09-09 23:40:12 +0000898 } else {
899 auto *IE = cast<InsertElementInst>(I);
900 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
901 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000902 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000903 return InsertElementInst::Create(VecUndef, ScalarUndef,
904 IE->getOperand(2), Name, IE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000905 }
Philip Reames66287132015-09-09 23:40:12 +0000906
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000907 };
908 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
909 // Add metadata marking this as a base value
910 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000911 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000912 }
913
Philip Reames3ea15892015-09-03 21:57:40 +0000914 // Returns a instruction which produces the base pointer for a given
915 // instruction. The instruction is assumed to be an input to one of the BDVs
916 // seen in the inference algorithm above. As such, we must either already
917 // know it's base defining value is a base, or have inserted a new
918 // instruction to propagate the base of it's BDV and have entered that newly
919 // introduced instruction into the state table. In either case, we are
920 // assured to be able to determine an instruction which produces it's base
921 // pointer.
922 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
923 Value *BDV = findBaseOrBDV(Input, cache);
924 Value *Base = nullptr;
925 if (isKnownBaseResult(BDV)) {
926 Base = BDV;
927 } else {
928 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000929 assert(States.count(BDV));
930 Base = States[BDV].getBase();
Philip Reames3ea15892015-09-03 21:57:40 +0000931 }
932 assert(Base && "can't be null");
933 // The cast is needed since base traversal may strip away bitcasts
934 if (Base->getType() != Input->getType() &&
935 InsertPt) {
936 Base = new BitCastInst(Base, Input->getType(), "cast",
937 InsertPt);
938 }
939 return Base;
940 };
941
Philip Reames15d55632015-09-09 23:26:08 +0000942 // Fixup all the inputs of the new PHIs. Visit order needs to be
943 // deterministic and predictable because we're naming newly created
944 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000945 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000946 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000947 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000948
Philip Reames7540e3a2015-09-10 00:01:53 +0000949 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000950 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
951 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000952 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000953
Philip Reamesc8ded462015-09-10 00:27:50 +0000954 if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000955 PHINode *phi = cast<PHINode>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +0000956 unsigned NumPHIValues = phi->getNumIncomingValues();
957 for (unsigned i = 0; i < NumPHIValues; i++) {
958 Value *InVal = phi->getIncomingValue(i);
959 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000960
Philip Reames28e61ce2015-02-28 01:57:44 +0000961 // If we've already seen InBB, add the same incoming value
962 // we added for it earlier. The IR verifier requires phi
963 // nodes with multiple entries from the same basic block
964 // to have the same incoming value for each of those
965 // entries. If we don't do this check here and basephi
966 // has a different type than base, we'll end up adding two
967 // bitcasts (and hence two distinct values) as incoming
968 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000969
Philip Reames28e61ce2015-02-28 01:57:44 +0000970 int blockIndex = basephi->getBasicBlockIndex(InBB);
971 if (blockIndex != -1) {
972 Value *oldBase = basephi->getIncomingValue(blockIndex);
973 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +0000974
Philip Reamesd16a9b12015-02-20 01:06:44 +0000975#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +0000976 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000977 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +0000978 // values incoming from the same basic block may be
979 // different is by being different bitcasts of the same
980 // value. A cleanup that remains TODO is changing
981 // findBaseOrBDV to return an llvm::Value of the correct
982 // type (and still remain pure). This will remove the
983 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +0000984 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +0000985 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000986#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000987 continue;
988 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000989
Philip Reames3ea15892015-09-03 21:57:40 +0000990 // Find the instruction which produces the base for each input. We may
991 // need to insert a bitcast in the incoming block.
992 // TODO: Need to split critical edges if insertion is needed
993 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
994 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +0000995 }
996 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reamesc8ded462015-09-10 00:27:50 +0000997 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000998 SelectInst *Sel = cast<SelectInst>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +0000999 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1000 // something more safe and less hacky.
1001 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001002 Value *InVal = Sel->getOperand(i);
1003 // Find the instruction which produces the base for each input. We may
1004 // need to insert a bitcast.
1005 Value *Base = getBaseForInput(InVal, BaseSel);
1006 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001007 }
Philip Reamesc8ded462015-09-10 00:27:50 +00001008 } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001009 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001010 // Find the instruction which produces the base for each input. We may
1011 // need to insert a bitcast.
1012 Value *Base = getBaseForInput(InVal, BaseEE);
Philip Reames9ac4e382015-08-12 21:00:20 +00001013 BaseEE->setOperand(0, Base);
Philip Reames66287132015-09-09 23:40:12 +00001014 } else {
Philip Reamesc8ded462015-09-10 00:27:50 +00001015 auto *BaseIE = cast<InsertElementInst>(State.getBase());
Philip Reames7540e3a2015-09-10 00:01:53 +00001016 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001017 auto UpdateOperand = [&](int OperandIdx) {
1018 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001019 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001020 BaseIE->setOperand(OperandIdx, Base);
1021 };
1022 UpdateOperand(0); // vector operand
1023 UpdateOperand(1); // scalar operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001024 }
Philip Reames66287132015-09-09 23:40:12 +00001025
Philip Reamesd16a9b12015-02-20 01:06:44 +00001026 }
1027
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001028 // Now that we're done with the algorithm, see if we can optimize the
1029 // results slightly by reducing the number of new instructions needed.
1030 // Arguably, this should be integrated into the algorithm above, but
1031 // doing as a post process step is easier to reason about for the moment.
1032 DenseMap<Value *, Value *> ReverseMap;
1033 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001034 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001035 // Note: We need to visit the states in a deterministic order. We uses the
1036 // Keys we sorted above for this purpose. Note that we are papering over a
1037 // bigger problem with the algorithm above - it's visit order is not
1038 // deterministic. A larger change is needed to fix this.
Philip Reames34d7a742015-09-10 00:22:49 +00001039 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001040 auto *BDV = Pair.first;
1041 auto State = Pair.second;
Philip Reames246e6182015-09-03 20:24:29 +00001042 Value *Base = State.getBase();
Philip Reames15d55632015-09-09 23:26:08 +00001043 assert(BDV && Base);
1044 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001045 assert(isKnownBaseResult(Base) &&
1046 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001047 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001048 continue;
1049
Philip Reames15d55632015-09-09 23:26:08 +00001050 ReverseMap[Base] = BDV;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001051 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1052 NewInsts.insert(BaseI);
1053 Worklist.insert(BaseI);
1054 }
1055 }
Philip Reames9546f362015-09-02 22:25:07 +00001056 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1057 Value *Replacement) {
1058 // Add users which are new instructions (excluding self references)
1059 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001060 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001061 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001062 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001063 // Then do the actual replacement
1064 NewInsts.erase(BaseI);
1065 ReverseMap.erase(BaseI);
1066 BaseI->replaceAllUsesWith(Replacement);
Philip Reames34d7a742015-09-10 00:22:49 +00001067 assert(States.count(BDV));
1068 assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
1069 States[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesdd0948a2015-12-18 03:53:28 +00001070 BaseI->eraseFromParent();
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001071 };
1072 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1073 while (!Worklist.empty()) {
1074 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001075 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001076 Value *Bdv = ReverseMap[BaseI];
1077 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1078 if (BaseI->isIdenticalTo(BdvI)) {
1079 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001080 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001081 continue;
1082 }
1083 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1084 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001085 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001086 continue;
1087 }
1088 }
1089
Philip Reamesd16a9b12015-02-20 01:06:44 +00001090 // Cache all of our results so we can cheaply reuse them
1091 // NOTE: This is actually two caches: one of the base defining value
1092 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001093 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001094 auto *BDV = Pair.first;
1095 Value *base = Pair.second.getBase();
1096 assert(BDV && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001097
Philip Reamesece70b82015-09-09 23:57:18 +00001098 std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
Philip Reamesdab35f32015-09-02 21:11:44 +00001099 DEBUG(dbgs() << "Updating base value cache"
Philip Reamesece70b82015-09-09 23:57:18 +00001100 << " for: " << BDV->getName()
Philip Reamesdab35f32015-09-02 21:11:44 +00001101 << " from: " << fromstr
Philip Reamesece70b82015-09-09 23:57:18 +00001102 << " to: " << base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001103
Philip Reames15d55632015-09-09 23:26:08 +00001104 if (cache.count(BDV)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001105 // Once we transition from the BDV relation being store in the cache to
1106 // the base relation being stored, it must be stable
Philip Reames15d55632015-09-09 23:26:08 +00001107 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001108 "base relation should be stable");
1109 }
Philip Reames15d55632015-09-09 23:26:08 +00001110 cache[BDV] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001111 }
Manuel Jacob67f1d3a2015-12-29 22:16:41 +00001112 assert(cache.count(def));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001113 return cache[def];
1114}
1115
1116// For a set of live pointers (base and/or derived), identify the base
1117// pointer of the object which they are derived from. This routine will
1118// mutate the IR graph as needed to make the 'base' pointer live at the
1119// definition site of 'derived'. This ensures that any use of 'derived' can
1120// also use 'base'. This may involve the insertion of a number of
1121// additional PHI nodes.
1122//
1123// preconditions: live is a set of pointer type Values
1124//
1125// side effects: may insert PHI nodes into the existing CFG, will preserve
1126// CFG, will not remove or mutate any existing nodes
1127//
Philip Reamesf2041322015-02-20 19:26:04 +00001128// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001129// pointer in live. Note that derived can be equal to base if the original
1130// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001131static void
1132findBasePointers(const StatepointLiveSetTy &live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001133 DenseMap<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001134 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001135 // For the naming of values inserted to be deterministic - which makes for
1136 // much cleaner and more stable tests - we need to assign an order to the
1137 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001138 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001139 Temp.insert(Temp.end(), live.begin(), live.end());
1140 std::sort(Temp.begin(), Temp.end(), order_by_name);
1141 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001142 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001143 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001144 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001145 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1146 DT->dominates(cast<Instruction>(base)->getParent(),
1147 cast<Instruction>(ptr)->getParent())) &&
1148 "The base we found better dominate the derived pointer");
1149
David Blaikie82ad7872015-02-20 23:44:24 +00001150 // If you see this trip and like to live really dangerously, the code should
1151 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001152 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001153 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001154 "the relocation code needs adjustment to handle the relocation of "
1155 "a null pointer constant without causing false positives in the "
1156 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001157 }
1158}
1159
1160/// Find the required based pointers (and adjust the live set) for the given
1161/// parse point.
1162static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1163 const CallSite &CS,
1164 PartiallyConstructedSafepointRecord &result) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001165 DenseMap<Value *, Value *> PointerToBase;
1166 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001167
1168 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001169 // Note: Need to print these in a stable order since this is checked in
1170 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001171 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001172 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001173 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001174 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001175 Temp.push_back(Pair.first);
1176 }
1177 std::sort(Temp.begin(), Temp.end(), order_by_name);
1178 for (Value *Ptr : Temp) {
1179 Value *Base = PointerToBase[Ptr];
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00001180 errs() << " derived ";
1181 Ptr->printAsOperand(errs(), false);
1182 errs() << " base ";
1183 Base->printAsOperand(errs(), false);
1184 errs() << "\n";;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001185 }
1186 }
1187
Philip Reamesf2041322015-02-20 19:26:04 +00001188 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001189}
1190
Philip Reamesdf1ef082015-04-10 22:53:14 +00001191/// Given an updated version of the dataflow liveness results, update the
1192/// liveset and base pointer maps for the call site CS.
1193static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1194 const CallSite &CS,
1195 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001196
Philip Reamesdf1ef082015-04-10 22:53:14 +00001197static void recomputeLiveInValues(
Justin Bogner843fb202015-12-15 19:40:57 +00001198 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001199 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001200 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001201 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001202 GCPtrLivenessData RevisedLivenessData;
1203 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001204 for (size_t i = 0; i < records.size(); i++) {
1205 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001206 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001207 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001208 }
1209}
1210
Sanjoy Das7ad67642015-10-20 01:06:24 +00001211// When inserting gc.relocate and gc.result calls, we need to ensure there are
1212// no uses of the original value / return value between the gc.statepoint and
1213// the gc.relocate / gc.result call. One case which can arise is a phi node
1214// starting one of the successor blocks. We also need to be able to insert the
1215// gc.relocates only on the path which goes through the statepoint. We might
1216// need to split an edge to make this possible.
Philip Reamesf209a152015-04-13 20:00:30 +00001217static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001218normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1219 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001220 BasicBlock *Ret = BB;
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001221 if (!BB->getUniquePredecessor())
Chandler Carruth96ada252015-07-22 09:52:54 +00001222 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001223
Sanjoy Das7ad67642015-10-20 01:06:24 +00001224 // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
Philip Reames69e51ca2015-04-13 18:07:21 +00001225 // from it
1226 FoldSingleEntryPHINodes(Ret);
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001227 assert(!isa<PHINode>(Ret->begin()) &&
1228 "All PHI nodes should have been removed!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001229
Sanjoy Das7ad67642015-10-20 01:06:24 +00001230 // At this point, we can safely insert a gc.relocate or gc.result as the first
1231 // instruction in Ret if needed.
Philip Reames69e51ca2015-04-13 18:07:21 +00001232 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001233}
1234
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001235// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001236// from original call to the safepoint.
1237static AttributeSet legalizeCallAttributes(AttributeSet AS) {
Sanjoy Das810a59d2015-10-16 02:41:11 +00001238 AttributeSet Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001239
1240 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
Sanjoy Das810a59d2015-10-16 02:41:11 +00001241 unsigned Index = AS.getSlotIndex(Slot);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001242
Sanjoy Das810a59d2015-10-16 02:41:11 +00001243 if (Index == AttributeSet::ReturnIndex ||
1244 Index == AttributeSet::FunctionIndex) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001245
Sanjoy Das810a59d2015-10-16 02:41:11 +00001246 for (Attribute Attr : make_range(AS.begin(Slot), AS.end(Slot))) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001247
1248 // Do not allow certain attributes - just skip them
1249 // Safepoint can not be read only or read none.
Sanjoy Das810a59d2015-10-16 02:41:11 +00001250 if (Attr.hasAttribute(Attribute::ReadNone) ||
1251 Attr.hasAttribute(Attribute::ReadOnly))
Philip Reamesd16a9b12015-02-20 01:06:44 +00001252 continue;
1253
Sanjoy Das58fae7c2015-10-16 02:41:23 +00001254 // These attributes control the generation of the gc.statepoint call /
1255 // invoke itself; and once the gc.statepoint is in place, they're of no
1256 // use.
1257 if (Attr.hasAttribute("statepoint-num-patch-bytes") ||
1258 Attr.hasAttribute("statepoint-id"))
1259 continue;
1260
Sanjoy Das810a59d2015-10-16 02:41:11 +00001261 Ret = Ret.addAttributes(
1262 AS.getContext(), Index,
1263 AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001264 }
1265 }
1266
1267 // Just skip parameter attributes for now
1268 }
1269
Sanjoy Das810a59d2015-10-16 02:41:11 +00001270 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001271}
1272
1273/// Helper function to place all gc relocates necessary for the given
1274/// statepoint.
1275/// Inputs:
1276/// liveVariables - list of variables to be relocated.
1277/// liveStart - index of the first live variable.
1278/// basePtrs - base pointers.
1279/// statepointToken - statepoint instruction to which relocates should be
1280/// bound.
1281/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001282static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001283 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001284 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001285 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001286 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001287 if (LiveVariables.empty())
1288 return;
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001289
1290 auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1291 auto ValIt = std::find(LiveVec.begin(), LiveVec.end(), Val);
1292 assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1293 size_t Index = std::distance(LiveVec.begin(), ValIt);
1294 assert(Index < LiveVec.size() && "Bug in std::find?");
1295 return Index;
1296 };
Philip Reames74ce2e72015-07-21 16:51:17 +00001297 Module *M = StatepointToken->getModule();
Philip Reames5715f572016-01-09 01:31:13 +00001298
1299 // All gc_relocate are generated as i8 addrspace(1)* (or a vector type whose
1300 // element type is i8 addrspace(1)*). We originally generated unique
1301 // declarations for each pointer type, but this proved problematic because
1302 // the intrinsic mangling code is incomplete and fragile. Since we're moving
1303 // towards a single unified pointer type anyways, we can just cast everything
1304 // to an i8* of the right address space. A bitcast is added later to convert
1305 // gc_relocate to the actual value's type.
1306 auto getGCRelocateDecl = [&] (Type *Ty) {
1307 assert(isHandledGCPointerType(Ty));
1308 auto AS = Ty->getScalarType()->getPointerAddressSpace();
1309 Type *NewTy = Type::getInt8PtrTy(M->getContext(), AS);
1310 if (auto *VT = dyn_cast<VectorType>(Ty))
1311 NewTy = VectorType::get(NewTy, VT->getNumElements());
1312 return Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate,
1313 {NewTy});
1314 };
1315
1316 // Lazily populated map from input types to the canonicalized form mentioned
1317 // in the comment above. This should probably be cached somewhere more
1318 // broadly.
1319 DenseMap<Type*, Value*> TypeToDeclMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001320
Sanjoy Das5665c992015-05-11 23:47:27 +00001321 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001322 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001323 Value *BaseIdx =
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001324 Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
Sanjoy Das3020b1b2015-10-20 01:06:31 +00001325 Value *LiveIdx = Builder.getInt32(LiveStart + i);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001326
Philip Reames5715f572016-01-09 01:31:13 +00001327 Type *Ty = LiveVariables[i]->getType();
1328 if (!TypeToDeclMap.count(Ty))
1329 TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1330 Value *GCRelocateDecl = TypeToDeclMap[Ty];
1331
Philip Reamesd16a9b12015-02-20 01:06:44 +00001332 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001333 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001334 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001335 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001336 // Trick CodeGen into thinking there are lots of free registers at this
1337 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001338 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001339 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001340}
1341
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001342namespace {
1343
1344/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1345/// avoids having to worry about keeping around dangling pointers to Values.
1346class DeferredReplacement {
1347 AssertingVH<Instruction> Old;
1348 AssertingVH<Instruction> New;
1349
1350public:
1351 explicit DeferredReplacement(Instruction *Old, Instruction *New) :
1352 Old(Old), New(New) {
1353 assert(Old != New && "Not allowed!");
1354 }
1355
1356 /// Does the task represented by this instance.
1357 void doReplacement() {
1358 Instruction *OldI = Old;
1359 Instruction *NewI = New;
1360
1361 assert(OldI != NewI && "Disallowed at construction?!");
1362
1363 Old = nullptr;
1364 New = nullptr;
1365
1366 if (NewI)
1367 OldI->replaceAllUsesWith(NewI);
1368 OldI->eraseFromParent();
1369 }
1370};
1371}
1372
Philip Reamesd16a9b12015-02-20 01:06:44 +00001373static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001374makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1375 const SmallVectorImpl<Value *> &BasePtrs,
1376 const SmallVectorImpl<Value *> &LiveVariables,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001377 PartiallyConstructedSafepointRecord &Result,
1378 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001379 assert(BasePtrs.size() == LiveVariables.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001380
Philip Reamesd16a9b12015-02-20 01:06:44 +00001381 // Then go ahead and use the builder do actually do the inserts. We insert
1382 // immediately before the previous instruction under the assumption that all
1383 // arguments will be available here. We can't insert afterwards since we may
1384 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001385 Instruction *InsertBefore = CS.getInstruction();
1386 IRBuilder<> Builder(InsertBefore);
1387
Sanjoy Das3c520a12015-10-08 23:18:38 +00001388 ArrayRef<Value *> GCArgs(LiveVariables);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001389 uint64_t StatepointID = 0xABCDEF00;
1390 uint32_t NumPatchBytes = 0;
1391 uint32_t Flags = uint32_t(StatepointFlags::None);
Sanjoy Das3c520a12015-10-08 23:18:38 +00001392
Sanjoy Dasbcf27522016-01-29 01:03:20 +00001393 ArrayRef<Use> CallArgs(CS.arg_begin(), CS.arg_end());
1394 ArrayRef<Use> DeoptArgs = GetDeoptBundleOperands(CS);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001395 ArrayRef<Use> TransitionArgs;
Sanjoy Das40992972016-01-29 01:03:17 +00001396 if (auto TransitionBundle =
1397 CS.getOperandBundle(LLVMContext::OB_gc_transition)) {
1398 Flags |= uint32_t(StatepointFlags::GCTransition);
1399 TransitionArgs = TransitionBundle->Inputs;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001400 }
Sanjoy Das40992972016-01-29 01:03:17 +00001401
Sanjoy Dasbcf27522016-01-29 01:03:20 +00001402 Value *CallTarget = CS.getCalledValue();
1403 AttributeSet OriginalAttrs = CS.getAttributes();
Sanjoy Das40992972016-01-29 01:03:17 +00001404 Attribute AttrID = OriginalAttrs.getAttribute(AttributeSet::FunctionIndex,
1405 "statepoint-id");
1406 if (AttrID.isStringAttribute())
1407 AttrID.getValueAsString().getAsInteger(10, StatepointID);
1408
1409 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
1410 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
1411 if (AttrNumPatchBytes.isStringAttribute())
1412 AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
1413
Philip Reamesd16a9b12015-02-20 01:06:44 +00001414 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001415 Instruction *Token = nullptr;
1416 AttributeSet ReturnAttrs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001417 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001418 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Das3c520a12015-10-08 23:18:38 +00001419 CallInst *Call = Builder.CreateGCStatepointCall(
1420 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1421 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1422
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001423 Call->setTailCall(ToReplace->isTailCall());
1424 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001425
1426 // Currently we will fail on parameter attributes and on certain
1427 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001428 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001429 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001430 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001431 Call->setAttributes(NewAttrs.getFnAttributes());
1432 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001433
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001434 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001435
1436 // Put the following gc_result and gc_relocate calls immediately after the
1437 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001438 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1439 Builder.SetInsertPoint(ToReplace->getNextNode());
1440 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001441 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001442 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001443
1444 // Insert the new invoke into the old block. We'll remove the old one in a
1445 // moment at which point this will become the new terminator for the
1446 // original block.
Sanjoy Das3c520a12015-10-08 23:18:38 +00001447 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1448 StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1449 ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1450 GCArgs, "statepoint_token");
1451
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001452 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001453
1454 // Currently we will fail on parameter attributes and on certain
1455 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001456 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001457 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001458 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001459 Invoke->setAttributes(NewAttrs.getFnAttributes());
1460 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001461
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001462 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001463
1464 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001465 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1466 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1467 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001468 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001469
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001470 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001471 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001472
Chen Lid71999e2015-12-26 07:54:32 +00001473 // Attach exceptional gc relocates to the landingpad.
1474 Instruction *ExceptionalToken = UnwindBlock->getLandingPadInst();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001475 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001476
Sanjoy Das3c520a12015-10-08 23:18:38 +00001477 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001478 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1479 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001480
1481 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001482 BasicBlock *NormalDest = ToReplace->getNormalDest();
1483 assert(!isa<PHINode>(NormalDest->begin()) &&
1484 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001485 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001486
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001487 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001488
1489 // gc relocates will be generated later as if it were regular call
1490 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001491 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001492 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001493
Sanjoy Das40992972016-01-29 01:03:17 +00001494 Token->setName("statepoint_token");
1495 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1496 StringRef Name =
1497 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1498 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
1499 GCResult->setAttributes(CS.getAttributes().getRetAttributes());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001500
Sanjoy Das40992972016-01-29 01:03:17 +00001501 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1502 // live set of some other safepoint, in which case that safepoint's
1503 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1504 // llvm::Instruction. Instead, we defer the replacement and deletion to
1505 // after the live sets have been made explicit in the IR, and we no longer
1506 // have raw pointers to worry about.
1507 Replacements.emplace_back(CS.getInstruction(), GCResult);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001508 } else {
Sanjoy Das40992972016-01-29 01:03:17 +00001509 Replacements.emplace_back(CS.getInstruction(), nullptr);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001510 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001511
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001512 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001513
Philip Reamesd16a9b12015-02-20 01:06:44 +00001514 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001515 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001516 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001517}
1518
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001519static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
1520 SmallVectorImpl<Value *> &LiveVec) {
1521 assert(BaseVec.size() == LiveVec.size());
1522
Sanjoy Das3794eeb2016-01-29 16:50:34 +00001523 struct BaseDerivedPair {
1524 Value *Base;
1525 Value *Derived;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001526
Sanjoy Das3794eeb2016-01-29 16:50:34 +00001527 BaseDerivedPair(Value *B, Value *D) : Base(B), Derived(D) {}
1528 };
1529
1530 SmallVector<BaseDerivedPair, 64> NameOrdering;
1531 NameOrdering.reserve(BaseVec.size());
1532
1533 for (size_t i = 0, e = BaseVec.size(); i < e; i++)
1534 NameOrdering.emplace_back(BaseVec[i], LiveVec[i]);
1535
1536 auto Compare = [](BaseDerivedPair &L, BaseDerivedPair &R) {
1537 return L.Derived->getName() < R.Derived->getName();
1538 };
1539
1540 std::sort(NameOrdering.begin(), NameOrdering.end(), Compare);
1541
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001542 for (size_t i = 0; i < BaseVec.size(); i++) {
Sanjoy Das3794eeb2016-01-29 16:50:34 +00001543 BaseVec[i] = NameOrdering[i].Base;
1544 LiveVec[i] = NameOrdering[i].Derived;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001545 }
1546}
1547
1548// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1549// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001550//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001551// WARNING: Does not do any fixup to adjust users of the original live
1552// values. That's the callers responsibility.
1553static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001554makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001555 PartiallyConstructedSafepointRecord &Result,
1556 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001557 const auto &LiveSet = Result.LiveSet;
1558 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001559
1560 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001561 SmallVector<Value *, 64> BaseVec, LiveVec;
1562 LiveVec.reserve(LiveSet.size());
1563 BaseVec.reserve(LiveSet.size());
1564 for (Value *L : LiveSet) {
1565 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001566 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001567 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001568 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001569 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001570 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001571
1572 // To make the output IR slightly more stable (for use in diffs), ensure a
1573 // fixed order of the values in the safepoint (by sorting the value name).
1574 // The order is otherwise meaningless.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001575 StabilizeOrder(BaseVec, LiveVec);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001576
1577 // Do the actual rewriting and delete the old statepoint
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001578 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001579}
1580
1581// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001582//
1583// It receives iterator to the statepoint gc relocates and emits a store to the
1584// assigned location (via allocaMap) for the each one of them. It adds the
1585// visited values into the visitedLiveValues set, which we will later use them
1586// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001587static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001588insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1589 DenseMap<Value *, Value *> &AllocaMap,
1590 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001591
Sanjoy Das5665c992015-05-11 23:47:27 +00001592 for (User *U : GCRelocs) {
Manuel Jacob83eefa62016-01-05 04:03:00 +00001593 GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U);
1594 if (!Relocate)
Philip Reamesd16a9b12015-02-20 01:06:44 +00001595 continue;
1596
Manuel Jacob83eefa62016-01-05 04:03:00 +00001597 Value *OriginalValue = const_cast<Value *>(Relocate->getDerivedPtr());
Sanjoy Das5665c992015-05-11 23:47:27 +00001598 assert(AllocaMap.count(OriginalValue));
1599 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001600
1601 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001602 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001603 // the correct type according to alloca.
Manuel Jacob83eefa62016-01-05 04:03:00 +00001604 assert(Relocate->getNextNode() &&
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001605 "Should always have one since it's not a terminator");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001606 IRBuilder<> Builder(Relocate->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001607 Value *CastedRelocatedValue =
Manuel Jacob83eefa62016-01-05 04:03:00 +00001608 Builder.CreateBitCast(Relocate,
Philip Reamesece70b82015-09-09 23:57:18 +00001609 cast<AllocaInst>(Alloca)->getAllocatedType(),
Manuel Jacob83eefa62016-01-05 04:03:00 +00001610 suffixed_name_or(Relocate, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001611
Sanjoy Das5665c992015-05-11 23:47:27 +00001612 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1613 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001614
1615#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001616 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001617#endif
1618 }
1619}
1620
Igor Laevskye0317182015-05-19 15:59:05 +00001621// Helper function for the "relocationViaAlloca". Similar to the
1622// "insertRelocationStores" but works for rematerialized values.
1623static void
1624insertRematerializationStores(
1625 RematerializedValueMapTy RematerializedValues,
1626 DenseMap<Value *, Value *> &AllocaMap,
1627 DenseSet<Value *> &VisitedLiveValues) {
1628
1629 for (auto RematerializedValuePair: RematerializedValues) {
1630 Instruction *RematerializedValue = RematerializedValuePair.first;
1631 Value *OriginalValue = RematerializedValuePair.second;
1632
1633 assert(AllocaMap.count(OriginalValue) &&
1634 "Can not find alloca for rematerialized value");
1635 Value *Alloca = AllocaMap[OriginalValue];
1636
1637 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1638 Store->insertAfter(RematerializedValue);
1639
1640#ifndef NDEBUG
1641 VisitedLiveValues.insert(OriginalValue);
1642#endif
1643 }
1644}
1645
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001646/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001647static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001648 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001649 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001650#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001651 // record initial number of (static) allocas; we'll check we have the same
1652 // number when we get done.
1653 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001654 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1655 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001656 if (isa<AllocaInst>(*I))
1657 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001658#endif
1659
1660 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001661 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001662 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001663 // Used later to chack that we have enough allocas to store all values
1664 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001665 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001666
Igor Laevskye0317182015-05-19 15:59:05 +00001667 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1668 // "PromotableAllocas"
1669 auto emitAllocaFor = [&](Value *LiveValue) {
1670 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1671 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001672 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001673 PromotableAllocas.push_back(Alloca);
1674 };
1675
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001676 // Emit alloca for each live gc pointer
1677 for (Value *V : Live)
1678 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001679
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001680 // Emit allocas for rematerialized values
1681 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001682 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001683 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001684 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001685 continue;
1686
1687 emitAllocaFor(OriginalValue);
1688 ++NumRematerializedValues;
1689 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001690
Philip Reamesd16a9b12015-02-20 01:06:44 +00001691 // The next two loops are part of the same conceptual operation. We need to
1692 // insert a store to the alloca after the original def and at each
1693 // redefinition. We need to insert a load before each use. These are split
1694 // into distinct loops for performance reasons.
1695
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001696 // Update gc pointer after each statepoint: either store a relocated value or
1697 // null (if no relocated value was found for this gc pointer and it is not a
1698 // gc_result). This must happen before we update the statepoint with load of
1699 // alloca otherwise we lose the link between statepoint and old def.
1700 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001701 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001702
1703 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001704 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001705
1706 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001707 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001708
1709 // In case if it was invoke statepoint
1710 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001711 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001712 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1713 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001714 }
1715
Igor Laevskye0317182015-05-19 15:59:05 +00001716 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001717 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1718 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001719
Philip Reamese73300b2015-04-13 16:41:32 +00001720 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001721 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001722 // the gc.statepoint. This will turn some subtle GC problems into
1723 // slightly easier to debug SEGVs. Note that on large IR files with
1724 // lots of gc.statepoints this is extremely costly both memory and time
1725 // wise.
1726 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001727 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001728 Value *Def = Pair.first;
1729 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001730
Philip Reamese73300b2015-04-13 16:41:32 +00001731 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001732 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001733 continue;
1734 }
1735 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001736 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001737
Philip Reamese73300b2015-04-13 16:41:32 +00001738 auto InsertClobbersAt = [&](Instruction *IP) {
1739 for (auto *AI : ToClobber) {
Eduard Burtescu90c44492016-01-18 00:10:01 +00001740 auto PT = cast<PointerType>(AI->getAllocatedType());
Philip Reamese73300b2015-04-13 16:41:32 +00001741 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001742 StoreInst *Store = new StoreInst(CPN, AI);
1743 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001744 }
1745 };
1746
1747 // Insert the clobbering stores. These may get intermixed with the
1748 // gc.results and gc.relocates, but that's fine.
1749 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001750 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1751 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001752 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001753 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001754 }
David Blaikie82ad7872015-02-20 23:44:24 +00001755 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001756 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001757
1758 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001759 for (auto Pair : AllocaMap) {
1760 Value *Def = Pair.first;
1761 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001762
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001763 // We pre-record the uses of allocas so that we dont have to worry about
1764 // later update that changes the user information..
1765
Igor Laevsky285fe842015-05-19 16:29:43 +00001766 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001767 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001768 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1769 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001770 if (!isa<ConstantExpr>(U)) {
1771 // If the def has a ConstantExpr use, then the def is either a
1772 // ConstantExpr use itself or null. In either case
1773 // (recursively in the first, directly in the second), the oop
1774 // it is ultimately dependent on is null and this particular
1775 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001776 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001777 }
1778 }
1779
Igor Laevsky285fe842015-05-19 16:29:43 +00001780 std::sort(Uses.begin(), Uses.end());
1781 auto Last = std::unique(Uses.begin(), Uses.end());
1782 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001783
Igor Laevsky285fe842015-05-19 16:29:43 +00001784 for (Instruction *Use : Uses) {
1785 if (isa<PHINode>(Use)) {
1786 PHINode *Phi = cast<PHINode>(Use);
1787 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1788 if (Def == Phi->getIncomingValue(i)) {
1789 LoadInst *Load = new LoadInst(
1790 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1791 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001792 }
1793 }
1794 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001795 LoadInst *Load = new LoadInst(Alloca, "", Use);
1796 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001797 }
1798 }
1799
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001800 // Emit store for the initial gc value. Store must be inserted after load,
1801 // otherwise store will be in alloca's use list and an extra load will be
1802 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001803 StoreInst *Store = new StoreInst(Def, Alloca);
1804 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1805 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001806 // InvokeInst is a TerminatorInst so the store need to be inserted
1807 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001808 BasicBlock *NormalDest = Invoke->getNormalDest();
1809 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001810 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001811 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001812 "The only TerminatorInst that can produce a value is "
1813 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001814 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001815 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001816 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001817 assert(isa<Argument>(Def));
1818 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001819 }
1820 }
1821
Igor Laevsky285fe842015-05-19 16:29:43 +00001822 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001823 "we must have the same allocas with lives");
1824 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001825 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001826 PromoteMemToReg(PromotableAllocas, DT);
1827 }
1828
1829#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001830 for (auto &I : F.getEntryBlock())
1831 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001832 InitialAllocaNum--;
1833 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001834#endif
1835}
1836
1837/// Implement a unique function which doesn't require we sort the input
1838/// vector. Doing so has the effect of changing the output of a couple of
1839/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001840template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001841 SmallSet<T, 8> Seen;
1842 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1843 return !Seen.insert(V).second;
1844 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001845}
1846
Philip Reamesd16a9b12015-02-20 01:06:44 +00001847/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001848/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001849static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001850 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001851 if (Values.empty())
1852 // No values to hold live, might as well not insert the empty holder
1853 return;
1854
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001855 Module *M = CS.getInstruction()->getModule();
Philip Reamesf209a152015-04-13 20:00:30 +00001856 // Use a dummy vararg function to actually hold the values live
1857 Function *Func = cast<Function>(M->getOrInsertFunction(
1858 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001859 if (CS.isCall()) {
1860 // For call safepoints insert dummy calls right after safepoint
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001861 Holders.push_back(CallInst::Create(Func, Values, "",
1862 &*++CS.getInstruction()->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001863 return;
1864 }
1865 // For invoke safepooints insert dummy calls both in normal and
1866 // exceptional destination blocks
1867 auto *II = cast<InvokeInst>(CS.getInstruction());
1868 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001869 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001870 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001871 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001872}
1873
1874static void findLiveReferences(
Justin Bogner843fb202015-12-15 19:40:57 +00001875 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001876 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001877 GCPtrLivenessData OriginalLivenessData;
1878 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001879 for (size_t i = 0; i < records.size(); i++) {
1880 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001881 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001882 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001883 }
1884}
1885
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001886/// Remove any vector of pointers from the live set by scalarizing them over the
1887/// statepoint instruction. Adds the scalarized pieces to the live set. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001888/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001889/// the lowering code currently does not handle that. Extending it would be
1890/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001891/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001892static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001893 StatepointLiveSetTy &LiveSet,
1894 DenseMap<Value *, Value *>& PointerToBase,
1895 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001896 SmallVector<Value *, 16> ToSplit;
1897 for (Value *V : LiveSet)
1898 if (isa<VectorType>(V->getType()))
1899 ToSplit.push_back(V);
1900
1901 if (ToSplit.empty())
1902 return;
1903
Philip Reames8fe7f132015-06-26 22:47:37 +00001904 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1905
Philip Reames8531d8c2015-04-10 21:48:25 +00001906 Function &F = *(StatepointInst->getParent()->getParent());
1907
Philip Reames704e78b2015-04-10 22:34:56 +00001908 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001909 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001910 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001911 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001912 AllocaInst *Alloca =
1913 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001914 AllocaMap[V] = Alloca;
1915
1916 VectorType *VT = cast<VectorType>(V->getType());
1917 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001918 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001919 for (unsigned i = 0; i < VT->getNumElements(); i++)
1920 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001921 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001922
1923 auto InsertVectorReform = [&](Instruction *IP) {
1924 Builder.SetInsertPoint(IP);
1925 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1926 Value *ResultVec = UndefValue::get(VT);
1927 for (unsigned i = 0; i < VT->getNumElements(); i++)
1928 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1929 Builder.getInt32(i));
1930 return ResultVec;
1931 };
1932
1933 if (isa<CallInst>(StatepointInst)) {
1934 BasicBlock::iterator Next(StatepointInst);
1935 Next++;
1936 Instruction *IP = &*(Next);
1937 Replacements[V].first = InsertVectorReform(IP);
1938 Replacements[V].second = nullptr;
1939 } else {
1940 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1941 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001942 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001943 BasicBlock *NormalDest = Invoke->getNormalDest();
1944 assert(!isa<PHINode>(NormalDest->begin()));
1945 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1946 assert(!isa<PHINode>(UnwindDest->begin()));
1947 // Insert insert element sequences in both successors
1948 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1949 Replacements[V].first = InsertVectorReform(IP);
1950 IP = &*(UnwindDest->getFirstInsertionPt());
1951 Replacements[V].second = InsertVectorReform(IP);
1952 }
1953 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001954
Philip Reames8531d8c2015-04-10 21:48:25 +00001955 for (Value *V : ToSplit) {
1956 AllocaInst *Alloca = AllocaMap[V];
1957
1958 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001959 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001960 for (User *U : V->users())
1961 Users.push_back(cast<Instruction>(U));
1962
1963 for (Instruction *I : Users) {
1964 if (auto Phi = dyn_cast<PHINode>(I)) {
1965 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1966 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001967 LoadInst *Load = new LoadInst(
1968 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001969 Phi->setIncomingValue(i, Load);
1970 }
1971 } else {
1972 LoadInst *Load = new LoadInst(Alloca, "", I);
1973 I->replaceUsesOfWith(V, Load);
1974 }
1975 }
1976
1977 // Store the original value and the replacement value into the alloca
1978 StoreInst *Store = new StoreInst(V, Alloca);
1979 if (auto I = dyn_cast<Instruction>(V))
1980 Store->insertAfter(I);
1981 else
1982 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001983
Philip Reames8531d8c2015-04-10 21:48:25 +00001984 // Normal return for invoke, or call return
1985 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1986 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1987 // Unwind return for invoke only
1988 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1989 if (Replacement)
1990 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1991 }
1992
1993 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001994 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001995 for (Value *V : ToSplit)
1996 Allocas.push_back(AllocaMap[V]);
1997 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001998
1999 // Update our tracking of live pointers and base mappings to account for the
2000 // changes we just made.
2001 for (Value *V : ToSplit) {
2002 auto &Elements = ElementMapping[V];
2003
2004 LiveSet.erase(V);
2005 LiveSet.insert(Elements.begin(), Elements.end());
2006 // We need to update the base mapping as well.
2007 assert(PointerToBase.count(V));
2008 Value *OldBase = PointerToBase[V];
2009 auto &BaseElements = ElementMapping[OldBase];
2010 PointerToBase.erase(V);
2011 assert(Elements.size() == BaseElements.size());
2012 for (unsigned i = 0; i < Elements.size(); i++) {
2013 Value *Elem = Elements[i];
2014 PointerToBase[Elem] = BaseElements[i];
2015 }
2016 }
Philip Reames8531d8c2015-04-10 21:48:25 +00002017}
2018
Igor Laevskye0317182015-05-19 15:59:05 +00002019// Helper function for the "rematerializeLiveValues". It walks use chain
2020// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2021// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002022// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00002023// Fills "ChainToBase" array with all visited values. "BaseValue" is not
2024// recorded.
2025static bool findRematerializableChainToBasePointer(
2026 SmallVectorImpl<Instruction*> &ChainToBase,
2027 Value *CurrentValue, Value *BaseValue) {
2028
2029 // We have found a base value
2030 if (CurrentValue == BaseValue) {
2031 return true;
2032 }
2033
2034 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2035 ChainToBase.push_back(GEP);
2036 return findRematerializableChainToBasePointer(ChainToBase,
2037 GEP->getPointerOperand(),
2038 BaseValue);
2039 }
2040
2041 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
Igor Laevskye0317182015-05-19 15:59:05 +00002042 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2043 return false;
2044
2045 ChainToBase.push_back(CI);
Manuel Jacob9db5b932015-12-28 20:14:05 +00002046 return findRematerializableChainToBasePointer(ChainToBase,
2047 CI->getOperand(0), BaseValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002048 }
2049
2050 // Not supported instruction in the chain
2051 return false;
2052}
2053
2054// Helper function for the "rematerializeLiveValues". Compute cost of the use
2055// chain we are going to rematerialize.
2056static unsigned
2057chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2058 TargetTransformInfo &TTI) {
2059 unsigned Cost = 0;
2060
2061 for (Instruction *Instr : Chain) {
2062 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2063 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2064 "non noop cast is found during rematerialization");
2065
2066 Type *SrcTy = CI->getOperand(0)->getType();
2067 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2068
2069 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2070 // Cost of the address calculation
Eduard Burtescu19eb0312016-01-19 17:28:00 +00002071 Type *ValTy = GEP->getSourceElementType();
Igor Laevskye0317182015-05-19 15:59:05 +00002072 Cost += TTI.getAddressComputationCost(ValTy);
2073
2074 // And cost of the GEP itself
2075 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2076 // allowed for the external usage)
2077 if (!GEP->hasAllConstantIndices())
2078 Cost += 2;
2079
2080 } else {
2081 llvm_unreachable("unsupported instruciton type during rematerialization");
2082 }
2083 }
2084
2085 return Cost;
2086}
2087
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002088// From the statepoint live set pick values that are cheaper to recompute then
2089// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00002090// statepoint and record them in "Info" structure. Note that similar to
2091// relocated values we don't do any user adjustments here.
2092static void rematerializeLiveValues(CallSite CS,
2093 PartiallyConstructedSafepointRecord &Info,
2094 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002095 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002096
Igor Laevskye0317182015-05-19 15:59:05 +00002097 // Record values we are going to delete from this statepoint live set.
2098 // We can not di this in following loop due to iterator invalidation.
2099 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2100
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002101 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00002102 // For each live pointer find it's defining chain
2103 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002104 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002105 bool FoundChain =
2106 findRematerializableChainToBasePointer(ChainToBase,
2107 LiveValue,
2108 Info.PointerToBase[LiveValue]);
2109 // Nothing to do, or chain is too long
2110 if (!FoundChain ||
2111 ChainToBase.size() == 0 ||
2112 ChainToBase.size() > ChainLengthThreshold)
2113 continue;
2114
2115 // Compute cost of this chain
2116 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2117 // TODO: We can also account for cases when we will be able to remove some
2118 // of the rematerialized values by later optimization passes. I.e if
2119 // we rematerialized several intersecting chains. Or if original values
2120 // don't have any uses besides this statepoint.
2121
2122 // For invokes we need to rematerialize each chain twice - for normal and
2123 // for unwind basic blocks. Model this by multiplying cost by two.
2124 if (CS.isInvoke()) {
2125 Cost *= 2;
2126 }
2127 // If it's too expensive - skip it
2128 if (Cost >= RematerializationThreshold)
2129 continue;
2130
2131 // Remove value from the live set
2132 LiveValuesToBeDeleted.push_back(LiveValue);
2133
2134 // Clone instructions and record them inside "Info" structure
2135
2136 // Walk backwards to visit top-most instructions first
2137 std::reverse(ChainToBase.begin(), ChainToBase.end());
2138
2139 // Utility function which clones all instructions from "ChainToBase"
2140 // and inserts them before "InsertBefore". Returns rematerialized value
2141 // which should be used after statepoint.
2142 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2143 Instruction *LastClonedValue = nullptr;
2144 Instruction *LastValue = nullptr;
2145 for (Instruction *Instr: ChainToBase) {
2146 // Only GEP's and casts are suported as we need to be careful to not
2147 // introduce any new uses of pointers not in the liveset.
2148 // Note that it's fine to introduce new uses of pointers which were
2149 // otherwise not used after this statepoint.
2150 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2151
2152 Instruction *ClonedValue = Instr->clone();
2153 ClonedValue->insertBefore(InsertBefore);
2154 ClonedValue->setName(Instr->getName() + ".remat");
2155
2156 // If it is not first instruction in the chain then it uses previously
2157 // cloned value. We should update it to use cloned value.
2158 if (LastClonedValue) {
2159 assert(LastValue);
2160 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2161#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002162 // Assert that cloned instruction does not use any instructions from
2163 // this chain other than LastClonedValue
2164 for (auto OpValue : ClonedValue->operand_values()) {
2165 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2166 ChainToBase.end() &&
2167 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002168 }
2169#endif
2170 }
2171
2172 LastClonedValue = ClonedValue;
2173 LastValue = Instr;
2174 }
2175 assert(LastClonedValue);
2176 return LastClonedValue;
2177 };
2178
2179 // Different cases for calls and invokes. For invokes we need to clone
2180 // instructions both on normal and unwind path.
2181 if (CS.isCall()) {
2182 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2183 assert(InsertBefore);
2184 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2185 Info.RematerializedValues[RematerializedValue] = LiveValue;
2186 } else {
2187 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2188
2189 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002190 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002191 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002192 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002193
2194 Instruction *NormalRematerializedValue =
2195 rematerializeChain(NormalInsertBefore);
2196 Instruction *UnwindRematerializedValue =
2197 rematerializeChain(UnwindInsertBefore);
2198
2199 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2200 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2201 }
2202 }
2203
2204 // Remove rematerializaed values from the live set
2205 for (auto LiveValue: LiveValuesToBeDeleted) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002206 Info.LiveSet.erase(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002207 }
2208}
2209
Justin Bogner843fb202015-12-15 19:40:57 +00002210static bool insertParsePoints(Function &F, DominatorTree &DT,
2211 TargetTransformInfo &TTI,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002212 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002213#ifndef NDEBUG
2214 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002215 std::set<CallSite> Uniqued;
2216 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2217 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002218
Sanjoy Dasbcf27522016-01-29 01:03:20 +00002219 for (CallSite CS : ToUpdate)
2220 assert(CS.getInstruction()->getFunction() == &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002221#endif
2222
Philip Reames69e51ca2015-04-13 18:07:21 +00002223 // When inserting gc.relocates for invokes, we need to be able to insert at
2224 // the top of the successor blocks. See the comment on
2225 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002226 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002227 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002228 if (!CS.isInvoke())
2229 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002230 auto *II = cast<InvokeInst>(CS.getInstruction());
2231 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2232 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002233 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002234
Philip Reamesd16a9b12015-02-20 01:06:44 +00002235 // A list of dummy calls added to the IR to keep various values obviously
2236 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002237 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002238
2239 // Insert a dummy call with all of the arguments to the vm_state we'll need
2240 // for the actual safepoint insertion. This ensures reference arguments in
2241 // the deopt argument list are considered live through the safepoint (and
2242 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002243 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002244 SmallVector<Value *, 64> DeoptValues;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002245
Sanjoy Das40992972016-01-29 01:03:17 +00002246 for (Value *Arg : GetDeoptBundleOperands(CS)) {
Philip Reames8531d8c2015-04-10 21:48:25 +00002247 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2248 "support for FCA unimplemented");
2249 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002250 DeoptValues.push_back(Arg);
2251 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002252
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002253 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002254 }
2255
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002256 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002257
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002258 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002259 // site.
Justin Bogner843fb202015-12-15 19:40:57 +00002260 findLiveReferences(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002261
2262 // B) Find the base pointers for each live pointer
2263 /* scope for caching */ {
2264 // Cache the 'defining value' relation used in the computation and
2265 // insertion of base phis and selects. This ensures that we don't insert
2266 // large numbers of duplicate base_phis.
2267 DefiningValueMapTy DVCache;
2268
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002269 for (size_t i = 0; i < Records.size(); i++) {
2270 PartiallyConstructedSafepointRecord &info = Records[i];
2271 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002272 }
2273 } // end of cache scope
2274
2275 // The base phi insertion logic (for any safepoint) may have inserted new
2276 // instructions which are now live at some safepoint. The simplest such
2277 // example is:
2278 // loop:
2279 // phi a <-- will be a new base_phi here
2280 // safepoint 1 <-- that needs to be live here
2281 // gep a + 1
2282 // safepoint 2
2283 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002284 // We insert some dummy calls after each safepoint to definitely hold live
2285 // the base pointers which were identified for that safepoint. We'll then
2286 // ask liveness for _every_ base inserted to see what is now live. Then we
2287 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002288 Holders.reserve(Holders.size() + Records.size());
2289 for (size_t i = 0; i < Records.size(); i++) {
2290 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002291
2292 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002293 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002294 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002295
2296 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002297 }
2298
Philip Reamesdf1ef082015-04-10 22:53:14 +00002299 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2300 // need to rerun liveness. We may *also* have inserted new defs, but that's
2301 // not the key issue.
Justin Bogner843fb202015-12-15 19:40:57 +00002302 recomputeLiveInValues(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002303
Philip Reamesd16a9b12015-02-20 01:06:44 +00002304 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002305 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002306 errs() << "Base Pairs: (w/Relocation)\n";
Manuel Jacoba4efd8a2015-12-23 00:19:45 +00002307 for (auto Pair : Info.PointerToBase) {
2308 errs() << " derived ";
2309 Pair.first->printAsOperand(errs(), false);
2310 errs() << " base ";
2311 Pair.second->printAsOperand(errs(), false);
2312 errs() << "\n";
2313 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002314 }
2315 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002316
Manuel Jacob990dfa62015-12-22 16:50:44 +00002317 // It is possible that non-constant live variables have a constant base. For
2318 // example, a GEP with a variable offset from a global. In this case we can
2319 // remove it from the liveset. We already don't add constants to the liveset
2320 // because we assume they won't move at runtime and the GC doesn't need to be
2321 // informed about them. The same reasoning applies if the base is constant.
2322 // Note that the relocation placement code relies on this filtering for
2323 // correctness as it expects the base to be in the liveset, which isn't true
2324 // if the base is constant.
2325 for (auto &Info : Records)
2326 for (auto &BasePair : Info.PointerToBase)
2327 if (isa<Constant>(BasePair.second))
2328 Info.LiveSet.erase(BasePair.first);
2329
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002330 for (CallInst *CI : Holders)
2331 CI->eraseFromParent();
2332
2333 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002334
Philip Reames8fe7f132015-06-26 22:47:37 +00002335 // Do a limited scalarization of any live at safepoint vector values which
2336 // contain pointers. This enables this pass to run after vectorization at
Philip Reames103d2382016-01-07 02:20:11 +00002337 // the cost of some possible performance loss. Note: This is known to not
2338 // handle updating of the side tables correctly which can lead to relocation
2339 // bugs when the same vector is live at multiple statepoints. We're in the
2340 // process of implementing the alternate lowering - relocating the
2341 // vector-of-pointers as first class item and updating the backend to
2342 // understand that - but that's not yet complete.
2343 if (UseVectorSplit)
2344 for (size_t i = 0; i < Records.size(); i++) {
2345 PartiallyConstructedSafepointRecord &Info = Records[i];
2346 Instruction *Statepoint = ToUpdate[i].getInstruction();
2347 splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
2348 Info.PointerToBase, DT);
2349 }
Philip Reames8fe7f132015-06-26 22:47:37 +00002350
Igor Laevskye0317182015-05-19 15:59:05 +00002351 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002352 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002353 // does not influence correctness.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002354 for (size_t i = 0; i < Records.size(); i++)
2355 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002356
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002357 // We need this to safely RAUW and delete call or invoke return values that
2358 // may themselves be live over a statepoint. For details, please see usage in
2359 // makeStatepointExplicitImpl.
2360 std::vector<DeferredReplacement> Replacements;
2361
Philip Reamesd16a9b12015-02-20 01:06:44 +00002362 // Now run through and replace the existing statepoints with new ones with
2363 // the live variables listed. We do not yet update uses of the values being
2364 // relocated. We have references to live variables that need to
2365 // survive to the last iteration of this loop. (By construction, the
2366 // previous statepoint can not be a live variable, thus we can and remove
2367 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002368 for (size_t i = 0; i < Records.size(); i++)
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002369 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002370
2371 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002372
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002373 for (auto &PR : Replacements)
2374 PR.doReplacement();
2375
2376 Replacements.clear();
2377
2378 for (auto &Info : Records) {
2379 // These live sets may contain state Value pointers, since we replaced calls
2380 // with operand bundles with calls wrapped in gc.statepoint, and some of
2381 // those calls may have been def'ing live gc pointers. Clear these out to
2382 // avoid accidentally using them.
2383 //
2384 // TODO: We should create a separate data structure that does not contain
2385 // these live sets, and migrate to using that data structure from this point
2386 // onward.
2387 Info.LiveSet.clear();
2388 Info.PointerToBase.clear();
2389 }
2390
Philip Reamesd16a9b12015-02-20 01:06:44 +00002391 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002392 SmallVector<Value *, 128> Live;
2393 for (size_t i = 0; i < Records.size(); i++) {
2394 PartiallyConstructedSafepointRecord &Info = Records[i];
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002395
Philip Reamesd16a9b12015-02-20 01:06:44 +00002396 // We can't simply save the live set from the original insertion. One of
2397 // the live values might be the result of a call which needs a safepoint.
2398 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002399 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002400 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002401 Statepoint Statepoint(Info.StatepointToken);
2402 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2403 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002404#ifndef NDEBUG
2405 // Do some basic sanity checks on our liveness results before performing
2406 // relocation. Relocation can and will turn mistakes in liveness results
2407 // into non-sensical code which is must harder to debug.
2408 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002409 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002410 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002411 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002412 if (!isa<Instruction>(V))
2413 // Non-instruction values trivial dominate all possible uses
2414 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002415 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002416 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2417 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002418 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002419 "basic SSA liveness expectation violated by liveness analysis");
2420 }
2421#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002422 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002423 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002424
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002425#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002426 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002427 for (auto *Ptr : Live)
Philip Reames5715f572016-01-09 01:31:13 +00002428 assert(isHandledGCPointerType(Ptr->getType()) &&
2429 "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002430#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002431
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002432 relocationViaAlloca(F, DT, Live, Records);
2433 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002434}
2435
Sanjoy Das353a19e2015-06-02 22:33:37 +00002436// Handles both return values and arguments for Functions and CallSites.
2437template <typename AttrHolder>
Igor Laevskydde00292015-10-23 22:42:44 +00002438static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2439 unsigned Index) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002440 AttrBuilder R;
2441 if (AH.getDereferenceableBytes(Index))
2442 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2443 AH.getDereferenceableBytes(Index)));
2444 if (AH.getDereferenceableOrNullBytes(Index))
2445 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2446 AH.getDereferenceableOrNullBytes(Index)));
Igor Laevsky1ef06552015-10-26 19:06:01 +00002447 if (AH.doesNotAlias(Index))
2448 R.addAttribute(Attribute::NoAlias);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002449
2450 if (!R.empty())
2451 AH.setAttributes(AH.getAttributes().removeAttributes(
2452 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002453}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002454
2455void
Igor Laevskydde00292015-10-23 22:42:44 +00002456RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002457 LLVMContext &Ctx = F.getContext();
2458
2459 for (Argument &A : F.args())
2460 if (isa<PointerType>(A.getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002461 RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002462
2463 if (isa<PointerType>(F.getReturnType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002464 RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002465}
2466
Igor Laevskydde00292015-10-23 22:42:44 +00002467void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002468 if (F.empty())
2469 return;
2470
2471 LLVMContext &Ctx = F.getContext();
2472 MDBuilder Builder(Ctx);
2473
Nico Rieck78199512015-08-06 19:10:45 +00002474 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002475 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2476 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2477 bool IsImmutableTBAA =
2478 MD->getNumOperands() == 4 &&
2479 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2480
2481 if (!IsImmutableTBAA)
2482 continue; // no work to do, MD_tbaa is already marked mutable
2483
2484 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2485 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2486 uint64_t Offset =
2487 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2488
2489 MDNode *MutableTBAA =
2490 Builder.createTBAAStructTagNode(Base, Access, Offset);
2491 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2492 }
2493
2494 if (CallSite CS = CallSite(&I)) {
2495 for (int i = 0, e = CS.arg_size(); i != e; i++)
2496 if (isa<PointerType>(CS.getArgument(i)->getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002497 RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002498 if (isa<PointerType>(CS.getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002499 RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002500 }
2501 }
2502}
2503
Philip Reamesd16a9b12015-02-20 01:06:44 +00002504/// Returns true if this function should be rewritten by this pass. The main
2505/// point of this function is as an extension point for custom logic.
2506static bool shouldRewriteStatepointsIn(Function &F) {
2507 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002508 if (F.hasGC()) {
Mehdi Amini599ebf22016-01-08 02:28:20 +00002509 const auto &FunctionGCName = F.getGC();
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002510 const StringRef StatepointExampleName("statepoint-example");
2511 const StringRef CoreCLRName("coreclr");
2512 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002513 (CoreCLRName == FunctionGCName);
2514 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002515 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002516}
2517
Igor Laevskydde00292015-10-23 22:42:44 +00002518void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002519#ifndef NDEBUG
2520 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2521 "precondition!");
2522#endif
2523
2524 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002525 stripNonValidAttributesFromPrototype(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002526
2527 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002528 stripNonValidAttributesFromBody(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002529}
2530
Philip Reamesd16a9b12015-02-20 01:06:44 +00002531bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2532 // Nothing to do for declarations.
2533 if (F.isDeclaration() || F.empty())
2534 return false;
2535
2536 // Policy choice says not to rewrite - the most common reason is that we're
2537 // compiling code without a GCStrategy.
2538 if (!shouldRewriteStatepointsIn(F))
2539 return false;
2540
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002541 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00002542 TargetTransformInfo &TTI =
2543 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Philip Reames704e78b2015-04-10 22:34:56 +00002544
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002545 auto NeedsRewrite = [](Instruction &I) {
Sanjoy Das40992972016-01-29 01:03:17 +00002546 if (ImmutableCallSite CS = ImmutableCallSite(&I))
2547 return !callsGCLeafFunction(CS);
2548 return false;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002549 };
2550
Philip Reames85b36a82015-04-10 22:07:04 +00002551 // Gather all the statepoints which need rewritten. Be careful to only
2552 // consider those in reachable code since we need to ask dominance queries
2553 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002554 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002555 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002556 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002557 // TODO: only the ones with the flag set!
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002558 if (NeedsRewrite(I)) {
Philip Reames85b36a82015-04-10 22:07:04 +00002559 if (DT.isReachableFromEntry(I.getParent()))
2560 ParsePointNeeded.push_back(CallSite(&I));
2561 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002562 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002563 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002564 }
2565
Philip Reames85b36a82015-04-10 22:07:04 +00002566 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002567
Philip Reames85b36a82015-04-10 22:07:04 +00002568 // Delete any unreachable statepoints so that we don't have unrewritten
2569 // statepoints surviving this pass. This makes testing easier and the
2570 // resulting IR less confusing to human readers. Rather than be fancy, we
2571 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002572 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002573 MadeChange |= removeUnreachableBlocks(F);
2574
Philip Reamesd16a9b12015-02-20 01:06:44 +00002575 // Return early if no work to do.
2576 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002577 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002578
Philip Reames85b36a82015-04-10 22:07:04 +00002579 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2580 // These are created by LCSSA. They have the effect of increasing the size
2581 // of liveness sets for no good reason. It may be harder to do this post
2582 // insertion since relocations and base phis can confuse things.
2583 for (BasicBlock &BB : F)
2584 if (BB.getUniquePredecessor()) {
2585 MadeChange = true;
2586 FoldSingleEntryPHINodes(&BB);
2587 }
2588
Philip Reames971dc3a2015-08-12 22:11:45 +00002589 // Before we start introducing relocations, we want to tweak the IR a bit to
2590 // avoid unfortunate code generation effects. The main example is that we
2591 // want to try to make sure the comparison feeding a branch is after any
2592 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2593 // values feeding a branch after relocation. This is semantically correct,
2594 // but results in extra register pressure since both the pre-relocation and
2595 // post-relocation copies must be available in registers. For code without
2596 // relocations this is handled elsewhere, but teaching the scheduler to
2597 // reverse the transform we're about to do would be slightly complex.
2598 // Note: This may extend the live range of the inputs to the icmp and thus
2599 // increase the liveset of any statepoint we move over. This is profitable
2600 // as long as all statepoints are in rare blocks. If we had in-register
2601 // lowering for live values this would be a much safer transform.
2602 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2603 if (auto *BI = dyn_cast<BranchInst>(TI))
2604 if (BI->isConditional())
2605 return dyn_cast<Instruction>(BI->getCondition());
2606 // TODO: Extend this to handle switches
2607 return nullptr;
2608 };
2609 for (BasicBlock &BB : F) {
2610 TerminatorInst *TI = BB.getTerminator();
2611 if (auto *Cond = getConditionInst(TI))
2612 // TODO: Handle more than just ICmps here. We should be able to move
2613 // most instructions without side effects or memory access.
2614 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2615 MadeChange = true;
2616 Cond->moveBefore(TI);
2617 }
2618 }
2619
Justin Bogner843fb202015-12-15 19:40:57 +00002620 MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
Philip Reames85b36a82015-04-10 22:07:04 +00002621 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002622}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002623
2624// liveness computation via standard dataflow
2625// -------------------------------------------------------------------
2626
2627// TODO: Consider using bitvectors for liveness, the set of potentially
2628// interesting values should be small and easy to pre-compute.
2629
Philip Reamesdf1ef082015-04-10 22:53:14 +00002630/// Compute the live-in set for the location rbegin starting from
2631/// the live-out set of the basic block
2632static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2633 BasicBlock::reverse_iterator rend,
2634 DenseSet<Value *> &LiveTmp) {
2635
2636 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2637 Instruction *I = &*ritr;
2638
2639 // KILL/Def - Remove this definition from LiveIn
2640 LiveTmp.erase(I);
2641
2642 // Don't consider *uses* in PHI nodes, we handle their contribution to
2643 // predecessor blocks when we seed the LiveOut sets
2644 if (isa<PHINode>(I))
2645 continue;
2646
2647 // USE - Add to the LiveIn set for this instruction
2648 for (Value *V : I->operands()) {
2649 assert(!isUnhandledGCPointerType(V->getType()) &&
2650 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002651 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2652 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002653 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002654 // - We assume that things which are constant (from LLVM's definition)
2655 // do not move at runtime. For example, the address of a global
2656 // variable is fixed, even though it's contents may not be.
2657 // - Second, we can't disallow arbitrary inttoptr constants even
2658 // if the language frontend does. Optimization passes are free to
2659 // locally exploit facts without respect to global reachability. This
2660 // can create sections of code which are dynamically unreachable and
2661 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002662 LiveTmp.insert(V);
2663 }
2664 }
2665 }
2666}
2667
2668static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2669
2670 for (BasicBlock *Succ : successors(BB)) {
2671 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2672 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2673 PHINode *Phi = cast<PHINode>(&*I);
2674 Value *V = Phi->getIncomingValueForBlock(BB);
2675 assert(!isUnhandledGCPointerType(V->getType()) &&
2676 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002677 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002678 LiveTmp.insert(V);
2679 }
2680 }
2681 }
2682}
2683
2684static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2685 DenseSet<Value *> KillSet;
2686 for (Instruction &I : *BB)
2687 if (isHandledGCPointerType(I.getType()))
2688 KillSet.insert(&I);
2689 return KillSet;
2690}
2691
Philip Reames9638ff92015-04-11 00:06:47 +00002692#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002693/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2694/// sanity check for the liveness computation.
2695static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2696 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002697 for (Value *V : Live) {
2698 if (auto *I = dyn_cast<Instruction>(V)) {
2699 // The terminator can be a member of the LiveOut set. LLVM's definition
2700 // of instruction dominance states that V does not dominate itself. As
2701 // such, we need to special case this to allow it.
2702 if (TermOkay && TI == I)
2703 continue;
2704 assert(DT.dominates(I, TI) &&
2705 "basic SSA liveness expectation violated by liveness analysis");
2706 }
2707 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002708}
2709
2710/// Check that all the liveness sets used during the computation of liveness
2711/// obey basic SSA properties. This is useful for finding cases where we miss
2712/// a def.
2713static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2714 BasicBlock &BB) {
2715 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2716 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2717 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2718}
Philip Reames9638ff92015-04-11 00:06:47 +00002719#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002720
2721static void computeLiveInValues(DominatorTree &DT, Function &F,
2722 GCPtrLivenessData &Data) {
2723
Philip Reames4d80ede2015-04-10 23:11:26 +00002724 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002725 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002726 // We use a SetVector so that we don't have duplicates in the worklist.
2727 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002728 };
2729 auto NextItem = [&]() {
2730 BasicBlock *BB = Worklist.back();
2731 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002732 return BB;
2733 };
2734
2735 // Seed the liveness for each individual block
2736 for (BasicBlock &BB : F) {
2737 Data.KillSet[&BB] = computeKillSet(&BB);
2738 Data.LiveSet[&BB].clear();
2739 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2740
2741#ifndef NDEBUG
2742 for (Value *Kill : Data.KillSet[&BB])
2743 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2744#endif
2745
2746 Data.LiveOut[&BB] = DenseSet<Value *>();
2747 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2748 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2749 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2750 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2751 if (!Data.LiveIn[&BB].empty())
2752 AddPredsToWorklist(&BB);
2753 }
2754
2755 // Propagate that liveness until stable
2756 while (!Worklist.empty()) {
2757 BasicBlock *BB = NextItem();
2758
2759 // Compute our new liveout set, then exit early if it hasn't changed
2760 // despite the contribution of our successor.
2761 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2762 const auto OldLiveOutSize = LiveOut.size();
2763 for (BasicBlock *Succ : successors(BB)) {
2764 assert(Data.LiveIn.count(Succ));
2765 set_union(LiveOut, Data.LiveIn[Succ]);
2766 }
2767 // assert OutLiveOut is a subset of LiveOut
2768 if (OldLiveOutSize == LiveOut.size()) {
2769 // If the sets are the same size, then we didn't actually add anything
2770 // when unioning our successors LiveIn Thus, the LiveIn of this block
2771 // hasn't changed.
2772 continue;
2773 }
2774 Data.LiveOut[BB] = LiveOut;
2775
2776 // Apply the effects of this basic block
2777 DenseSet<Value *> LiveTmp = LiveOut;
2778 set_union(LiveTmp, Data.LiveSet[BB]);
2779 set_subtract(LiveTmp, Data.KillSet[BB]);
2780
2781 assert(Data.LiveIn.count(BB));
2782 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2783 // assert: OldLiveIn is a subset of LiveTmp
2784 if (OldLiveIn.size() != LiveTmp.size()) {
2785 Data.LiveIn[BB] = LiveTmp;
2786 AddPredsToWorklist(BB);
2787 }
2788 } // while( !worklist.empty() )
2789
2790#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002791 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002792 // missing kills during the above iteration.
2793 for (BasicBlock &BB : F) {
2794 checkBasicSSA(DT, Data, BB);
2795 }
2796#endif
2797}
2798
2799static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2800 StatepointLiveSetTy &Out) {
2801
2802 BasicBlock *BB = Inst->getParent();
2803
2804 // Note: The copy is intentional and required
2805 assert(Data.LiveOut.count(BB));
2806 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2807
2808 // We want to handle the statepoint itself oddly. It's
2809 // call result is not live (normal), nor are it's arguments
2810 // (unless they're used again later). This adjustment is
2811 // specifically what we need to relocate
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002812 BasicBlock::reverse_iterator rend(Inst->getIterator());
Philip Reamesdf1ef082015-04-10 22:53:14 +00002813 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2814 LiveOut.erase(Inst);
2815 Out.insert(LiveOut.begin(), LiveOut.end());
2816}
2817
2818static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2819 const CallSite &CS,
2820 PartiallyConstructedSafepointRecord &Info) {
2821 Instruction *Inst = CS.getInstruction();
2822 StatepointLiveSetTy Updated;
2823 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2824
2825#ifndef NDEBUG
2826 DenseSet<Value *> Bases;
2827 for (auto KVPair : Info.PointerToBase) {
2828 Bases.insert(KVPair.second);
2829 }
2830#endif
2831 // We may have base pointers which are now live that weren't before. We need
2832 // to update the PointerToBase structure to reflect this.
2833 for (auto V : Updated)
2834 if (!Info.PointerToBase.count(V)) {
2835 assert(Bases.count(V) && "can't find base for unexpected live value");
2836 Info.PointerToBase[V] = V;
2837 continue;
2838 }
2839
2840#ifndef NDEBUG
2841 for (auto V : Updated) {
2842 assert(Info.PointerToBase.count(V) &&
2843 "must be able to find base for live value");
2844 }
2845#endif
2846
2847 // Remove any stale base mappings - this can happen since our liveness is
2848 // more precise then the one inherent in the base pointer analysis
2849 DenseSet<Value *> ToErase;
2850 for (auto KVPair : Info.PointerToBase)
2851 if (!Updated.count(KVPair.first))
2852 ToErase.insert(KVPair.first);
2853 for (auto V : ToErase)
2854 Info.PointerToBase.erase(V);
2855
2856#ifndef NDEBUG
2857 for (auto KVPair : Info.PointerToBase)
2858 assert(Updated.count(KVPair.first) && "record for non-live value");
2859#endif
2860
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002861 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002862}