blob: 16ee5bbaecbc67f484afc21abc5570a6c5d9784b [file] [log] [blame]
Philip Reamesd16a9b12015-02-20 01:06:44 +00001//===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Rewrite an existing set of gc.statepoints such that they make potential
11// relocations performed by the garbage collector explicit in the IR.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Pass.h"
16#include "llvm/Analysis/CFG.h"
Philip Reamesabcdc5e2015-08-27 01:02:28 +000017#include "llvm/Analysis/InstructionSimplify.h"
Igor Laevskye0317182015-05-19 15:59:05 +000018#include "llvm/Analysis/TargetTransformInfo.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000019#include "llvm/ADT/SetOperations.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/ADT/DenseSet.h"
Philip Reames4d80ede2015-04-10 23:11:26 +000022#include "llvm/ADT/SetVector.h"
Swaroop Sridhar665bc9c2015-05-20 01:07:23 +000023#include "llvm/ADT/StringRef.h"
Philip Reames15d55632015-09-09 23:26:08 +000024#include "llvm/ADT/MapVector.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000025#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallSite.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
30#include "llvm/IR/InstIterator.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Module.h"
Sanjoy Das353a19e2015-06-02 22:33:37 +000035#include "llvm/IR/MDBuilder.h"
Philip Reamesd16a9b12015-02-20 01:06:44 +000036#include "llvm/IR/Statepoint.h"
37#include "llvm/IR/Value.h"
38#include "llvm/IR/Verifier.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/Transforms/Scalar.h"
42#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43#include "llvm/Transforms/Utils/Cloning.h"
44#include "llvm/Transforms/Utils/Local.h"
45#include "llvm/Transforms/Utils/PromoteMemToReg.h"
46
47#define DEBUG_TYPE "rewrite-statepoints-for-gc"
48
49using namespace llvm;
50
Philip Reamesd16a9b12015-02-20 01:06:44 +000051// Print the liveset found at the insert location
52static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
53 cl::init(false));
Philip Reames704e78b2015-04-10 22:34:56 +000054static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
55 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000056// Print out the base pointers for debugging
Philip Reames704e78b2015-04-10 22:34:56 +000057static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
58 cl::init(false));
Philip Reamesd16a9b12015-02-20 01:06:44 +000059
Igor Laevskye0317182015-05-19 15:59:05 +000060// Cost threshold measuring when it is profitable to rematerialize value instead
61// of relocating it
62static cl::opt<unsigned>
63RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
64 cl::init(6));
65
Philip Reamese73300b2015-04-13 16:41:32 +000066#ifdef XDEBUG
67static bool ClobberNonLive = true;
68#else
69static bool ClobberNonLive = false;
70#endif
71static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
72 cl::location(ClobberNonLive),
73 cl::Hidden);
74
Sanjoy Das25ec1a32015-10-16 02:41:00 +000075static cl::opt<bool> UseDeoptBundles("rs4gc-use-deopt-bundles", cl::Hidden,
76 cl::init(false));
77static cl::opt<bool>
78 AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info",
79 cl::Hidden, cl::init(true));
80
Benjamin Kramer6f665452015-02-20 14:00:58 +000081namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000082struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000083 static char ID; // Pass identification, replacement for typeid
84
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000085 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000086 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
87 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000088 bool runOnFunction(Function &F);
89 bool runOnModule(Module &M) override {
90 bool Changed = false;
91 for (Function &F : M)
92 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000093
94 if (Changed) {
Igor Laevskydde00292015-10-23 22:42:44 +000095 // stripNonValidAttributes asserts that shouldRewriteStatepointsIn
Sanjoy Das353a19e2015-06-02 22:33:37 +000096 // returns true for at least one function in the module. Since at least
97 // one function changed, we know that the precondition is satisfied.
Igor Laevskydde00292015-10-23 22:42:44 +000098 stripNonValidAttributes(M);
Sanjoy Das353a19e2015-06-02 22:33:37 +000099 }
100
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000101 return Changed;
102 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000103
104 void getAnalysisUsage(AnalysisUsage &AU) const override {
105 // We add and rewrite a bunch of instructions, but don't really do much
106 // else. We could in theory preserve a lot more analyses here.
107 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000108 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000109 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000110
111 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
112 /// dereferenceability that are no longer valid/correct after
113 /// RewriteStatepointsForGC has run. This is because semantically, after
114 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
Igor Laevskydde00292015-10-23 22:42:44 +0000115 /// heap. stripNonValidAttributes (conservatively) restores correctness
Sanjoy Das353a19e2015-06-02 22:33:37 +0000116 /// by erasing all attributes in the module that externally imply
117 /// dereferenceability.
Igor Laevsky1ef06552015-10-26 19:06:01 +0000118 /// Similar reasoning also applies to the noalias attributes. gc.statepoint
119 /// can touch the entire heap including noalias objects.
Igor Laevskydde00292015-10-23 22:42:44 +0000120 void stripNonValidAttributes(Module &M);
Sanjoy Das353a19e2015-06-02 22:33:37 +0000121
Igor Laevskydde00292015-10-23 22:42:44 +0000122 // Helpers for stripNonValidAttributes
123 void stripNonValidAttributesFromBody(Function &F);
124 void stripNonValidAttributesFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000125};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000126} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000127
128char RewriteStatepointsForGC::ID = 0;
129
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000130ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000131 return new RewriteStatepointsForGC();
132}
133
134INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
135 "Make relocations explicit at statepoints", false, false)
136INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
137INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
138 "Make relocations explicit at statepoints", false, false)
139
140namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000141struct GCPtrLivenessData {
142 /// Values defined in this block.
143 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
144 /// Values used in this block (and thus live); does not included values
145 /// killed within this block.
146 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
147
148 /// Values live into this basic block (i.e. used by any
149 /// instruction in this basic block or ones reachable from here)
150 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
151
152 /// Values live out of this basic block (i.e. live into
153 /// any successor block)
154 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
155};
156
Philip Reamesd16a9b12015-02-20 01:06:44 +0000157// The type of the internal cache used inside the findBasePointers family
158// of functions. From the callers perspective, this is an opaque type and
159// should not be inspected.
160//
161// In the actual implementation this caches two relations:
162// - The base relation itself (i.e. this pointer is based on that one)
163// - The base defining value relation (i.e. before base_phi insertion)
164// Generally, after the execution of a full findBasePointer call, only the
165// base relation will remain. Internally, we add a mixture of the two
166// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000167typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000168typedef DenseSet<Value *> StatepointLiveSetTy;
Sanjoy Das40bdd042015-10-07 21:32:35 +0000169typedef DenseMap<AssertingVH<Instruction>, AssertingVH<Value>>
170 RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000171
Philip Reamesd16a9b12015-02-20 01:06:44 +0000172struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000173 /// The set of values known to be live across this safepoint
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000174 StatepointLiveSetTy LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000175
176 /// Mapping from live pointers to a base-defining-value
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000177 DenseMap<Value *, Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000178
Philip Reames0a3240f2015-02-20 21:34:11 +0000179 /// The *new* gc.statepoint instruction itself. This produces the token
180 /// that normal path gc.relocates and the gc.result are tied to.
181 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000182
Philip Reamesf2041322015-02-20 19:26:04 +0000183 /// Instruction to which exceptional gc relocates are attached
184 /// Makes it easier to iterate through them during relocationViaAlloca.
185 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000186
187 /// Record live values we are rematerialized instead of relocating.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000188 /// They are not included into 'LiveSet' field.
Igor Laevskye0317182015-05-19 15:59:05 +0000189 /// Maps rematerialized copy to it's original value.
190 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000191};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000192}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000193
Sanjoy Das25ec1a32015-10-16 02:41:00 +0000194static ArrayRef<Use> GetDeoptBundleOperands(ImmutableCallSite CS) {
195 assert(UseDeoptBundles && "Should not be called otherwise!");
196
197 Optional<OperandBundleUse> DeoptBundle = CS.getOperandBundle("deopt");
198
199 if (!DeoptBundle.hasValue()) {
200 assert(AllowStatepointWithNoDeoptInfo &&
201 "Found non-leaf call without deopt info!");
202 return None;
203 }
204
205 return DeoptBundle.getValue().Inputs;
206}
207
Philip Reamesdf1ef082015-04-10 22:53:14 +0000208/// Compute the live-in set for every basic block in the function
209static void computeLiveInValues(DominatorTree &DT, Function &F,
210 GCPtrLivenessData &Data);
211
212/// Given results from the dataflow liveness computation, find the set of live
213/// Values at a particular instruction.
214static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
215 StatepointLiveSetTy &out);
216
Philip Reamesd16a9b12015-02-20 01:06:44 +0000217// TODO: Once we can get to the GCStrategy, this becomes
218// Optional<bool> isGCManagedPointer(const Value *V) const override {
219
Craig Toppere3dcce92015-08-01 22:20:21 +0000220static bool isGCPointerType(Type *T) {
221 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000222 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
223 // GC managed heap. We know that a pointer into this heap needs to be
224 // updated and that no other pointer does.
225 return (1 == PT->getAddressSpace());
226 return false;
227}
228
Philip Reames8531d8c2015-04-10 21:48:25 +0000229// Return true if this type is one which a) is a gc pointer or contains a GC
230// pointer and b) is of a type this code expects to encounter as a live value.
231// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000232// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000233static bool isHandledGCPointerType(Type *T) {
234 // We fully support gc pointers
235 if (isGCPointerType(T))
236 return true;
237 // We partially support vectors of gc pointers. The code will assert if it
238 // can't handle something.
239 if (auto VT = dyn_cast<VectorType>(T))
240 if (isGCPointerType(VT->getElementType()))
241 return true;
242 return false;
243}
244
245#ifndef NDEBUG
246/// Returns true if this type contains a gc pointer whether we know how to
247/// handle that type or not.
248static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000249 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000250 return true;
251 if (VectorType *VT = dyn_cast<VectorType>(Ty))
252 return isGCPointerType(VT->getScalarType());
253 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
254 return containsGCPtrType(AT->getElementType());
255 if (StructType *ST = dyn_cast<StructType>(Ty))
Craig Topperd896b032015-11-29 05:38:08 +0000256 return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
257 containsGCPtrType);
Philip Reames8531d8c2015-04-10 21:48:25 +0000258 return false;
259}
260
261// Returns true if this is a type which a) is a gc pointer or contains a GC
262// pointer and b) is of a type which the code doesn't expect (i.e. first class
263// aggregates). Used to trip assertions.
264static bool isUnhandledGCPointerType(Type *Ty) {
265 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
266}
267#endif
268
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000269static bool order_by_name(Value *a, Value *b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000270 if (a->hasName() && b->hasName()) {
271 return -1 == a->getName().compare(b->getName());
272 } else if (a->hasName() && !b->hasName()) {
273 return true;
274 } else if (!a->hasName() && b->hasName()) {
275 return false;
276 } else {
277 // Better than nothing, but not stable
278 return a < b;
279 }
280}
281
Philip Reamesece70b82015-09-09 23:57:18 +0000282// Return the name of the value suffixed with the provided value, or if the
283// value didn't have a name, the default value specified.
284static std::string suffixed_name_or(Value *V, StringRef Suffix,
285 StringRef DefaultName) {
286 return V->hasName() ? (V->getName() + Suffix).str() : DefaultName.str();
287}
288
Philip Reamesdf1ef082015-04-10 22:53:14 +0000289// Conservatively identifies any definitions which might be live at the
290// given instruction. The analysis is performed immediately before the
291// given instruction. Values defined by that instruction are not considered
292// live. Values used by that instruction are considered live.
293static void analyzeParsePointLiveness(
294 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
295 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000296 Instruction *inst = CS.getInstruction();
297
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000298 StatepointLiveSetTy LiveSet;
299 findLiveSetAtInst(inst, OriginalLivenessData, LiveSet);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000300
301 if (PrintLiveSet) {
302 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000303 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000304 // by name
Philip Reamesdab35f32015-09-02 21:11:44 +0000305 SmallVector<Value *, 64> Temp;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000306 Temp.insert(Temp.end(), LiveSet.begin(), LiveSet.end());
Philip Reamesdab35f32015-09-02 21:11:44 +0000307 std::sort(Temp.begin(), Temp.end(), order_by_name);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000308 errs() << "Live Variables:\n";
Philip Reamesdab35f32015-09-02 21:11:44 +0000309 for (Value *V : Temp)
310 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000311 }
312 if (PrintLiveSetSize) {
313 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000314 errs() << "Number live values: " << LiveSet.size() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000315 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +0000316 result.LiveSet = LiveSet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000317}
318
Philip Reamesf5b8e472015-09-03 21:34:30 +0000319static bool isKnownBaseResult(Value *V);
320namespace {
321/// A single base defining value - An immediate base defining value for an
322/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
323/// For instructions which have multiple pointer [vector] inputs or that
324/// transition between vector and scalar types, there is no immediate base
325/// defining value. The 'base defining value' for 'Def' is the transitive
326/// closure of this relation stopping at the first instruction which has no
327/// immediate base defining value. The b.d.v. might itself be a base pointer,
328/// but it can also be an arbitrary derived pointer.
329struct BaseDefiningValueResult {
330 /// Contains the value which is the base defining value.
331 Value * const BDV;
332 /// True if the base defining value is also known to be an actual base
333 /// pointer.
334 const bool IsKnownBase;
335 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
336 : BDV(BDV), IsKnownBase(IsKnownBase) {
337#ifndef NDEBUG
338 // Check consistency between new and old means of checking whether a BDV is
339 // a base.
340 bool MustBeBase = isKnownBaseResult(BDV);
341 assert(!MustBeBase || MustBeBase == IsKnownBase);
342#endif
343 }
344};
345}
346
347static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000348
Philip Reames8fe7f132015-06-26 22:47:37 +0000349/// Return a base defining value for the 'Index' element of the given vector
350/// instruction 'I'. If Index is null, returns a BDV for the entire vector
351/// 'I'. As an optimization, this method will try to determine when the
352/// element is known to already be a base pointer. If this can be established,
353/// the second value in the returned pair will be true. Note that either a
354/// vector or a pointer typed value can be returned. For the former, the
355/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
356/// If the later, the return pointer is a BDV (or possibly a base) for the
357/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000358static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000359findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000360 assert(I->getType()->isVectorTy() &&
361 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
362 "Illegal to ask for the base pointer of a non-pointer type");
363
364 // Each case parallels findBaseDefiningValue below, see that code for
365 // detailed motivation.
366
367 if (isa<Argument>(I))
368 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000369 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000370
371 // We shouldn't see the address of a global as a vector value?
372 assert(!isa<GlobalVariable>(I) &&
373 "unexpected global variable found in base of vector");
374
375 // inlining could possibly introduce phi node that contains
376 // undef if callee has multiple returns
377 if (isa<UndefValue>(I))
378 // utterly meaningless, but useful for dealing with partially optimized
379 // code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000380 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000381
382 // Due to inheritance, this must be _after_ the global variable and undef
383 // checks
384 if (Constant *Con = dyn_cast<Constant>(I)) {
385 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
386 "order of checks wrong!");
387 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000388 return BaseDefiningValueResult(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000389 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000390
Philip Reames8531d8c2015-04-10 21:48:25 +0000391 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000392 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000393
Philip Reames66287132015-09-09 23:40:12 +0000394 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000395 // We don't know whether this vector contains entirely base pointers or
396 // not. To be conservatively correct, we treat it as a BDV and will
397 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000398 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000399
Philip Reames8fe7f132015-06-26 22:47:37 +0000400 if (isa<ShuffleVectorInst>(I))
401 // We don't know whether this vector contains entirely base pointers or
402 // not. To be conservatively correct, we treat it as a BDV and will
403 // duplicate code as needed to construct a parallel vector of bases.
404 // TODO: There a number of local optimizations which could be applied here
405 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000406 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000407
408 // A PHI or Select is a base defining value. The outer findBasePointer
409 // algorithm is responsible for constructing a base value for this BDV.
410 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
411 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000412 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000413}
414
Philip Reamesd16a9b12015-02-20 01:06:44 +0000415/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000416/// defines the base pointer for the input, b) blocks the simple search
417/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
418/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000419static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000420 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000421 return findBaseDefiningValueOfVector(I);
Philip Reames8fe7f132015-06-26 22:47:37 +0000422
Philip Reamesd16a9b12015-02-20 01:06:44 +0000423 assert(I->getType()->isPointerTy() &&
424 "Illegal to ask for the base pointer of a non-pointer type");
425
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000426 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000427 // An incoming argument to the function is a base pointer
428 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000429 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000430
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000431 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000432 // base case
Philip Reamesf5b8e472015-09-03 21:34:30 +0000433 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000434
435 // inlining could possibly introduce phi node that contains
436 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000437 if (isa<UndefValue>(I))
438 // utterly meaningless, but useful for dealing with
439 // partially optimized code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000440 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000441
442 // Due to inheritance, this must be _after_ the global variable and undef
443 // checks
Philip Reames3ea15892015-09-03 21:57:40 +0000444 if (isa<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000445 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
446 "order of checks wrong!");
Philip Reames5d546892015-12-19 02:38:22 +0000447 // Note: Even for frontends which don't have constant references, we can
448 // see constants appearing after optimizations. A simple example is
449 // specialization of an address computation on null feeding into a merge
450 // point where the actual use of the now-constant input is protected by
451 // another null check. (e.g. test4 in constants.ll)
Philip Reamesf5b8e472015-09-03 21:34:30 +0000452 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000453 }
454
455 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000456 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000457 // If we find a cast instruction here, it means we've found a cast which is
458 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
459 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000460 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
461 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000462 }
463
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000464 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000465 // The value loaded is an gc base itself
466 return BaseDefiningValueResult(I, true);
467
Philip Reamesd16a9b12015-02-20 01:06:44 +0000468
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000469 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
470 // The base of this GEP is the base
471 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000472
473 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
474 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000475 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000476 default:
477 // fall through to general call handling
478 break;
479 case Intrinsic::experimental_gc_statepoint:
480 case Intrinsic::experimental_gc_result_float:
481 case Intrinsic::experimental_gc_result_int:
482 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000483 case Intrinsic::experimental_gc_relocate: {
484 // Rerunning safepoint insertion after safepoints are already
485 // inserted is not supported. It could probably be made to work,
486 // but why are you doing this? There's no good reason.
487 llvm_unreachable("repeat safepoint insertion is not supported");
488 }
489 case Intrinsic::gcroot:
490 // Currently, this mechanism hasn't been extended to work with gcroot.
491 // There's no reason it couldn't be, but I haven't thought about the
492 // implications much.
493 llvm_unreachable(
494 "interaction with the gcroot mechanism is not supported");
495 }
496 }
497 // We assume that functions in the source language only return base
498 // pointers. This should probably be generalized via attributes to support
499 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000500 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000501 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000502
503 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000504 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000505 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
506
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000507 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000508 // A CAS is effectively a atomic store and load combined under a
509 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000510 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000511 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000512
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000513 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000514 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000515
516 // The aggregate ops. Aggregates can either be in the heap or on the
517 // stack, but in either case, this is simply a field load. As a result,
518 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000519 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000520 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000521
522 // We should never see an insert vector since that would require we be
523 // tracing back a struct value not a pointer value.
524 assert(!isa<InsertValueInst>(I) &&
525 "Base pointer for a struct is meaningless");
526
Philip Reames9ac4e382015-08-12 21:00:20 +0000527 // An extractelement produces a base result exactly when it's input does.
528 // We may need to insert a parallel instruction to extract the appropriate
529 // element out of the base vector corresponding to the input. Given this,
530 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000531 if (isa<ExtractElementInst>(I))
532 // Note: There a lot of obvious peephole cases here. This are deliberately
533 // handled after the main base pointer inference algorithm to make writing
534 // test cases to exercise that code easier.
535 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000536
Philip Reamesd16a9b12015-02-20 01:06:44 +0000537 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000538 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000539 // derived pointers (each with it's own base potentially). It's the job of
540 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000541 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000542 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000543 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000544}
545
546/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000547static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
548 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000549 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000550 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000551 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
552 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000553 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000554 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000555 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000556}
557
558/// Return a base pointer for this value if known. Otherwise, return it's
559/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000560static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
561 Value *Def = findBaseDefiningValueCached(I, Cache);
562 auto Found = Cache.find(Def);
563 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000564 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000565 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000566 }
567 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000568 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000569}
570
571/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
572/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000573static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000574 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
575 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
576 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000577 // no recursion possible
578 return true;
579 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000580 if (isa<Instruction>(V) &&
581 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000582 // This is a previously inserted base phi or select. We know
583 // that this is a base value.
584 return true;
585 }
586
587 // We need to keep searching
588 return false;
589}
590
Philip Reamesd16a9b12015-02-20 01:06:44 +0000591namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000592/// Models the state of a single base defining value in the findBasePointer
593/// algorithm for determining where a new instruction is needed to propagate
594/// the base of this BDV.
595class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000596public:
597 enum Status { Unknown, Base, Conflict };
598
Philip Reames9b141ed2015-07-23 22:49:14 +0000599 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000600 assert(status != Base || b);
601 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000602 explicit BDVState(Value *b) : status(Base), base(b) {}
603 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000604
605 Status getStatus() const { return status; }
606 Value *getBase() const { return base; }
607
608 bool isBase() const { return getStatus() == Base; }
609 bool isUnknown() const { return getStatus() == Unknown; }
610 bool isConflict() const { return getStatus() == Conflict; }
611
Philip Reames9b141ed2015-07-23 22:49:14 +0000612 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000613 return base == other.base && status == other.status;
614 }
615
Philip Reames9b141ed2015-07-23 22:49:14 +0000616 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000617
Philip Reames2a892a62015-07-23 22:25:26 +0000618 LLVM_DUMP_METHOD
619 void dump() const { print(dbgs()); dbgs() << '\n'; }
620
621 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000622 switch (status) {
623 case Unknown:
624 OS << "U";
625 break;
626 case Base:
627 OS << "B";
628 break;
629 case Conflict:
630 OS << "C";
631 break;
632 };
633 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000634 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000635 }
636
637private:
638 Status status;
Philip Reamesdd0948a2015-12-18 03:53:28 +0000639 AssertingVH<Value> base; // non null only if status == base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000640};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000641}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000642
Philip Reames6906e922015-09-02 21:57:17 +0000643#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000644static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000645 State.print(OS);
646 return OS;
647}
Philip Reames6906e922015-09-02 21:57:17 +0000648#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000649
Philip Reamesb3967cd2015-09-02 22:30:53 +0000650namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000651// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000652// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000653// operation is implemented in MeetBDVStates::pureMeet
654class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000655public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000656 /// Initializes the currentResult to the TOP state so that if can be met with
657 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000658 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000659
Philip Reames9b141ed2015-07-23 22:49:14 +0000660 // Destructively meet the current result with the given BDVState
661 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000662 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000663 }
664
Philip Reames9b141ed2015-07-23 22:49:14 +0000665 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000666
667private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000668 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000669
Philip Reames9b141ed2015-07-23 22:49:14 +0000670 /// Perform a meet operation on two elements of the BDVState lattice.
671 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000672 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
673 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000674 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000675 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
676 << " produced " << Result << "\n");
677 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000678 }
679
Philip Reames9b141ed2015-07-23 22:49:14 +0000680 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000681 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000682 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000683 return stateB;
684
Philip Reames9b141ed2015-07-23 22:49:14 +0000685 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000686 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000687 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000688 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000689
690 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000691 if (stateA.getBase() == stateB.getBase()) {
692 assert(stateA == stateB && "equality broken!");
693 return stateA;
694 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000695 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000696 }
David Blaikie82ad7872015-02-20 23:44:24 +0000697 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000698 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000699
Philip Reames9b141ed2015-07-23 22:49:14 +0000700 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000701 return stateA;
702 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000703 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000704 }
705};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000706}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000707
708
Philip Reamesd16a9b12015-02-20 01:06:44 +0000709/// For a given value or instruction, figure out what base ptr it's derived
710/// from. For gc objects, this is simply itself. On success, returns a value
711/// which is the base pointer. (This is reliable and can be used for
712/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000713static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000714 Value *def = findBaseOrBDV(I, cache);
715
716 if (isKnownBaseResult(def)) {
717 return def;
718 }
719
720 // Here's the rough algorithm:
721 // - For every SSA value, construct a mapping to either an actual base
722 // pointer or a PHI which obscures the base pointer.
723 // - Construct a mapping from PHI to unknown TOP state. Use an
724 // optimistic algorithm to propagate base pointer information. Lattice
725 // looks like:
726 // UNKNOWN
727 // b1 b2 b3 b4
728 // CONFLICT
729 // When algorithm terminates, all PHIs will either have a single concrete
730 // base or be in a conflict state.
731 // - For every conflict, insert a dummy PHI node without arguments. Add
732 // these to the base[Instruction] = BasePtr mapping. For every
733 // non-conflict, add the actual base.
734 // - For every conflict, add arguments for the base[a] of each input
735 // arguments.
736 //
737 // Note: A simpler form of this would be to add the conflict form of all
738 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000739 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000740 // overall worse solution.
741
Philip Reames29e9ae72015-07-24 00:42:55 +0000742#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000743 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000744 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
745 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000746 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000747#endif
Philip Reames88958b22015-07-24 00:02:11 +0000748
749 // Once populated, will contain a mapping from each potentially non-base BDV
750 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000751 // We use the order of insertion (DFS over the def/use graph) to provide a
752 // stable deterministic ordering for visiting DenseMaps (which are unordered)
753 // below. This is important for deterministic compilation.
Philip Reames34d7a742015-09-10 00:22:49 +0000754 MapVector<Value *, BDVState> States;
Philip Reames15d55632015-09-09 23:26:08 +0000755
756 // Recursively fill in all base defining values reachable from the initial
757 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000758 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000759 SmallVector<Value*, 16> Worklist;
760 Worklist.push_back(def);
Philip Reames34d7a742015-09-10 00:22:49 +0000761 States.insert(std::make_pair(def, BDVState()));
Philip Reames88958b22015-07-24 00:02:11 +0000762 while (!Worklist.empty()) {
763 Value *Current = Worklist.pop_back_val();
764 assert(!isKnownBaseResult(Current) && "why did it get added?");
765
766 auto visitIncomingValue = [&](Value *InVal) {
767 Value *Base = findBaseOrBDV(InVal, cache);
768 if (isKnownBaseResult(Base))
769 // Known bases won't need new instructions introduced and can be
770 // ignored safely
771 return;
772 assert(isExpectedBDVType(Base) && "the only non-base values "
773 "we see should be base defining values");
Philip Reames34d7a742015-09-10 00:22:49 +0000774 if (States.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000775 Worklist.push_back(Base);
776 };
777 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
778 for (Value *InVal : Phi->incoming_values())
779 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000780 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000781 visitIncomingValue(Sel->getTrueValue());
782 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000783 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
784 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000785 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
786 visitIncomingValue(IE->getOperand(0)); // vector operand
787 visitIncomingValue(IE->getOperand(1)); // scalar operand
Philip Reames9ac4e382015-08-12 21:00:20 +0000788 } else {
Philip Reames66287132015-09-09 23:40:12 +0000789 // There is one known class of instructions we know we don't handle.
790 assert(isa<ShuffleVectorInst>(Current));
Philip Reames9ac4e382015-08-12 21:00:20 +0000791 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000792 }
793 }
794 }
795
Philip Reamesdab35f32015-09-02 21:11:44 +0000796#ifndef NDEBUG
797 DEBUG(dbgs() << "States after initialization:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000798 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000799 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000800 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000801#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000802
Philip Reames273e6bb2015-07-23 21:41:27 +0000803 // Return a phi state for a base defining value. We'll generate a new
804 // base state for known bases and expect to find a cached state otherwise.
805 auto getStateForBDV = [&](Value *baseValue) {
806 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000807 return BDVState(baseValue);
Philip Reames34d7a742015-09-10 00:22:49 +0000808 auto I = States.find(baseValue);
809 assert(I != States.end() && "lookup failed!");
Philip Reames273e6bb2015-07-23 21:41:27 +0000810 return I->second;
811 };
812
Philip Reamesd16a9b12015-02-20 01:06:44 +0000813 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000814 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000815#ifndef NDEBUG
Philip Reamesb4e55f32015-09-10 00:32:56 +0000816 const size_t oldSize = States.size();
Yaron Keren42a7adf2015-02-28 13:11:24 +0000817#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000818 progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000819 // We're only changing values in this loop, thus safe to keep iterators.
820 // Since this is computing a fixed point, the order of visit does not
821 // effect the result. TODO: We could use a worklist here and make this run
822 // much faster.
Philip Reames34d7a742015-09-10 00:22:49 +0000823 for (auto Pair : States) {
Philip Reamesece70b82015-09-09 23:57:18 +0000824 Value *BDV = Pair.first;
825 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000826
Philip Reames9b141ed2015-07-23 22:49:14 +0000827 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000828 // instance which represents the BDV of that value.
829 auto getStateForInput = [&](Value *V) mutable {
830 Value *BDV = findBaseOrBDV(V, cache);
831 return getStateForBDV(BDV);
832 };
833
Philip Reames9b141ed2015-07-23 22:49:14 +0000834 MeetBDVStates calculateMeet;
Philip Reamesece70b82015-09-09 23:57:18 +0000835 if (SelectInst *select = dyn_cast<SelectInst>(BDV)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000836 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
837 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reamesece70b82015-09-09 23:57:18 +0000838 } else if (PHINode *Phi = dyn_cast<PHINode>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000839 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000840 calculateMeet.meetWith(getStateForInput(Val));
Philip Reamesece70b82015-09-09 23:57:18 +0000841 } else if (auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000842 // The 'meet' for an extractelement is slightly trivial, but it's still
843 // useful in that it drives us to conflict if our input is.
Philip Reames9ac4e382015-08-12 21:00:20 +0000844 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
Philip Reames66287132015-09-09 23:40:12 +0000845 } else {
846 // Given there's a inherent type mismatch between the operands, will
847 // *always* produce Conflict.
Philip Reamesece70b82015-09-09 23:57:18 +0000848 auto *IE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +0000849 calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
850 calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000851 }
852
Philip Reames34d7a742015-09-10 00:22:49 +0000853 BDVState oldState = States[BDV];
Philip Reames9b141ed2015-07-23 22:49:14 +0000854 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000855 if (oldState != newState) {
856 progress = true;
Philip Reames34d7a742015-09-10 00:22:49 +0000857 States[BDV] = newState;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000858 }
859 }
860
Philip Reamesb4e55f32015-09-10 00:32:56 +0000861 assert(oldSize == States.size() &&
862 "fixed point shouldn't be adding any new nodes to state");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000863 }
864
Philip Reamesdab35f32015-09-02 21:11:44 +0000865#ifndef NDEBUG
866 DEBUG(dbgs() << "States after meet iteration:\n");
Philip Reames34d7a742015-09-10 00:22:49 +0000867 for (auto Pair : States) {
Philip Reamesdab35f32015-09-02 21:11:44 +0000868 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000869 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000870#endif
871
Philip Reamesd16a9b12015-02-20 01:06:44 +0000872 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000873 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames34d7a742015-09-10 00:22:49 +0000874 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +0000875 Instruction *I = cast<Instruction>(Pair.first);
876 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000877 assert(!isKnownBaseResult(I) && "why did it get added?");
878 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000879
880 // extractelement instructions are a bit special in that we may need to
881 // insert an extract even when we know an exact base for the instruction.
882 // The problem is that we need to convert from a vector base to a scalar
883 // base for the particular indice we're interested in.
884 if (State.isBase() && isa<ExtractElementInst>(I) &&
885 isa<VectorType>(State.getBase()->getType())) {
886 auto *EE = cast<ExtractElementInst>(I);
887 // TODO: In many cases, the new instruction is just EE itself. We should
888 // exploit this, but can't do it here since it would break the invariant
889 // about the BDV not being known to be a base.
890 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
891 EE->getIndexOperand(),
892 "base_ee", EE);
893 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000894 States[I] = BDVState(BDVState::Base, BaseInst);
Philip Reames9ac4e382015-08-12 21:00:20 +0000895 }
Philip Reames66287132015-09-09 23:40:12 +0000896
897 // Since we're joining a vector and scalar base, they can never be the
898 // same. As a result, we should always see insert element having reached
899 // the conflict state.
900 if (isa<InsertElementInst>(I)) {
901 assert(State.isConflict());
902 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000903
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000904 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000905 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000906
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000907 /// Create and insert a new instruction which will represent the base of
908 /// the given instruction 'I'.
909 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
910 if (isa<PHINode>(I)) {
911 BasicBlock *BB = I->getParent();
912 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
913 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesece70b82015-09-09 23:57:18 +0000914 std::string Name = suffixed_name_or(I, ".base", "base_phi");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000915 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000916 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
917 // The undef will be replaced later
918 UndefValue *Undef = UndefValue::get(Sel->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000919 std::string Name = suffixed_name_or(I, ".base", "base_select");
Philip Reames9ac4e382015-08-12 21:00:20 +0000920 return SelectInst::Create(Sel->getCondition(), Undef,
921 Undef, Name, Sel);
Philip Reames66287132015-09-09 23:40:12 +0000922 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000923 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000924 std::string Name = suffixed_name_or(I, ".base", "base_ee");
Philip Reames9ac4e382015-08-12 21:00:20 +0000925 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
926 EE);
Philip Reames66287132015-09-09 23:40:12 +0000927 } else {
928 auto *IE = cast<InsertElementInst>(I);
929 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
930 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
Philip Reamesece70b82015-09-09 23:57:18 +0000931 std::string Name = suffixed_name_or(I, ".base", "base_ie");
Philip Reames66287132015-09-09 23:40:12 +0000932 return InsertElementInst::Create(VecUndef, ScalarUndef,
933 IE->getOperand(2), Name, IE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000934 }
Philip Reames66287132015-09-09 23:40:12 +0000935
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000936 };
937 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
938 // Add metadata marking this as a base value
939 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames34d7a742015-09-10 00:22:49 +0000940 States[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000941 }
942
Philip Reames3ea15892015-09-03 21:57:40 +0000943 // Returns a instruction which produces the base pointer for a given
944 // instruction. The instruction is assumed to be an input to one of the BDVs
945 // seen in the inference algorithm above. As such, we must either already
946 // know it's base defining value is a base, or have inserted a new
947 // instruction to propagate the base of it's BDV and have entered that newly
948 // introduced instruction into the state table. In either case, we are
949 // assured to be able to determine an instruction which produces it's base
950 // pointer.
951 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
952 Value *BDV = findBaseOrBDV(Input, cache);
953 Value *Base = nullptr;
954 if (isKnownBaseResult(BDV)) {
955 Base = BDV;
956 } else {
957 // Either conflict or base.
Philip Reames34d7a742015-09-10 00:22:49 +0000958 assert(States.count(BDV));
959 Base = States[BDV].getBase();
Philip Reames3ea15892015-09-03 21:57:40 +0000960 }
961 assert(Base && "can't be null");
962 // The cast is needed since base traversal may strip away bitcasts
963 if (Base->getType() != Input->getType() &&
964 InsertPt) {
965 Base = new BitCastInst(Base, Input->getType(), "cast",
966 InsertPt);
967 }
968 return Base;
969 };
970
Philip Reames15d55632015-09-09 23:26:08 +0000971 // Fixup all the inputs of the new PHIs. Visit order needs to be
972 // deterministic and predictable because we're naming newly created
973 // instructions.
Philip Reames34d7a742015-09-10 00:22:49 +0000974 for (auto Pair : States) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000975 Instruction *BDV = cast<Instruction>(Pair.first);
Philip Reamesc8ded462015-09-10 00:27:50 +0000976 BDVState State = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000977
Philip Reames7540e3a2015-09-10 00:01:53 +0000978 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesc8ded462015-09-10 00:27:50 +0000979 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
980 if (!State.isConflict())
Philip Reames28e61ce2015-02-28 01:57:44 +0000981 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000982
Philip Reamesc8ded462015-09-10 00:27:50 +0000983 if (PHINode *basephi = dyn_cast<PHINode>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +0000984 PHINode *phi = cast<PHINode>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +0000985 unsigned NumPHIValues = phi->getNumIncomingValues();
986 for (unsigned i = 0; i < NumPHIValues; i++) {
987 Value *InVal = phi->getIncomingValue(i);
988 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000989
Philip Reames28e61ce2015-02-28 01:57:44 +0000990 // If we've already seen InBB, add the same incoming value
991 // we added for it earlier. The IR verifier requires phi
992 // nodes with multiple entries from the same basic block
993 // to have the same incoming value for each of those
994 // entries. If we don't do this check here and basephi
995 // has a different type than base, we'll end up adding two
996 // bitcasts (and hence two distinct values) as incoming
997 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000998
Philip Reames28e61ce2015-02-28 01:57:44 +0000999 int blockIndex = basephi->getBasicBlockIndex(InBB);
1000 if (blockIndex != -1) {
1001 Value *oldBase = basephi->getIncomingValue(blockIndex);
1002 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +00001003
Philip Reamesd16a9b12015-02-20 01:06:44 +00001004#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +00001005 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001006 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +00001007 // values incoming from the same basic block may be
1008 // different is by being different bitcasts of the same
1009 // value. A cleanup that remains TODO is changing
1010 // findBaseOrBDV to return an llvm::Value of the correct
1011 // type (and still remain pure). This will remove the
1012 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +00001013 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +00001014 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001015#endif
Philip Reames28e61ce2015-02-28 01:57:44 +00001016 continue;
1017 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001018
Philip Reames3ea15892015-09-03 21:57:40 +00001019 // Find the instruction which produces the base for each input. We may
1020 // need to insert a bitcast in the incoming block.
1021 // TODO: Need to split critical edges if insertion is needed
1022 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1023 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001024 }
1025 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reamesc8ded462015-09-10 00:27:50 +00001026 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001027 SelectInst *Sel = cast<SelectInst>(BDV);
Philip Reames28e61ce2015-02-28 01:57:44 +00001028 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1029 // something more safe and less hacky.
1030 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001031 Value *InVal = Sel->getOperand(i);
1032 // Find the instruction which produces the base for each input. We may
1033 // need to insert a bitcast.
1034 Value *Base = getBaseForInput(InVal, BaseSel);
1035 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001036 }
Philip Reamesc8ded462015-09-10 00:27:50 +00001037 } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(State.getBase())) {
Philip Reames7540e3a2015-09-10 00:01:53 +00001038 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001039 // Find the instruction which produces the base for each input. We may
1040 // need to insert a bitcast.
1041 Value *Base = getBaseForInput(InVal, BaseEE);
Philip Reames9ac4e382015-08-12 21:00:20 +00001042 BaseEE->setOperand(0, Base);
Philip Reames66287132015-09-09 23:40:12 +00001043 } else {
Philip Reamesc8ded462015-09-10 00:27:50 +00001044 auto *BaseIE = cast<InsertElementInst>(State.getBase());
Philip Reames7540e3a2015-09-10 00:01:53 +00001045 auto *BdvIE = cast<InsertElementInst>(BDV);
Philip Reames66287132015-09-09 23:40:12 +00001046 auto UpdateOperand = [&](int OperandIdx) {
1047 Value *InVal = BdvIE->getOperand(OperandIdx);
Philip Reames953817b2015-09-10 00:44:10 +00001048 Value *Base = getBaseForInput(InVal, BaseIE);
Philip Reames66287132015-09-09 23:40:12 +00001049 BaseIE->setOperand(OperandIdx, Base);
1050 };
1051 UpdateOperand(0); // vector operand
1052 UpdateOperand(1); // scalar operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001053 }
Philip Reames66287132015-09-09 23:40:12 +00001054
Philip Reamesd16a9b12015-02-20 01:06:44 +00001055 }
1056
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001057 // Now that we're done with the algorithm, see if we can optimize the
1058 // results slightly by reducing the number of new instructions needed.
1059 // Arguably, this should be integrated into the algorithm above, but
1060 // doing as a post process step is easier to reason about for the moment.
1061 DenseMap<Value *, Value *> ReverseMap;
1062 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001063 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001064 // Note: We need to visit the states in a deterministic order. We uses the
1065 // Keys we sorted above for this purpose. Note that we are papering over a
1066 // bigger problem with the algorithm above - it's visit order is not
1067 // deterministic. A larger change is needed to fix this.
Philip Reames34d7a742015-09-10 00:22:49 +00001068 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001069 auto *BDV = Pair.first;
1070 auto State = Pair.second;
Philip Reames246e6182015-09-03 20:24:29 +00001071 Value *Base = State.getBase();
Philip Reames15d55632015-09-09 23:26:08 +00001072 assert(BDV && Base);
1073 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001074 assert(isKnownBaseResult(Base) &&
1075 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001076 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001077 continue;
1078
Philip Reames15d55632015-09-09 23:26:08 +00001079 ReverseMap[Base] = BDV;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001080 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1081 NewInsts.insert(BaseI);
1082 Worklist.insert(BaseI);
1083 }
1084 }
Philip Reames9546f362015-09-02 22:25:07 +00001085 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1086 Value *Replacement) {
1087 // Add users which are new instructions (excluding self references)
1088 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001089 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001090 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001091 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001092 // Then do the actual replacement
1093 NewInsts.erase(BaseI);
1094 ReverseMap.erase(BaseI);
1095 BaseI->replaceAllUsesWith(Replacement);
Philip Reames34d7a742015-09-10 00:22:49 +00001096 assert(States.count(BDV));
1097 assert(States[BDV].isConflict() && States[BDV].getBase() == BaseI);
1098 States[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesdd0948a2015-12-18 03:53:28 +00001099 BaseI->eraseFromParent();
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001100 };
1101 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1102 while (!Worklist.empty()) {
1103 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001104 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001105 Value *Bdv = ReverseMap[BaseI];
1106 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1107 if (BaseI->isIdenticalTo(BdvI)) {
1108 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001109 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001110 continue;
1111 }
1112 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1113 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001114 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001115 continue;
1116 }
1117 }
1118
Philip Reamesd16a9b12015-02-20 01:06:44 +00001119 // Cache all of our results so we can cheaply reuse them
1120 // NOTE: This is actually two caches: one of the base defining value
1121 // relation and one of the base pointer relation! FIXME
Philip Reames34d7a742015-09-10 00:22:49 +00001122 for (auto Pair : States) {
Philip Reames15d55632015-09-09 23:26:08 +00001123 auto *BDV = Pair.first;
1124 Value *base = Pair.second.getBase();
1125 assert(BDV && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001126
Philip Reamesece70b82015-09-09 23:57:18 +00001127 std::string fromstr = cache.count(BDV) ? cache[BDV]->getName() : "none";
Philip Reamesdab35f32015-09-02 21:11:44 +00001128 DEBUG(dbgs() << "Updating base value cache"
Philip Reamesece70b82015-09-09 23:57:18 +00001129 << " for: " << BDV->getName()
Philip Reamesdab35f32015-09-02 21:11:44 +00001130 << " from: " << fromstr
Philip Reamesece70b82015-09-09 23:57:18 +00001131 << " to: " << base->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001132
Philip Reames15d55632015-09-09 23:26:08 +00001133 if (cache.count(BDV)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001134 // Once we transition from the BDV relation being store in the cache to
1135 // the base relation being stored, it must be stable
Philip Reames15d55632015-09-09 23:26:08 +00001136 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001137 "base relation should be stable");
1138 }
Philip Reames15d55632015-09-09 23:26:08 +00001139 cache[BDV] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001140 }
1141 assert(cache.find(def) != cache.end());
1142 return cache[def];
1143}
1144
1145// For a set of live pointers (base and/or derived), identify the base
1146// pointer of the object which they are derived from. This routine will
1147// mutate the IR graph as needed to make the 'base' pointer live at the
1148// definition site of 'derived'. This ensures that any use of 'derived' can
1149// also use 'base'. This may involve the insertion of a number of
1150// additional PHI nodes.
1151//
1152// preconditions: live is a set of pointer type Values
1153//
1154// side effects: may insert PHI nodes into the existing CFG, will preserve
1155// CFG, will not remove or mutate any existing nodes
1156//
Philip Reamesf2041322015-02-20 19:26:04 +00001157// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001158// pointer in live. Note that derived can be equal to base if the original
1159// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001160static void
1161findBasePointers(const StatepointLiveSetTy &live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001162 DenseMap<Value *, Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001163 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001164 // For the naming of values inserted to be deterministic - which makes for
1165 // much cleaner and more stable tests - we need to assign an order to the
1166 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001167 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001168 Temp.insert(Temp.end(), live.begin(), live.end());
1169 std::sort(Temp.begin(), Temp.end(), order_by_name);
1170 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001171 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001172 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001173 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001174 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1175 DT->dominates(cast<Instruction>(base)->getParent(),
1176 cast<Instruction>(ptr)->getParent())) &&
1177 "The base we found better dominate the derived pointer");
1178
David Blaikie82ad7872015-02-20 23:44:24 +00001179 // If you see this trip and like to live really dangerously, the code should
1180 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001181 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001182 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001183 "the relocation code needs adjustment to handle the relocation of "
1184 "a null pointer constant without causing false positives in the "
1185 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001186 }
1187}
1188
1189/// Find the required based pointers (and adjust the live set) for the given
1190/// parse point.
1191static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1192 const CallSite &CS,
1193 PartiallyConstructedSafepointRecord &result) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001194 DenseMap<Value *, Value *> PointerToBase;
1195 findBasePointers(result.LiveSet, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001196
1197 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001198 // Note: Need to print these in a stable order since this is checked in
1199 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001200 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001201 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001202 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001203 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001204 Temp.push_back(Pair.first);
1205 }
1206 std::sort(Temp.begin(), Temp.end(), order_by_name);
1207 for (Value *Ptr : Temp) {
1208 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001209 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1210 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001211 }
1212 }
1213
Philip Reamesf2041322015-02-20 19:26:04 +00001214 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001215}
1216
Philip Reamesdf1ef082015-04-10 22:53:14 +00001217/// Given an updated version of the dataflow liveness results, update the
1218/// liveset and base pointer maps for the call site CS.
1219static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1220 const CallSite &CS,
1221 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001222
Philip Reamesdf1ef082015-04-10 22:53:14 +00001223static void recomputeLiveInValues(
Justin Bogner843fb202015-12-15 19:40:57 +00001224 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001225 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001226 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001227 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001228 GCPtrLivenessData RevisedLivenessData;
1229 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001230 for (size_t i = 0; i < records.size(); i++) {
1231 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001232 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001233 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001234 }
1235}
1236
Sanjoy Das7ad67642015-10-20 01:06:24 +00001237// When inserting gc.relocate and gc.result calls, we need to ensure there are
1238// no uses of the original value / return value between the gc.statepoint and
1239// the gc.relocate / gc.result call. One case which can arise is a phi node
1240// starting one of the successor blocks. We also need to be able to insert the
1241// gc.relocates only on the path which goes through the statepoint. We might
1242// need to split an edge to make this possible.
Philip Reamesf209a152015-04-13 20:00:30 +00001243static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001244normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1245 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001246 BasicBlock *Ret = BB;
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001247 if (!BB->getUniquePredecessor())
Chandler Carruth96ada252015-07-22 09:52:54 +00001248 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001249
Sanjoy Das7ad67642015-10-20 01:06:24 +00001250 // Now that 'Ret' has unique predecessor we can safely remove all phi nodes
Philip Reames69e51ca2015-04-13 18:07:21 +00001251 // from it
1252 FoldSingleEntryPHINodes(Ret);
Sanjoy Dasff3dba72015-10-20 01:06:17 +00001253 assert(!isa<PHINode>(Ret->begin()) &&
1254 "All PHI nodes should have been removed!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001255
Sanjoy Das7ad67642015-10-20 01:06:24 +00001256 // At this point, we can safely insert a gc.relocate or gc.result as the first
1257 // instruction in Ret if needed.
Philip Reames69e51ca2015-04-13 18:07:21 +00001258 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001259}
1260
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001261// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001262// from original call to the safepoint.
1263static AttributeSet legalizeCallAttributes(AttributeSet AS) {
Sanjoy Das810a59d2015-10-16 02:41:11 +00001264 AttributeSet Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001265
1266 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
Sanjoy Das810a59d2015-10-16 02:41:11 +00001267 unsigned Index = AS.getSlotIndex(Slot);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001268
Sanjoy Das810a59d2015-10-16 02:41:11 +00001269 if (Index == AttributeSet::ReturnIndex ||
1270 Index == AttributeSet::FunctionIndex) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001271
Sanjoy Das810a59d2015-10-16 02:41:11 +00001272 for (Attribute Attr : make_range(AS.begin(Slot), AS.end(Slot))) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001273
1274 // Do not allow certain attributes - just skip them
1275 // Safepoint can not be read only or read none.
Sanjoy Das810a59d2015-10-16 02:41:11 +00001276 if (Attr.hasAttribute(Attribute::ReadNone) ||
1277 Attr.hasAttribute(Attribute::ReadOnly))
Philip Reamesd16a9b12015-02-20 01:06:44 +00001278 continue;
1279
Sanjoy Das58fae7c2015-10-16 02:41:23 +00001280 // These attributes control the generation of the gc.statepoint call /
1281 // invoke itself; and once the gc.statepoint is in place, they're of no
1282 // use.
1283 if (Attr.hasAttribute("statepoint-num-patch-bytes") ||
1284 Attr.hasAttribute("statepoint-id"))
1285 continue;
1286
Sanjoy Das810a59d2015-10-16 02:41:11 +00001287 Ret = Ret.addAttributes(
1288 AS.getContext(), Index,
1289 AttributeSet::get(AS.getContext(), Index, AttrBuilder(Attr)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001290 }
1291 }
1292
1293 // Just skip parameter attributes for now
1294 }
1295
Sanjoy Das810a59d2015-10-16 02:41:11 +00001296 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001297}
1298
1299/// Helper function to place all gc relocates necessary for the given
1300/// statepoint.
1301/// Inputs:
1302/// liveVariables - list of variables to be relocated.
1303/// liveStart - index of the first live variable.
1304/// basePtrs - base pointers.
1305/// statepointToken - statepoint instruction to which relocates should be
1306/// bound.
1307/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001308static void CreateGCRelocates(ArrayRef<Value *> LiveVariables,
Sanjoy Das5665c992015-05-11 23:47:27 +00001309 const int LiveStart,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001310 ArrayRef<Value *> BasePtrs,
Sanjoy Das5665c992015-05-11 23:47:27 +00001311 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001312 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001313 if (LiveVariables.empty())
1314 return;
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001315
1316 auto FindIndex = [](ArrayRef<Value *> LiveVec, Value *Val) {
1317 auto ValIt = std::find(LiveVec.begin(), LiveVec.end(), Val);
1318 assert(ValIt != LiveVec.end() && "Val not found in LiveVec!");
1319 size_t Index = std::distance(LiveVec.begin(), ValIt);
1320 assert(Index < LiveVec.size() && "Bug in std::find?");
1321 return Index;
1322 };
1323
Philip Reames94babb72015-07-21 17:18:03 +00001324 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1325 // unique declarations for each pointer type, but this proved problematic
1326 // because the intrinsic mangling code is incomplete and fragile. Since
1327 // we're moving towards a single unified pointer type anyways, we can just
1328 // cast everything to an i8* of the right address space. A bitcast is added
1329 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001330 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001331 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1332 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1333 Value *GCRelocateDecl =
1334 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001335
Sanjoy Das5665c992015-05-11 23:47:27 +00001336 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001337 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001338 Value *BaseIdx =
Sanjoy Dasb1942f12015-10-20 01:06:28 +00001339 Builder.getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
Sanjoy Das3020b1b2015-10-20 01:06:31 +00001340 Value *LiveIdx = Builder.getInt32(LiveStart + i);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001341
1342 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001343 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001344 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Philip Reamesece70b82015-09-09 23:57:18 +00001345 suffixed_name_or(LiveVariables[i], ".relocated", ""));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001346 // Trick CodeGen into thinking there are lots of free registers at this
1347 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001348 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001349 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001350}
1351
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001352namespace {
1353
1354/// This struct is used to defer RAUWs and `eraseFromParent` s. Using this
1355/// avoids having to worry about keeping around dangling pointers to Values.
1356class DeferredReplacement {
1357 AssertingVH<Instruction> Old;
1358 AssertingVH<Instruction> New;
1359
1360public:
1361 explicit DeferredReplacement(Instruction *Old, Instruction *New) :
1362 Old(Old), New(New) {
1363 assert(Old != New && "Not allowed!");
1364 }
1365
1366 /// Does the task represented by this instance.
1367 void doReplacement() {
1368 Instruction *OldI = Old;
1369 Instruction *NewI = New;
1370
1371 assert(OldI != NewI && "Disallowed at construction?!");
1372
1373 Old = nullptr;
1374 New = nullptr;
1375
1376 if (NewI)
1377 OldI->replaceAllUsesWith(NewI);
1378 OldI->eraseFromParent();
1379 }
1380};
1381}
1382
Philip Reamesd16a9b12015-02-20 01:06:44 +00001383static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001384makeStatepointExplicitImpl(const CallSite CS, /* to replace */
1385 const SmallVectorImpl<Value *> &BasePtrs,
1386 const SmallVectorImpl<Value *> &LiveVariables,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001387 PartiallyConstructedSafepointRecord &Result,
1388 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001389 assert(BasePtrs.size() == LiveVariables.size());
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001390 assert((UseDeoptBundles || isStatepoint(CS)) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001391 "This method expects to be rewriting a statepoint");
1392
Philip Reamesd16a9b12015-02-20 01:06:44 +00001393 // Then go ahead and use the builder do actually do the inserts. We insert
1394 // immediately before the previous instruction under the assumption that all
1395 // arguments will be available here. We can't insert afterwards since we may
1396 // be replacing a terminator.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001397 Instruction *InsertBefore = CS.getInstruction();
1398 IRBuilder<> Builder(InsertBefore);
1399
Sanjoy Das3c520a12015-10-08 23:18:38 +00001400 ArrayRef<Value *> GCArgs(LiveVariables);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001401 uint64_t StatepointID = 0xABCDEF00;
1402 uint32_t NumPatchBytes = 0;
1403 uint32_t Flags = uint32_t(StatepointFlags::None);
Sanjoy Das3c520a12015-10-08 23:18:38 +00001404
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001405 ArrayRef<Use> CallArgs;
1406 ArrayRef<Use> DeoptArgs;
1407 ArrayRef<Use> TransitionArgs;
1408
1409 Value *CallTarget = nullptr;
1410
1411 if (UseDeoptBundles) {
1412 CallArgs = {CS.arg_begin(), CS.arg_end()};
1413 DeoptArgs = GetDeoptBundleOperands(CS);
1414 // TODO: we don't fill in TransitionArgs or Flags in this branch, but we
1415 // could have an operand bundle for that too.
1416 AttributeSet OriginalAttrs = CS.getAttributes();
1417
1418 Attribute AttrID = OriginalAttrs.getAttribute(AttributeSet::FunctionIndex,
1419 "statepoint-id");
1420 if (AttrID.isStringAttribute())
1421 AttrID.getValueAsString().getAsInteger(10, StatepointID);
1422
1423 Attribute AttrNumPatchBytes = OriginalAttrs.getAttribute(
1424 AttributeSet::FunctionIndex, "statepoint-num-patch-bytes");
1425 if (AttrNumPatchBytes.isStringAttribute())
1426 AttrNumPatchBytes.getValueAsString().getAsInteger(10, NumPatchBytes);
1427
1428 CallTarget = CS.getCalledValue();
1429 } else {
1430 // This branch will be gone soon, and we will soon only support the
1431 // UseDeoptBundles == true configuration.
1432 Statepoint OldSP(CS);
1433 StatepointID = OldSP.getID();
1434 NumPatchBytes = OldSP.getNumPatchBytes();
1435 Flags = OldSP.getFlags();
1436
1437 CallArgs = {OldSP.arg_begin(), OldSP.arg_end()};
1438 DeoptArgs = {OldSP.vm_state_begin(), OldSP.vm_state_end()};
1439 TransitionArgs = {OldSP.gc_transition_args_begin(),
1440 OldSP.gc_transition_args_end()};
1441 CallTarget = OldSP.getCalledValue();
1442 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001443
1444 // Create the statepoint given all the arguments
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001445 Instruction *Token = nullptr;
1446 AttributeSet ReturnAttrs;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001447 if (CS.isCall()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001448 CallInst *ToReplace = cast<CallInst>(CS.getInstruction());
Sanjoy Das3c520a12015-10-08 23:18:38 +00001449 CallInst *Call = Builder.CreateGCStatepointCall(
1450 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1451 TransitionArgs, DeoptArgs, GCArgs, "safepoint_token");
1452
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001453 Call->setTailCall(ToReplace->isTailCall());
1454 Call->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001455
1456 // Currently we will fail on parameter attributes and on certain
1457 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001458 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001459 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001460 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001461 Call->setAttributes(NewAttrs.getFnAttributes());
1462 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001463
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001464 Token = Call;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001465
1466 // Put the following gc_result and gc_relocate calls immediately after the
1467 // the old call (which we're about to delete)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001468 assert(ToReplace->getNextNode() && "Not a terminator, must have next!");
1469 Builder.SetInsertPoint(ToReplace->getNextNode());
1470 Builder.SetCurrentDebugLocation(ToReplace->getNextNode()->getDebugLoc());
David Blaikie82ad7872015-02-20 23:44:24 +00001471 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001472 InvokeInst *ToReplace = cast<InvokeInst>(CS.getInstruction());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001473
1474 // Insert the new invoke into the old block. We'll remove the old one in a
1475 // moment at which point this will become the new terminator for the
1476 // original block.
Sanjoy Das3c520a12015-10-08 23:18:38 +00001477 InvokeInst *Invoke = Builder.CreateGCStatepointInvoke(
1478 StatepointID, NumPatchBytes, CallTarget, ToReplace->getNormalDest(),
1479 ToReplace->getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1480 GCArgs, "statepoint_token");
1481
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001482 Invoke->setCallingConv(ToReplace->getCallingConv());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001483
1484 // Currently we will fail on parameter attributes and on certain
1485 // function attributes.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001486 AttributeSet NewAttrs = legalizeCallAttributes(ToReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001487 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001488 // directly on statepoint and return attrs later for gc_result intrinsic.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001489 Invoke->setAttributes(NewAttrs.getFnAttributes());
1490 ReturnAttrs = NewAttrs.getRetAttributes();
Philip Reamesd16a9b12015-02-20 01:06:44 +00001491
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001492 Token = Invoke;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001493
1494 // Generate gc relocates in exceptional path
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001495 BasicBlock *UnwindBlock = ToReplace->getUnwindDest();
1496 assert(!isa<PHINode>(UnwindBlock->begin()) &&
1497 UnwindBlock->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001498 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001499
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001500 Builder.SetInsertPoint(&*UnwindBlock->getFirstInsertionPt());
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001501 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001502
1503 // Extract second element from landingpad return value. We will attach
1504 // exceptional gc relocates to it.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001505 Instruction *ExceptionalToken =
Philip Reamesd16a9b12015-02-20 01:06:44 +00001506 cast<Instruction>(Builder.CreateExtractValue(
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001507 UnwindBlock->getLandingPadInst(), 1, "relocate_token"));
1508 Result.UnwindToken = ExceptionalToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001509
Sanjoy Das3c520a12015-10-08 23:18:38 +00001510 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001511 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, ExceptionalToken,
1512 Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001513
1514 // Generate gc relocates and returns for normal block
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001515 BasicBlock *NormalDest = ToReplace->getNormalDest();
1516 assert(!isa<PHINode>(NormalDest->begin()) &&
1517 NormalDest->getUniquePredecessor() &&
Philip Reames69e51ca2015-04-13 18:07:21 +00001518 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001519
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001520 Builder.SetInsertPoint(&*NormalDest->getFirstInsertionPt());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001521
1522 // gc relocates will be generated later as if it were regular call
1523 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001524 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001525 assert(Token && "Should be set in one of the above branches!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001526
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001527 if (UseDeoptBundles) {
1528 Token->setName("statepoint_token");
1529 if (!CS.getType()->isVoidTy() && !CS.getInstruction()->use_empty()) {
1530 StringRef Name =
1531 CS.getInstruction()->hasName() ? CS.getInstruction()->getName() : "";
1532 CallInst *GCResult = Builder.CreateGCResult(Token, CS.getType(), Name);
1533 GCResult->setAttributes(CS.getAttributes().getRetAttributes());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001534
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001535 // We cannot RAUW or delete CS.getInstruction() because it could be in the
1536 // live set of some other safepoint, in which case that safepoint's
1537 // PartiallyConstructedSafepointRecord will hold a raw pointer to this
1538 // llvm::Instruction. Instead, we defer the replacement and deletion to
1539 // after the live sets have been made explicit in the IR, and we no longer
1540 // have raw pointers to worry about.
1541 Replacements.emplace_back(CS.getInstruction(), GCResult);
1542 } else {
1543 Replacements.emplace_back(CS.getInstruction(), nullptr);
1544 }
1545 } else {
1546 assert(!CS.getInstruction()->hasNUsesOrMore(2) &&
1547 "only valid use before rewrite is gc.result");
1548 assert(!CS.getInstruction()->hasOneUse() ||
1549 isGCResult(cast<Instruction>(*CS.getInstruction()->user_begin())));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001550
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001551 // Take the name of the original statepoint token if there was one.
1552 Token->takeName(CS.getInstruction());
1553
1554 // Update the gc.result of the original statepoint (if any) to use the newly
1555 // inserted statepoint. This is safe to do here since the token can't be
1556 // considered a live reference.
1557 CS.getInstruction()->replaceAllUsesWith(Token);
1558 CS.getInstruction()->eraseFromParent();
1559 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001560
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001561 Result.StatepointToken = Token;
Philip Reames0a3240f2015-02-20 21:34:11 +00001562
Philip Reamesd16a9b12015-02-20 01:06:44 +00001563 // Second, create a gc.relocate for every live variable
Sanjoy Das3c520a12015-10-08 23:18:38 +00001564 const unsigned LiveStartIdx = Statepoint(Token).gcArgsStartIdx();
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001565 CreateGCRelocates(LiveVariables, LiveStartIdx, BasePtrs, Token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001566}
1567
1568namespace {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001569struct NameOrdering {
1570 Value *Base;
1571 Value *Derived;
1572
1573 bool operator()(NameOrdering const &a, NameOrdering const &b) {
1574 return -1 == a.Derived->getName().compare(b.Derived->getName());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001575 }
1576};
1577}
Philip Reamesd16a9b12015-02-20 01:06:44 +00001578
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001579static void StabilizeOrder(SmallVectorImpl<Value *> &BaseVec,
1580 SmallVectorImpl<Value *> &LiveVec) {
1581 assert(BaseVec.size() == LiveVec.size());
1582
1583 SmallVector<NameOrdering, 64> Temp;
1584 for (size_t i = 0; i < BaseVec.size(); i++) {
1585 NameOrdering v;
1586 v.Base = BaseVec[i];
1587 v.Derived = LiveVec[i];
1588 Temp.push_back(v);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001589 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001590
1591 std::sort(Temp.begin(), Temp.end(), NameOrdering());
1592 for (size_t i = 0; i < BaseVec.size(); i++) {
1593 BaseVec[i] = Temp[i].Base;
1594 LiveVec[i] = Temp[i].Derived;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001595 }
1596}
1597
1598// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1599// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001600//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001601// WARNING: Does not do any fixup to adjust users of the original live
1602// values. That's the callers responsibility.
1603static void
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001604makeStatepointExplicit(DominatorTree &DT, const CallSite &CS,
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001605 PartiallyConstructedSafepointRecord &Result,
1606 std::vector<DeferredReplacement> &Replacements) {
Sanjoy Das1ede5362015-10-08 23:18:22 +00001607 const auto &LiveSet = Result.LiveSet;
1608 const auto &PointerToBase = Result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001609
1610 // Convert to vector for efficient cross referencing.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001611 SmallVector<Value *, 64> BaseVec, LiveVec;
1612 LiveVec.reserve(LiveSet.size());
1613 BaseVec.reserve(LiveSet.size());
1614 for (Value *L : LiveSet) {
1615 LiveVec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001616 assert(PointerToBase.count(L));
Sanjoy Das1ede5362015-10-08 23:18:22 +00001617 Value *Base = PointerToBase.find(L)->second;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001618 BaseVec.push_back(Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001619 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001620 assert(LiveVec.size() == BaseVec.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001621
1622 // To make the output IR slightly more stable (for use in diffs), ensure a
1623 // fixed order of the values in the safepoint (by sorting the value name).
1624 // The order is otherwise meaningless.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001625 StabilizeOrder(BaseVec, LiveVec);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001626
1627 // Do the actual rewriting and delete the old statepoint
Sanjoy Das25ec1a32015-10-16 02:41:00 +00001628 makeStatepointExplicitImpl(CS, BaseVec, LiveVec, Result, Replacements);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001629}
1630
1631// Helper function for the relocationViaAlloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001632//
1633// It receives iterator to the statepoint gc relocates and emits a store to the
1634// assigned location (via allocaMap) for the each one of them. It adds the
1635// visited values into the visitedLiveValues set, which we will later use them
1636// for sanity checking.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001637static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001638insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1639 DenseMap<Value *, Value *> &AllocaMap,
1640 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001641
Sanjoy Das5665c992015-05-11 23:47:27 +00001642 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001643 if (!isa<IntrinsicInst>(U))
1644 continue;
1645
Sanjoy Das5665c992015-05-11 23:47:27 +00001646 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001647
1648 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001649 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001650 Intrinsic::experimental_gc_relocate) {
1651 continue;
1652 }
1653
Sanjoy Das5665c992015-05-11 23:47:27 +00001654 GCRelocateOperands RelocateOperands(RelocatedValue);
1655 Value *OriginalValue =
1656 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1657 assert(AllocaMap.count(OriginalValue));
1658 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001659
1660 // Emit store into the related alloca
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001661 // All gc_relocates are i8 addrspace(1)* typed, and it must be bitcasted to
Sanjoy Das89c54912015-05-11 18:49:34 +00001662 // the correct type according to alloca.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001663 assert(RelocatedValue->getNextNode() &&
1664 "Should always have one since it's not a terminator");
Sanjoy Das5665c992015-05-11 23:47:27 +00001665 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001666 Value *CastedRelocatedValue =
Philip Reamesece70b82015-09-09 23:57:18 +00001667 Builder.CreateBitCast(RelocatedValue,
1668 cast<AllocaInst>(Alloca)->getAllocatedType(),
1669 suffixed_name_or(RelocatedValue, ".casted", ""));
Sanjoy Das89c54912015-05-11 18:49:34 +00001670
Sanjoy Das5665c992015-05-11 23:47:27 +00001671 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1672 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001673
1674#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001675 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001676#endif
1677 }
1678}
1679
Igor Laevskye0317182015-05-19 15:59:05 +00001680// Helper function for the "relocationViaAlloca". Similar to the
1681// "insertRelocationStores" but works for rematerialized values.
1682static void
1683insertRematerializationStores(
1684 RematerializedValueMapTy RematerializedValues,
1685 DenseMap<Value *, Value *> &AllocaMap,
1686 DenseSet<Value *> &VisitedLiveValues) {
1687
1688 for (auto RematerializedValuePair: RematerializedValues) {
1689 Instruction *RematerializedValue = RematerializedValuePair.first;
1690 Value *OriginalValue = RematerializedValuePair.second;
1691
1692 assert(AllocaMap.count(OriginalValue) &&
1693 "Can not find alloca for rematerialized value");
1694 Value *Alloca = AllocaMap[OriginalValue];
1695
1696 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1697 Store->insertAfter(RematerializedValue);
1698
1699#ifndef NDEBUG
1700 VisitedLiveValues.insert(OriginalValue);
1701#endif
1702 }
1703}
1704
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001705/// Do all the relocation update via allocas and mem2reg
Philip Reamesd16a9b12015-02-20 01:06:44 +00001706static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001707 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001708 ArrayRef<PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001709#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001710 // record initial number of (static) allocas; we'll check we have the same
1711 // number when we get done.
1712 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001713 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1714 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001715 if (isa<AllocaInst>(*I))
1716 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001717#endif
1718
1719 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001720 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001721 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001722 // Used later to chack that we have enough allocas to store all values
1723 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001724 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001725
Igor Laevskye0317182015-05-19 15:59:05 +00001726 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1727 // "PromotableAllocas"
1728 auto emitAllocaFor = [&](Value *LiveValue) {
1729 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1730 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001731 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001732 PromotableAllocas.push_back(Alloca);
1733 };
1734
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001735 // Emit alloca for each live gc pointer
1736 for (Value *V : Live)
1737 emitAllocaFor(V);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001738
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001739 // Emit allocas for rematerialized values
1740 for (const auto &Info : Records)
Igor Laevsky285fe842015-05-19 16:29:43 +00001741 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001742 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001743 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001744 continue;
1745
1746 emitAllocaFor(OriginalValue);
1747 ++NumRematerializedValues;
1748 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001749
Philip Reamesd16a9b12015-02-20 01:06:44 +00001750 // The next two loops are part of the same conceptual operation. We need to
1751 // insert a store to the alloca after the original def and at each
1752 // redefinition. We need to insert a load before each use. These are split
1753 // into distinct loops for performance reasons.
1754
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001755 // Update gc pointer after each statepoint: either store a relocated value or
1756 // null (if no relocated value was found for this gc pointer and it is not a
1757 // gc_result). This must happen before we update the statepoint with load of
1758 // alloca otherwise we lose the link between statepoint and old def.
1759 for (const auto &Info : Records) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001760 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001761
1762 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001763 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001764
1765 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001766 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001767
1768 // In case if it was invoke statepoint
1769 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001770 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001771 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1772 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001773 }
1774
Igor Laevskye0317182015-05-19 15:59:05 +00001775 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001776 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1777 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001778
Philip Reamese73300b2015-04-13 16:41:32 +00001779 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001780 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001781 // the gc.statepoint. This will turn some subtle GC problems into
1782 // slightly easier to debug SEGVs. Note that on large IR files with
1783 // lots of gc.statepoints this is extremely costly both memory and time
1784 // wise.
1785 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001786 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001787 Value *Def = Pair.first;
1788 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001789
Philip Reamese73300b2015-04-13 16:41:32 +00001790 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001791 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001792 continue;
1793 }
1794 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001795 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001796
Philip Reamese73300b2015-04-13 16:41:32 +00001797 auto InsertClobbersAt = [&](Instruction *IP) {
1798 for (auto *AI : ToClobber) {
1799 auto AIType = cast<PointerType>(AI->getType());
1800 auto PT = cast<PointerType>(AIType->getElementType());
1801 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001802 StoreInst *Store = new StoreInst(CPN, AI);
1803 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001804 }
1805 };
1806
1807 // Insert the clobbering stores. These may get intermixed with the
1808 // gc.results and gc.relocates, but that's fine.
1809 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001810 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1811 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
Philip Reamese73300b2015-04-13 16:41:32 +00001812 } else {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001813 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001814 }
David Blaikie82ad7872015-02-20 23:44:24 +00001815 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001816 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001817
1818 // Update use with load allocas and add store for gc_relocated.
Igor Laevsky285fe842015-05-19 16:29:43 +00001819 for (auto Pair : AllocaMap) {
1820 Value *Def = Pair.first;
1821 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001822
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001823 // We pre-record the uses of allocas so that we dont have to worry about
1824 // later update that changes the user information..
1825
Igor Laevsky285fe842015-05-19 16:29:43 +00001826 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001827 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001828 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1829 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001830 if (!isa<ConstantExpr>(U)) {
1831 // If the def has a ConstantExpr use, then the def is either a
1832 // ConstantExpr use itself or null. In either case
1833 // (recursively in the first, directly in the second), the oop
1834 // it is ultimately dependent on is null and this particular
1835 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001836 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001837 }
1838 }
1839
Igor Laevsky285fe842015-05-19 16:29:43 +00001840 std::sort(Uses.begin(), Uses.end());
1841 auto Last = std::unique(Uses.begin(), Uses.end());
1842 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001843
Igor Laevsky285fe842015-05-19 16:29:43 +00001844 for (Instruction *Use : Uses) {
1845 if (isa<PHINode>(Use)) {
1846 PHINode *Phi = cast<PHINode>(Use);
1847 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1848 if (Def == Phi->getIncomingValue(i)) {
1849 LoadInst *Load = new LoadInst(
1850 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1851 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001852 }
1853 }
1854 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001855 LoadInst *Load = new LoadInst(Alloca, "", Use);
1856 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001857 }
1858 }
1859
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001860 // Emit store for the initial gc value. Store must be inserted after load,
1861 // otherwise store will be in alloca's use list and an extra load will be
1862 // inserted before it.
Igor Laevsky285fe842015-05-19 16:29:43 +00001863 StoreInst *Store = new StoreInst(Def, Alloca);
1864 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1865 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001866 // InvokeInst is a TerminatorInst so the store need to be inserted
1867 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001868 BasicBlock *NormalDest = Invoke->getNormalDest();
1869 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001870 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001871 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001872 "The only TerminatorInst that can produce a value is "
1873 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001874 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001875 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001876 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001877 assert(isa<Argument>(Def));
1878 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001879 }
1880 }
1881
Igor Laevsky285fe842015-05-19 16:29:43 +00001882 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001883 "we must have the same allocas with lives");
1884 if (!PromotableAllocas.empty()) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001885 // Apply mem2reg to promote alloca to SSA
Philip Reamesd16a9b12015-02-20 01:06:44 +00001886 PromoteMemToReg(PromotableAllocas, DT);
1887 }
1888
1889#ifndef NDEBUG
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001890 for (auto &I : F.getEntryBlock())
1891 if (isa<AllocaInst>(I))
Philip Reamesa6ebf072015-03-27 05:53:16 +00001892 InitialAllocaNum--;
1893 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001894#endif
1895}
1896
1897/// Implement a unique function which doesn't require we sort the input
1898/// vector. Doing so has the effect of changing the output of a couple of
1899/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001900template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001901 SmallSet<T, 8> Seen;
1902 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1903 return !Seen.insert(V).second;
1904 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001905}
1906
Philip Reamesd16a9b12015-02-20 01:06:44 +00001907/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001908/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001909static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001910 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001911 if (Values.empty())
1912 // No values to hold live, might as well not insert the empty holder
1913 return;
1914
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001915 Module *M = CS.getInstruction()->getModule();
Philip Reamesf209a152015-04-13 20:00:30 +00001916 // Use a dummy vararg function to actually hold the values live
1917 Function *Func = cast<Function>(M->getOrInsertFunction(
1918 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001919 if (CS.isCall()) {
1920 // For call safepoints insert dummy calls right after safepoint
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001921 Holders.push_back(CallInst::Create(Func, Values, "",
1922 &*++CS.getInstruction()->getIterator()));
Philip Reamesf209a152015-04-13 20:00:30 +00001923 return;
1924 }
1925 // For invoke safepooints insert dummy calls both in normal and
1926 // exceptional destination blocks
1927 auto *II = cast<InvokeInst>(CS.getInstruction());
1928 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001929 Func, Values, "", &*II->getNormalDest()->getFirstInsertionPt()));
Philip Reamesf209a152015-04-13 20:00:30 +00001930 Holders.push_back(CallInst::Create(
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001931 Func, Values, "", &*II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001932}
1933
1934static void findLiveReferences(
Justin Bogner843fb202015-12-15 19:40:57 +00001935 Function &F, DominatorTree &DT, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001936 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001937 GCPtrLivenessData OriginalLivenessData;
1938 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001939 for (size_t i = 0; i < records.size(); i++) {
1940 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001941 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001942 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001943 }
1944}
1945
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00001946/// Remove any vector of pointers from the live set by scalarizing them over the
1947/// statepoint instruction. Adds the scalarized pieces to the live set. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001948/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001949/// the lowering code currently does not handle that. Extending it would be
1950/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001951/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001952static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001953 StatepointLiveSetTy &LiveSet,
1954 DenseMap<Value *, Value *>& PointerToBase,
1955 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001956 SmallVector<Value *, 16> ToSplit;
1957 for (Value *V : LiveSet)
1958 if (isa<VectorType>(V->getType()))
1959 ToSplit.push_back(V);
1960
1961 if (ToSplit.empty())
1962 return;
1963
Philip Reames8fe7f132015-06-26 22:47:37 +00001964 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1965
Philip Reames8531d8c2015-04-10 21:48:25 +00001966 Function &F = *(StatepointInst->getParent()->getParent());
1967
Philip Reames704e78b2015-04-10 22:34:56 +00001968 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001969 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001970 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001971 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001972 AllocaInst *Alloca =
1973 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001974 AllocaMap[V] = Alloca;
1975
1976 VectorType *VT = cast<VectorType>(V->getType());
1977 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001978 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001979 for (unsigned i = 0; i < VT->getNumElements(); i++)
1980 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001981 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001982
1983 auto InsertVectorReform = [&](Instruction *IP) {
1984 Builder.SetInsertPoint(IP);
1985 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1986 Value *ResultVec = UndefValue::get(VT);
1987 for (unsigned i = 0; i < VT->getNumElements(); i++)
1988 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1989 Builder.getInt32(i));
1990 return ResultVec;
1991 };
1992
1993 if (isa<CallInst>(StatepointInst)) {
1994 BasicBlock::iterator Next(StatepointInst);
1995 Next++;
1996 Instruction *IP = &*(Next);
1997 Replacements[V].first = InsertVectorReform(IP);
1998 Replacements[V].second = nullptr;
1999 } else {
2000 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
2001 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00002002 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00002003 BasicBlock *NormalDest = Invoke->getNormalDest();
2004 assert(!isa<PHINode>(NormalDest->begin()));
2005 BasicBlock *UnwindDest = Invoke->getUnwindDest();
2006 assert(!isa<PHINode>(UnwindDest->begin()));
2007 // Insert insert element sequences in both successors
2008 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
2009 Replacements[V].first = InsertVectorReform(IP);
2010 IP = &*(UnwindDest->getFirstInsertionPt());
2011 Replacements[V].second = InsertVectorReform(IP);
2012 }
2013 }
Philip Reames8fe7f132015-06-26 22:47:37 +00002014
Philip Reames8531d8c2015-04-10 21:48:25 +00002015 for (Value *V : ToSplit) {
2016 AllocaInst *Alloca = AllocaMap[V];
2017
2018 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00002019 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00002020 for (User *U : V->users())
2021 Users.push_back(cast<Instruction>(U));
2022
2023 for (Instruction *I : Users) {
2024 if (auto Phi = dyn_cast<PHINode>(I)) {
2025 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
2026 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00002027 LoadInst *Load = new LoadInst(
2028 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00002029 Phi->setIncomingValue(i, Load);
2030 }
2031 } else {
2032 LoadInst *Load = new LoadInst(Alloca, "", I);
2033 I->replaceUsesOfWith(V, Load);
2034 }
2035 }
2036
2037 // Store the original value and the replacement value into the alloca
2038 StoreInst *Store = new StoreInst(V, Alloca);
2039 if (auto I = dyn_cast<Instruction>(V))
2040 Store->insertAfter(I);
2041 else
2042 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00002043
Philip Reames8531d8c2015-04-10 21:48:25 +00002044 // Normal return for invoke, or call return
2045 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
2046 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2047 // Unwind return for invoke only
2048 Replacement = cast_or_null<Instruction>(Replacements[V].second);
2049 if (Replacement)
2050 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
2051 }
2052
2053 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00002054 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00002055 for (Value *V : ToSplit)
2056 Allocas.push_back(AllocaMap[V]);
2057 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00002058
2059 // Update our tracking of live pointers and base mappings to account for the
2060 // changes we just made.
2061 for (Value *V : ToSplit) {
2062 auto &Elements = ElementMapping[V];
2063
2064 LiveSet.erase(V);
2065 LiveSet.insert(Elements.begin(), Elements.end());
2066 // We need to update the base mapping as well.
2067 assert(PointerToBase.count(V));
2068 Value *OldBase = PointerToBase[V];
2069 auto &BaseElements = ElementMapping[OldBase];
2070 PointerToBase.erase(V);
2071 assert(Elements.size() == BaseElements.size());
2072 for (unsigned i = 0; i < Elements.size(); i++) {
2073 Value *Elem = Elements[i];
2074 PointerToBase[Elem] = BaseElements[i];
2075 }
2076 }
Philip Reames8531d8c2015-04-10 21:48:25 +00002077}
2078
Igor Laevskye0317182015-05-19 15:59:05 +00002079// Helper function for the "rematerializeLiveValues". It walks use chain
2080// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2081// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002082// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00002083// Fills "ChainToBase" array with all visited values. "BaseValue" is not
2084// recorded.
2085static bool findRematerializableChainToBasePointer(
2086 SmallVectorImpl<Instruction*> &ChainToBase,
2087 Value *CurrentValue, Value *BaseValue) {
2088
2089 // We have found a base value
2090 if (CurrentValue == BaseValue) {
2091 return true;
2092 }
2093
2094 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2095 ChainToBase.push_back(GEP);
2096 return findRematerializableChainToBasePointer(ChainToBase,
2097 GEP->getPointerOperand(),
2098 BaseValue);
2099 }
2100
2101 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2102 Value *Def = CI->stripPointerCasts();
2103
2104 // This two checks are basically similar. First one is here for the
2105 // consistency with findBasePointers logic.
2106 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2107 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2108 return false;
2109
2110 ChainToBase.push_back(CI);
2111 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2112 }
2113
2114 // Not supported instruction in the chain
2115 return false;
2116}
2117
2118// Helper function for the "rematerializeLiveValues". Compute cost of the use
2119// chain we are going to rematerialize.
2120static unsigned
2121chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2122 TargetTransformInfo &TTI) {
2123 unsigned Cost = 0;
2124
2125 for (Instruction *Instr : Chain) {
2126 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2127 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2128 "non noop cast is found during rematerialization");
2129
2130 Type *SrcTy = CI->getOperand(0)->getType();
2131 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2132
2133 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2134 // Cost of the address calculation
2135 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2136 Cost += TTI.getAddressComputationCost(ValTy);
2137
2138 // And cost of the GEP itself
2139 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2140 // allowed for the external usage)
2141 if (!GEP->hasAllConstantIndices())
2142 Cost += 2;
2143
2144 } else {
2145 llvm_unreachable("unsupported instruciton type during rematerialization");
2146 }
2147 }
2148
2149 return Cost;
2150}
2151
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002152// From the statepoint live set pick values that are cheaper to recompute then
2153// to relocate. Remove this values from the live set, rematerialize them after
Igor Laevskye0317182015-05-19 15:59:05 +00002154// statepoint and record them in "Info" structure. Note that similar to
2155// relocated values we don't do any user adjustments here.
2156static void rematerializeLiveValues(CallSite CS,
2157 PartiallyConstructedSafepointRecord &Info,
2158 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002159 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002160
Igor Laevskye0317182015-05-19 15:59:05 +00002161 // Record values we are going to delete from this statepoint live set.
2162 // We can not di this in following loop due to iterator invalidation.
2163 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2164
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002165 for (Value *LiveValue: Info.LiveSet) {
Igor Laevskye0317182015-05-19 15:59:05 +00002166 // For each live pointer find it's defining chain
2167 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002168 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002169 bool FoundChain =
2170 findRematerializableChainToBasePointer(ChainToBase,
2171 LiveValue,
2172 Info.PointerToBase[LiveValue]);
2173 // Nothing to do, or chain is too long
2174 if (!FoundChain ||
2175 ChainToBase.size() == 0 ||
2176 ChainToBase.size() > ChainLengthThreshold)
2177 continue;
2178
2179 // Compute cost of this chain
2180 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2181 // TODO: We can also account for cases when we will be able to remove some
2182 // of the rematerialized values by later optimization passes. I.e if
2183 // we rematerialized several intersecting chains. Or if original values
2184 // don't have any uses besides this statepoint.
2185
2186 // For invokes we need to rematerialize each chain twice - for normal and
2187 // for unwind basic blocks. Model this by multiplying cost by two.
2188 if (CS.isInvoke()) {
2189 Cost *= 2;
2190 }
2191 // If it's too expensive - skip it
2192 if (Cost >= RematerializationThreshold)
2193 continue;
2194
2195 // Remove value from the live set
2196 LiveValuesToBeDeleted.push_back(LiveValue);
2197
2198 // Clone instructions and record them inside "Info" structure
2199
2200 // Walk backwards to visit top-most instructions first
2201 std::reverse(ChainToBase.begin(), ChainToBase.end());
2202
2203 // Utility function which clones all instructions from "ChainToBase"
2204 // and inserts them before "InsertBefore". Returns rematerialized value
2205 // which should be used after statepoint.
2206 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2207 Instruction *LastClonedValue = nullptr;
2208 Instruction *LastValue = nullptr;
2209 for (Instruction *Instr: ChainToBase) {
2210 // Only GEP's and casts are suported as we need to be careful to not
2211 // introduce any new uses of pointers not in the liveset.
2212 // Note that it's fine to introduce new uses of pointers which were
2213 // otherwise not used after this statepoint.
2214 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2215
2216 Instruction *ClonedValue = Instr->clone();
2217 ClonedValue->insertBefore(InsertBefore);
2218 ClonedValue->setName(Instr->getName() + ".remat");
2219
2220 // If it is not first instruction in the chain then it uses previously
2221 // cloned value. We should update it to use cloned value.
2222 if (LastClonedValue) {
2223 assert(LastValue);
2224 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2225#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002226 // Assert that cloned instruction does not use any instructions from
2227 // this chain other than LastClonedValue
2228 for (auto OpValue : ClonedValue->operand_values()) {
2229 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2230 ChainToBase.end() &&
2231 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002232 }
2233#endif
2234 }
2235
2236 LastClonedValue = ClonedValue;
2237 LastValue = Instr;
2238 }
2239 assert(LastClonedValue);
2240 return LastClonedValue;
2241 };
2242
2243 // Different cases for calls and invokes. For invokes we need to clone
2244 // instructions both on normal and unwind path.
2245 if (CS.isCall()) {
2246 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2247 assert(InsertBefore);
2248 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2249 Info.RematerializedValues[RematerializedValue] = LiveValue;
2250 } else {
2251 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2252
2253 Instruction *NormalInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002254 &*Invoke->getNormalDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002255 Instruction *UnwindInsertBefore =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002256 &*Invoke->getUnwindDest()->getFirstInsertionPt();
Igor Laevskye0317182015-05-19 15:59:05 +00002257
2258 Instruction *NormalRematerializedValue =
2259 rematerializeChain(NormalInsertBefore);
2260 Instruction *UnwindRematerializedValue =
2261 rematerializeChain(UnwindInsertBefore);
2262
2263 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2264 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2265 }
2266 }
2267
2268 // Remove rematerializaed values from the live set
2269 for (auto LiveValue: LiveValuesToBeDeleted) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002270 Info.LiveSet.erase(LiveValue);
Igor Laevskye0317182015-05-19 15:59:05 +00002271 }
2272}
2273
Justin Bogner843fb202015-12-15 19:40:57 +00002274static bool insertParsePoints(Function &F, DominatorTree &DT,
2275 TargetTransformInfo &TTI,
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002276 SmallVectorImpl<CallSite> &ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002277#ifndef NDEBUG
2278 // sanity check the input
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002279 std::set<CallSite> Uniqued;
2280 Uniqued.insert(ToUpdate.begin(), ToUpdate.end());
2281 assert(Uniqued.size() == ToUpdate.size() && "no duplicates please!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002282
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002283 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002284 assert(CS.getInstruction()->getParent()->getParent() == &F);
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002285 assert((UseDeoptBundles || isStatepoint(CS)) &&
2286 "expected to already be a deopt statepoint");
Philip Reamesd16a9b12015-02-20 01:06:44 +00002287 }
2288#endif
2289
Philip Reames69e51ca2015-04-13 18:07:21 +00002290 // When inserting gc.relocates for invokes, we need to be able to insert at
2291 // the top of the successor blocks. See the comment on
2292 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002293 // may restructure the CFG.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002294 for (CallSite CS : ToUpdate) {
Philip Reamesf209a152015-04-13 20:00:30 +00002295 if (!CS.isInvoke())
2296 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002297 auto *II = cast<InvokeInst>(CS.getInstruction());
2298 normalizeForInvokeSafepoint(II->getNormalDest(), II->getParent(), DT);
2299 normalizeForInvokeSafepoint(II->getUnwindDest(), II->getParent(), DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002300 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002301
Philip Reamesd16a9b12015-02-20 01:06:44 +00002302 // A list of dummy calls added to the IR to keep various values obviously
2303 // live in the IR. We'll remove all of these when done.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002304 SmallVector<CallInst *, 64> Holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002305
2306 // Insert a dummy call with all of the arguments to the vm_state we'll need
2307 // for the actual safepoint insertion. This ensures reference arguments in
2308 // the deopt argument list are considered live through the safepoint (and
2309 // thus makes sure they get relocated.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002310 for (CallSite CS : ToUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002311 SmallVector<Value *, 64> DeoptValues;
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002312
2313 iterator_range<const Use *> DeoptStateRange =
2314 UseDeoptBundles
2315 ? iterator_range<const Use *>(GetDeoptBundleOperands(CS))
2316 : iterator_range<const Use *>(Statepoint(CS).vm_state_args());
2317
2318 for (Value *Arg : DeoptStateRange) {
Philip Reames8531d8c2015-04-10 21:48:25 +00002319 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2320 "support for FCA unimplemented");
2321 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002322 DeoptValues.push_back(Arg);
2323 }
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002324
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002325 insertUseHolderAfter(CS, DeoptValues, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002326 }
2327
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002328 SmallVector<PartiallyConstructedSafepointRecord, 64> Records(ToUpdate.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00002329
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002330 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002331 // site.
Justin Bogner843fb202015-12-15 19:40:57 +00002332 findLiveReferences(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002333
2334 // B) Find the base pointers for each live pointer
2335 /* scope for caching */ {
2336 // Cache the 'defining value' relation used in the computation and
2337 // insertion of base phis and selects. This ensures that we don't insert
2338 // large numbers of duplicate base_phis.
2339 DefiningValueMapTy DVCache;
2340
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002341 for (size_t i = 0; i < Records.size(); i++) {
2342 PartiallyConstructedSafepointRecord &info = Records[i];
2343 findBasePointers(DT, DVCache, ToUpdate[i], info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002344 }
2345 } // end of cache scope
2346
2347 // The base phi insertion logic (for any safepoint) may have inserted new
2348 // instructions which are now live at some safepoint. The simplest such
2349 // example is:
2350 // loop:
2351 // phi a <-- will be a new base_phi here
2352 // safepoint 1 <-- that needs to be live here
2353 // gep a + 1
2354 // safepoint 2
2355 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002356 // We insert some dummy calls after each safepoint to definitely hold live
2357 // the base pointers which were identified for that safepoint. We'll then
2358 // ask liveness for _every_ base inserted to see what is now live. Then we
2359 // remove the dummy calls.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002360 Holders.reserve(Holders.size() + Records.size());
2361 for (size_t i = 0; i < Records.size(); i++) {
2362 PartiallyConstructedSafepointRecord &Info = Records[i];
Philip Reamesd16a9b12015-02-20 01:06:44 +00002363
2364 SmallVector<Value *, 128> Bases;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002365 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002366 Bases.push_back(Pair.second);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002367
2368 insertUseHolderAfter(ToUpdate[i], Bases, Holders);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002369 }
2370
Philip Reamesdf1ef082015-04-10 22:53:14 +00002371 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2372 // need to rerun liveness. We may *also* have inserted new defs, but that's
2373 // not the key issue.
Justin Bogner843fb202015-12-15 19:40:57 +00002374 recomputeLiveInValues(F, DT, ToUpdate, Records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002375
Philip Reamesd16a9b12015-02-20 01:06:44 +00002376 if (PrintBasePointers) {
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002377 for (auto &Info : Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002378 errs() << "Base Pairs: (w/Relocation)\n";
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002379 for (auto Pair : Info.PointerToBase)
Philip Reamesd16a9b12015-02-20 01:06:44 +00002380 errs() << " derived %" << Pair.first->getName() << " base %"
2381 << Pair.second->getName() << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00002382 }
2383 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002384
2385 for (CallInst *CI : Holders)
2386 CI->eraseFromParent();
2387
2388 Holders.clear();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002389
Philip Reames8fe7f132015-06-26 22:47:37 +00002390 // Do a limited scalarization of any live at safepoint vector values which
2391 // contain pointers. This enables this pass to run after vectorization at
2392 // the cost of some possible performance loss. TODO: it would be nice to
2393 // natively support vectors all the way through the backend so we don't need
2394 // to scalarize here.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002395 for (size_t i = 0; i < Records.size(); i++) {
2396 PartiallyConstructedSafepointRecord &Info = Records[i];
2397 Instruction *Statepoint = ToUpdate[i].getInstruction();
2398 splitVectorValues(cast<Instruction>(Statepoint), Info.LiveSet,
2399 Info.PointerToBase, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00002400 }
2401
Igor Laevskye0317182015-05-19 15:59:05 +00002402 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002403 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002404 // does not influence correctness.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002405 for (size_t i = 0; i < Records.size(); i++)
2406 rematerializeLiveValues(ToUpdate[i], Records[i], TTI);
Igor Laevskye0317182015-05-19 15:59:05 +00002407
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002408 // We need this to safely RAUW and delete call or invoke return values that
2409 // may themselves be live over a statepoint. For details, please see usage in
2410 // makeStatepointExplicitImpl.
2411 std::vector<DeferredReplacement> Replacements;
2412
Philip Reamesd16a9b12015-02-20 01:06:44 +00002413 // Now run through and replace the existing statepoints with new ones with
2414 // the live variables listed. We do not yet update uses of the values being
2415 // relocated. We have references to live variables that need to
2416 // survive to the last iteration of this loop. (By construction, the
2417 // previous statepoint can not be a live variable, thus we can and remove
2418 // the old statepoint calls as we go.)
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002419 for (size_t i = 0; i < Records.size(); i++)
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002420 makeStatepointExplicit(DT, ToUpdate[i], Records[i], Replacements);
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002421
2422 ToUpdate.clear(); // prevent accident use of invalid CallSites
Philip Reamesd16a9b12015-02-20 01:06:44 +00002423
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002424 for (auto &PR : Replacements)
2425 PR.doReplacement();
2426
2427 Replacements.clear();
2428
2429 for (auto &Info : Records) {
2430 // These live sets may contain state Value pointers, since we replaced calls
2431 // with operand bundles with calls wrapped in gc.statepoint, and some of
2432 // those calls may have been def'ing live gc pointers. Clear these out to
2433 // avoid accidentally using them.
2434 //
2435 // TODO: We should create a separate data structure that does not contain
2436 // these live sets, and migrate to using that data structure from this point
2437 // onward.
2438 Info.LiveSet.clear();
2439 Info.PointerToBase.clear();
2440 }
2441
Philip Reamesd16a9b12015-02-20 01:06:44 +00002442 // Do all the fixups of the original live variables to their relocated selves
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002443 SmallVector<Value *, 128> Live;
2444 for (size_t i = 0; i < Records.size(); i++) {
2445 PartiallyConstructedSafepointRecord &Info = Records[i];
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002446
Philip Reamesd16a9b12015-02-20 01:06:44 +00002447 // We can't simply save the live set from the original insertion. One of
2448 // the live values might be the result of a call which needs a safepoint.
2449 // That Value* no longer exists and we need to use the new gc_result.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002450 // Thankfully, the live set is embedded in the statepoint (and updated), so
Philip Reamesd16a9b12015-02-20 01:06:44 +00002451 // we just grab that.
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002452 Statepoint Statepoint(Info.StatepointToken);
2453 Live.insert(Live.end(), Statepoint.gc_args_begin(),
2454 Statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002455#ifndef NDEBUG
2456 // Do some basic sanity checks on our liveness results before performing
2457 // relocation. Relocation can and will turn mistakes in liveness results
2458 // into non-sensical code which is must harder to debug.
2459 // TODO: It would be nice to test consistency as well
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002460 assert(DT.isReachableFromEntry(Info.StatepointToken->getParent()) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002461 "statepoint must be reachable or liveness is meaningless");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002462 for (Value *V : Statepoint.gc_args()) {
Philip Reames9a2e01d2015-04-13 17:35:55 +00002463 if (!isa<Instruction>(V))
2464 // Non-instruction values trivial dominate all possible uses
2465 continue;
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002466 auto *LiveInst = cast<Instruction>(V);
Philip Reames9a2e01d2015-04-13 17:35:55 +00002467 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2468 "unreachable values should never be live");
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002469 assert(DT.dominates(LiveInst, Info.StatepointToken) &&
Philip Reames9a2e01d2015-04-13 17:35:55 +00002470 "basic SSA liveness expectation violated by liveness analysis");
2471 }
2472#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002473 }
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002474 unique_unsorted(Live);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002475
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002476#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002477 // sanity check
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002478 for (auto *Ptr : Live)
2479 assert(isGCPointerType(Ptr->getType()) && "must be a gc pointer type");
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002480#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002481
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002482 relocationViaAlloca(F, DT, Live, Records);
2483 return !Records.empty();
Philip Reamesd16a9b12015-02-20 01:06:44 +00002484}
2485
Sanjoy Das353a19e2015-06-02 22:33:37 +00002486// Handles both return values and arguments for Functions and CallSites.
2487template <typename AttrHolder>
Igor Laevskydde00292015-10-23 22:42:44 +00002488static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2489 unsigned Index) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002490 AttrBuilder R;
2491 if (AH.getDereferenceableBytes(Index))
2492 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2493 AH.getDereferenceableBytes(Index)));
2494 if (AH.getDereferenceableOrNullBytes(Index))
2495 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2496 AH.getDereferenceableOrNullBytes(Index)));
Igor Laevsky1ef06552015-10-26 19:06:01 +00002497 if (AH.doesNotAlias(Index))
2498 R.addAttribute(Attribute::NoAlias);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002499
2500 if (!R.empty())
2501 AH.setAttributes(AH.getAttributes().removeAttributes(
2502 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002503}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002504
2505void
Igor Laevskydde00292015-10-23 22:42:44 +00002506RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002507 LLVMContext &Ctx = F.getContext();
2508
2509 for (Argument &A : F.args())
2510 if (isa<PointerType>(A.getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002511 RemoveNonValidAttrAtIndex(Ctx, F, A.getArgNo() + 1);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002512
2513 if (isa<PointerType>(F.getReturnType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002514 RemoveNonValidAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002515}
2516
Igor Laevskydde00292015-10-23 22:42:44 +00002517void RewriteStatepointsForGC::stripNonValidAttributesFromBody(Function &F) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002518 if (F.empty())
2519 return;
2520
2521 LLVMContext &Ctx = F.getContext();
2522 MDBuilder Builder(Ctx);
2523
Nico Rieck78199512015-08-06 19:10:45 +00002524 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002525 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2526 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2527 bool IsImmutableTBAA =
2528 MD->getNumOperands() == 4 &&
2529 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2530
2531 if (!IsImmutableTBAA)
2532 continue; // no work to do, MD_tbaa is already marked mutable
2533
2534 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2535 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2536 uint64_t Offset =
2537 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2538
2539 MDNode *MutableTBAA =
2540 Builder.createTBAAStructTagNode(Base, Access, Offset);
2541 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2542 }
2543
2544 if (CallSite CS = CallSite(&I)) {
2545 for (int i = 0, e = CS.arg_size(); i != e; i++)
2546 if (isa<PointerType>(CS.getArgument(i)->getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002547 RemoveNonValidAttrAtIndex(Ctx, CS, i + 1);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002548 if (isa<PointerType>(CS.getType()))
Igor Laevskydde00292015-10-23 22:42:44 +00002549 RemoveNonValidAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002550 }
2551 }
2552}
2553
Philip Reamesd16a9b12015-02-20 01:06:44 +00002554/// Returns true if this function should be rewritten by this pass. The main
2555/// point of this function is as an extension point for custom logic.
2556static bool shouldRewriteStatepointsIn(Function &F) {
2557 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002558 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002559 const char *FunctionGCName = F.getGC();
2560 const StringRef StatepointExampleName("statepoint-example");
2561 const StringRef CoreCLRName("coreclr");
2562 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002563 (CoreCLRName == FunctionGCName);
2564 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002565 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002566}
2567
Igor Laevskydde00292015-10-23 22:42:44 +00002568void RewriteStatepointsForGC::stripNonValidAttributes(Module &M) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002569#ifndef NDEBUG
2570 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2571 "precondition!");
2572#endif
2573
2574 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002575 stripNonValidAttributesFromPrototype(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002576
2577 for (Function &F : M)
Igor Laevskydde00292015-10-23 22:42:44 +00002578 stripNonValidAttributesFromBody(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +00002579}
2580
Philip Reamesd16a9b12015-02-20 01:06:44 +00002581bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2582 // Nothing to do for declarations.
2583 if (F.isDeclaration() || F.empty())
2584 return false;
2585
2586 // Policy choice says not to rewrite - the most common reason is that we're
2587 // compiling code without a GCStrategy.
2588 if (!shouldRewriteStatepointsIn(F))
2589 return false;
2590
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002591 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00002592 TargetTransformInfo &TTI =
2593 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Philip Reames704e78b2015-04-10 22:34:56 +00002594
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002595 auto NeedsRewrite = [](Instruction &I) {
2596 if (UseDeoptBundles) {
2597 if (ImmutableCallSite CS = ImmutableCallSite(&I))
2598 return !callsGCLeafFunction(CS);
2599 return false;
2600 }
2601
2602 return isStatepoint(I);
2603 };
2604
Philip Reames85b36a82015-04-10 22:07:04 +00002605 // Gather all the statepoints which need rewritten. Be careful to only
2606 // consider those in reachable code since we need to ask dominance queries
2607 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002608 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002609 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002610 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002611 // TODO: only the ones with the flag set!
Sanjoy Das25ec1a32015-10-16 02:41:00 +00002612 if (NeedsRewrite(I)) {
Philip Reames85b36a82015-04-10 22:07:04 +00002613 if (DT.isReachableFromEntry(I.getParent()))
2614 ParsePointNeeded.push_back(CallSite(&I));
2615 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002616 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002617 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002618 }
2619
Philip Reames85b36a82015-04-10 22:07:04 +00002620 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002621
Philip Reames85b36a82015-04-10 22:07:04 +00002622 // Delete any unreachable statepoints so that we don't have unrewritten
2623 // statepoints surviving this pass. This makes testing easier and the
2624 // resulting IR less confusing to human readers. Rather than be fancy, we
2625 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002626 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002627 MadeChange |= removeUnreachableBlocks(F);
2628
Philip Reamesd16a9b12015-02-20 01:06:44 +00002629 // Return early if no work to do.
2630 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002631 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002632
Philip Reames85b36a82015-04-10 22:07:04 +00002633 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2634 // These are created by LCSSA. They have the effect of increasing the size
2635 // of liveness sets for no good reason. It may be harder to do this post
2636 // insertion since relocations and base phis can confuse things.
2637 for (BasicBlock &BB : F)
2638 if (BB.getUniquePredecessor()) {
2639 MadeChange = true;
2640 FoldSingleEntryPHINodes(&BB);
2641 }
2642
Philip Reames971dc3a2015-08-12 22:11:45 +00002643 // Before we start introducing relocations, we want to tweak the IR a bit to
2644 // avoid unfortunate code generation effects. The main example is that we
2645 // want to try to make sure the comparison feeding a branch is after any
2646 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2647 // values feeding a branch after relocation. This is semantically correct,
2648 // but results in extra register pressure since both the pre-relocation and
2649 // post-relocation copies must be available in registers. For code without
2650 // relocations this is handled elsewhere, but teaching the scheduler to
2651 // reverse the transform we're about to do would be slightly complex.
2652 // Note: This may extend the live range of the inputs to the icmp and thus
2653 // increase the liveset of any statepoint we move over. This is profitable
2654 // as long as all statepoints are in rare blocks. If we had in-register
2655 // lowering for live values this would be a much safer transform.
2656 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2657 if (auto *BI = dyn_cast<BranchInst>(TI))
2658 if (BI->isConditional())
2659 return dyn_cast<Instruction>(BI->getCondition());
2660 // TODO: Extend this to handle switches
2661 return nullptr;
2662 };
2663 for (BasicBlock &BB : F) {
2664 TerminatorInst *TI = BB.getTerminator();
2665 if (auto *Cond = getConditionInst(TI))
2666 // TODO: Handle more than just ICmps here. We should be able to move
2667 // most instructions without side effects or memory access.
2668 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2669 MadeChange = true;
2670 Cond->moveBefore(TI);
2671 }
2672 }
2673
Justin Bogner843fb202015-12-15 19:40:57 +00002674 MadeChange |= insertParsePoints(F, DT, TTI, ParsePointNeeded);
Philip Reames85b36a82015-04-10 22:07:04 +00002675 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002676}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002677
2678// liveness computation via standard dataflow
2679// -------------------------------------------------------------------
2680
2681// TODO: Consider using bitvectors for liveness, the set of potentially
2682// interesting values should be small and easy to pre-compute.
2683
Philip Reamesdf1ef082015-04-10 22:53:14 +00002684/// Compute the live-in set for the location rbegin starting from
2685/// the live-out set of the basic block
2686static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2687 BasicBlock::reverse_iterator rend,
2688 DenseSet<Value *> &LiveTmp) {
2689
2690 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2691 Instruction *I = &*ritr;
2692
2693 // KILL/Def - Remove this definition from LiveIn
2694 LiveTmp.erase(I);
2695
2696 // Don't consider *uses* in PHI nodes, we handle their contribution to
2697 // predecessor blocks when we seed the LiveOut sets
2698 if (isa<PHINode>(I))
2699 continue;
2700
2701 // USE - Add to the LiveIn set for this instruction
2702 for (Value *V : I->operands()) {
2703 assert(!isUnhandledGCPointerType(V->getType()) &&
2704 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002705 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2706 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002707 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002708 // - We assume that things which are constant (from LLVM's definition)
2709 // do not move at runtime. For example, the address of a global
2710 // variable is fixed, even though it's contents may not be.
2711 // - Second, we can't disallow arbitrary inttoptr constants even
2712 // if the language frontend does. Optimization passes are free to
2713 // locally exploit facts without respect to global reachability. This
2714 // can create sections of code which are dynamically unreachable and
2715 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002716 LiveTmp.insert(V);
2717 }
2718 }
2719 }
2720}
2721
2722static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2723
2724 for (BasicBlock *Succ : successors(BB)) {
2725 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2726 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2727 PHINode *Phi = cast<PHINode>(&*I);
2728 Value *V = Phi->getIncomingValueForBlock(BB);
2729 assert(!isUnhandledGCPointerType(V->getType()) &&
2730 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002731 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002732 LiveTmp.insert(V);
2733 }
2734 }
2735 }
2736}
2737
2738static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2739 DenseSet<Value *> KillSet;
2740 for (Instruction &I : *BB)
2741 if (isHandledGCPointerType(I.getType()))
2742 KillSet.insert(&I);
2743 return KillSet;
2744}
2745
Philip Reames9638ff92015-04-11 00:06:47 +00002746#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002747/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2748/// sanity check for the liveness computation.
2749static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2750 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002751 for (Value *V : Live) {
2752 if (auto *I = dyn_cast<Instruction>(V)) {
2753 // The terminator can be a member of the LiveOut set. LLVM's definition
2754 // of instruction dominance states that V does not dominate itself. As
2755 // such, we need to special case this to allow it.
2756 if (TermOkay && TI == I)
2757 continue;
2758 assert(DT.dominates(I, TI) &&
2759 "basic SSA liveness expectation violated by liveness analysis");
2760 }
2761 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002762}
2763
2764/// Check that all the liveness sets used during the computation of liveness
2765/// obey basic SSA properties. This is useful for finding cases where we miss
2766/// a def.
2767static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2768 BasicBlock &BB) {
2769 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2770 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2771 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2772}
Philip Reames9638ff92015-04-11 00:06:47 +00002773#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002774
2775static void computeLiveInValues(DominatorTree &DT, Function &F,
2776 GCPtrLivenessData &Data) {
2777
Philip Reames4d80ede2015-04-10 23:11:26 +00002778 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002779 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002780 // We use a SetVector so that we don't have duplicates in the worklist.
2781 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002782 };
2783 auto NextItem = [&]() {
2784 BasicBlock *BB = Worklist.back();
2785 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002786 return BB;
2787 };
2788
2789 // Seed the liveness for each individual block
2790 for (BasicBlock &BB : F) {
2791 Data.KillSet[&BB] = computeKillSet(&BB);
2792 Data.LiveSet[&BB].clear();
2793 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2794
2795#ifndef NDEBUG
2796 for (Value *Kill : Data.KillSet[&BB])
2797 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2798#endif
2799
2800 Data.LiveOut[&BB] = DenseSet<Value *>();
2801 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2802 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2803 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2804 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2805 if (!Data.LiveIn[&BB].empty())
2806 AddPredsToWorklist(&BB);
2807 }
2808
2809 // Propagate that liveness until stable
2810 while (!Worklist.empty()) {
2811 BasicBlock *BB = NextItem();
2812
2813 // Compute our new liveout set, then exit early if it hasn't changed
2814 // despite the contribution of our successor.
2815 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2816 const auto OldLiveOutSize = LiveOut.size();
2817 for (BasicBlock *Succ : successors(BB)) {
2818 assert(Data.LiveIn.count(Succ));
2819 set_union(LiveOut, Data.LiveIn[Succ]);
2820 }
2821 // assert OutLiveOut is a subset of LiveOut
2822 if (OldLiveOutSize == LiveOut.size()) {
2823 // If the sets are the same size, then we didn't actually add anything
2824 // when unioning our successors LiveIn Thus, the LiveIn of this block
2825 // hasn't changed.
2826 continue;
2827 }
2828 Data.LiveOut[BB] = LiveOut;
2829
2830 // Apply the effects of this basic block
2831 DenseSet<Value *> LiveTmp = LiveOut;
2832 set_union(LiveTmp, Data.LiveSet[BB]);
2833 set_subtract(LiveTmp, Data.KillSet[BB]);
2834
2835 assert(Data.LiveIn.count(BB));
2836 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2837 // assert: OldLiveIn is a subset of LiveTmp
2838 if (OldLiveIn.size() != LiveTmp.size()) {
2839 Data.LiveIn[BB] = LiveTmp;
2840 AddPredsToWorklist(BB);
2841 }
2842 } // while( !worklist.empty() )
2843
2844#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002845 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002846 // missing kills during the above iteration.
2847 for (BasicBlock &BB : F) {
2848 checkBasicSSA(DT, Data, BB);
2849 }
2850#endif
2851}
2852
2853static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2854 StatepointLiveSetTy &Out) {
2855
2856 BasicBlock *BB = Inst->getParent();
2857
2858 // Note: The copy is intentional and required
2859 assert(Data.LiveOut.count(BB));
2860 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2861
2862 // We want to handle the statepoint itself oddly. It's
2863 // call result is not live (normal), nor are it's arguments
2864 // (unless they're used again later). This adjustment is
2865 // specifically what we need to relocate
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002866 BasicBlock::reverse_iterator rend(Inst->getIterator());
Philip Reamesdf1ef082015-04-10 22:53:14 +00002867 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2868 LiveOut.erase(Inst);
2869 Out.insert(LiveOut.begin(), LiveOut.end());
2870}
2871
2872static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2873 const CallSite &CS,
2874 PartiallyConstructedSafepointRecord &Info) {
2875 Instruction *Inst = CS.getInstruction();
2876 StatepointLiveSetTy Updated;
2877 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2878
2879#ifndef NDEBUG
2880 DenseSet<Value *> Bases;
2881 for (auto KVPair : Info.PointerToBase) {
2882 Bases.insert(KVPair.second);
2883 }
2884#endif
2885 // We may have base pointers which are now live that weren't before. We need
2886 // to update the PointerToBase structure to reflect this.
2887 for (auto V : Updated)
2888 if (!Info.PointerToBase.count(V)) {
2889 assert(Bases.count(V) && "can't find base for unexpected live value");
2890 Info.PointerToBase[V] = V;
2891 continue;
2892 }
2893
2894#ifndef NDEBUG
2895 for (auto V : Updated) {
2896 assert(Info.PointerToBase.count(V) &&
2897 "must be able to find base for live value");
2898 }
2899#endif
2900
2901 // Remove any stale base mappings - this can happen since our liveness is
2902 // more precise then the one inherent in the base pointer analysis
2903 DenseSet<Value *> ToErase;
2904 for (auto KVPair : Info.PointerToBase)
2905 if (!Updated.count(KVPair.first))
2906 ToErase.insert(KVPair.first);
2907 for (auto V : ToErase)
2908 Info.PointerToBase.erase(V);
2909
2910#ifndef NDEBUG
2911 for (auto KVPair : Info.PointerToBase)
2912 assert(Updated.count(KVPair.first) && "record for non-live value");
2913#endif
2914
Sanjoy Dasb40bd1a2015-10-07 02:39:18 +00002915 Info.LiveSet = Updated;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002916}