blob: c70619cf27c5490522aa1e13dfabdc2a0c8cd27c [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
Benjamin Kramer6f665452015-02-20 14:00:58 +000075namespace {
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000076struct RewriteStatepointsForGC : public ModulePass {
Philip Reamesd16a9b12015-02-20 01:06:44 +000077 static char ID; // Pass identification, replacement for typeid
78
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000079 RewriteStatepointsForGC() : ModulePass(ID) {
Philip Reamesd16a9b12015-02-20 01:06:44 +000080 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
81 }
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000082 bool runOnFunction(Function &F);
83 bool runOnModule(Module &M) override {
84 bool Changed = false;
85 for (Function &F : M)
86 Changed |= runOnFunction(F);
Sanjoy Das353a19e2015-06-02 22:33:37 +000087
88 if (Changed) {
89 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
90 // returns true for at least one function in the module. Since at least
91 // one function changed, we know that the precondition is satisfied.
92 stripDereferenceabilityInfo(M);
93 }
94
Sanjoy Dasea45f0e2015-06-02 22:33:34 +000095 return Changed;
96 }
Philip Reamesd16a9b12015-02-20 01:06:44 +000097
98 void getAnalysisUsage(AnalysisUsage &AU) const override {
99 // We add and rewrite a bunch of instructions, but don't really do much
100 // else. We could in theory preserve a lot more analyses here.
101 AU.addRequired<DominatorTreeWrapperPass>();
Igor Laevskye0317182015-05-19 15:59:05 +0000102 AU.addRequired<TargetTransformInfoWrapperPass>();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000103 }
Sanjoy Das353a19e2015-06-02 22:33:37 +0000104
105 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
106 /// dereferenceability that are no longer valid/correct after
107 /// RewriteStatepointsForGC has run. This is because semantically, after
108 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
109 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
110 /// by erasing all attributes in the module that externally imply
111 /// dereferenceability.
112 ///
113 void stripDereferenceabilityInfo(Module &M);
114
115 // Helpers for stripDereferenceabilityInfo
116 void stripDereferenceabilityInfoFromBody(Function &F);
117 void stripDereferenceabilityInfoFromPrototype(Function &F);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000118};
Benjamin Kramer6f665452015-02-20 14:00:58 +0000119} // namespace
Philip Reamesd16a9b12015-02-20 01:06:44 +0000120
121char RewriteStatepointsForGC::ID = 0;
122
Sanjoy Dasea45f0e2015-06-02 22:33:34 +0000123ModulePass *llvm::createRewriteStatepointsForGCPass() {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000124 return new RewriteStatepointsForGC();
125}
126
127INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
128 "Make relocations explicit at statepoints", false, false)
129INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
130INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
131 "Make relocations explicit at statepoints", false, false)
132
133namespace {
Philip Reamesdf1ef082015-04-10 22:53:14 +0000134struct GCPtrLivenessData {
135 /// Values defined in this block.
136 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
137 /// Values used in this block (and thus live); does not included values
138 /// killed within this block.
139 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
140
141 /// Values live into this basic block (i.e. used by any
142 /// instruction in this basic block or ones reachable from here)
143 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
144
145 /// Values live out of this basic block (i.e. live into
146 /// any successor block)
147 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
148};
149
Philip Reamesd16a9b12015-02-20 01:06:44 +0000150// The type of the internal cache used inside the findBasePointers family
151// of functions. From the callers perspective, this is an opaque type and
152// should not be inspected.
153//
154// In the actual implementation this caches two relations:
155// - The base relation itself (i.e. this pointer is based on that one)
156// - The base defining value relation (i.e. before base_phi insertion)
157// Generally, after the execution of a full findBasePointer call, only the
158// base relation will remain. Internally, we add a mixture of the two
159// types, then update all the second type to the first type
Philip Reamese9c3b9b2015-02-20 22:48:20 +0000160typedef DenseMap<Value *, Value *> DefiningValueMapTy;
Philip Reames1f017542015-02-20 23:16:52 +0000161typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
Igor Laevskye0317182015-05-19 15:59:05 +0000162typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000163
Philip Reamesd16a9b12015-02-20 01:06:44 +0000164struct PartiallyConstructedSafepointRecord {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000165 /// The set of values known to be live across this safepoint
Philip Reames860660e2015-02-20 22:05:18 +0000166 StatepointLiveSetTy liveset;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000167
168 /// Mapping from live pointers to a base-defining-value
Philip Reamesf2041322015-02-20 19:26:04 +0000169 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000170
Philip Reames0a3240f2015-02-20 21:34:11 +0000171 /// The *new* gc.statepoint instruction itself. This produces the token
172 /// that normal path gc.relocates and the gc.result are tied to.
173 Instruction *StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000174
Philip Reamesf2041322015-02-20 19:26:04 +0000175 /// Instruction to which exceptional gc relocates are attached
176 /// Makes it easier to iterate through them during relocationViaAlloca.
177 Instruction *UnwindToken;
Igor Laevskye0317182015-05-19 15:59:05 +0000178
179 /// Record live values we are rematerialized instead of relocating.
180 /// They are not included into 'liveset' field.
181 /// Maps rematerialized copy to it's original value.
182 RematerializedValueMapTy RematerializedValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000183};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000184}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000185
Philip Reamesdf1ef082015-04-10 22:53:14 +0000186/// Compute the live-in set for every basic block in the function
187static void computeLiveInValues(DominatorTree &DT, Function &F,
188 GCPtrLivenessData &Data);
189
190/// Given results from the dataflow liveness computation, find the set of live
191/// Values at a particular instruction.
192static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
193 StatepointLiveSetTy &out);
194
Philip Reamesd16a9b12015-02-20 01:06:44 +0000195// TODO: Once we can get to the GCStrategy, this becomes
196// Optional<bool> isGCManagedPointer(const Value *V) const override {
197
Craig Toppere3dcce92015-08-01 22:20:21 +0000198static bool isGCPointerType(Type *T) {
199 if (auto *PT = dyn_cast<PointerType>(T))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000200 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
201 // GC managed heap. We know that a pointer into this heap needs to be
202 // updated and that no other pointer does.
203 return (1 == PT->getAddressSpace());
204 return false;
205}
206
Philip Reames8531d8c2015-04-10 21:48:25 +0000207// Return true if this type is one which a) is a gc pointer or contains a GC
208// pointer and b) is of a type this code expects to encounter as a live value.
209// (The insertion code will assert that a type which matches (a) and not (b)
Philip Reames704e78b2015-04-10 22:34:56 +0000210// is not encountered.)
Philip Reames8531d8c2015-04-10 21:48:25 +0000211static bool isHandledGCPointerType(Type *T) {
212 // We fully support gc pointers
213 if (isGCPointerType(T))
214 return true;
215 // We partially support vectors of gc pointers. The code will assert if it
216 // can't handle something.
217 if (auto VT = dyn_cast<VectorType>(T))
218 if (isGCPointerType(VT->getElementType()))
219 return true;
220 return false;
221}
222
223#ifndef NDEBUG
224/// Returns true if this type contains a gc pointer whether we know how to
225/// handle that type or not.
226static bool containsGCPtrType(Type *Ty) {
Philip Reames704e78b2015-04-10 22:34:56 +0000227 if (isGCPointerType(Ty))
Philip Reames8531d8c2015-04-10 21:48:25 +0000228 return true;
229 if (VectorType *VT = dyn_cast<VectorType>(Ty))
230 return isGCPointerType(VT->getScalarType());
231 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
232 return containsGCPtrType(AT->getElementType());
233 if (StructType *ST = dyn_cast<StructType>(Ty))
Philip Reames704e78b2015-04-10 22:34:56 +0000234 return std::any_of(
235 ST->subtypes().begin(), ST->subtypes().end(),
236 [](Type *SubType) { return containsGCPtrType(SubType); });
Philip Reames8531d8c2015-04-10 21:48:25 +0000237 return false;
238}
239
240// Returns true if this is a type which a) is a gc pointer or contains a GC
241// pointer and b) is of a type which the code doesn't expect (i.e. first class
242// aggregates). Used to trip assertions.
243static bool isUnhandledGCPointerType(Type *Ty) {
244 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
245}
246#endif
247
Philip Reamesd16a9b12015-02-20 01:06:44 +0000248static bool order_by_name(llvm::Value *a, llvm::Value *b) {
249 if (a->hasName() && b->hasName()) {
250 return -1 == a->getName().compare(b->getName());
251 } else if (a->hasName() && !b->hasName()) {
252 return true;
253 } else if (!a->hasName() && b->hasName()) {
254 return false;
255 } else {
256 // Better than nothing, but not stable
257 return a < b;
258 }
259}
260
Philip Reamesdf1ef082015-04-10 22:53:14 +0000261// Conservatively identifies any definitions which might be live at the
262// given instruction. The analysis is performed immediately before the
263// given instruction. Values defined by that instruction are not considered
264// live. Values used by that instruction are considered live.
265static void analyzeParsePointLiveness(
266 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
267 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000268 Instruction *inst = CS.getInstruction();
269
Philip Reames1f017542015-02-20 23:16:52 +0000270 StatepointLiveSetTy liveset;
Philip Reamesdf1ef082015-04-10 22:53:14 +0000271 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000272
273 if (PrintLiveSet) {
274 // Note: This output is used by several of the test cases
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000275 // The order of elements in a set is not stable, put them in a vec and sort
Philip Reamesd16a9b12015-02-20 01:06:44 +0000276 // by name
Philip Reamesdab35f32015-09-02 21:11:44 +0000277 SmallVector<Value *, 64> Temp;
278 Temp.insert(Temp.end(), liveset.begin(), liveset.end());
279 std::sort(Temp.begin(), Temp.end(), order_by_name);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000280 errs() << "Live Variables:\n";
Philip Reamesdab35f32015-09-02 21:11:44 +0000281 for (Value *V : Temp)
282 dbgs() << " " << V->getName() << " " << *V << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000283 }
284 if (PrintLiveSetSize) {
285 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
286 errs() << "Number live values: " << liveset.size() << "\n";
287 }
288 result.liveset = liveset;
289}
290
Philip Reamesf5b8e472015-09-03 21:34:30 +0000291static bool isKnownBaseResult(Value *V);
292namespace {
293/// A single base defining value - An immediate base defining value for an
294/// instruction 'Def' is an input to 'Def' whose base is also a base of 'Def'.
295/// For instructions which have multiple pointer [vector] inputs or that
296/// transition between vector and scalar types, there is no immediate base
297/// defining value. The 'base defining value' for 'Def' is the transitive
298/// closure of this relation stopping at the first instruction which has no
299/// immediate base defining value. The b.d.v. might itself be a base pointer,
300/// but it can also be an arbitrary derived pointer.
301struct BaseDefiningValueResult {
302 /// Contains the value which is the base defining value.
303 Value * const BDV;
304 /// True if the base defining value is also known to be an actual base
305 /// pointer.
306 const bool IsKnownBase;
307 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
308 : BDV(BDV), IsKnownBase(IsKnownBase) {
309#ifndef NDEBUG
310 // Check consistency between new and old means of checking whether a BDV is
311 // a base.
312 bool MustBeBase = isKnownBaseResult(BDV);
313 assert(!MustBeBase || MustBeBase == IsKnownBase);
314#endif
315 }
316};
317}
318
319static BaseDefiningValueResult findBaseDefiningValue(Value *I);
Philip Reames311f7102015-05-12 22:19:52 +0000320
Philip Reames8fe7f132015-06-26 22:47:37 +0000321/// Return a base defining value for the 'Index' element of the given vector
322/// instruction 'I'. If Index is null, returns a BDV for the entire vector
323/// 'I'. As an optimization, this method will try to determine when the
324/// element is known to already be a base pointer. If this can be established,
325/// the second value in the returned pair will be true. Note that either a
326/// vector or a pointer typed value can be returned. For the former, the
327/// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
328/// If the later, the return pointer is a BDV (or possibly a base) for the
329/// particular element in 'I'.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000330static BaseDefiningValueResult
Philip Reames66287132015-09-09 23:40:12 +0000331findBaseDefiningValueOfVector(Value *I) {
Philip Reames8531d8c2015-04-10 21:48:25 +0000332 assert(I->getType()->isVectorTy() &&
333 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
334 "Illegal to ask for the base pointer of a non-pointer type");
335
336 // Each case parallels findBaseDefiningValue below, see that code for
337 // detailed motivation.
338
339 if (isa<Argument>(I))
340 // An incoming argument to the function is a base pointer
Philip Reamesf5b8e472015-09-03 21:34:30 +0000341 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000342
343 // We shouldn't see the address of a global as a vector value?
344 assert(!isa<GlobalVariable>(I) &&
345 "unexpected global variable found in base of vector");
346
347 // inlining could possibly introduce phi node that contains
348 // undef if callee has multiple returns
349 if (isa<UndefValue>(I))
350 // utterly meaningless, but useful for dealing with partially optimized
351 // code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000352 return BaseDefiningValueResult(I, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000353
354 // Due to inheritance, this must be _after_ the global variable and undef
355 // checks
356 if (Constant *Con = dyn_cast<Constant>(I)) {
357 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
358 "order of checks wrong!");
359 assert(Con->isNullValue() && "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000360 return BaseDefiningValueResult(Con, true);
Philip Reames8531d8c2015-04-10 21:48:25 +0000361 }
Philip Reames8fe7f132015-06-26 22:47:37 +0000362
Philip Reames8531d8c2015-04-10 21:48:25 +0000363 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000364 return BaseDefiningValueResult(I, true);
Philip Reamesf5b8e472015-09-03 21:34:30 +0000365
Philip Reames66287132015-09-09 23:40:12 +0000366 if (isa<InsertElementInst>(I))
Philip Reames8fe7f132015-06-26 22:47:37 +0000367 // We don't know whether this vector contains entirely base pointers or
368 // not. To be conservatively correct, we treat it as a BDV and will
369 // duplicate code as needed to construct a parallel vector of bases.
Philip Reames66287132015-09-09 23:40:12 +0000370 return BaseDefiningValueResult(I, false);
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000371
Philip Reames8fe7f132015-06-26 22:47:37 +0000372 if (isa<ShuffleVectorInst>(I))
373 // We don't know whether this vector contains entirely base pointers or
374 // not. To be conservatively correct, we treat it as a BDV and will
375 // duplicate code as needed to construct a parallel vector of bases.
376 // TODO: There a number of local optimizations which could be applied here
377 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000378 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000379
380 // A PHI or Select is a base defining value. The outer findBasePointer
381 // algorithm is responsible for constructing a base value for this BDV.
382 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
383 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000384 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000385}
386
Philip Reamesd16a9b12015-02-20 01:06:44 +0000387/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000388/// defines the base pointer for the input, b) blocks the simple search
389/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
390/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000391static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000392 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000393 return findBaseDefiningValueOfVector(I);
Philip Reames8fe7f132015-06-26 22:47:37 +0000394
Philip Reamesd16a9b12015-02-20 01:06:44 +0000395 assert(I->getType()->isPointerTy() &&
396 "Illegal to ask for the base pointer of a non-pointer type");
397
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000398 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000399 // An incoming argument to the function is a base pointer
400 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000401 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000402
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000403 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000404 // base case
Philip Reamesf5b8e472015-09-03 21:34:30 +0000405 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000406
407 // inlining could possibly introduce phi node that contains
408 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000409 if (isa<UndefValue>(I))
410 // utterly meaningless, but useful for dealing with
411 // partially optimized code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000412 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000413
414 // Due to inheritance, this must be _after_ the global variable and undef
415 // checks
Philip Reames3ea15892015-09-03 21:57:40 +0000416 if (isa<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000417 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
418 "order of checks wrong!");
419 // Note: Finding a constant base for something marked for relocation
420 // doesn't really make sense. The most likely case is either a) some
421 // screwed up the address space usage or b) your validating against
422 // compiled C++ code w/o the proper separation. The only real exception
423 // is a null pointer. You could have generic code written to index of
424 // off a potentially null value and have proven it null. We also use
425 // null pointers in dead paths of relocation phis (which we might later
426 // want to find a base pointer for).
Philip Reames3ea15892015-09-03 21:57:40 +0000427 assert(isa<ConstantPointerNull>(I) &&
Philip Reames24c6cd52015-03-27 05:47:00 +0000428 "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000429 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000430 }
431
432 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000433 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000434 // If we find a cast instruction here, it means we've found a cast which is
435 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
436 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000437 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
438 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000439 }
440
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000441 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000442 // The value loaded is an gc base itself
443 return BaseDefiningValueResult(I, true);
444
Philip Reamesd16a9b12015-02-20 01:06:44 +0000445
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000446 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
447 // The base of this GEP is the base
448 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000449
450 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
451 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000452 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000453 default:
454 // fall through to general call handling
455 break;
456 case Intrinsic::experimental_gc_statepoint:
457 case Intrinsic::experimental_gc_result_float:
458 case Intrinsic::experimental_gc_result_int:
459 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000460 case Intrinsic::experimental_gc_relocate: {
461 // Rerunning safepoint insertion after safepoints are already
462 // inserted is not supported. It could probably be made to work,
463 // but why are you doing this? There's no good reason.
464 llvm_unreachable("repeat safepoint insertion is not supported");
465 }
466 case Intrinsic::gcroot:
467 // Currently, this mechanism hasn't been extended to work with gcroot.
468 // There's no reason it couldn't be, but I haven't thought about the
469 // implications much.
470 llvm_unreachable(
471 "interaction with the gcroot mechanism is not supported");
472 }
473 }
474 // We assume that functions in the source language only return base
475 // pointers. This should probably be generalized via attributes to support
476 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000477 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000478 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000479
480 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000481 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000482 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
483
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000484 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000485 // A CAS is effectively a atomic store and load combined under a
486 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000487 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000488 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000489
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000490 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000491 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000492
493 // The aggregate ops. Aggregates can either be in the heap or on the
494 // stack, but in either case, this is simply a field load. As a result,
495 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000496 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000497 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000498
499 // We should never see an insert vector since that would require we be
500 // tracing back a struct value not a pointer value.
501 assert(!isa<InsertValueInst>(I) &&
502 "Base pointer for a struct is meaningless");
503
Philip Reames9ac4e382015-08-12 21:00:20 +0000504 // An extractelement produces a base result exactly when it's input does.
505 // We may need to insert a parallel instruction to extract the appropriate
506 // element out of the base vector corresponding to the input. Given this,
507 // it's analogous to the phi and select case even though it's not a merge.
Philip Reames66287132015-09-09 23:40:12 +0000508 if (isa<ExtractElementInst>(I))
509 // Note: There a lot of obvious peephole cases here. This are deliberately
510 // handled after the main base pointer inference algorithm to make writing
511 // test cases to exercise that code easier.
512 return BaseDefiningValueResult(I, false);
Philip Reames9ac4e382015-08-12 21:00:20 +0000513
Philip Reamesd16a9b12015-02-20 01:06:44 +0000514 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000515 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000516 // derived pointers (each with it's own base potentially). It's the job of
517 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000518 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000519 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000520 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000521}
522
523/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000524static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
525 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000526 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000527 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000528 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
529 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000530 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000531 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000532 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000533}
534
535/// Return a base pointer for this value if known. Otherwise, return it's
536/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000537static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
538 Value *Def = findBaseDefiningValueCached(I, Cache);
539 auto Found = Cache.find(Def);
540 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000541 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000542 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000543 }
544 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000545 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000546}
547
548/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
549/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000550static bool isKnownBaseResult(Value *V) {
Philip Reames66287132015-09-09 23:40:12 +0000551 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
552 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
553 !isa<ShuffleVectorInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000554 // no recursion possible
555 return true;
556 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000557 if (isa<Instruction>(V) &&
558 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000559 // This is a previously inserted base phi or select. We know
560 // that this is a base value.
561 return true;
562 }
563
564 // We need to keep searching
565 return false;
566}
567
Philip Reamesd16a9b12015-02-20 01:06:44 +0000568namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000569/// Models the state of a single base defining value in the findBasePointer
570/// algorithm for determining where a new instruction is needed to propagate
571/// the base of this BDV.
572class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000573public:
574 enum Status { Unknown, Base, Conflict };
575
Philip Reames9b141ed2015-07-23 22:49:14 +0000576 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000577 assert(status != Base || b);
578 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000579 explicit BDVState(Value *b) : status(Base), base(b) {}
580 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000581
582 Status getStatus() const { return status; }
583 Value *getBase() const { return base; }
584
585 bool isBase() const { return getStatus() == Base; }
586 bool isUnknown() const { return getStatus() == Unknown; }
587 bool isConflict() const { return getStatus() == Conflict; }
588
Philip Reames9b141ed2015-07-23 22:49:14 +0000589 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000590 return base == other.base && status == other.status;
591 }
592
Philip Reames9b141ed2015-07-23 22:49:14 +0000593 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000594
Philip Reames2a892a62015-07-23 22:25:26 +0000595 LLVM_DUMP_METHOD
596 void dump() const { print(dbgs()); dbgs() << '\n'; }
597
598 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000599 switch (status) {
600 case Unknown:
601 OS << "U";
602 break;
603 case Base:
604 OS << "B";
605 break;
606 case Conflict:
607 OS << "C";
608 break;
609 };
610 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000611 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000612 }
613
614private:
615 Status status;
616 Value *base; // non null only if status == base
617};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000618}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000619
Philip Reames6906e922015-09-02 21:57:17 +0000620#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000621static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000622 State.print(OS);
623 return OS;
624}
Philip Reames6906e922015-09-02 21:57:17 +0000625#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000626
Philip Reamesb3967cd2015-09-02 22:30:53 +0000627namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000628// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000629// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000630// operation is implemented in MeetBDVStates::pureMeet
631class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000632public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000633 /// Initializes the currentResult to the TOP state so that if can be met with
634 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000635 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000636
Philip Reames9b141ed2015-07-23 22:49:14 +0000637 // Destructively meet the current result with the given BDVState
638 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000639 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000640 }
641
Philip Reames9b141ed2015-07-23 22:49:14 +0000642 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000643
644private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000645 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000646
Philip Reames9b141ed2015-07-23 22:49:14 +0000647 /// Perform a meet operation on two elements of the BDVState lattice.
648 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000649 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
650 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000651 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000652 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
653 << " produced " << Result << "\n");
654 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000655 }
656
Philip Reames9b141ed2015-07-23 22:49:14 +0000657 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000658 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000659 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000660 return stateB;
661
Philip Reames9b141ed2015-07-23 22:49:14 +0000662 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000663 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000664 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000665 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000666
667 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000668 if (stateA.getBase() == stateB.getBase()) {
669 assert(stateA == stateB && "equality broken!");
670 return stateA;
671 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000672 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000673 }
David Blaikie82ad7872015-02-20 23:44:24 +0000674 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000675 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000676
Philip Reames9b141ed2015-07-23 22:49:14 +0000677 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000678 return stateA;
679 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000680 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000681 }
682};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000683}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000684
685
Philip Reamesd16a9b12015-02-20 01:06:44 +0000686/// For a given value or instruction, figure out what base ptr it's derived
687/// from. For gc objects, this is simply itself. On success, returns a value
688/// which is the base pointer. (This is reliable and can be used for
689/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000690static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000691 Value *def = findBaseOrBDV(I, cache);
692
693 if (isKnownBaseResult(def)) {
694 return def;
695 }
696
697 // Here's the rough algorithm:
698 // - For every SSA value, construct a mapping to either an actual base
699 // pointer or a PHI which obscures the base pointer.
700 // - Construct a mapping from PHI to unknown TOP state. Use an
701 // optimistic algorithm to propagate base pointer information. Lattice
702 // looks like:
703 // UNKNOWN
704 // b1 b2 b3 b4
705 // CONFLICT
706 // When algorithm terminates, all PHIs will either have a single concrete
707 // base or be in a conflict state.
708 // - For every conflict, insert a dummy PHI node without arguments. Add
709 // these to the base[Instruction] = BasePtr mapping. For every
710 // non-conflict, add the actual base.
711 // - For every conflict, add arguments for the base[a] of each input
712 // arguments.
713 //
714 // Note: A simpler form of this would be to add the conflict form of all
715 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000716 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000717 // overall worse solution.
718
Philip Reames29e9ae72015-07-24 00:42:55 +0000719#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000720 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames66287132015-09-09 23:40:12 +0000721 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
722 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000723 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000724#endif
Philip Reames88958b22015-07-24 00:02:11 +0000725
726 // Once populated, will contain a mapping from each potentially non-base BDV
727 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000728 // We use the order of insertion (DFS over the def/use graph) to provide a
729 // stable deterministic ordering for visiting DenseMaps (which are unordered)
730 // below. This is important for deterministic compilation.
731 MapVector<Value *, BDVState> states;
732
733 // Recursively fill in all base defining values reachable from the initial
734 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000735 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000736 SmallVector<Value*, 16> Worklist;
737 Worklist.push_back(def);
Philip Reames15d55632015-09-09 23:26:08 +0000738 states.insert(std::make_pair(def, BDVState()));
Philip Reames88958b22015-07-24 00:02:11 +0000739 while (!Worklist.empty()) {
740 Value *Current = Worklist.pop_back_val();
741 assert(!isKnownBaseResult(Current) && "why did it get added?");
742
743 auto visitIncomingValue = [&](Value *InVal) {
744 Value *Base = findBaseOrBDV(InVal, cache);
745 if (isKnownBaseResult(Base))
746 // Known bases won't need new instructions introduced and can be
747 // ignored safely
748 return;
749 assert(isExpectedBDVType(Base) && "the only non-base values "
750 "we see should be base defining values");
Philip Reames15d55632015-09-09 23:26:08 +0000751 if (states.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000752 Worklist.push_back(Base);
753 };
754 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
755 for (Value *InVal : Phi->incoming_values())
756 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000757 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000758 visitIncomingValue(Sel->getTrueValue());
759 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000760 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
761 visitIncomingValue(EE->getVectorOperand());
Philip Reames66287132015-09-09 23:40:12 +0000762 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
763 visitIncomingValue(IE->getOperand(0)); // vector operand
764 visitIncomingValue(IE->getOperand(1)); // scalar operand
Philip Reames9ac4e382015-08-12 21:00:20 +0000765 } else {
Philip Reames66287132015-09-09 23:40:12 +0000766 // There is one known class of instructions we know we don't handle.
767 assert(isa<ShuffleVectorInst>(Current));
Philip Reames9ac4e382015-08-12 21:00:20 +0000768 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000769 }
770 }
771 }
772
Philip Reamesdab35f32015-09-02 21:11:44 +0000773#ifndef NDEBUG
774 DEBUG(dbgs() << "States after initialization:\n");
775 for (auto Pair : states) {
776 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000777 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000778#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000779
Philip Reames273e6bb2015-07-23 21:41:27 +0000780 // Return a phi state for a base defining value. We'll generate a new
781 // base state for known bases and expect to find a cached state otherwise.
782 auto getStateForBDV = [&](Value *baseValue) {
783 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000784 return BDVState(baseValue);
Philip Reames273e6bb2015-07-23 21:41:27 +0000785 auto I = states.find(baseValue);
786 assert(I != states.end() && "lookup failed!");
787 return I->second;
788 };
789
Philip Reamesd16a9b12015-02-20 01:06:44 +0000790 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000791 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000792#ifndef NDEBUG
793 size_t oldSize = states.size();
794#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000795 progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000796 // We're only changing values in this loop, thus safe to keep iterators.
797 // Since this is computing a fixed point, the order of visit does not
798 // effect the result. TODO: We could use a worklist here and make this run
799 // much faster.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000800 for (auto Pair : states) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000801 Value *v = Pair.first;
802 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000803
Philip Reames9b141ed2015-07-23 22:49:14 +0000804 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000805 // instance which represents the BDV of that value.
806 auto getStateForInput = [&](Value *V) mutable {
807 Value *BDV = findBaseOrBDV(V, cache);
808 return getStateForBDV(BDV);
809 };
810
Philip Reames9b141ed2015-07-23 22:49:14 +0000811 MeetBDVStates calculateMeet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000812 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000813 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
814 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reames9ac4e382015-08-12 21:00:20 +0000815 } else if (PHINode *Phi = dyn_cast<PHINode>(v)) {
816 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000817 calculateMeet.meetWith(getStateForInput(Val));
Philip Reames66287132015-09-09 23:40:12 +0000818 } else if (auto *EE = dyn_cast<ExtractElementInst>(v)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000819 // The 'meet' for an extractelement is slightly trivial, but it's still
820 // useful in that it drives us to conflict if our input is.
Philip Reames9ac4e382015-08-12 21:00:20 +0000821 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
Philip Reames66287132015-09-09 23:40:12 +0000822 } else {
823 // Given there's a inherent type mismatch between the operands, will
824 // *always* produce Conflict.
825 auto *IE = cast<InsertElementInst>(v);
826 calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
827 calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
Philip Reames9ac4e382015-08-12 21:00:20 +0000828 }
829
Philip Reames9b141ed2015-07-23 22:49:14 +0000830 BDVState oldState = states[v];
831 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000832 if (oldState != newState) {
833 progress = true;
834 states[v] = newState;
835 }
836 }
837
838 assert(oldSize <= states.size());
839 assert(oldSize == states.size() || progress);
840 }
841
Philip Reamesdab35f32015-09-02 21:11:44 +0000842#ifndef NDEBUG
843 DEBUG(dbgs() << "States after meet iteration:\n");
844 for (auto Pair : states) {
845 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000846 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000847#endif
848
Philip Reamesd16a9b12015-02-20 01:06:44 +0000849 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000850 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames15d55632015-09-09 23:26:08 +0000851 for (auto Pair : states) {
852 Instruction *I = cast<Instruction>(Pair.first);
853 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000854 assert(!isKnownBaseResult(I) && "why did it get added?");
855 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000856
857 // extractelement instructions are a bit special in that we may need to
858 // insert an extract even when we know an exact base for the instruction.
859 // The problem is that we need to convert from a vector base to a scalar
860 // base for the particular indice we're interested in.
861 if (State.isBase() && isa<ExtractElementInst>(I) &&
862 isa<VectorType>(State.getBase()->getType())) {
863 auto *EE = cast<ExtractElementInst>(I);
864 // TODO: In many cases, the new instruction is just EE itself. We should
865 // exploit this, but can't do it here since it would break the invariant
866 // about the BDV not being known to be a base.
867 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
868 EE->getIndexOperand(),
869 "base_ee", EE);
870 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
871 states[I] = BDVState(BDVState::Base, BaseInst);
872 }
Philip Reames66287132015-09-09 23:40:12 +0000873
874 // Since we're joining a vector and scalar base, they can never be the
875 // same. As a result, we should always see insert element having reached
876 // the conflict state.
877 if (isa<InsertElementInst>(I)) {
878 assert(State.isConflict());
879 }
Philip Reames9ac4e382015-08-12 21:00:20 +0000880
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000881 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000882 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000883
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000884 /// Create and insert a new instruction which will represent the base of
885 /// the given instruction 'I'.
886 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
887 if (isa<PHINode>(I)) {
888 BasicBlock *BB = I->getParent();
889 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
890 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000891 std::string Name = I->hasName() ?
892 (I->getName() + ".base").str() : "base_phi";
893 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000894 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
895 // The undef will be replaced later
896 UndefValue *Undef = UndefValue::get(Sel->getType());
897 std::string Name = I->hasName() ?
898 (I->getName() + ".base").str() : "base_select";
899 return SelectInst::Create(Sel->getCondition(), Undef,
900 Undef, Name, Sel);
Philip Reames66287132015-09-09 23:40:12 +0000901 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000902 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
903 std::string Name = I->hasName() ?
904 (I->getName() + ".base").str() : "base_ee";
905 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
906 EE);
Philip Reames66287132015-09-09 23:40:12 +0000907 } else {
908 auto *IE = cast<InsertElementInst>(I);
909 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
910 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
911 std::string Name = I->hasName() ?
912 (I->getName() + ".base").str() : "base_ie";
913 return InsertElementInst::Create(VecUndef, ScalarUndef,
914 IE->getOperand(2), Name, IE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000915 }
Philip Reames66287132015-09-09 23:40:12 +0000916
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000917 };
918 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
919 // Add metadata marking this as a base value
920 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames9b141ed2015-07-23 22:49:14 +0000921 states[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000922 }
923
Philip Reames3ea15892015-09-03 21:57:40 +0000924 // Returns a instruction which produces the base pointer for a given
925 // instruction. The instruction is assumed to be an input to one of the BDVs
926 // seen in the inference algorithm above. As such, we must either already
927 // know it's base defining value is a base, or have inserted a new
928 // instruction to propagate the base of it's BDV and have entered that newly
929 // introduced instruction into the state table. In either case, we are
930 // assured to be able to determine an instruction which produces it's base
931 // pointer.
932 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
933 Value *BDV = findBaseOrBDV(Input, cache);
934 Value *Base = nullptr;
935 if (isKnownBaseResult(BDV)) {
936 Base = BDV;
937 } else {
938 // Either conflict or base.
939 assert(states.count(BDV));
940 Base = states[BDV].getBase();
941 }
942 assert(Base && "can't be null");
943 // The cast is needed since base traversal may strip away bitcasts
944 if (Base->getType() != Input->getType() &&
945 InsertPt) {
946 Base = new BitCastInst(Base, Input->getType(), "cast",
947 InsertPt);
948 }
949 return Base;
950 };
951
Philip Reames15d55632015-09-09 23:26:08 +0000952 // Fixup all the inputs of the new PHIs. Visit order needs to be
953 // deterministic and predictable because we're naming newly created
954 // instructions.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000955 for (auto Pair : states) {
956 Instruction *v = cast<Instruction>(Pair.first);
Philip Reames9b141ed2015-07-23 22:49:14 +0000957 BDVState state = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000958
959 assert(!isKnownBaseResult(v) && "why did it get added?");
960 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000961 if (!state.isConflict())
962 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000963
Philip Reames28e61ce2015-02-28 01:57:44 +0000964 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
965 PHINode *phi = cast<PHINode>(v);
966 unsigned NumPHIValues = phi->getNumIncomingValues();
967 for (unsigned i = 0; i < NumPHIValues; i++) {
968 Value *InVal = phi->getIncomingValue(i);
969 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000970
Philip Reames28e61ce2015-02-28 01:57:44 +0000971 // If we've already seen InBB, add the same incoming value
972 // we added for it earlier. The IR verifier requires phi
973 // nodes with multiple entries from the same basic block
974 // to have the same incoming value for each of those
975 // entries. If we don't do this check here and basephi
976 // has a different type than base, we'll end up adding two
977 // bitcasts (and hence two distinct values) as incoming
978 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000979
Philip Reames28e61ce2015-02-28 01:57:44 +0000980 int blockIndex = basephi->getBasicBlockIndex(InBB);
981 if (blockIndex != -1) {
982 Value *oldBase = basephi->getIncomingValue(blockIndex);
983 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +0000984
Philip Reamesd16a9b12015-02-20 01:06:44 +0000985#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +0000986 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000987 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +0000988 // values incoming from the same basic block may be
989 // different is by being different bitcasts of the same
990 // value. A cleanup that remains TODO is changing
991 // findBaseOrBDV to return an llvm::Value of the correct
992 // type (and still remain pure). This will remove the
993 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +0000994 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +0000995 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000996#endif
Philip Reames28e61ce2015-02-28 01:57:44 +0000997 continue;
998 }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000999
Philip Reames3ea15892015-09-03 21:57:40 +00001000 // Find the instruction which produces the base for each input. We may
1001 // need to insert a bitcast in the incoming block.
1002 // TODO: Need to split critical edges if insertion is needed
1003 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1004 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001005 }
1006 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reames3ea15892015-09-03 21:57:40 +00001007 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(state.getBase())) {
1008 SelectInst *Sel = cast<SelectInst>(v);
Philip Reames28e61ce2015-02-28 01:57:44 +00001009 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1010 // something more safe and less hacky.
1011 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001012 Value *InVal = Sel->getOperand(i);
1013 // Find the instruction which produces the base for each input. We may
1014 // need to insert a bitcast.
1015 Value *Base = getBaseForInput(InVal, BaseSel);
1016 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001017 }
Philip Reames66287132015-09-09 23:40:12 +00001018 } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(state.getBase())) {
Philip Reames9ac4e382015-08-12 21:00:20 +00001019 Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001020 // Find the instruction which produces the base for each input. We may
1021 // need to insert a bitcast.
1022 Value *Base = getBaseForInput(InVal, BaseEE);
Philip Reames9ac4e382015-08-12 21:00:20 +00001023 BaseEE->setOperand(0, Base);
Philip Reames66287132015-09-09 23:40:12 +00001024 } else {
1025 auto *BaseIE = cast<InsertElementInst>(state.getBase());
1026 auto *BdvIE = cast<InsertElementInst>(v);
1027 auto UpdateOperand = [&](int OperandIdx) {
1028 Value *InVal = BdvIE->getOperand(OperandIdx);
1029 Value *Base = findBaseOrBDV(InVal, cache);
1030 if (!isKnownBaseResult(Base)) {
1031 // Either conflict or base.
1032 assert(states.count(Base));
1033 Base = states[Base].getBase();
1034 assert(Base != nullptr && "unknown BDVState!");
1035 }
1036 assert(Base && "can't be null");
1037 BaseIE->setOperand(OperandIdx, Base);
1038 };
1039 UpdateOperand(0); // vector operand
1040 UpdateOperand(1); // scalar operand
Philip Reamesd16a9b12015-02-20 01:06:44 +00001041 }
Philip Reames66287132015-09-09 23:40:12 +00001042
Philip Reamesd16a9b12015-02-20 01:06:44 +00001043 }
1044
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001045 // Now that we're done with the algorithm, see if we can optimize the
1046 // results slightly by reducing the number of new instructions needed.
1047 // Arguably, this should be integrated into the algorithm above, but
1048 // doing as a post process step is easier to reason about for the moment.
1049 DenseMap<Value *, Value *> ReverseMap;
1050 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001051 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001052 // Note: We need to visit the states in a deterministic order. We uses the
1053 // Keys we sorted above for this purpose. Note that we are papering over a
1054 // bigger problem with the algorithm above - it's visit order is not
1055 // deterministic. A larger change is needed to fix this.
Philip Reames15d55632015-09-09 23:26:08 +00001056 for (auto Pair : states) {
1057 auto *BDV = Pair.first;
1058 auto State = Pair.second;
Philip Reames246e6182015-09-03 20:24:29 +00001059 Value *Base = State.getBase();
Philip Reames15d55632015-09-09 23:26:08 +00001060 assert(BDV && Base);
1061 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001062 assert(isKnownBaseResult(Base) &&
1063 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001064 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001065 continue;
1066
Philip Reames15d55632015-09-09 23:26:08 +00001067 ReverseMap[Base] = BDV;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001068 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1069 NewInsts.insert(BaseI);
1070 Worklist.insert(BaseI);
1071 }
1072 }
Philip Reames9546f362015-09-02 22:25:07 +00001073 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1074 Value *Replacement) {
1075 // Add users which are new instructions (excluding self references)
1076 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001077 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001078 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001079 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001080 // Then do the actual replacement
1081 NewInsts.erase(BaseI);
1082 ReverseMap.erase(BaseI);
1083 BaseI->replaceAllUsesWith(Replacement);
1084 BaseI->eraseFromParent();
1085 assert(states.count(BDV));
1086 assert(states[BDV].isConflict() && states[BDV].getBase() == BaseI);
1087 states[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001088 };
1089 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1090 while (!Worklist.empty()) {
1091 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001092 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001093 Value *Bdv = ReverseMap[BaseI];
1094 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1095 if (BaseI->isIdenticalTo(BdvI)) {
1096 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001097 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001098 continue;
1099 }
1100 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1101 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001102 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001103 continue;
1104 }
1105 }
1106
Philip Reamesd16a9b12015-02-20 01:06:44 +00001107 // Cache all of our results so we can cheaply reuse them
1108 // NOTE: This is actually two caches: one of the base defining value
1109 // relation and one of the base pointer relation! FIXME
Philip Reames15d55632015-09-09 23:26:08 +00001110 for (auto Pair : states) {
1111 auto *BDV = Pair.first;
1112 Value *base = Pair.second.getBase();
1113 assert(BDV && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001114
Philip Reamesdab35f32015-09-02 21:11:44 +00001115 std::string fromstr =
Philip Reames15d55632015-09-09 23:26:08 +00001116 cache.count(BDV) ? (cache[BDV]->hasName() ? cache[BDV]->getName() : "")
Philip Reamesdab35f32015-09-02 21:11:44 +00001117 : "none";
1118 DEBUG(dbgs() << "Updating base value cache"
Philip Reames15d55632015-09-09 23:26:08 +00001119 << " for: " << (BDV->hasName() ? BDV->getName() : "")
Philip Reamesdab35f32015-09-02 21:11:44 +00001120 << " from: " << fromstr
1121 << " to: " << (base->hasName() ? base->getName() : "") << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001122
Philip Reames15d55632015-09-09 23:26:08 +00001123 if (cache.count(BDV)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001124 // Once we transition from the BDV relation being store in the cache to
1125 // the base relation being stored, it must be stable
Philip Reames15d55632015-09-09 23:26:08 +00001126 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001127 "base relation should be stable");
1128 }
Philip Reames15d55632015-09-09 23:26:08 +00001129 cache[BDV] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001130 }
1131 assert(cache.find(def) != cache.end());
1132 return cache[def];
1133}
1134
1135// For a set of live pointers (base and/or derived), identify the base
1136// pointer of the object which they are derived from. This routine will
1137// mutate the IR graph as needed to make the 'base' pointer live at the
1138// definition site of 'derived'. This ensures that any use of 'derived' can
1139// also use 'base'. This may involve the insertion of a number of
1140// additional PHI nodes.
1141//
1142// preconditions: live is a set of pointer type Values
1143//
1144// side effects: may insert PHI nodes into the existing CFG, will preserve
1145// CFG, will not remove or mutate any existing nodes
1146//
Philip Reamesf2041322015-02-20 19:26:04 +00001147// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001148// pointer in live. Note that derived can be equal to base if the original
1149// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001150static void
1151findBasePointers(const StatepointLiveSetTy &live,
1152 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001153 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001154 // For the naming of values inserted to be deterministic - which makes for
1155 // much cleaner and more stable tests - we need to assign an order to the
1156 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001157 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001158 Temp.insert(Temp.end(), live.begin(), live.end());
1159 std::sort(Temp.begin(), Temp.end(), order_by_name);
1160 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001161 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001162 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001163 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001164 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1165 DT->dominates(cast<Instruction>(base)->getParent(),
1166 cast<Instruction>(ptr)->getParent())) &&
1167 "The base we found better dominate the derived pointer");
1168
David Blaikie82ad7872015-02-20 23:44:24 +00001169 // If you see this trip and like to live really dangerously, the code should
1170 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001171 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001172 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001173 "the relocation code needs adjustment to handle the relocation of "
1174 "a null pointer constant without causing false positives in the "
1175 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001176 }
1177}
1178
1179/// Find the required based pointers (and adjust the live set) for the given
1180/// parse point.
1181static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1182 const CallSite &CS,
1183 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001184 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +00001185 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001186
1187 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001188 // Note: Need to print these in a stable order since this is checked in
1189 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001190 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001191 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001192 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001193 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001194 Temp.push_back(Pair.first);
1195 }
1196 std::sort(Temp.begin(), Temp.end(), order_by_name);
1197 for (Value *Ptr : Temp) {
1198 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001199 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1200 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001201 }
1202 }
1203
Philip Reamesf2041322015-02-20 19:26:04 +00001204 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001205}
1206
Philip Reamesdf1ef082015-04-10 22:53:14 +00001207/// Given an updated version of the dataflow liveness results, update the
1208/// liveset and base pointer maps for the call site CS.
1209static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1210 const CallSite &CS,
1211 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001212
Philip Reamesdf1ef082015-04-10 22:53:14 +00001213static void recomputeLiveInValues(
1214 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001215 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001216 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001217 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001218 GCPtrLivenessData RevisedLivenessData;
1219 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001220 for (size_t i = 0; i < records.size(); i++) {
1221 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001222 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001223 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001224 }
1225}
1226
Philip Reames69e51ca2015-04-13 18:07:21 +00001227// When inserting gc.relocate calls, we need to ensure there are no uses
1228// of the original value between the gc.statepoint and the gc.relocate call.
1229// One case which can arise is a phi node starting one of the successor blocks.
1230// We also need to be able to insert the gc.relocates only on the path which
1231// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001232// possible.
1233static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001234normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1235 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001236 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001237 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001238 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001239 }
1240
Philip Reames69e51ca2015-04-13 18:07:21 +00001241 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1242 // from it
1243 FoldSingleEntryPHINodes(Ret);
1244 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001245
Philip Reames69e51ca2015-04-13 18:07:21 +00001246 // At this point, we can safely insert a gc.relocate as the first instruction
1247 // in Ret if needed.
1248 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001249}
1250
Philip Reamesd2b66462015-02-20 22:39:41 +00001251static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001252 auto itr = std::find(livevec.begin(), livevec.end(), val);
1253 assert(livevec.end() != itr);
1254 size_t index = std::distance(livevec.begin(), itr);
1255 assert(index < livevec.size());
1256 return index;
1257}
1258
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001259// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001260// from original call to the safepoint.
1261static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1262 AttributeSet ret;
1263
1264 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1265 unsigned index = AS.getSlotIndex(Slot);
1266
1267 if (index == AttributeSet::ReturnIndex ||
1268 index == AttributeSet::FunctionIndex) {
1269
1270 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1271 ++it) {
1272 Attribute attr = *it;
1273
1274 // Do not allow certain attributes - just skip them
1275 // Safepoint can not be read only or read none.
1276 if (attr.hasAttribute(Attribute::ReadNone) ||
1277 attr.hasAttribute(Attribute::ReadOnly))
1278 continue;
1279
1280 ret = ret.addAttributes(
1281 AS.getContext(), index,
1282 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1283 }
1284 }
1285
1286 // Just skip parameter attributes for now
1287 }
1288
1289 return ret;
1290}
1291
1292/// Helper function to place all gc relocates necessary for the given
1293/// statepoint.
1294/// Inputs:
1295/// liveVariables - list of variables to be relocated.
1296/// liveStart - index of the first live variable.
1297/// basePtrs - base pointers.
1298/// statepointToken - statepoint instruction to which relocates should be
1299/// bound.
1300/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001301static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1302 const int LiveStart,
1303 ArrayRef<llvm::Value *> BasePtrs,
1304 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001305 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001306 if (LiveVariables.empty())
1307 return;
1308
1309 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1310 // unique declarations for each pointer type, but this proved problematic
1311 // because the intrinsic mangling code is incomplete and fragile. Since
1312 // we're moving towards a single unified pointer type anyways, we can just
1313 // cast everything to an i8* of the right address space. A bitcast is added
1314 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001315 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001316 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1317 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1318 Value *GCRelocateDecl =
1319 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001320
Sanjoy Das5665c992015-05-11 23:47:27 +00001321 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001322 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001323 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001324 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1325 Value *LiveIdx =
1326 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001327
1328 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001329 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001330 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001331 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001332 : "");
1333 // Trick CodeGen into thinking there are lots of free registers at this
1334 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001335 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001336 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001337}
1338
1339static void
1340makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1341 const SmallVectorImpl<llvm::Value *> &basePtrs,
1342 const SmallVectorImpl<llvm::Value *> &liveVariables,
1343 Pass *P,
1344 PartiallyConstructedSafepointRecord &result) {
1345 assert(basePtrs.size() == liveVariables.size());
1346 assert(isStatepoint(CS) &&
1347 "This method expects to be rewriting a statepoint");
1348
1349 BasicBlock *BB = CS.getInstruction()->getParent();
1350 assert(BB);
1351 Function *F = BB->getParent();
1352 assert(F && "must be set");
1353 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001354 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001355 assert(M && "must be set");
1356
1357 // We're not changing the function signature of the statepoint since the gc
1358 // arguments go into the var args section.
1359 Function *gc_statepoint_decl = CS.getCalledFunction();
1360
1361 // Then go ahead and use the builder do actually do the inserts. We insert
1362 // immediately before the previous instruction under the assumption that all
1363 // arguments will be available here. We can't insert afterwards since we may
1364 // be replacing a terminator.
1365 Instruction *insertBefore = CS.getInstruction();
1366 IRBuilder<> Builder(insertBefore);
1367 // Copy all of the arguments from the original statepoint - this includes the
1368 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001369 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001370 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1371 // TODO: Clear the 'needs rewrite' flag
1372
1373 // add all the pointers to be relocated (gc arguments)
1374 // Capture the start of the live variable list for use in the gc_relocates
1375 const int live_start = args.size();
1376 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1377
1378 // Create the statepoint given all the arguments
1379 Instruction *token = nullptr;
1380 AttributeSet return_attributes;
1381 if (CS.isCall()) {
1382 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1383 CallInst *call =
1384 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1385 call->setTailCall(toReplace->isTailCall());
1386 call->setCallingConv(toReplace->getCallingConv());
1387
1388 // Currently we will fail on parameter attributes and on certain
1389 // function attributes.
1390 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001391 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001392 // directly on statepoint and return attrs later for gc_result intrinsic.
1393 call->setAttributes(new_attrs.getFnAttributes());
1394 return_attributes = new_attrs.getRetAttributes();
1395
1396 token = call;
1397
1398 // Put the following gc_result and gc_relocate calls immediately after the
1399 // the old call (which we're about to delete)
1400 BasicBlock::iterator next(toReplace);
1401 assert(BB->end() != next && "not a terminator, must have next");
1402 next++;
1403 Instruction *IP = &*(next);
1404 Builder.SetInsertPoint(IP);
1405 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1406
David Blaikie82ad7872015-02-20 23:44:24 +00001407 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001408 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1409
1410 // Insert the new invoke into the old block. We'll remove the old one in a
1411 // moment at which point this will become the new terminator for the
1412 // original block.
1413 InvokeInst *invoke = InvokeInst::Create(
1414 gc_statepoint_decl, toReplace->getNormalDest(),
Philip Reamesfa2c6302015-07-24 19:01:39 +00001415 toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001416 invoke->setCallingConv(toReplace->getCallingConv());
1417
1418 // Currently we will fail on parameter attributes and on certain
1419 // function attributes.
1420 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001421 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001422 // directly on statepoint and return attrs later for gc_result intrinsic.
1423 invoke->setAttributes(new_attrs.getFnAttributes());
1424 return_attributes = new_attrs.getRetAttributes();
1425
1426 token = invoke;
1427
1428 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001429 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1430 assert(!isa<PHINode>(unwindBlock->begin()) &&
1431 unwindBlock->getUniquePredecessor() &&
1432 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001433
1434 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1435 Builder.SetInsertPoint(IP);
1436 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1437
1438 // Extract second element from landingpad return value. We will attach
1439 // exceptional gc relocates to it.
1440 const unsigned idx = 1;
1441 Instruction *exceptional_token =
1442 cast<Instruction>(Builder.CreateExtractValue(
1443 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001444 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001445
Philip Reames6ff1a1e32015-07-21 19:04:38 +00001446 CreateGCRelocates(liveVariables, live_start, basePtrs,
1447 exceptional_token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001448
1449 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001450 BasicBlock *normalDest = toReplace->getNormalDest();
1451 assert(!isa<PHINode>(normalDest->begin()) &&
1452 normalDest->getUniquePredecessor() &&
1453 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001454
1455 IP = &*(normalDest->getFirstInsertionPt());
1456 Builder.SetInsertPoint(IP);
1457
1458 // gc relocates will be generated later as if it were regular call
1459 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001460 }
1461 assert(token);
1462
1463 // Take the name of the original value call if it had one.
1464 token->takeName(CS.getInstruction());
1465
Philip Reames704e78b2015-04-10 22:34:56 +00001466// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001467#ifndef NDEBUG
1468 Instruction *toReplace = CS.getInstruction();
1469 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1470 "only valid use before rewrite is gc.result");
1471 assert(!toReplace->hasOneUse() ||
1472 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1473#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001474
1475 // Update the gc.result of the original statepoint (if any) to use the newly
1476 // inserted statepoint. This is safe to do here since the token can't be
1477 // considered a live reference.
1478 CS.getInstruction()->replaceAllUsesWith(token);
1479
Philip Reames0a3240f2015-02-20 21:34:11 +00001480 result.StatepointToken = token;
1481
Philip Reamesd16a9b12015-02-20 01:06:44 +00001482 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001483 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001484}
1485
1486namespace {
1487struct name_ordering {
1488 Value *base;
1489 Value *derived;
1490 bool operator()(name_ordering const &a, name_ordering const &b) {
1491 return -1 == a.derived->getName().compare(b.derived->getName());
1492 }
1493};
1494}
1495static void stablize_order(SmallVectorImpl<Value *> &basevec,
1496 SmallVectorImpl<Value *> &livevec) {
1497 assert(basevec.size() == livevec.size());
1498
Philip Reames860660e2015-02-20 22:05:18 +00001499 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001500 for (size_t i = 0; i < basevec.size(); i++) {
1501 name_ordering v;
1502 v.base = basevec[i];
1503 v.derived = livevec[i];
1504 temp.push_back(v);
1505 }
1506 std::sort(temp.begin(), temp.end(), name_ordering());
1507 for (size_t i = 0; i < basevec.size(); i++) {
1508 basevec[i] = temp[i].base;
1509 livevec[i] = temp[i].derived;
1510 }
1511}
1512
1513// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1514// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001515//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001516// WARNING: Does not do any fixup to adjust users of the original live
1517// values. That's the callers responsibility.
1518static void
1519makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1520 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001521 auto liveset = result.liveset;
1522 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001523
1524 // Convert to vector for efficient cross referencing.
1525 SmallVector<Value *, 64> basevec, livevec;
1526 livevec.reserve(liveset.size());
1527 basevec.reserve(liveset.size());
1528 for (Value *L : liveset) {
1529 livevec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001530 assert(PointerToBase.count(L));
Philip Reamesf2041322015-02-20 19:26:04 +00001531 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001532 basevec.push_back(base);
1533 }
1534 assert(livevec.size() == basevec.size());
1535
1536 // To make the output IR slightly more stable (for use in diffs), ensure a
1537 // fixed order of the values in the safepoint (by sorting the value name).
1538 // The order is otherwise meaningless.
1539 stablize_order(basevec, livevec);
1540
1541 // Do the actual rewriting and delete the old statepoint
1542 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1543 CS.getInstruction()->eraseFromParent();
1544}
1545
1546// Helper function for the relocationViaAlloca.
1547// It receives iterator to the statepoint gc relocates and emits store to the
1548// assigned
1549// location (via allocaMap) for the each one of them.
1550// Add visited values into the visitedLiveValues set we will later use them
1551// for sanity check.
1552static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001553insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1554 DenseMap<Value *, Value *> &AllocaMap,
1555 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001556
Sanjoy Das5665c992015-05-11 23:47:27 +00001557 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001558 if (!isa<IntrinsicInst>(U))
1559 continue;
1560
Sanjoy Das5665c992015-05-11 23:47:27 +00001561 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001562
1563 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001564 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001565 Intrinsic::experimental_gc_relocate) {
1566 continue;
1567 }
1568
Sanjoy Das5665c992015-05-11 23:47:27 +00001569 GCRelocateOperands RelocateOperands(RelocatedValue);
1570 Value *OriginalValue =
1571 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1572 assert(AllocaMap.count(OriginalValue));
1573 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001574
1575 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001576 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1577 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001578 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1579 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001580 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001581 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1582 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001583
Sanjoy Das5665c992015-05-11 23:47:27 +00001584 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1585 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001586
1587#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001588 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001589#endif
1590 }
1591}
1592
Igor Laevskye0317182015-05-19 15:59:05 +00001593// Helper function for the "relocationViaAlloca". Similar to the
1594// "insertRelocationStores" but works for rematerialized values.
1595static void
1596insertRematerializationStores(
1597 RematerializedValueMapTy RematerializedValues,
1598 DenseMap<Value *, Value *> &AllocaMap,
1599 DenseSet<Value *> &VisitedLiveValues) {
1600
1601 for (auto RematerializedValuePair: RematerializedValues) {
1602 Instruction *RematerializedValue = RematerializedValuePair.first;
1603 Value *OriginalValue = RematerializedValuePair.second;
1604
1605 assert(AllocaMap.count(OriginalValue) &&
1606 "Can not find alloca for rematerialized value");
1607 Value *Alloca = AllocaMap[OriginalValue];
1608
1609 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1610 Store->insertAfter(RematerializedValue);
1611
1612#ifndef NDEBUG
1613 VisitedLiveValues.insert(OriginalValue);
1614#endif
1615 }
1616}
1617
Philip Reamesd16a9b12015-02-20 01:06:44 +00001618/// do all the relocation update via allocas and mem2reg
1619static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001620 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1621 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001622#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001623 // record initial number of (static) allocas; we'll check we have the same
1624 // number when we get done.
1625 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001626 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1627 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001628 if (isa<AllocaInst>(*I))
1629 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001630#endif
1631
1632 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001633 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001634 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001635 // Used later to chack that we have enough allocas to store all values
1636 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001637 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001638
Igor Laevskye0317182015-05-19 15:59:05 +00001639 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1640 // "PromotableAllocas"
1641 auto emitAllocaFor = [&](Value *LiveValue) {
1642 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1643 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001644 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001645 PromotableAllocas.push_back(Alloca);
1646 };
1647
Philip Reamesd16a9b12015-02-20 01:06:44 +00001648 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001649 for (unsigned i = 0; i < Live.size(); i++) {
1650 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001651 }
1652
Igor Laevskye0317182015-05-19 15:59:05 +00001653 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001654 for (size_t i = 0; i < Records.size(); i++) {
1655 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001656
Igor Laevsky285fe842015-05-19 16:29:43 +00001657 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001658 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001659 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001660 continue;
1661
1662 emitAllocaFor(OriginalValue);
1663 ++NumRematerializedValues;
1664 }
1665 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001666
Philip Reamesd16a9b12015-02-20 01:06:44 +00001667 // The next two loops are part of the same conceptual operation. We need to
1668 // insert a store to the alloca after the original def and at each
1669 // redefinition. We need to insert a load before each use. These are split
1670 // into distinct loops for performance reasons.
1671
1672 // update gc pointer after each statepoint
1673 // either store a relocated value or null (if no relocated value found for
1674 // this gc pointer and it is not a gc_result)
1675 // this must happen before we update the statepoint with load of alloca
1676 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001677 for (size_t i = 0; i < Records.size(); i++) {
1678 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1679 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001680
1681 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001682 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001683
1684 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001685 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001686
1687 // In case if it was invoke statepoint
1688 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001689 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001690 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1691 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001692 }
1693
Igor Laevskye0317182015-05-19 15:59:05 +00001694 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001695 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1696 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001697
Philip Reamese73300b2015-04-13 16:41:32 +00001698 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001699 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001700 // the gc.statepoint. This will turn some subtle GC problems into
1701 // slightly easier to debug SEGVs. Note that on large IR files with
1702 // lots of gc.statepoints this is extremely costly both memory and time
1703 // wise.
1704 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001705 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001706 Value *Def = Pair.first;
1707 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001708
Philip Reamese73300b2015-04-13 16:41:32 +00001709 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001710 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001711 continue;
1712 }
1713 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001714 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001715
Philip Reamese73300b2015-04-13 16:41:32 +00001716 auto InsertClobbersAt = [&](Instruction *IP) {
1717 for (auto *AI : ToClobber) {
1718 auto AIType = cast<PointerType>(AI->getType());
1719 auto PT = cast<PointerType>(AIType->getElementType());
1720 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001721 StoreInst *Store = new StoreInst(CPN, AI);
1722 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001723 }
1724 };
1725
1726 // Insert the clobbering stores. These may get intermixed with the
1727 // gc.results and gc.relocates, but that's fine.
1728 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1729 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1730 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1731 } else {
1732 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1733 Next++;
1734 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001735 }
David Blaikie82ad7872015-02-20 23:44:24 +00001736 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001737 }
1738 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001739 for (auto Pair : AllocaMap) {
1740 Value *Def = Pair.first;
1741 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001742
1743 // we pre-record the uses of allocas so that we dont have to worry about
1744 // later update
1745 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001746 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001747 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001748 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1749 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001750 if (!isa<ConstantExpr>(U)) {
1751 // If the def has a ConstantExpr use, then the def is either a
1752 // ConstantExpr use itself or null. In either case
1753 // (recursively in the first, directly in the second), the oop
1754 // it is ultimately dependent on is null and this particular
1755 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001756 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001757 }
1758 }
1759
Igor Laevsky285fe842015-05-19 16:29:43 +00001760 std::sort(Uses.begin(), Uses.end());
1761 auto Last = std::unique(Uses.begin(), Uses.end());
1762 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001763
Igor Laevsky285fe842015-05-19 16:29:43 +00001764 for (Instruction *Use : Uses) {
1765 if (isa<PHINode>(Use)) {
1766 PHINode *Phi = cast<PHINode>(Use);
1767 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1768 if (Def == Phi->getIncomingValue(i)) {
1769 LoadInst *Load = new LoadInst(
1770 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1771 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001772 }
1773 }
1774 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001775 LoadInst *Load = new LoadInst(Alloca, "", Use);
1776 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001777 }
1778 }
1779
1780 // emit store for the initial gc value
1781 // store must be inserted after load, otherwise store will be in alloca's
1782 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001783 StoreInst *Store = new StoreInst(Def, Alloca);
1784 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1785 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001786 // InvokeInst is a TerminatorInst so the store need to be inserted
1787 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001788 BasicBlock *NormalDest = Invoke->getNormalDest();
1789 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001790 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001791 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001792 "The only TerminatorInst that can produce a value is "
1793 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001794 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001795 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001796 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001797 assert(isa<Argument>(Def));
1798 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001799 }
1800 }
1801
Igor Laevsky285fe842015-05-19 16:29:43 +00001802 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001803 "we must have the same allocas with lives");
1804 if (!PromotableAllocas.empty()) {
1805 // apply mem2reg to promote alloca to SSA
1806 PromoteMemToReg(PromotableAllocas, DT);
1807 }
1808
1809#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001810 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1811 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001812 if (isa<AllocaInst>(*I))
1813 InitialAllocaNum--;
1814 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001815#endif
1816}
1817
1818/// Implement a unique function which doesn't require we sort the input
1819/// vector. Doing so has the effect of changing the output of a couple of
1820/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001821template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001822 SmallSet<T, 8> Seen;
1823 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1824 return !Seen.insert(V).second;
1825 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001826}
1827
Philip Reamesd16a9b12015-02-20 01:06:44 +00001828/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001829/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001830static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001831 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001832 if (Values.empty())
1833 // No values to hold live, might as well not insert the empty holder
1834 return;
1835
Philip Reamesd16a9b12015-02-20 01:06:44 +00001836 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001837 // Use a dummy vararg function to actually hold the values live
1838 Function *Func = cast<Function>(M->getOrInsertFunction(
1839 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001840 if (CS.isCall()) {
1841 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001842 BasicBlock::iterator Next(CS.getInstruction());
1843 Next++;
1844 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1845 return;
1846 }
1847 // For invoke safepooints insert dummy calls both in normal and
1848 // exceptional destination blocks
1849 auto *II = cast<InvokeInst>(CS.getInstruction());
1850 Holders.push_back(CallInst::Create(
1851 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1852 Holders.push_back(CallInst::Create(
1853 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001854}
1855
1856static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001857 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1858 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001859 GCPtrLivenessData OriginalLivenessData;
1860 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001861 for (size_t i = 0; i < records.size(); i++) {
1862 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001863 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001864 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001865 }
1866}
1867
Philip Reames8531d8c2015-04-10 21:48:25 +00001868/// Remove any vector of pointers from the liveset by scalarizing them over the
1869/// statepoint instruction. Adds the scalarized pieces to the liveset. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001870/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001871/// the lowering code currently does not handle that. Extending it would be
1872/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001873/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001874static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001875 StatepointLiveSetTy &LiveSet,
1876 DenseMap<Value *, Value *>& PointerToBase,
1877 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001878 SmallVector<Value *, 16> ToSplit;
1879 for (Value *V : LiveSet)
1880 if (isa<VectorType>(V->getType()))
1881 ToSplit.push_back(V);
1882
1883 if (ToSplit.empty())
1884 return;
1885
Philip Reames8fe7f132015-06-26 22:47:37 +00001886 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1887
Philip Reames8531d8c2015-04-10 21:48:25 +00001888 Function &F = *(StatepointInst->getParent()->getParent());
1889
Philip Reames704e78b2015-04-10 22:34:56 +00001890 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001891 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001892 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001893 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001894 AllocaInst *Alloca =
1895 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001896 AllocaMap[V] = Alloca;
1897
1898 VectorType *VT = cast<VectorType>(V->getType());
1899 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001900 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001901 for (unsigned i = 0; i < VT->getNumElements(); i++)
1902 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001903 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001904
1905 auto InsertVectorReform = [&](Instruction *IP) {
1906 Builder.SetInsertPoint(IP);
1907 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1908 Value *ResultVec = UndefValue::get(VT);
1909 for (unsigned i = 0; i < VT->getNumElements(); i++)
1910 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1911 Builder.getInt32(i));
1912 return ResultVec;
1913 };
1914
1915 if (isa<CallInst>(StatepointInst)) {
1916 BasicBlock::iterator Next(StatepointInst);
1917 Next++;
1918 Instruction *IP = &*(Next);
1919 Replacements[V].first = InsertVectorReform(IP);
1920 Replacements[V].second = nullptr;
1921 } else {
1922 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1923 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001924 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001925 BasicBlock *NormalDest = Invoke->getNormalDest();
1926 assert(!isa<PHINode>(NormalDest->begin()));
1927 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1928 assert(!isa<PHINode>(UnwindDest->begin()));
1929 // Insert insert element sequences in both successors
1930 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1931 Replacements[V].first = InsertVectorReform(IP);
1932 IP = &*(UnwindDest->getFirstInsertionPt());
1933 Replacements[V].second = InsertVectorReform(IP);
1934 }
1935 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001936
Philip Reames8531d8c2015-04-10 21:48:25 +00001937 for (Value *V : ToSplit) {
1938 AllocaInst *Alloca = AllocaMap[V];
1939
1940 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001941 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001942 for (User *U : V->users())
1943 Users.push_back(cast<Instruction>(U));
1944
1945 for (Instruction *I : Users) {
1946 if (auto Phi = dyn_cast<PHINode>(I)) {
1947 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1948 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001949 LoadInst *Load = new LoadInst(
1950 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001951 Phi->setIncomingValue(i, Load);
1952 }
1953 } else {
1954 LoadInst *Load = new LoadInst(Alloca, "", I);
1955 I->replaceUsesOfWith(V, Load);
1956 }
1957 }
1958
1959 // Store the original value and the replacement value into the alloca
1960 StoreInst *Store = new StoreInst(V, Alloca);
1961 if (auto I = dyn_cast<Instruction>(V))
1962 Store->insertAfter(I);
1963 else
1964 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001965
Philip Reames8531d8c2015-04-10 21:48:25 +00001966 // Normal return for invoke, or call return
1967 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1968 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1969 // Unwind return for invoke only
1970 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1971 if (Replacement)
1972 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1973 }
1974
1975 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001976 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001977 for (Value *V : ToSplit)
1978 Allocas.push_back(AllocaMap[V]);
1979 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001980
1981 // Update our tracking of live pointers and base mappings to account for the
1982 // changes we just made.
1983 for (Value *V : ToSplit) {
1984 auto &Elements = ElementMapping[V];
1985
1986 LiveSet.erase(V);
1987 LiveSet.insert(Elements.begin(), Elements.end());
1988 // We need to update the base mapping as well.
1989 assert(PointerToBase.count(V));
1990 Value *OldBase = PointerToBase[V];
1991 auto &BaseElements = ElementMapping[OldBase];
1992 PointerToBase.erase(V);
1993 assert(Elements.size() == BaseElements.size());
1994 for (unsigned i = 0; i < Elements.size(); i++) {
1995 Value *Elem = Elements[i];
1996 PointerToBase[Elem] = BaseElements[i];
1997 }
1998 }
Philip Reames8531d8c2015-04-10 21:48:25 +00001999}
2000
Igor Laevskye0317182015-05-19 15:59:05 +00002001// Helper function for the "rematerializeLiveValues". It walks use chain
2002// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2003// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002004// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00002005// Fills "ChainToBase" array with all visited values. "BaseValue" is not
2006// recorded.
2007static bool findRematerializableChainToBasePointer(
2008 SmallVectorImpl<Instruction*> &ChainToBase,
2009 Value *CurrentValue, Value *BaseValue) {
2010
2011 // We have found a base value
2012 if (CurrentValue == BaseValue) {
2013 return true;
2014 }
2015
2016 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2017 ChainToBase.push_back(GEP);
2018 return findRematerializableChainToBasePointer(ChainToBase,
2019 GEP->getPointerOperand(),
2020 BaseValue);
2021 }
2022
2023 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2024 Value *Def = CI->stripPointerCasts();
2025
2026 // This two checks are basically similar. First one is here for the
2027 // consistency with findBasePointers logic.
2028 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2029 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2030 return false;
2031
2032 ChainToBase.push_back(CI);
2033 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2034 }
2035
2036 // Not supported instruction in the chain
2037 return false;
2038}
2039
2040// Helper function for the "rematerializeLiveValues". Compute cost of the use
2041// chain we are going to rematerialize.
2042static unsigned
2043chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2044 TargetTransformInfo &TTI) {
2045 unsigned Cost = 0;
2046
2047 for (Instruction *Instr : Chain) {
2048 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2049 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2050 "non noop cast is found during rematerialization");
2051
2052 Type *SrcTy = CI->getOperand(0)->getType();
2053 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2054
2055 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2056 // Cost of the address calculation
2057 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2058 Cost += TTI.getAddressComputationCost(ValTy);
2059
2060 // And cost of the GEP itself
2061 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2062 // allowed for the external usage)
2063 if (!GEP->hasAllConstantIndices())
2064 Cost += 2;
2065
2066 } else {
2067 llvm_unreachable("unsupported instruciton type during rematerialization");
2068 }
2069 }
2070
2071 return Cost;
2072}
2073
2074// From the statepoint liveset pick values that are cheaper to recompute then to
2075// relocate. Remove this values from the liveset, rematerialize them after
2076// statepoint and record them in "Info" structure. Note that similar to
2077// relocated values we don't do any user adjustments here.
2078static void rematerializeLiveValues(CallSite CS,
2079 PartiallyConstructedSafepointRecord &Info,
2080 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002081 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002082
Igor Laevskye0317182015-05-19 15:59:05 +00002083 // Record values we are going to delete from this statepoint live set.
2084 // We can not di this in following loop due to iterator invalidation.
2085 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2086
2087 for (Value *LiveValue: Info.liveset) {
2088 // For each live pointer find it's defining chain
2089 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002090 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002091 bool FoundChain =
2092 findRematerializableChainToBasePointer(ChainToBase,
2093 LiveValue,
2094 Info.PointerToBase[LiveValue]);
2095 // Nothing to do, or chain is too long
2096 if (!FoundChain ||
2097 ChainToBase.size() == 0 ||
2098 ChainToBase.size() > ChainLengthThreshold)
2099 continue;
2100
2101 // Compute cost of this chain
2102 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2103 // TODO: We can also account for cases when we will be able to remove some
2104 // of the rematerialized values by later optimization passes. I.e if
2105 // we rematerialized several intersecting chains. Or if original values
2106 // don't have any uses besides this statepoint.
2107
2108 // For invokes we need to rematerialize each chain twice - for normal and
2109 // for unwind basic blocks. Model this by multiplying cost by two.
2110 if (CS.isInvoke()) {
2111 Cost *= 2;
2112 }
2113 // If it's too expensive - skip it
2114 if (Cost >= RematerializationThreshold)
2115 continue;
2116
2117 // Remove value from the live set
2118 LiveValuesToBeDeleted.push_back(LiveValue);
2119
2120 // Clone instructions and record them inside "Info" structure
2121
2122 // Walk backwards to visit top-most instructions first
2123 std::reverse(ChainToBase.begin(), ChainToBase.end());
2124
2125 // Utility function which clones all instructions from "ChainToBase"
2126 // and inserts them before "InsertBefore". Returns rematerialized value
2127 // which should be used after statepoint.
2128 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2129 Instruction *LastClonedValue = nullptr;
2130 Instruction *LastValue = nullptr;
2131 for (Instruction *Instr: ChainToBase) {
2132 // Only GEP's and casts are suported as we need to be careful to not
2133 // introduce any new uses of pointers not in the liveset.
2134 // Note that it's fine to introduce new uses of pointers which were
2135 // otherwise not used after this statepoint.
2136 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2137
2138 Instruction *ClonedValue = Instr->clone();
2139 ClonedValue->insertBefore(InsertBefore);
2140 ClonedValue->setName(Instr->getName() + ".remat");
2141
2142 // If it is not first instruction in the chain then it uses previously
2143 // cloned value. We should update it to use cloned value.
2144 if (LastClonedValue) {
2145 assert(LastValue);
2146 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2147#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002148 // Assert that cloned instruction does not use any instructions from
2149 // this chain other than LastClonedValue
2150 for (auto OpValue : ClonedValue->operand_values()) {
2151 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2152 ChainToBase.end() &&
2153 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002154 }
2155#endif
2156 }
2157
2158 LastClonedValue = ClonedValue;
2159 LastValue = Instr;
2160 }
2161 assert(LastClonedValue);
2162 return LastClonedValue;
2163 };
2164
2165 // Different cases for calls and invokes. For invokes we need to clone
2166 // instructions both on normal and unwind path.
2167 if (CS.isCall()) {
2168 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2169 assert(InsertBefore);
2170 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2171 Info.RematerializedValues[RematerializedValue] = LiveValue;
2172 } else {
2173 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2174
2175 Instruction *NormalInsertBefore =
2176 Invoke->getNormalDest()->getFirstInsertionPt();
2177 Instruction *UnwindInsertBefore =
2178 Invoke->getUnwindDest()->getFirstInsertionPt();
2179
2180 Instruction *NormalRematerializedValue =
2181 rematerializeChain(NormalInsertBefore);
2182 Instruction *UnwindRematerializedValue =
2183 rematerializeChain(UnwindInsertBefore);
2184
2185 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2186 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2187 }
2188 }
2189
2190 // Remove rematerializaed values from the live set
2191 for (auto LiveValue: LiveValuesToBeDeleted) {
2192 Info.liveset.erase(LiveValue);
2193 }
2194}
2195
Philip Reamesd16a9b12015-02-20 01:06:44 +00002196static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00002197 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002198#ifndef NDEBUG
2199 // sanity check the input
2200 std::set<CallSite> uniqued;
2201 uniqued.insert(toUpdate.begin(), toUpdate.end());
2202 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2203
2204 for (size_t i = 0; i < toUpdate.size(); i++) {
2205 CallSite &CS = toUpdate[i];
2206 assert(CS.getInstruction()->getParent()->getParent() == &F);
2207 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2208 }
2209#endif
2210
Philip Reames69e51ca2015-04-13 18:07:21 +00002211 // When inserting gc.relocates for invokes, we need to be able to insert at
2212 // the top of the successor blocks. See the comment on
2213 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002214 // may restructure the CFG.
2215 for (CallSite CS : toUpdate) {
2216 if (!CS.isInvoke())
2217 continue;
2218 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2219 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002220 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002221 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002222 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002223 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002224
Philip Reamesd16a9b12015-02-20 01:06:44 +00002225 // A list of dummy calls added to the IR to keep various values obviously
2226 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002227 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002228
2229 // Insert a dummy call with all of the arguments to the vm_state we'll need
2230 // for the actual safepoint insertion. This ensures reference arguments in
2231 // the deopt argument list are considered live through the safepoint (and
2232 // thus makes sure they get relocated.)
2233 for (size_t i = 0; i < toUpdate.size(); i++) {
2234 CallSite &CS = toUpdate[i];
2235 Statepoint StatepointCS(CS);
2236
2237 SmallVector<Value *, 64> DeoptValues;
2238 for (Use &U : StatepointCS.vm_state_args()) {
2239 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002240 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2241 "support for FCA unimplemented");
2242 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002243 DeoptValues.push_back(Arg);
2244 }
2245 insertUseHolderAfter(CS, DeoptValues, holders);
2246 }
2247
Philip Reamesd2b66462015-02-20 22:39:41 +00002248 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002249 records.reserve(toUpdate.size());
2250 for (size_t i = 0; i < toUpdate.size(); i++) {
2251 struct PartiallyConstructedSafepointRecord info;
2252 records.push_back(info);
2253 }
2254 assert(records.size() == toUpdate.size());
2255
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002256 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002257 // site.
2258 findLiveReferences(F, DT, P, toUpdate, records);
2259
2260 // B) Find the base pointers for each live pointer
2261 /* scope for caching */ {
2262 // Cache the 'defining value' relation used in the computation and
2263 // insertion of base phis and selects. This ensures that we don't insert
2264 // large numbers of duplicate base_phis.
2265 DefiningValueMapTy DVCache;
2266
2267 for (size_t i = 0; i < records.size(); i++) {
2268 struct PartiallyConstructedSafepointRecord &info = records[i];
2269 CallSite &CS = toUpdate[i];
2270 findBasePointers(DT, DVCache, CS, info);
2271 }
2272 } // end of cache scope
2273
2274 // The base phi insertion logic (for any safepoint) may have inserted new
2275 // instructions which are now live at some safepoint. The simplest such
2276 // example is:
2277 // loop:
2278 // phi a <-- will be a new base_phi here
2279 // safepoint 1 <-- that needs to be live here
2280 // gep a + 1
2281 // safepoint 2
2282 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002283 // We insert some dummy calls after each safepoint to definitely hold live
2284 // the base pointers which were identified for that safepoint. We'll then
2285 // ask liveness for _every_ base inserted to see what is now live. Then we
2286 // remove the dummy calls.
2287 holders.reserve(holders.size() + records.size());
2288 for (size_t i = 0; i < records.size(); i++) {
2289 struct PartiallyConstructedSafepointRecord &info = records[i];
2290 CallSite &CS = toUpdate[i];
2291
2292 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002293 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002294 Bases.push_back(Pair.second);
2295 }
2296 insertUseHolderAfter(CS, Bases, holders);
2297 }
2298
Philip Reamesdf1ef082015-04-10 22:53:14 +00002299 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2300 // need to rerun liveness. We may *also* have inserted new defs, but that's
2301 // not the key issue.
2302 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002303
Philip Reamesd16a9b12015-02-20 01:06:44 +00002304 if (PrintBasePointers) {
2305 for (size_t i = 0; i < records.size(); i++) {
2306 struct PartiallyConstructedSafepointRecord &info = records[i];
2307 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002308 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002309 errs() << " derived %" << Pair.first->getName() << " base %"
2310 << Pair.second->getName() << "\n";
2311 }
2312 }
2313 }
2314 for (size_t i = 0; i < holders.size(); i++) {
2315 holders[i]->eraseFromParent();
2316 holders[i] = nullptr;
2317 }
2318 holders.clear();
2319
Philip Reames8fe7f132015-06-26 22:47:37 +00002320 // Do a limited scalarization of any live at safepoint vector values which
2321 // contain pointers. This enables this pass to run after vectorization at
2322 // the cost of some possible performance loss. TODO: it would be nice to
2323 // natively support vectors all the way through the backend so we don't need
2324 // to scalarize here.
2325 for (size_t i = 0; i < records.size(); i++) {
2326 struct PartiallyConstructedSafepointRecord &info = records[i];
2327 Instruction *statepoint = toUpdate[i].getInstruction();
2328 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2329 info.PointerToBase, DT);
2330 }
2331
Igor Laevskye0317182015-05-19 15:59:05 +00002332 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002333 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002334 // does not influence correctness.
2335 TargetTransformInfo &TTI =
2336 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2337
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002338 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002339 struct PartiallyConstructedSafepointRecord &info = records[i];
2340 CallSite &CS = toUpdate[i];
2341
2342 rematerializeLiveValues(CS, info, TTI);
2343 }
2344
Philip Reamesd16a9b12015-02-20 01:06:44 +00002345 // Now run through and replace the existing statepoints with new ones with
2346 // the live variables listed. We do not yet update uses of the values being
2347 // relocated. We have references to live variables that need to
2348 // survive to the last iteration of this loop. (By construction, the
2349 // previous statepoint can not be a live variable, thus we can and remove
2350 // the old statepoint calls as we go.)
2351 for (size_t i = 0; i < records.size(); i++) {
2352 struct PartiallyConstructedSafepointRecord &info = records[i];
2353 CallSite &CS = toUpdate[i];
2354 makeStatepointExplicit(DT, CS, P, info);
2355 }
2356 toUpdate.clear(); // prevent accident use of invalid CallSites
2357
Philip Reamesd16a9b12015-02-20 01:06:44 +00002358 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002359 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002360 for (size_t i = 0; i < records.size(); i++) {
2361 struct PartiallyConstructedSafepointRecord &info = records[i];
2362 // We can't simply save the live set from the original insertion. One of
2363 // the live values might be the result of a call which needs a safepoint.
2364 // That Value* no longer exists and we need to use the new gc_result.
2365 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2366 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002367 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002368 live.insert(live.end(), statepoint.gc_args_begin(),
2369 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002370#ifndef NDEBUG
2371 // Do some basic sanity checks on our liveness results before performing
2372 // relocation. Relocation can and will turn mistakes in liveness results
2373 // into non-sensical code which is must harder to debug.
2374 // TODO: It would be nice to test consistency as well
2375 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2376 "statepoint must be reachable or liveness is meaningless");
2377 for (Value *V : statepoint.gc_args()) {
2378 if (!isa<Instruction>(V))
2379 // Non-instruction values trivial dominate all possible uses
2380 continue;
2381 auto LiveInst = cast<Instruction>(V);
2382 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2383 "unreachable values should never be live");
2384 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2385 "basic SSA liveness expectation violated by liveness analysis");
2386 }
2387#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002388 }
2389 unique_unsorted(live);
2390
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002391#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002392 // sanity check
2393 for (auto ptr : live) {
2394 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2395 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002396#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002397
2398 relocationViaAlloca(F, DT, live, records);
2399 return !records.empty();
2400}
2401
Sanjoy Das353a19e2015-06-02 22:33:37 +00002402// Handles both return values and arguments for Functions and CallSites.
2403template <typename AttrHolder>
2404static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2405 unsigned Index) {
2406 AttrBuilder R;
2407 if (AH.getDereferenceableBytes(Index))
2408 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2409 AH.getDereferenceableBytes(Index)));
2410 if (AH.getDereferenceableOrNullBytes(Index))
2411 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2412 AH.getDereferenceableOrNullBytes(Index)));
2413
2414 if (!R.empty())
2415 AH.setAttributes(AH.getAttributes().removeAttributes(
2416 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002417}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002418
2419void
2420RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2421 LLVMContext &Ctx = F.getContext();
2422
2423 for (Argument &A : F.args())
2424 if (isa<PointerType>(A.getType()))
2425 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2426
2427 if (isa<PointerType>(F.getReturnType()))
2428 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2429}
2430
2431void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2432 if (F.empty())
2433 return;
2434
2435 LLVMContext &Ctx = F.getContext();
2436 MDBuilder Builder(Ctx);
2437
Nico Rieck78199512015-08-06 19:10:45 +00002438 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002439 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2440 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2441 bool IsImmutableTBAA =
2442 MD->getNumOperands() == 4 &&
2443 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2444
2445 if (!IsImmutableTBAA)
2446 continue; // no work to do, MD_tbaa is already marked mutable
2447
2448 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2449 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2450 uint64_t Offset =
2451 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2452
2453 MDNode *MutableTBAA =
2454 Builder.createTBAAStructTagNode(Base, Access, Offset);
2455 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2456 }
2457
2458 if (CallSite CS = CallSite(&I)) {
2459 for (int i = 0, e = CS.arg_size(); i != e; i++)
2460 if (isa<PointerType>(CS.getArgument(i)->getType()))
2461 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2462 if (isa<PointerType>(CS.getType()))
2463 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2464 }
2465 }
2466}
2467
Philip Reamesd16a9b12015-02-20 01:06:44 +00002468/// Returns true if this function should be rewritten by this pass. The main
2469/// point of this function is as an extension point for custom logic.
2470static bool shouldRewriteStatepointsIn(Function &F) {
2471 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002472 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002473 const char *FunctionGCName = F.getGC();
2474 const StringRef StatepointExampleName("statepoint-example");
2475 const StringRef CoreCLRName("coreclr");
2476 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002477 (CoreCLRName == FunctionGCName);
2478 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002479 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002480}
2481
Sanjoy Das353a19e2015-06-02 22:33:37 +00002482void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2483#ifndef NDEBUG
2484 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2485 "precondition!");
2486#endif
2487
2488 for (Function &F : M)
2489 stripDereferenceabilityInfoFromPrototype(F);
2490
2491 for (Function &F : M)
2492 stripDereferenceabilityInfoFromBody(F);
2493}
2494
Philip Reamesd16a9b12015-02-20 01:06:44 +00002495bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2496 // Nothing to do for declarations.
2497 if (F.isDeclaration() || F.empty())
2498 return false;
2499
2500 // Policy choice says not to rewrite - the most common reason is that we're
2501 // compiling code without a GCStrategy.
2502 if (!shouldRewriteStatepointsIn(F))
2503 return false;
2504
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002505 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002506
Philip Reames85b36a82015-04-10 22:07:04 +00002507 // Gather all the statepoints which need rewritten. Be careful to only
2508 // consider those in reachable code since we need to ask dominance queries
2509 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002510 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002511 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002512 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002513 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002514 if (isStatepoint(I)) {
2515 if (DT.isReachableFromEntry(I.getParent()))
2516 ParsePointNeeded.push_back(CallSite(&I));
2517 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002518 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002519 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002520 }
2521
Philip Reames85b36a82015-04-10 22:07:04 +00002522 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002523
Philip Reames85b36a82015-04-10 22:07:04 +00002524 // Delete any unreachable statepoints so that we don't have unrewritten
2525 // statepoints surviving this pass. This makes testing easier and the
2526 // resulting IR less confusing to human readers. Rather than be fancy, we
2527 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002528 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002529 MadeChange |= removeUnreachableBlocks(F);
2530
Philip Reamesd16a9b12015-02-20 01:06:44 +00002531 // Return early if no work to do.
2532 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002533 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002534
Philip Reames85b36a82015-04-10 22:07:04 +00002535 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2536 // These are created by LCSSA. They have the effect of increasing the size
2537 // of liveness sets for no good reason. It may be harder to do this post
2538 // insertion since relocations and base phis can confuse things.
2539 for (BasicBlock &BB : F)
2540 if (BB.getUniquePredecessor()) {
2541 MadeChange = true;
2542 FoldSingleEntryPHINodes(&BB);
2543 }
2544
Philip Reames971dc3a2015-08-12 22:11:45 +00002545 // Before we start introducing relocations, we want to tweak the IR a bit to
2546 // avoid unfortunate code generation effects. The main example is that we
2547 // want to try to make sure the comparison feeding a branch is after any
2548 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2549 // values feeding a branch after relocation. This is semantically correct,
2550 // but results in extra register pressure since both the pre-relocation and
2551 // post-relocation copies must be available in registers. For code without
2552 // relocations this is handled elsewhere, but teaching the scheduler to
2553 // reverse the transform we're about to do would be slightly complex.
2554 // Note: This may extend the live range of the inputs to the icmp and thus
2555 // increase the liveset of any statepoint we move over. This is profitable
2556 // as long as all statepoints are in rare blocks. If we had in-register
2557 // lowering for live values this would be a much safer transform.
2558 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2559 if (auto *BI = dyn_cast<BranchInst>(TI))
2560 if (BI->isConditional())
2561 return dyn_cast<Instruction>(BI->getCondition());
2562 // TODO: Extend this to handle switches
2563 return nullptr;
2564 };
2565 for (BasicBlock &BB : F) {
2566 TerminatorInst *TI = BB.getTerminator();
2567 if (auto *Cond = getConditionInst(TI))
2568 // TODO: Handle more than just ICmps here. We should be able to move
2569 // most instructions without side effects or memory access.
2570 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2571 MadeChange = true;
2572 Cond->moveBefore(TI);
2573 }
2574 }
2575
Philip Reames85b36a82015-04-10 22:07:04 +00002576 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2577 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002578}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002579
2580// liveness computation via standard dataflow
2581// -------------------------------------------------------------------
2582
2583// TODO: Consider using bitvectors for liveness, the set of potentially
2584// interesting values should be small and easy to pre-compute.
2585
Philip Reamesdf1ef082015-04-10 22:53:14 +00002586/// Compute the live-in set for the location rbegin starting from
2587/// the live-out set of the basic block
2588static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2589 BasicBlock::reverse_iterator rend,
2590 DenseSet<Value *> &LiveTmp) {
2591
2592 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2593 Instruction *I = &*ritr;
2594
2595 // KILL/Def - Remove this definition from LiveIn
2596 LiveTmp.erase(I);
2597
2598 // Don't consider *uses* in PHI nodes, we handle their contribution to
2599 // predecessor blocks when we seed the LiveOut sets
2600 if (isa<PHINode>(I))
2601 continue;
2602
2603 // USE - Add to the LiveIn set for this instruction
2604 for (Value *V : I->operands()) {
2605 assert(!isUnhandledGCPointerType(V->getType()) &&
2606 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002607 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2608 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002609 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002610 // - We assume that things which are constant (from LLVM's definition)
2611 // do not move at runtime. For example, the address of a global
2612 // variable is fixed, even though it's contents may not be.
2613 // - Second, we can't disallow arbitrary inttoptr constants even
2614 // if the language frontend does. Optimization passes are free to
2615 // locally exploit facts without respect to global reachability. This
2616 // can create sections of code which are dynamically unreachable and
2617 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002618 LiveTmp.insert(V);
2619 }
2620 }
2621 }
2622}
2623
2624static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2625
2626 for (BasicBlock *Succ : successors(BB)) {
2627 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2628 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2629 PHINode *Phi = cast<PHINode>(&*I);
2630 Value *V = Phi->getIncomingValueForBlock(BB);
2631 assert(!isUnhandledGCPointerType(V->getType()) &&
2632 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002633 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002634 LiveTmp.insert(V);
2635 }
2636 }
2637 }
2638}
2639
2640static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2641 DenseSet<Value *> KillSet;
2642 for (Instruction &I : *BB)
2643 if (isHandledGCPointerType(I.getType()))
2644 KillSet.insert(&I);
2645 return KillSet;
2646}
2647
Philip Reames9638ff92015-04-11 00:06:47 +00002648#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002649/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2650/// sanity check for the liveness computation.
2651static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2652 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002653 for (Value *V : Live) {
2654 if (auto *I = dyn_cast<Instruction>(V)) {
2655 // The terminator can be a member of the LiveOut set. LLVM's definition
2656 // of instruction dominance states that V does not dominate itself. As
2657 // such, we need to special case this to allow it.
2658 if (TermOkay && TI == I)
2659 continue;
2660 assert(DT.dominates(I, TI) &&
2661 "basic SSA liveness expectation violated by liveness analysis");
2662 }
2663 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002664}
2665
2666/// Check that all the liveness sets used during the computation of liveness
2667/// obey basic SSA properties. This is useful for finding cases where we miss
2668/// a def.
2669static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2670 BasicBlock &BB) {
2671 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2672 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2673 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2674}
Philip Reames9638ff92015-04-11 00:06:47 +00002675#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002676
2677static void computeLiveInValues(DominatorTree &DT, Function &F,
2678 GCPtrLivenessData &Data) {
2679
Philip Reames4d80ede2015-04-10 23:11:26 +00002680 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002681 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002682 // We use a SetVector so that we don't have duplicates in the worklist.
2683 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002684 };
2685 auto NextItem = [&]() {
2686 BasicBlock *BB = Worklist.back();
2687 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002688 return BB;
2689 };
2690
2691 // Seed the liveness for each individual block
2692 for (BasicBlock &BB : F) {
2693 Data.KillSet[&BB] = computeKillSet(&BB);
2694 Data.LiveSet[&BB].clear();
2695 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2696
2697#ifndef NDEBUG
2698 for (Value *Kill : Data.KillSet[&BB])
2699 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2700#endif
2701
2702 Data.LiveOut[&BB] = DenseSet<Value *>();
2703 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2704 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2705 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2706 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2707 if (!Data.LiveIn[&BB].empty())
2708 AddPredsToWorklist(&BB);
2709 }
2710
2711 // Propagate that liveness until stable
2712 while (!Worklist.empty()) {
2713 BasicBlock *BB = NextItem();
2714
2715 // Compute our new liveout set, then exit early if it hasn't changed
2716 // despite the contribution of our successor.
2717 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2718 const auto OldLiveOutSize = LiveOut.size();
2719 for (BasicBlock *Succ : successors(BB)) {
2720 assert(Data.LiveIn.count(Succ));
2721 set_union(LiveOut, Data.LiveIn[Succ]);
2722 }
2723 // assert OutLiveOut is a subset of LiveOut
2724 if (OldLiveOutSize == LiveOut.size()) {
2725 // If the sets are the same size, then we didn't actually add anything
2726 // when unioning our successors LiveIn Thus, the LiveIn of this block
2727 // hasn't changed.
2728 continue;
2729 }
2730 Data.LiveOut[BB] = LiveOut;
2731
2732 // Apply the effects of this basic block
2733 DenseSet<Value *> LiveTmp = LiveOut;
2734 set_union(LiveTmp, Data.LiveSet[BB]);
2735 set_subtract(LiveTmp, Data.KillSet[BB]);
2736
2737 assert(Data.LiveIn.count(BB));
2738 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2739 // assert: OldLiveIn is a subset of LiveTmp
2740 if (OldLiveIn.size() != LiveTmp.size()) {
2741 Data.LiveIn[BB] = LiveTmp;
2742 AddPredsToWorklist(BB);
2743 }
2744 } // while( !worklist.empty() )
2745
2746#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002747 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002748 // missing kills during the above iteration.
2749 for (BasicBlock &BB : F) {
2750 checkBasicSSA(DT, Data, BB);
2751 }
2752#endif
2753}
2754
2755static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2756 StatepointLiveSetTy &Out) {
2757
2758 BasicBlock *BB = Inst->getParent();
2759
2760 // Note: The copy is intentional and required
2761 assert(Data.LiveOut.count(BB));
2762 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2763
2764 // We want to handle the statepoint itself oddly. It's
2765 // call result is not live (normal), nor are it's arguments
2766 // (unless they're used again later). This adjustment is
2767 // specifically what we need to relocate
2768 BasicBlock::reverse_iterator rend(Inst);
2769 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2770 LiveOut.erase(Inst);
2771 Out.insert(LiveOut.begin(), LiveOut.end());
2772}
2773
2774static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2775 const CallSite &CS,
2776 PartiallyConstructedSafepointRecord &Info) {
2777 Instruction *Inst = CS.getInstruction();
2778 StatepointLiveSetTy Updated;
2779 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2780
2781#ifndef NDEBUG
2782 DenseSet<Value *> Bases;
2783 for (auto KVPair : Info.PointerToBase) {
2784 Bases.insert(KVPair.second);
2785 }
2786#endif
2787 // We may have base pointers which are now live that weren't before. We need
2788 // to update the PointerToBase structure to reflect this.
2789 for (auto V : Updated)
2790 if (!Info.PointerToBase.count(V)) {
2791 assert(Bases.count(V) && "can't find base for unexpected live value");
2792 Info.PointerToBase[V] = V;
2793 continue;
2794 }
2795
2796#ifndef NDEBUG
2797 for (auto V : Updated) {
2798 assert(Info.PointerToBase.count(V) &&
2799 "must be able to find base for live value");
2800 }
2801#endif
2802
2803 // Remove any stale base mappings - this can happen since our liveness is
2804 // more precise then the one inherent in the base pointer analysis
2805 DenseSet<Value *> ToErase;
2806 for (auto KVPair : Info.PointerToBase)
2807 if (!Updated.count(KVPair.first))
2808 ToErase.insert(KVPair.first);
2809 for (auto V : ToErase)
2810 Info.PointerToBase.erase(V);
2811
2812#ifndef NDEBUG
2813 for (auto KVPair : Info.PointerToBase)
2814 assert(Updated.count(KVPair.first) && "record for non-live value");
2815#endif
2816
2817 Info.liveset = Updated;
2818}