blob: 031f40e2caa6c0a11adc2700080893b2ce22d0d9 [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 Reames8fe7f132015-06-26 22:47:37 +0000331findBaseDefiningValueOfVector(Value *I, Value *Index = nullptr) {
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 Reames8fe7f132015-06-26 22:47:37 +0000365
Philip Reames311f7102015-05-12 22:19:52 +0000366 // For an insert element, we might be able to look through it if we know
Philip Reames8fe7f132015-06-26 22:47:37 +0000367 // something about the indexes.
Philip Reames311f7102015-05-12 22:19:52 +0000368 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000369 if (Index) {
370 Value *InsertIndex = IEI->getOperand(2);
371 // This index is inserting the value, look for its BDV
372 if (InsertIndex == Index)
Philip Reamesf5b8e472015-09-03 21:34:30 +0000373 return findBaseDefiningValue(IEI->getOperand(1));
Philip Reames8fe7f132015-06-26 22:47:37 +0000374 // Both constant, and can't be equal per above. This insert is definitely
375 // not relevant, look back at the rest of the vector and keep trying.
376 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
377 return findBaseDefiningValueOfVector(IEI->getOperand(0), Index);
378 }
Philip Reamesf5b8e472015-09-03 21:34:30 +0000379
380 // If both inputs to the insertelement are known bases, then so is the
381 // insertelement itself. NOTE: This should be handled within the generic
382 // base pointer inference code and after http://reviews.llvm.org/D12583,
383 // will be. However, when strengthening asserts I needed to add this to
384 // keep an existing test passing which was 'working'. FIXME
385 if (findBaseDefiningValue(IEI->getOperand(0)).IsKnownBase &&
386 findBaseDefiningValue(IEI->getOperand(1)).IsKnownBase)
387 return BaseDefiningValueResult(IEI, true);
Philip Reames8fe7f132015-06-26 22:47:37 +0000388
389 // We don't know whether this vector contains entirely base pointers or
390 // not. To be conservatively correct, we treat it as a BDV and will
391 // duplicate code as needed to construct a parallel vector of bases.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000392 return BaseDefiningValueResult(IEI, false);
Philip Reames311f7102015-05-12 22:19:52 +0000393 }
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +0000394
Philip Reames8fe7f132015-06-26 22:47:37 +0000395 if (isa<ShuffleVectorInst>(I))
396 // We don't know whether this vector contains entirely base pointers or
397 // not. To be conservatively correct, we treat it as a BDV and will
398 // duplicate code as needed to construct a parallel vector of bases.
399 // TODO: There a number of local optimizations which could be applied here
400 // for particular sufflevector patterns.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000401 return BaseDefiningValueResult(I, false);
Philip Reames8fe7f132015-06-26 22:47:37 +0000402
403 // A PHI or Select is a base defining value. The outer findBasePointer
404 // algorithm is responsible for constructing a base value for this BDV.
405 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
406 "unknown vector instruction - no base found for vector element");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000407 return BaseDefiningValueResult(I, false);
Philip Reames8531d8c2015-04-10 21:48:25 +0000408}
409
Philip Reamesd16a9b12015-02-20 01:06:44 +0000410/// Helper function for findBasePointer - Will return a value which either a)
Philip Reames9ac4e382015-08-12 21:00:20 +0000411/// defines the base pointer for the input, b) blocks the simple search
412/// (i.e. a PHI or Select of two derived pointers), or c) involves a change
413/// from pointer to vector type or back.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000414static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
Philip Reames8fe7f132015-06-26 22:47:37 +0000415 if (I->getType()->isVectorTy())
Philip Reamesf5b8e472015-09-03 21:34:30 +0000416 return findBaseDefiningValueOfVector(I);
Philip Reames8fe7f132015-06-26 22:47:37 +0000417
Philip Reamesd16a9b12015-02-20 01:06:44 +0000418 assert(I->getType()->isPointerTy() &&
419 "Illegal to ask for the base pointer of a non-pointer type");
420
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000421 if (isa<Argument>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000422 // An incoming argument to the function is a base pointer
423 // We should have never reached here if this argument isn't an gc value
Philip Reamesf5b8e472015-09-03 21:34:30 +0000424 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000425
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000426 if (isa<GlobalVariable>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000427 // base case
Philip Reamesf5b8e472015-09-03 21:34:30 +0000428 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000429
430 // inlining could possibly introduce phi node that contains
431 // undef if callee has multiple returns
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000432 if (isa<UndefValue>(I))
433 // utterly meaningless, but useful for dealing with
434 // partially optimized code.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000435 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000436
437 // Due to inheritance, this must be _after_ the global variable and undef
438 // checks
Philip Reames3ea15892015-09-03 21:57:40 +0000439 if (isa<Constant>(I)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000440 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
441 "order of checks wrong!");
442 // Note: Finding a constant base for something marked for relocation
443 // doesn't really make sense. The most likely case is either a) some
444 // screwed up the address space usage or b) your validating against
445 // compiled C++ code w/o the proper separation. The only real exception
446 // is a null pointer. You could have generic code written to index of
447 // off a potentially null value and have proven it null. We also use
448 // null pointers in dead paths of relocation phis (which we might later
449 // want to find a base pointer for).
Philip Reames3ea15892015-09-03 21:57:40 +0000450 assert(isa<ConstantPointerNull>(I) &&
Philip Reames24c6cd52015-03-27 05:47:00 +0000451 "null is the only case which makes sense");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000452 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000453 }
454
455 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000456 Value *Def = CI->stripPointerCasts();
David Blaikie82ad7872015-02-20 23:44:24 +0000457 // If we find a cast instruction here, it means we've found a cast which is
458 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
459 // handle int->ptr conversion.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000460 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
461 return findBaseDefiningValue(Def);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000462 }
463
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000464 if (isa<LoadInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000465 // The value loaded is an gc base itself
466 return BaseDefiningValueResult(I, true);
467
Philip Reamesd16a9b12015-02-20 01:06:44 +0000468
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000469 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
470 // The base of this GEP is the base
471 return findBaseDefiningValue(GEP->getPointerOperand());
Philip Reamesd16a9b12015-02-20 01:06:44 +0000472
473 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
474 switch (II->getIntrinsicID()) {
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000475 case Intrinsic::experimental_gc_result_ptr:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000476 default:
477 // fall through to general call handling
478 break;
479 case Intrinsic::experimental_gc_statepoint:
480 case Intrinsic::experimental_gc_result_float:
481 case Intrinsic::experimental_gc_result_int:
482 llvm_unreachable("these don't produce pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000483 case Intrinsic::experimental_gc_relocate: {
484 // Rerunning safepoint insertion after safepoints are already
485 // inserted is not supported. It could probably be made to work,
486 // but why are you doing this? There's no good reason.
487 llvm_unreachable("repeat safepoint insertion is not supported");
488 }
489 case Intrinsic::gcroot:
490 // Currently, this mechanism hasn't been extended to work with gcroot.
491 // There's no reason it couldn't be, but I haven't thought about the
492 // implications much.
493 llvm_unreachable(
494 "interaction with the gcroot mechanism is not supported");
495 }
496 }
497 // We assume that functions in the source language only return base
498 // pointers. This should probably be generalized via attributes to support
499 // both source language and internal functions.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000500 if (isa<CallInst>(I) || isa<InvokeInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000501 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000502
503 // I have absolutely no idea how to implement this part yet. It's not
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000504 // necessarily hard, I just haven't really looked at it yet.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000505 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
506
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000507 if (isa<AtomicCmpXchgInst>(I))
Philip Reamesd16a9b12015-02-20 01:06:44 +0000508 // A CAS is effectively a atomic store and load combined under a
509 // predicate. From the perspective of base pointers, we just treat it
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000510 // like a load.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000511 return BaseDefiningValueResult(I, true);
Philip Reames704e78b2015-04-10 22:34:56 +0000512
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000513 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
Philip Reames704e78b2015-04-10 22:34:56 +0000514 "binary ops which don't apply to pointers");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000515
516 // The aggregate ops. Aggregates can either be in the heap or on the
517 // stack, but in either case, this is simply a field load. As a result,
518 // this is a defining definition of the base just like a load is.
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000519 if (isa<ExtractValueInst>(I))
Philip Reamesf5b8e472015-09-03 21:34:30 +0000520 return BaseDefiningValueResult(I, true);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000521
522 // We should never see an insert vector since that would require we be
523 // tracing back a struct value not a pointer value.
524 assert(!isa<InsertValueInst>(I) &&
525 "Base pointer for a struct is meaningless");
526
Philip Reames9ac4e382015-08-12 21:00:20 +0000527 // An extractelement produces a base result exactly when it's input does.
528 // We may need to insert a parallel instruction to extract the appropriate
529 // element out of the base vector corresponding to the input. Given this,
530 // it's analogous to the phi and select case even though it's not a merge.
531 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
532 Value *VectorOperand = EEI->getVectorOperand();
533 Value *Index = EEI->getIndexOperand();
Philip Reamesf5b8e472015-09-03 21:34:30 +0000534 auto VecResult = findBaseDefiningValueOfVector(VectorOperand, Index);
535 Value *VectorBase = VecResult.BDV;
Philip Reames9ac4e382015-08-12 21:00:20 +0000536 if (VectorBase->getType()->isPointerTy())
537 // We found a BDV for this specific element with the vector. This is an
538 // optimization, but in practice it covers most of the useful cases
539 // created via scalarization. Note: The peephole optimization here is
540 // currently needed for correctness since the general algorithm doesn't
541 // yet handle insertelements. That will change shortly.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000542 return BaseDefiningValueResult(VectorBase, VecResult.IsKnownBase);
Philip Reames9ac4e382015-08-12 21:00:20 +0000543 else {
544 assert(VectorBase->getType()->isVectorTy());
545 // Otherwise, we have an instruction which potentially produces a
546 // derived pointer and we need findBasePointers to clone code for us
547 // such that we can create an instruction which produces the
548 // accompanying base pointer.
Philip Reamesf5b8e472015-09-03 21:34:30 +0000549 return BaseDefiningValueResult(I, VecResult.IsKnownBase);
Philip Reames9ac4e382015-08-12 21:00:20 +0000550 }
551 }
552
Philip Reamesd16a9b12015-02-20 01:06:44 +0000553 // The last two cases here don't return a base pointer. Instead, they
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000554 // return a value which dynamically selects from among several base
Philip Reamesd16a9b12015-02-20 01:06:44 +0000555 // derived pointers (each with it's own base potentially). It's the job of
556 // the caller to resolve these.
Philip Reames704e78b2015-04-10 22:34:56 +0000557 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
Philip Reamesaa66dfa2015-03-27 05:34:44 +0000558 "missing instruction case in findBaseDefiningValing");
Philip Reamesf5b8e472015-09-03 21:34:30 +0000559 return BaseDefiningValueResult(I, false);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000560}
561
562/// Returns the base defining value for this value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000563static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
564 Value *&Cached = Cache[I];
Benjamin Kramer6f665452015-02-20 14:00:58 +0000565 if (!Cached) {
Philip Reamesf5b8e472015-09-03 21:34:30 +0000566 Cached = findBaseDefiningValue(I).BDV;
Philip Reames2a892a62015-07-23 22:25:26 +0000567 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
568 << Cached->getName() << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000569 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000570 assert(Cache[I] != nullptr);
Benjamin Kramer6f665452015-02-20 14:00:58 +0000571 return Cached;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000572}
573
574/// Return a base pointer for this value if known. Otherwise, return it's
575/// base defining value.
Philip Reames18d0feb2015-03-27 05:39:32 +0000576static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
577 Value *Def = findBaseDefiningValueCached(I, Cache);
578 auto Found = Cache.find(Def);
579 if (Found != Cache.end()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000580 // Either a base-of relation, or a self reference. Caller must check.
Benjamin Kramer6f665452015-02-20 14:00:58 +0000581 return Found->second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000582 }
583 // Only a BDV available
Philip Reames18d0feb2015-03-27 05:39:32 +0000584 return Def;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000585}
586
587/// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
588/// is it known to be a base pointer? Or do we need to continue searching.
Philip Reames18d0feb2015-03-27 05:39:32 +0000589static bool isKnownBaseResult(Value *V) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000590 if (!isa<PHINode>(V) && !isa<SelectInst>(V) && !isa<ExtractElementInst>(V)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000591 // no recursion possible
592 return true;
593 }
Philip Reames18d0feb2015-03-27 05:39:32 +0000594 if (isa<Instruction>(V) &&
595 cast<Instruction>(V)->getMetadata("is_base_value")) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000596 // This is a previously inserted base phi or select. We know
597 // that this is a base value.
598 return true;
599 }
600
601 // We need to keep searching
602 return false;
603}
604
Philip Reamesd16a9b12015-02-20 01:06:44 +0000605namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000606/// Models the state of a single base defining value in the findBasePointer
607/// algorithm for determining where a new instruction is needed to propagate
608/// the base of this BDV.
609class BDVState {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000610public:
611 enum Status { Unknown, Base, Conflict };
612
Philip Reames9b141ed2015-07-23 22:49:14 +0000613 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000614 assert(status != Base || b);
615 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000616 explicit BDVState(Value *b) : status(Base), base(b) {}
617 BDVState() : status(Unknown), base(nullptr) {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000618
619 Status getStatus() const { return status; }
620 Value *getBase() const { return base; }
621
622 bool isBase() const { return getStatus() == Base; }
623 bool isUnknown() const { return getStatus() == Unknown; }
624 bool isConflict() const { return getStatus() == Conflict; }
625
Philip Reames9b141ed2015-07-23 22:49:14 +0000626 bool operator==(const BDVState &other) const {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000627 return base == other.base && status == other.status;
628 }
629
Philip Reames9b141ed2015-07-23 22:49:14 +0000630 bool operator!=(const BDVState &other) const { return !(*this == other); }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000631
Philip Reames2a892a62015-07-23 22:25:26 +0000632 LLVM_DUMP_METHOD
633 void dump() const { print(dbgs()); dbgs() << '\n'; }
634
635 void print(raw_ostream &OS) const {
Philip Reamesdab35f32015-09-02 21:11:44 +0000636 switch (status) {
637 case Unknown:
638 OS << "U";
639 break;
640 case Base:
641 OS << "B";
642 break;
643 case Conflict:
644 OS << "C";
645 break;
646 };
647 OS << " (" << base << " - "
Philip Reames2a892a62015-07-23 22:25:26 +0000648 << (base ? base->getName() : "nullptr") << "): ";
Philip Reamesd16a9b12015-02-20 01:06:44 +0000649 }
650
651private:
652 Status status;
653 Value *base; // non null only if status == base
654};
Philip Reamesb3967cd2015-09-02 22:30:53 +0000655}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000656
Philip Reames6906e922015-09-02 21:57:17 +0000657#ifndef NDEBUG
Philip Reamesb3967cd2015-09-02 22:30:53 +0000658static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
Philip Reames2a892a62015-07-23 22:25:26 +0000659 State.print(OS);
660 return OS;
661}
Philip Reames6906e922015-09-02 21:57:17 +0000662#endif
Philip Reames2a892a62015-07-23 22:25:26 +0000663
Philip Reamesb3967cd2015-09-02 22:30:53 +0000664namespace {
Philip Reames9b141ed2015-07-23 22:49:14 +0000665// Values of type BDVState form a lattice, and this is a helper
Philip Reamesd16a9b12015-02-20 01:06:44 +0000666// class that implementes the meet operation. The meat of the meet
Philip Reames9b141ed2015-07-23 22:49:14 +0000667// operation is implemented in MeetBDVStates::pureMeet
668class MeetBDVStates {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000669public:
Philip Reames273e6bb2015-07-23 21:41:27 +0000670 /// Initializes the currentResult to the TOP state so that if can be met with
671 /// any other state to produce that state.
Philip Reames9b141ed2015-07-23 22:49:14 +0000672 MeetBDVStates() {}
Philip Reamesd16a9b12015-02-20 01:06:44 +0000673
Philip Reames9b141ed2015-07-23 22:49:14 +0000674 // Destructively meet the current result with the given BDVState
675 void meetWith(BDVState otherState) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000676 currentResult = meet(otherState, currentResult);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000677 }
678
Philip Reames9b141ed2015-07-23 22:49:14 +0000679 BDVState getResult() const { return currentResult; }
Philip Reamesd16a9b12015-02-20 01:06:44 +0000680
681private:
Philip Reames9b141ed2015-07-23 22:49:14 +0000682 BDVState currentResult;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000683
Philip Reames9b141ed2015-07-23 22:49:14 +0000684 /// Perform a meet operation on two elements of the BDVState lattice.
685 static BDVState meet(BDVState LHS, BDVState RHS) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000686 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
687 "math is wrong: meet does not commute!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000688 BDVState Result = pureMeet(LHS, RHS);
Philip Reames2a892a62015-07-23 22:25:26 +0000689 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
690 << " produced " << Result << "\n");
691 return Result;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000692 }
693
Philip Reames9b141ed2015-07-23 22:49:14 +0000694 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000695 switch (stateA.getStatus()) {
Philip Reames9b141ed2015-07-23 22:49:14 +0000696 case BDVState::Unknown:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000697 return stateB;
698
Philip Reames9b141ed2015-07-23 22:49:14 +0000699 case BDVState::Base:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000700 assert(stateA.getBase() && "can't be null");
David Blaikie82ad7872015-02-20 23:44:24 +0000701 if (stateB.isUnknown())
Philip Reamesd16a9b12015-02-20 01:06:44 +0000702 return stateA;
David Blaikie82ad7872015-02-20 23:44:24 +0000703
704 if (stateB.isBase()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000705 if (stateA.getBase() == stateB.getBase()) {
706 assert(stateA == stateB && "equality broken!");
707 return stateA;
708 }
Philip Reames9b141ed2015-07-23 22:49:14 +0000709 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000710 }
David Blaikie82ad7872015-02-20 23:44:24 +0000711 assert(stateB.isConflict() && "only three states!");
Philip Reames9b141ed2015-07-23 22:49:14 +0000712 return BDVState(BDVState::Conflict);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000713
Philip Reames9b141ed2015-07-23 22:49:14 +0000714 case BDVState::Conflict:
Philip Reamesd16a9b12015-02-20 01:06:44 +0000715 return stateA;
716 }
Reid Klecknera070ee52015-02-20 19:46:02 +0000717 llvm_unreachable("only three states!");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000718 }
719};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000720}
Philip Reamesb3967cd2015-09-02 22:30:53 +0000721
722
Philip Reamesd16a9b12015-02-20 01:06:44 +0000723/// For a given value or instruction, figure out what base ptr it's derived
724/// from. For gc objects, this is simply itself. On success, returns a value
725/// which is the base pointer. (This is reliable and can be used for
726/// relocation.) On failure, returns nullptr.
Philip Reamesba198492015-04-14 00:41:34 +0000727static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000728 Value *def = findBaseOrBDV(I, cache);
729
730 if (isKnownBaseResult(def)) {
731 return def;
732 }
733
734 // Here's the rough algorithm:
735 // - For every SSA value, construct a mapping to either an actual base
736 // pointer or a PHI which obscures the base pointer.
737 // - Construct a mapping from PHI to unknown TOP state. Use an
738 // optimistic algorithm to propagate base pointer information. Lattice
739 // looks like:
740 // UNKNOWN
741 // b1 b2 b3 b4
742 // CONFLICT
743 // When algorithm terminates, all PHIs will either have a single concrete
744 // base or be in a conflict state.
745 // - For every conflict, insert a dummy PHI node without arguments. Add
746 // these to the base[Instruction] = BasePtr mapping. For every
747 // non-conflict, add the actual base.
748 // - For every conflict, add arguments for the base[a] of each input
749 // arguments.
750 //
751 // Note: A simpler form of this would be to add the conflict form of all
752 // PHIs without running the optimistic algorithm. This would be
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000753 // analogous to pessimistic data flow and would likely lead to an
Philip Reamesd16a9b12015-02-20 01:06:44 +0000754 // overall worse solution.
755
Philip Reames29e9ae72015-07-24 00:42:55 +0000756#ifndef NDEBUG
Philip Reames88958b22015-07-24 00:02:11 +0000757 auto isExpectedBDVType = [](Value *BDV) {
Philip Reames9ac4e382015-08-12 21:00:20 +0000758 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) || isa<ExtractElementInst>(BDV);
Philip Reames88958b22015-07-24 00:02:11 +0000759 };
Philip Reames29e9ae72015-07-24 00:42:55 +0000760#endif
Philip Reames88958b22015-07-24 00:02:11 +0000761
762 // Once populated, will contain a mapping from each potentially non-base BDV
763 // to a lattice value (described above) which corresponds to that BDV.
Philip Reames15d55632015-09-09 23:26:08 +0000764 // We use the order of insertion (DFS over the def/use graph) to provide a
765 // stable deterministic ordering for visiting DenseMaps (which are unordered)
766 // below. This is important for deterministic compilation.
767 MapVector<Value *, BDVState> states;
768
769 // Recursively fill in all base defining values reachable from the initial
770 // one for which we don't already know a definite base value for
Philip Reames88958b22015-07-24 00:02:11 +0000771 /* scope */ {
Philip Reames88958b22015-07-24 00:02:11 +0000772 SmallVector<Value*, 16> Worklist;
773 Worklist.push_back(def);
Philip Reames15d55632015-09-09 23:26:08 +0000774 states.insert(std::make_pair(def, BDVState()));
Philip Reames88958b22015-07-24 00:02:11 +0000775 while (!Worklist.empty()) {
776 Value *Current = Worklist.pop_back_val();
777 assert(!isKnownBaseResult(Current) && "why did it get added?");
778
779 auto visitIncomingValue = [&](Value *InVal) {
780 Value *Base = findBaseOrBDV(InVal, cache);
781 if (isKnownBaseResult(Base))
782 // Known bases won't need new instructions introduced and can be
783 // ignored safely
784 return;
785 assert(isExpectedBDVType(Base) && "the only non-base values "
786 "we see should be base defining values");
Philip Reames15d55632015-09-09 23:26:08 +0000787 if (states.insert(std::make_pair(Base, BDVState())).second)
Philip Reames88958b22015-07-24 00:02:11 +0000788 Worklist.push_back(Base);
789 };
790 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
791 for (Value *InVal : Phi->incoming_values())
792 visitIncomingValue(InVal);
Philip Reames9ac4e382015-08-12 21:00:20 +0000793 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
Philip Reames88958b22015-07-24 00:02:11 +0000794 visitIncomingValue(Sel->getTrueValue());
795 visitIncomingValue(Sel->getFalseValue());
Philip Reames9ac4e382015-08-12 21:00:20 +0000796 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
797 visitIncomingValue(EE->getVectorOperand());
798 } else {
799 // There are two classes of instructions we know we don't handle.
800 assert(isa<ShuffleVectorInst>(Current) ||
801 isa<InsertElementInst>(Current));
802 llvm_unreachable("unimplemented instruction case");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000803 }
804 }
805 }
806
Philip Reamesdab35f32015-09-02 21:11:44 +0000807#ifndef NDEBUG
808 DEBUG(dbgs() << "States after initialization:\n");
809 for (auto Pair : states) {
810 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000811 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000812#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000813
Philip Reames273e6bb2015-07-23 21:41:27 +0000814 // Return a phi state for a base defining value. We'll generate a new
815 // base state for known bases and expect to find a cached state otherwise.
816 auto getStateForBDV = [&](Value *baseValue) {
817 if (isKnownBaseResult(baseValue))
Philip Reames9b141ed2015-07-23 22:49:14 +0000818 return BDVState(baseValue);
Philip Reames273e6bb2015-07-23 21:41:27 +0000819 auto I = states.find(baseValue);
820 assert(I != states.end() && "lookup failed!");
821 return I->second;
822 };
823
Philip Reamesd16a9b12015-02-20 01:06:44 +0000824 bool progress = true;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000825 while (progress) {
Yaron Keren42a7adf2015-02-28 13:11:24 +0000826#ifndef NDEBUG
827 size_t oldSize = states.size();
828#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +0000829 progress = false;
Philip Reames15d55632015-09-09 23:26:08 +0000830 // We're only changing values in this loop, thus safe to keep iterators.
831 // Since this is computing a fixed point, the order of visit does not
832 // effect the result. TODO: We could use a worklist here and make this run
833 // much faster.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000834 for (auto Pair : states) {
Philip Reamesd16a9b12015-02-20 01:06:44 +0000835 Value *v = Pair.first;
836 assert(!isKnownBaseResult(v) && "why did it get added?");
Philip Reames273e6bb2015-07-23 21:41:27 +0000837
Philip Reames9b141ed2015-07-23 22:49:14 +0000838 // Given an input value for the current instruction, return a BDVState
Philip Reames273e6bb2015-07-23 21:41:27 +0000839 // instance which represents the BDV of that value.
840 auto getStateForInput = [&](Value *V) mutable {
841 Value *BDV = findBaseOrBDV(V, cache);
842 return getStateForBDV(BDV);
843 };
844
Philip Reames9b141ed2015-07-23 22:49:14 +0000845 MeetBDVStates calculateMeet;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000846 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
Philip Reames273e6bb2015-07-23 21:41:27 +0000847 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
848 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
Philip Reames9ac4e382015-08-12 21:00:20 +0000849 } else if (PHINode *Phi = dyn_cast<PHINode>(v)) {
850 for (Value *Val : Phi->incoming_values())
Philip Reames273e6bb2015-07-23 21:41:27 +0000851 calculateMeet.meetWith(getStateForInput(Val));
Philip Reames9ac4e382015-08-12 21:00:20 +0000852 } else {
853 // The 'meet' for an extractelement is slightly trivial, but it's still
854 // useful in that it drives us to conflict if our input is.
855 auto *EE = cast<ExtractElementInst>(v);
856 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
857 }
858
Philip Reames9b141ed2015-07-23 22:49:14 +0000859 BDVState oldState = states[v];
860 BDVState newState = calculateMeet.getResult();
Philip Reamesd16a9b12015-02-20 01:06:44 +0000861 if (oldState != newState) {
862 progress = true;
863 states[v] = newState;
864 }
865 }
866
867 assert(oldSize <= states.size());
868 assert(oldSize == states.size() || progress);
869 }
870
Philip Reamesdab35f32015-09-02 21:11:44 +0000871#ifndef NDEBUG
872 DEBUG(dbgs() << "States after meet iteration:\n");
873 for (auto Pair : states) {
874 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +0000875 }
Philip Reamesdab35f32015-09-02 21:11:44 +0000876#endif
877
Philip Reamesd16a9b12015-02-20 01:06:44 +0000878 // Insert Phis for all conflicts
Philip Reames2e5bcbe2015-02-28 01:52:09 +0000879 // TODO: adjust naming patterns to avoid this order of iteration dependency
Philip Reames15d55632015-09-09 23:26:08 +0000880 for (auto Pair : states) {
881 Instruction *I = cast<Instruction>(Pair.first);
882 BDVState State = Pair.second;
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000883 assert(!isKnownBaseResult(I) && "why did it get added?");
884 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames9ac4e382015-08-12 21:00:20 +0000885
886 // extractelement instructions are a bit special in that we may need to
887 // insert an extract even when we know an exact base for the instruction.
888 // The problem is that we need to convert from a vector base to a scalar
889 // base for the particular indice we're interested in.
890 if (State.isBase() && isa<ExtractElementInst>(I) &&
891 isa<VectorType>(State.getBase()->getType())) {
892 auto *EE = cast<ExtractElementInst>(I);
893 // TODO: In many cases, the new instruction is just EE itself. We should
894 // exploit this, but can't do it here since it would break the invariant
895 // about the BDV not being known to be a base.
896 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
897 EE->getIndexOperand(),
898 "base_ee", EE);
899 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
900 states[I] = BDVState(BDVState::Base, BaseInst);
901 }
902
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000903 if (!State.isConflict())
Philip Reamesf986d682015-02-28 00:54:41 +0000904 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000905
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000906 /// Create and insert a new instruction which will represent the base of
907 /// the given instruction 'I'.
908 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
909 if (isa<PHINode>(I)) {
910 BasicBlock *BB = I->getParent();
911 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
912 assert(NumPreds > 0 && "how did we reach here");
Philip Reamesfa2c6302015-07-24 19:01:39 +0000913 std::string Name = I->hasName() ?
914 (I->getName() + ".base").str() : "base_phi";
915 return PHINode::Create(I->getType(), NumPreds, Name, I);
Philip Reames9ac4e382015-08-12 21:00:20 +0000916 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
917 // The undef will be replaced later
918 UndefValue *Undef = UndefValue::get(Sel->getType());
919 std::string Name = I->hasName() ?
920 (I->getName() + ".base").str() : "base_select";
921 return SelectInst::Create(Sel->getCondition(), Undef,
922 Undef, Name, Sel);
923 } else {
924 auto *EE = cast<ExtractElementInst>(I);
925 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
926 std::string Name = I->hasName() ?
927 (I->getName() + ".base").str() : "base_ee";
928 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
929 EE);
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000930 }
Philip Reames6ff1a1e32015-07-21 19:04:38 +0000931 };
932 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
933 // Add metadata marking this as a base value
934 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
Philip Reames9b141ed2015-07-23 22:49:14 +0000935 states[I] = BDVState(BDVState::Conflict, BaseInst);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000936 }
937
Philip Reames3ea15892015-09-03 21:57:40 +0000938 // Returns a instruction which produces the base pointer for a given
939 // instruction. The instruction is assumed to be an input to one of the BDVs
940 // seen in the inference algorithm above. As such, we must either already
941 // know it's base defining value is a base, or have inserted a new
942 // instruction to propagate the base of it's BDV and have entered that newly
943 // introduced instruction into the state table. In either case, we are
944 // assured to be able to determine an instruction which produces it's base
945 // pointer.
946 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
947 Value *BDV = findBaseOrBDV(Input, cache);
948 Value *Base = nullptr;
949 if (isKnownBaseResult(BDV)) {
950 Base = BDV;
951 } else {
952 // Either conflict or base.
953 assert(states.count(BDV));
954 Base = states[BDV].getBase();
955 }
956 assert(Base && "can't be null");
957 // The cast is needed since base traversal may strip away bitcasts
958 if (Base->getType() != Input->getType() &&
959 InsertPt) {
960 Base = new BitCastInst(Base, Input->getType(), "cast",
961 InsertPt);
962 }
963 return Base;
964 };
965
Philip Reames15d55632015-09-09 23:26:08 +0000966 // Fixup all the inputs of the new PHIs. Visit order needs to be
967 // deterministic and predictable because we're naming newly created
968 // instructions.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000969 for (auto Pair : states) {
970 Instruction *v = cast<Instruction>(Pair.first);
Philip Reames9b141ed2015-07-23 22:49:14 +0000971 BDVState state = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +0000972
973 assert(!isKnownBaseResult(v) && "why did it get added?");
974 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
Philip Reames28e61ce2015-02-28 01:57:44 +0000975 if (!state.isConflict())
976 continue;
Philip Reames704e78b2015-04-10 22:34:56 +0000977
Philip Reames28e61ce2015-02-28 01:57:44 +0000978 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
979 PHINode *phi = cast<PHINode>(v);
980 unsigned NumPHIValues = phi->getNumIncomingValues();
981 for (unsigned i = 0; i < NumPHIValues; i++) {
982 Value *InVal = phi->getIncomingValue(i);
983 BasicBlock *InBB = phi->getIncomingBlock(i);
Philip Reamesd16a9b12015-02-20 01:06:44 +0000984
Philip Reames28e61ce2015-02-28 01:57:44 +0000985 // If we've already seen InBB, add the same incoming value
986 // we added for it earlier. The IR verifier requires phi
987 // nodes with multiple entries from the same basic block
988 // to have the same incoming value for each of those
989 // entries. If we don't do this check here and basephi
990 // has a different type than base, we'll end up adding two
991 // bitcasts (and hence two distinct values) as incoming
992 // values for the same basic block.
Philip Reamesd16a9b12015-02-20 01:06:44 +0000993
Philip Reames28e61ce2015-02-28 01:57:44 +0000994 int blockIndex = basephi->getBasicBlockIndex(InBB);
995 if (blockIndex != -1) {
996 Value *oldBase = basephi->getIncomingValue(blockIndex);
997 basephi->addIncoming(oldBase, InBB);
Philip Reames3ea15892015-09-03 21:57:40 +0000998
Philip Reamesd16a9b12015-02-20 01:06:44 +0000999#ifndef NDEBUG
Philip Reames3ea15892015-09-03 21:57:40 +00001000 Value *Base = getBaseForInput(InVal, nullptr);
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001001 // In essence this assert states: the only way two
Philip Reames28e61ce2015-02-28 01:57:44 +00001002 // values incoming from the same basic block may be
1003 // different is by being different bitcasts of the same
1004 // value. A cleanup that remains TODO is changing
1005 // findBaseOrBDV to return an llvm::Value of the correct
1006 // type (and still remain pure). This will remove the
1007 // need to add bitcasts.
Philip Reames3ea15892015-09-03 21:57:40 +00001008 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
Philip Reames28e61ce2015-02-28 01:57:44 +00001009 "sanity -- findBaseOrBDV should be pure!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001010#endif
Philip Reames28e61ce2015-02-28 01:57:44 +00001011 continue;
1012 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001013
Philip Reames3ea15892015-09-03 21:57:40 +00001014 // Find the instruction which produces the base for each input. We may
1015 // need to insert a bitcast in the incoming block.
1016 // TODO: Need to split critical edges if insertion is needed
1017 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1018 basephi->addIncoming(Base, InBB);
Philip Reames28e61ce2015-02-28 01:57:44 +00001019 }
1020 assert(basephi->getNumIncomingValues() == NumPHIValues);
Philip Reames3ea15892015-09-03 21:57:40 +00001021 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(state.getBase())) {
1022 SelectInst *Sel = cast<SelectInst>(v);
Philip Reames28e61ce2015-02-28 01:57:44 +00001023 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1024 // something more safe and less hacky.
1025 for (int i = 1; i <= 2; i++) {
Philip Reames3ea15892015-09-03 21:57:40 +00001026 Value *InVal = Sel->getOperand(i);
1027 // Find the instruction which produces the base for each input. We may
1028 // need to insert a bitcast.
1029 Value *Base = getBaseForInput(InVal, BaseSel);
1030 BaseSel->setOperand(i, Base);
Philip Reames28e61ce2015-02-28 01:57:44 +00001031 }
Philip Reames9ac4e382015-08-12 21:00:20 +00001032 } else {
1033 auto *BaseEE = cast<ExtractElementInst>(state.getBase());
1034 Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
Philip Reames3ea15892015-09-03 21:57:40 +00001035 // Find the instruction which produces the base for each input. We may
1036 // need to insert a bitcast.
1037 Value *Base = getBaseForInput(InVal, BaseEE);
Philip Reames9ac4e382015-08-12 21:00:20 +00001038 BaseEE->setOperand(0, Base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001039 }
1040 }
1041
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001042 // Now that we're done with the algorithm, see if we can optimize the
1043 // results slightly by reducing the number of new instructions needed.
1044 // Arguably, this should be integrated into the algorithm above, but
1045 // doing as a post process step is easier to reason about for the moment.
1046 DenseMap<Value *, Value *> ReverseMap;
1047 SmallPtrSet<Instruction *, 16> NewInsts;
Philip Reames9546f362015-09-02 22:25:07 +00001048 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
Philip Reames246e6182015-09-03 20:24:29 +00001049 // Note: We need to visit the states in a deterministic order. We uses the
1050 // Keys we sorted above for this purpose. Note that we are papering over a
1051 // bigger problem with the algorithm above - it's visit order is not
1052 // deterministic. A larger change is needed to fix this.
Philip Reames15d55632015-09-09 23:26:08 +00001053 for (auto Pair : states) {
1054 auto *BDV = Pair.first;
1055 auto State = Pair.second;
Philip Reames246e6182015-09-03 20:24:29 +00001056 Value *Base = State.getBase();
Philip Reames15d55632015-09-09 23:26:08 +00001057 assert(BDV && Base);
1058 assert(!isKnownBaseResult(BDV) && "why did it get added?");
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001059 assert(isKnownBaseResult(Base) &&
1060 "must be something we 'know' is a base pointer");
Philip Reames246e6182015-09-03 20:24:29 +00001061 if (!State.isConflict())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001062 continue;
1063
Philip Reames15d55632015-09-09 23:26:08 +00001064 ReverseMap[Base] = BDV;
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001065 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1066 NewInsts.insert(BaseI);
1067 Worklist.insert(BaseI);
1068 }
1069 }
Philip Reames9546f362015-09-02 22:25:07 +00001070 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1071 Value *Replacement) {
1072 // Add users which are new instructions (excluding self references)
1073 for (User *U : BaseI->users())
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001074 if (auto *UI = dyn_cast<Instruction>(U))
Philip Reames9546f362015-09-02 22:25:07 +00001075 if (NewInsts.count(UI) && UI != BaseI)
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001076 Worklist.insert(UI);
Philip Reames9546f362015-09-02 22:25:07 +00001077 // Then do the actual replacement
1078 NewInsts.erase(BaseI);
1079 ReverseMap.erase(BaseI);
1080 BaseI->replaceAllUsesWith(Replacement);
1081 BaseI->eraseFromParent();
1082 assert(states.count(BDV));
1083 assert(states[BDV].isConflict() && states[BDV].getBase() == BaseI);
1084 states[BDV] = BDVState(BDVState::Conflict, Replacement);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001085 };
1086 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1087 while (!Worklist.empty()) {
1088 Instruction *BaseI = Worklist.pop_back_val();
Philip Reamesdab35f32015-09-02 21:11:44 +00001089 assert(NewInsts.count(BaseI));
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001090 Value *Bdv = ReverseMap[BaseI];
1091 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1092 if (BaseI->isIdenticalTo(BdvI)) {
1093 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001094 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001095 continue;
1096 }
1097 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1098 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
Philip Reames9546f362015-09-02 22:25:07 +00001099 ReplaceBaseInstWith(Bdv, BaseI, V);
Philip Reamesabcdc5e2015-08-27 01:02:28 +00001100 continue;
1101 }
1102 }
1103
Philip Reamesd16a9b12015-02-20 01:06:44 +00001104 // Cache all of our results so we can cheaply reuse them
1105 // NOTE: This is actually two caches: one of the base defining value
1106 // relation and one of the base pointer relation! FIXME
Philip Reames15d55632015-09-09 23:26:08 +00001107 for (auto Pair : states) {
1108 auto *BDV = Pair.first;
1109 Value *base = Pair.second.getBase();
1110 assert(BDV && base);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001111
Philip Reamesdab35f32015-09-02 21:11:44 +00001112 std::string fromstr =
Philip Reames15d55632015-09-09 23:26:08 +00001113 cache.count(BDV) ? (cache[BDV]->hasName() ? cache[BDV]->getName() : "")
Philip Reamesdab35f32015-09-02 21:11:44 +00001114 : "none";
1115 DEBUG(dbgs() << "Updating base value cache"
Philip Reames15d55632015-09-09 23:26:08 +00001116 << " for: " << (BDV->hasName() ? BDV->getName() : "")
Philip Reamesdab35f32015-09-02 21:11:44 +00001117 << " from: " << fromstr
1118 << " to: " << (base->hasName() ? base->getName() : "") << "\n");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001119
Philip Reames15d55632015-09-09 23:26:08 +00001120 if (cache.count(BDV)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001121 // Once we transition from the BDV relation being store in the cache to
1122 // the base relation being stored, it must be stable
Philip Reames15d55632015-09-09 23:26:08 +00001123 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001124 "base relation should be stable");
1125 }
Philip Reames15d55632015-09-09 23:26:08 +00001126 cache[BDV] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001127 }
1128 assert(cache.find(def) != cache.end());
1129 return cache[def];
1130}
1131
1132// For a set of live pointers (base and/or derived), identify the base
1133// pointer of the object which they are derived from. This routine will
1134// mutate the IR graph as needed to make the 'base' pointer live at the
1135// definition site of 'derived'. This ensures that any use of 'derived' can
1136// also use 'base'. This may involve the insertion of a number of
1137// additional PHI nodes.
1138//
1139// preconditions: live is a set of pointer type Values
1140//
1141// side effects: may insert PHI nodes into the existing CFG, will preserve
1142// CFG, will not remove or mutate any existing nodes
1143//
Philip Reamesf2041322015-02-20 19:26:04 +00001144// post condition: PointerToBase contains one (derived, base) pair for every
Philip Reamesd16a9b12015-02-20 01:06:44 +00001145// pointer in live. Note that derived can be equal to base if the original
1146// pointer was a base pointer.
Philip Reames704e78b2015-04-10 22:34:56 +00001147static void
1148findBasePointers(const StatepointLiveSetTy &live,
1149 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
Philip Reamesba198492015-04-14 00:41:34 +00001150 DominatorTree *DT, DefiningValueMapTy &DVCache) {
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001151 // For the naming of values inserted to be deterministic - which makes for
1152 // much cleaner and more stable tests - we need to assign an order to the
1153 // live values. DenseSets do not provide a deterministic order across runs.
Philip Reames704e78b2015-04-10 22:34:56 +00001154 SmallVector<Value *, 64> Temp;
Philip Reames2e5bcbe2015-02-28 01:52:09 +00001155 Temp.insert(Temp.end(), live.begin(), live.end());
1156 std::sort(Temp.begin(), Temp.end(), order_by_name);
1157 for (Value *ptr : Temp) {
Philip Reamesba198492015-04-14 00:41:34 +00001158 Value *base = findBasePointer(ptr, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001159 assert(base && "failed to find base pointer");
Philip Reamesf2041322015-02-20 19:26:04 +00001160 PointerToBase[ptr] = base;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001161 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1162 DT->dominates(cast<Instruction>(base)->getParent(),
1163 cast<Instruction>(ptr)->getParent())) &&
1164 "The base we found better dominate the derived pointer");
1165
David Blaikie82ad7872015-02-20 23:44:24 +00001166 // If you see this trip and like to live really dangerously, the code should
1167 // be correct, just with idioms the verifier can't handle. You can try
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001168 // disabling the verifier at your own substantial risk.
Philip Reames704e78b2015-04-10 22:34:56 +00001169 assert(!isa<ConstantPointerNull>(base) &&
Philip Reames24c6cd52015-03-27 05:47:00 +00001170 "the relocation code needs adjustment to handle the relocation of "
1171 "a null pointer constant without causing false positives in the "
1172 "safepoint ir verifier.");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001173 }
1174}
1175
1176/// Find the required based pointers (and adjust the live set) for the given
1177/// parse point.
1178static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1179 const CallSite &CS,
1180 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001181 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
Philip Reamesba198492015-04-14 00:41:34 +00001182 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001183
1184 if (PrintBasePointers) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001185 // Note: Need to print these in a stable order since this is checked in
1186 // some tests.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001187 errs() << "Base Pairs (w/o Relocation):\n";
Philip Reames704e78b2015-04-10 22:34:56 +00001188 SmallVector<Value *, 64> Temp;
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001189 Temp.reserve(PointerToBase.size());
Philip Reamesf2041322015-02-20 19:26:04 +00001190 for (auto Pair : PointerToBase) {
Philip Reamesa5aeaf42015-02-28 00:20:48 +00001191 Temp.push_back(Pair.first);
1192 }
1193 std::sort(Temp.begin(), Temp.end(), order_by_name);
1194 for (Value *Ptr : Temp) {
1195 Value *Base = PointerToBase[Ptr];
Philip Reames704e78b2015-04-10 22:34:56 +00001196 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1197 << "\n";
Philip Reamesd16a9b12015-02-20 01:06:44 +00001198 }
1199 }
1200
Philip Reamesf2041322015-02-20 19:26:04 +00001201 result.PointerToBase = PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001202}
1203
Philip Reamesdf1ef082015-04-10 22:53:14 +00001204/// Given an updated version of the dataflow liveness results, update the
1205/// liveset and base pointer maps for the call site CS.
1206static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1207 const CallSite &CS,
1208 PartiallyConstructedSafepointRecord &result);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001209
Philip Reamesdf1ef082015-04-10 22:53:14 +00001210static void recomputeLiveInValues(
1211 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
Philip Reamesd2b66462015-02-20 22:39:41 +00001212 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001213 // TODO-PERF: reuse the original liveness, then simply run the dataflow
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001214 // again. The old values are still live and will help it stabilize quickly.
Philip Reamesdf1ef082015-04-10 22:53:14 +00001215 GCPtrLivenessData RevisedLivenessData;
1216 computeLiveInValues(DT, F, RevisedLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001217 for (size_t i = 0; i < records.size(); i++) {
1218 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001219 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001220 recomputeLiveInValues(RevisedLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001221 }
1222}
1223
Philip Reames69e51ca2015-04-13 18:07:21 +00001224// When inserting gc.relocate calls, we need to ensure there are no uses
1225// of the original value between the gc.statepoint and the gc.relocate call.
1226// One case which can arise is a phi node starting one of the successor blocks.
1227// We also need to be able to insert the gc.relocates only on the path which
1228// goes through the statepoint. We might need to split an edge to make this
Philip Reamesf209a152015-04-13 20:00:30 +00001229// possible.
1230static BasicBlock *
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00001231normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1232 DominatorTree &DT) {
Philip Reames69e51ca2015-04-13 18:07:21 +00001233 BasicBlock *Ret = BB;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001234 if (!BB->getUniquePredecessor()) {
Chandler Carruth96ada252015-07-22 09:52:54 +00001235 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001236 }
1237
Philip Reames69e51ca2015-04-13 18:07:21 +00001238 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1239 // from it
1240 FoldSingleEntryPHINodes(Ret);
1241 assert(!isa<PHINode>(Ret->begin()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001242
Philip Reames69e51ca2015-04-13 18:07:21 +00001243 // At this point, we can safely insert a gc.relocate as the first instruction
1244 // in Ret if needed.
1245 return Ret;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001246}
1247
Philip Reamesd2b66462015-02-20 22:39:41 +00001248static int find_index(ArrayRef<Value *> livevec, Value *val) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001249 auto itr = std::find(livevec.begin(), livevec.end(), val);
1250 assert(livevec.end() != itr);
1251 size_t index = std::distance(livevec.begin(), itr);
1252 assert(index < livevec.size());
1253 return index;
1254}
1255
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001256// Create new attribute set containing only attributes which can be transferred
Philip Reamesd16a9b12015-02-20 01:06:44 +00001257// from original call to the safepoint.
1258static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1259 AttributeSet ret;
1260
1261 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1262 unsigned index = AS.getSlotIndex(Slot);
1263
1264 if (index == AttributeSet::ReturnIndex ||
1265 index == AttributeSet::FunctionIndex) {
1266
1267 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1268 ++it) {
1269 Attribute attr = *it;
1270
1271 // Do not allow certain attributes - just skip them
1272 // Safepoint can not be read only or read none.
1273 if (attr.hasAttribute(Attribute::ReadNone) ||
1274 attr.hasAttribute(Attribute::ReadOnly))
1275 continue;
1276
1277 ret = ret.addAttributes(
1278 AS.getContext(), index,
1279 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1280 }
1281 }
1282
1283 // Just skip parameter attributes for now
1284 }
1285
1286 return ret;
1287}
1288
1289/// Helper function to place all gc relocates necessary for the given
1290/// statepoint.
1291/// Inputs:
1292/// liveVariables - list of variables to be relocated.
1293/// liveStart - index of the first live variable.
1294/// basePtrs - base pointers.
1295/// statepointToken - statepoint instruction to which relocates should be
1296/// bound.
1297/// Builder - Llvm IR builder to be used to construct new calls.
Sanjoy Das5665c992015-05-11 23:47:27 +00001298static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1299 const int LiveStart,
1300 ArrayRef<llvm::Value *> BasePtrs,
1301 Instruction *StatepointToken,
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001302 IRBuilder<> Builder) {
Philip Reames94babb72015-07-21 17:18:03 +00001303 if (LiveVariables.empty())
1304 return;
1305
1306 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1307 // unique declarations for each pointer type, but this proved problematic
1308 // because the intrinsic mangling code is incomplete and fragile. Since
1309 // we're moving towards a single unified pointer type anyways, we can just
1310 // cast everything to an i8* of the right address space. A bitcast is added
1311 // later to convert gc_relocate to the actual value's type.
Philip Reames74ce2e72015-07-21 16:51:17 +00001312 Module *M = StatepointToken->getModule();
Philip Reames94babb72015-07-21 17:18:03 +00001313 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1314 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1315 Value *GCRelocateDecl =
1316 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001317
Sanjoy Das5665c992015-05-11 23:47:27 +00001318 for (unsigned i = 0; i < LiveVariables.size(); i++) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001319 // Generate the gc.relocate call and save the result
Sanjoy Das5665c992015-05-11 23:47:27 +00001320 Value *BaseIdx =
Philip Reamesf3880502015-07-21 00:49:55 +00001321 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1322 Value *LiveIdx =
1323 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001324
1325 // only specify a debug name if we can give a useful one
Philip Reames74ce2e72015-07-21 16:51:17 +00001326 CallInst *Reloc = Builder.CreateCall(
David Blaikieff6409d2015-05-18 22:13:54 +00001327 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
Sanjoy Das5665c992015-05-11 23:47:27 +00001328 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
Philip Reamesd16a9b12015-02-20 01:06:44 +00001329 : "");
1330 // Trick CodeGen into thinking there are lots of free registers at this
1331 // fake call.
Philip Reames74ce2e72015-07-21 16:51:17 +00001332 Reloc->setCallingConv(CallingConv::Cold);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001333 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001334}
1335
1336static void
1337makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1338 const SmallVectorImpl<llvm::Value *> &basePtrs,
1339 const SmallVectorImpl<llvm::Value *> &liveVariables,
1340 Pass *P,
1341 PartiallyConstructedSafepointRecord &result) {
1342 assert(basePtrs.size() == liveVariables.size());
1343 assert(isStatepoint(CS) &&
1344 "This method expects to be rewriting a statepoint");
1345
1346 BasicBlock *BB = CS.getInstruction()->getParent();
1347 assert(BB);
1348 Function *F = BB->getParent();
1349 assert(F && "must be set");
1350 Module *M = F->getParent();
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00001351 (void)M;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001352 assert(M && "must be set");
1353
1354 // We're not changing the function signature of the statepoint since the gc
1355 // arguments go into the var args section.
1356 Function *gc_statepoint_decl = CS.getCalledFunction();
1357
1358 // Then go ahead and use the builder do actually do the inserts. We insert
1359 // immediately before the previous instruction under the assumption that all
1360 // arguments will be available here. We can't insert afterwards since we may
1361 // be replacing a terminator.
1362 Instruction *insertBefore = CS.getInstruction();
1363 IRBuilder<> Builder(insertBefore);
1364 // Copy all of the arguments from the original statepoint - this includes the
1365 // target, call args, and deopt args
Philip Reamesd2b66462015-02-20 22:39:41 +00001366 SmallVector<llvm::Value *, 64> args;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001367 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1368 // TODO: Clear the 'needs rewrite' flag
1369
1370 // add all the pointers to be relocated (gc arguments)
1371 // Capture the start of the live variable list for use in the gc_relocates
1372 const int live_start = args.size();
1373 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1374
1375 // Create the statepoint given all the arguments
1376 Instruction *token = nullptr;
1377 AttributeSet return_attributes;
1378 if (CS.isCall()) {
1379 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1380 CallInst *call =
1381 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1382 call->setTailCall(toReplace->isTailCall());
1383 call->setCallingConv(toReplace->getCallingConv());
1384
1385 // Currently we will fail on parameter attributes and on certain
1386 // function attributes.
1387 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001388 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001389 // directly on statepoint and return attrs later for gc_result intrinsic.
1390 call->setAttributes(new_attrs.getFnAttributes());
1391 return_attributes = new_attrs.getRetAttributes();
1392
1393 token = call;
1394
1395 // Put the following gc_result and gc_relocate calls immediately after the
1396 // the old call (which we're about to delete)
1397 BasicBlock::iterator next(toReplace);
1398 assert(BB->end() != next && "not a terminator, must have next");
1399 next++;
1400 Instruction *IP = &*(next);
1401 Builder.SetInsertPoint(IP);
1402 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1403
David Blaikie82ad7872015-02-20 23:44:24 +00001404 } else {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001405 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1406
1407 // Insert the new invoke into the old block. We'll remove the old one in a
1408 // moment at which point this will become the new terminator for the
1409 // original block.
1410 InvokeInst *invoke = InvokeInst::Create(
1411 gc_statepoint_decl, toReplace->getNormalDest(),
Philip Reamesfa2c6302015-07-24 19:01:39 +00001412 toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001413 invoke->setCallingConv(toReplace->getCallingConv());
1414
1415 // Currently we will fail on parameter attributes and on certain
1416 // function attributes.
1417 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001418 // In case if we can handle this set of attributes - set up function attrs
Philip Reamesd16a9b12015-02-20 01:06:44 +00001419 // directly on statepoint and return attrs later for gc_result intrinsic.
1420 invoke->setAttributes(new_attrs.getFnAttributes());
1421 return_attributes = new_attrs.getRetAttributes();
1422
1423 token = invoke;
1424
1425 // Generate gc relocates in exceptional path
Philip Reames69e51ca2015-04-13 18:07:21 +00001426 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1427 assert(!isa<PHINode>(unwindBlock->begin()) &&
1428 unwindBlock->getUniquePredecessor() &&
1429 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001430
1431 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1432 Builder.SetInsertPoint(IP);
1433 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1434
1435 // Extract second element from landingpad return value. We will attach
1436 // exceptional gc relocates to it.
1437 const unsigned idx = 1;
1438 Instruction *exceptional_token =
1439 cast<Instruction>(Builder.CreateExtractValue(
1440 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
Philip Reamesf2041322015-02-20 19:26:04 +00001441 result.UnwindToken = exceptional_token;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001442
Philip Reames6ff1a1e32015-07-21 19:04:38 +00001443 CreateGCRelocates(liveVariables, live_start, basePtrs,
1444 exceptional_token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001445
1446 // Generate gc relocates and returns for normal block
Philip Reames69e51ca2015-04-13 18:07:21 +00001447 BasicBlock *normalDest = toReplace->getNormalDest();
1448 assert(!isa<PHINode>(normalDest->begin()) &&
1449 normalDest->getUniquePredecessor() &&
1450 "can't safely insert in this block!");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001451
1452 IP = &*(normalDest->getFirstInsertionPt());
1453 Builder.SetInsertPoint(IP);
1454
1455 // gc relocates will be generated later as if it were regular call
1456 // statepoint
Philip Reamesd16a9b12015-02-20 01:06:44 +00001457 }
1458 assert(token);
1459
1460 // Take the name of the original value call if it had one.
1461 token->takeName(CS.getInstruction());
1462
Philip Reames704e78b2015-04-10 22:34:56 +00001463// The GCResult is already inserted, we just need to find it
David Blaikie5e5d7842015-02-22 20:58:38 +00001464#ifndef NDEBUG
1465 Instruction *toReplace = CS.getInstruction();
1466 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1467 "only valid use before rewrite is gc.result");
1468 assert(!toReplace->hasOneUse() ||
1469 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1470#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00001471
1472 // Update the gc.result of the original statepoint (if any) to use the newly
1473 // inserted statepoint. This is safe to do here since the token can't be
1474 // considered a live reference.
1475 CS.getInstruction()->replaceAllUsesWith(token);
1476
Philip Reames0a3240f2015-02-20 21:34:11 +00001477 result.StatepointToken = token;
1478
Philip Reamesd16a9b12015-02-20 01:06:44 +00001479 // Second, create a gc.relocate for every live variable
Philip Reames0a3240f2015-02-20 21:34:11 +00001480 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001481}
1482
1483namespace {
1484struct name_ordering {
1485 Value *base;
1486 Value *derived;
1487 bool operator()(name_ordering const &a, name_ordering const &b) {
1488 return -1 == a.derived->getName().compare(b.derived->getName());
1489 }
1490};
1491}
1492static void stablize_order(SmallVectorImpl<Value *> &basevec,
1493 SmallVectorImpl<Value *> &livevec) {
1494 assert(basevec.size() == livevec.size());
1495
Philip Reames860660e2015-02-20 22:05:18 +00001496 SmallVector<name_ordering, 64> temp;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001497 for (size_t i = 0; i < basevec.size(); i++) {
1498 name_ordering v;
1499 v.base = basevec[i];
1500 v.derived = livevec[i];
1501 temp.push_back(v);
1502 }
1503 std::sort(temp.begin(), temp.end(), name_ordering());
1504 for (size_t i = 0; i < basevec.size(); i++) {
1505 basevec[i] = temp[i].base;
1506 livevec[i] = temp[i].derived;
1507 }
1508}
1509
1510// Replace an existing gc.statepoint with a new one and a set of gc.relocates
1511// which make the relocations happening at this safepoint explicit.
Philip Reames704e78b2015-04-10 22:34:56 +00001512//
Philip Reamesd16a9b12015-02-20 01:06:44 +00001513// WARNING: Does not do any fixup to adjust users of the original live
1514// values. That's the callers responsibility.
1515static void
1516makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1517 PartiallyConstructedSafepointRecord &result) {
Philip Reamesf2041322015-02-20 19:26:04 +00001518 auto liveset = result.liveset;
1519 auto PointerToBase = result.PointerToBase;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001520
1521 // Convert to vector for efficient cross referencing.
1522 SmallVector<Value *, 64> basevec, livevec;
1523 livevec.reserve(liveset.size());
1524 basevec.reserve(liveset.size());
1525 for (Value *L : liveset) {
1526 livevec.push_back(L);
Philip Reames74ce2e72015-07-21 16:51:17 +00001527 assert(PointerToBase.count(L));
Philip Reamesf2041322015-02-20 19:26:04 +00001528 Value *base = PointerToBase[L];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001529 basevec.push_back(base);
1530 }
1531 assert(livevec.size() == basevec.size());
1532
1533 // To make the output IR slightly more stable (for use in diffs), ensure a
1534 // fixed order of the values in the safepoint (by sorting the value name).
1535 // The order is otherwise meaningless.
1536 stablize_order(basevec, livevec);
1537
1538 // Do the actual rewriting and delete the old statepoint
1539 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1540 CS.getInstruction()->eraseFromParent();
1541}
1542
1543// Helper function for the relocationViaAlloca.
1544// It receives iterator to the statepoint gc relocates and emits store to the
1545// assigned
1546// location (via allocaMap) for the each one of them.
1547// Add visited values into the visitedLiveValues set we will later use them
1548// for sanity check.
1549static void
Sanjoy Das5665c992015-05-11 23:47:27 +00001550insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1551 DenseMap<Value *, Value *> &AllocaMap,
1552 DenseSet<Value *> &VisitedLiveValues) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001553
Sanjoy Das5665c992015-05-11 23:47:27 +00001554 for (User *U : GCRelocs) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001555 if (!isa<IntrinsicInst>(U))
1556 continue;
1557
Sanjoy Das5665c992015-05-11 23:47:27 +00001558 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001559
1560 // We only care about relocates
Sanjoy Das5665c992015-05-11 23:47:27 +00001561 if (RelocatedValue->getIntrinsicID() !=
Philip Reamesd16a9b12015-02-20 01:06:44 +00001562 Intrinsic::experimental_gc_relocate) {
1563 continue;
1564 }
1565
Sanjoy Das5665c992015-05-11 23:47:27 +00001566 GCRelocateOperands RelocateOperands(RelocatedValue);
1567 Value *OriginalValue =
1568 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1569 assert(AllocaMap.count(OriginalValue));
1570 Value *Alloca = AllocaMap[OriginalValue];
Philip Reamesd16a9b12015-02-20 01:06:44 +00001571
1572 // Emit store into the related alloca
Sanjoy Das89c54912015-05-11 18:49:34 +00001573 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1574 // the correct type according to alloca.
Sanjoy Das5665c992015-05-11 23:47:27 +00001575 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1576 IRBuilder<> Builder(RelocatedValue->getNextNode());
Sanjoy Das89c54912015-05-11 18:49:34 +00001577 Value *CastedRelocatedValue =
Sanjoy Das5665c992015-05-11 23:47:27 +00001578 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1579 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
Sanjoy Das89c54912015-05-11 18:49:34 +00001580
Sanjoy Das5665c992015-05-11 23:47:27 +00001581 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1582 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001583
1584#ifndef NDEBUG
Sanjoy Das5665c992015-05-11 23:47:27 +00001585 VisitedLiveValues.insert(OriginalValue);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001586#endif
1587 }
1588}
1589
Igor Laevskye0317182015-05-19 15:59:05 +00001590// Helper function for the "relocationViaAlloca". Similar to the
1591// "insertRelocationStores" but works for rematerialized values.
1592static void
1593insertRematerializationStores(
1594 RematerializedValueMapTy RematerializedValues,
1595 DenseMap<Value *, Value *> &AllocaMap,
1596 DenseSet<Value *> &VisitedLiveValues) {
1597
1598 for (auto RematerializedValuePair: RematerializedValues) {
1599 Instruction *RematerializedValue = RematerializedValuePair.first;
1600 Value *OriginalValue = RematerializedValuePair.second;
1601
1602 assert(AllocaMap.count(OriginalValue) &&
1603 "Can not find alloca for rematerialized value");
1604 Value *Alloca = AllocaMap[OriginalValue];
1605
1606 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1607 Store->insertAfter(RematerializedValue);
1608
1609#ifndef NDEBUG
1610 VisitedLiveValues.insert(OriginalValue);
1611#endif
1612 }
1613}
1614
Philip Reamesd16a9b12015-02-20 01:06:44 +00001615/// do all the relocation update via allocas and mem2reg
1616static void relocationViaAlloca(
Igor Laevsky285fe842015-05-19 16:29:43 +00001617 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1618 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001619#ifndef NDEBUG
Philip Reamesa6ebf072015-03-27 05:53:16 +00001620 // record initial number of (static) allocas; we'll check we have the same
1621 // number when we get done.
1622 int InitialAllocaNum = 0;
Philip Reames704e78b2015-04-10 22:34:56 +00001623 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1624 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001625 if (isa<AllocaInst>(*I))
1626 InitialAllocaNum++;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001627#endif
1628
1629 // TODO-PERF: change data structures, reserve
Igor Laevsky285fe842015-05-19 16:29:43 +00001630 DenseMap<Value *, Value *> AllocaMap;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001631 SmallVector<AllocaInst *, 200> PromotableAllocas;
Igor Laevskye0317182015-05-19 15:59:05 +00001632 // Used later to chack that we have enough allocas to store all values
1633 std::size_t NumRematerializedValues = 0;
Igor Laevsky285fe842015-05-19 16:29:43 +00001634 PromotableAllocas.reserve(Live.size());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001635
Igor Laevskye0317182015-05-19 15:59:05 +00001636 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1637 // "PromotableAllocas"
1638 auto emitAllocaFor = [&](Value *LiveValue) {
1639 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1640 F.getEntryBlock().getFirstNonPHI());
Igor Laevsky285fe842015-05-19 16:29:43 +00001641 AllocaMap[LiveValue] = Alloca;
Igor Laevskye0317182015-05-19 15:59:05 +00001642 PromotableAllocas.push_back(Alloca);
1643 };
1644
Philip Reamesd16a9b12015-02-20 01:06:44 +00001645 // emit alloca for each live gc pointer
Igor Laevsky285fe842015-05-19 16:29:43 +00001646 for (unsigned i = 0; i < Live.size(); i++) {
1647 emitAllocaFor(Live[i]);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001648 }
1649
Igor Laevskye0317182015-05-19 15:59:05 +00001650 // emit allocas for rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001651 for (size_t i = 0; i < Records.size(); i++) {
1652 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
Igor Laevskye0317182015-05-19 15:59:05 +00001653
Igor Laevsky285fe842015-05-19 16:29:43 +00001654 for (auto RematerializedValuePair : Info.RematerializedValues) {
Igor Laevskye0317182015-05-19 15:59:05 +00001655 Value *OriginalValue = RematerializedValuePair.second;
Igor Laevsky285fe842015-05-19 16:29:43 +00001656 if (AllocaMap.count(OriginalValue) != 0)
Igor Laevskye0317182015-05-19 15:59:05 +00001657 continue;
1658
1659 emitAllocaFor(OriginalValue);
1660 ++NumRematerializedValues;
1661 }
1662 }
Igor Laevsky285fe842015-05-19 16:29:43 +00001663
Philip Reamesd16a9b12015-02-20 01:06:44 +00001664 // The next two loops are part of the same conceptual operation. We need to
1665 // insert a store to the alloca after the original def and at each
1666 // redefinition. We need to insert a load before each use. These are split
1667 // into distinct loops for performance reasons.
1668
1669 // update gc pointer after each statepoint
1670 // either store a relocated value or null (if no relocated value found for
1671 // this gc pointer and it is not a gc_result)
1672 // this must happen before we update the statepoint with load of alloca
1673 // otherwise we lose the link between statepoint and old def
Igor Laevsky285fe842015-05-19 16:29:43 +00001674 for (size_t i = 0; i < Records.size(); i++) {
1675 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1676 Value *Statepoint = Info.StatepointToken;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001677
1678 // This will be used for consistency check
Igor Laevsky285fe842015-05-19 16:29:43 +00001679 DenseSet<Value *> VisitedLiveValues;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001680
1681 // Insert stores for normal statepoint gc relocates
Igor Laevsky285fe842015-05-19 16:29:43 +00001682 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001683
1684 // In case if it was invoke statepoint
1685 // we will insert stores for exceptional path gc relocates.
Philip Reames0a3240f2015-02-20 21:34:11 +00001686 if (isa<InvokeInst>(Statepoint)) {
Igor Laevsky285fe842015-05-19 16:29:43 +00001687 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1688 VisitedLiveValues);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001689 }
1690
Igor Laevskye0317182015-05-19 15:59:05 +00001691 // Do similar thing with rematerialized values
Igor Laevsky285fe842015-05-19 16:29:43 +00001692 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1693 VisitedLiveValues);
Igor Laevskye0317182015-05-19 15:59:05 +00001694
Philip Reamese73300b2015-04-13 16:41:32 +00001695 if (ClobberNonLive) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001696 // As a debugging aid, pretend that an unrelocated pointer becomes null at
Philip Reamese73300b2015-04-13 16:41:32 +00001697 // the gc.statepoint. This will turn some subtle GC problems into
1698 // slightly easier to debug SEGVs. Note that on large IR files with
1699 // lots of gc.statepoints this is extremely costly both memory and time
1700 // wise.
1701 SmallVector<AllocaInst *, 64> ToClobber;
Igor Laevsky285fe842015-05-19 16:29:43 +00001702 for (auto Pair : AllocaMap) {
Philip Reamese73300b2015-04-13 16:41:32 +00001703 Value *Def = Pair.first;
1704 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001705
Philip Reamese73300b2015-04-13 16:41:32 +00001706 // This value was relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001707 if (VisitedLiveValues.count(Def)) {
Philip Reamese73300b2015-04-13 16:41:32 +00001708 continue;
1709 }
1710 ToClobber.push_back(Alloca);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001711 }
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001712
Philip Reamese73300b2015-04-13 16:41:32 +00001713 auto InsertClobbersAt = [&](Instruction *IP) {
1714 for (auto *AI : ToClobber) {
1715 auto AIType = cast<PointerType>(AI->getType());
1716 auto PT = cast<PointerType>(AIType->getElementType());
1717 Constant *CPN = ConstantPointerNull::get(PT);
Igor Laevsky285fe842015-05-19 16:29:43 +00001718 StoreInst *Store = new StoreInst(CPN, AI);
1719 Store->insertBefore(IP);
Philip Reamese73300b2015-04-13 16:41:32 +00001720 }
1721 };
1722
1723 // Insert the clobbering stores. These may get intermixed with the
1724 // gc.results and gc.relocates, but that's fine.
1725 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1726 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1727 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1728 } else {
1729 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1730 Next++;
1731 InsertClobbersAt(Next);
Philip Reamesfa2fcf172015-02-20 19:51:56 +00001732 }
David Blaikie82ad7872015-02-20 23:44:24 +00001733 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001734 }
1735 // update use with load allocas and add store for gc_relocated
Igor Laevsky285fe842015-05-19 16:29:43 +00001736 for (auto Pair : AllocaMap) {
1737 Value *Def = Pair.first;
1738 Value *Alloca = Pair.second;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001739
1740 // we pre-record the uses of allocas so that we dont have to worry about
1741 // later update
1742 // that change the user information.
Igor Laevsky285fe842015-05-19 16:29:43 +00001743 SmallVector<Instruction *, 20> Uses;
Philip Reamesd16a9b12015-02-20 01:06:44 +00001744 // PERF: trade a linear scan for repeated reallocation
Igor Laevsky285fe842015-05-19 16:29:43 +00001745 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1746 for (User *U : Def->users()) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00001747 if (!isa<ConstantExpr>(U)) {
1748 // If the def has a ConstantExpr use, then the def is either a
1749 // ConstantExpr use itself or null. In either case
1750 // (recursively in the first, directly in the second), the oop
1751 // it is ultimately dependent on is null and this particular
1752 // use does not need to be fixed up.
Igor Laevsky285fe842015-05-19 16:29:43 +00001753 Uses.push_back(cast<Instruction>(U));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001754 }
1755 }
1756
Igor Laevsky285fe842015-05-19 16:29:43 +00001757 std::sort(Uses.begin(), Uses.end());
1758 auto Last = std::unique(Uses.begin(), Uses.end());
1759 Uses.erase(Last, Uses.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001760
Igor Laevsky285fe842015-05-19 16:29:43 +00001761 for (Instruction *Use : Uses) {
1762 if (isa<PHINode>(Use)) {
1763 PHINode *Phi = cast<PHINode>(Use);
1764 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1765 if (Def == Phi->getIncomingValue(i)) {
1766 LoadInst *Load = new LoadInst(
1767 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1768 Phi->setIncomingValue(i, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001769 }
1770 }
1771 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001772 LoadInst *Load = new LoadInst(Alloca, "", Use);
1773 Use->replaceUsesOfWith(Def, Load);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001774 }
1775 }
1776
1777 // emit store for the initial gc value
1778 // store must be inserted after load, otherwise store will be in alloca's
1779 // use list and an extra load will be inserted before it
Igor Laevsky285fe842015-05-19 16:29:43 +00001780 StoreInst *Store = new StoreInst(Def, Alloca);
1781 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1782 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
Philip Reames6da37852015-03-04 00:13:52 +00001783 // InvokeInst is a TerminatorInst so the store need to be inserted
1784 // into its normal destination block.
Igor Laevsky285fe842015-05-19 16:29:43 +00001785 BasicBlock *NormalDest = Invoke->getNormalDest();
1786 Store->insertBefore(NormalDest->getFirstNonPHI());
Philip Reames6da37852015-03-04 00:13:52 +00001787 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001788 assert(!Inst->isTerminator() &&
Philip Reames6da37852015-03-04 00:13:52 +00001789 "The only TerminatorInst that can produce a value is "
1790 "InvokeInst which is handled above.");
Igor Laevsky285fe842015-05-19 16:29:43 +00001791 Store->insertAfter(Inst);
Philip Reames6da37852015-03-04 00:13:52 +00001792 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00001793 } else {
Igor Laevsky285fe842015-05-19 16:29:43 +00001794 assert(isa<Argument>(Def));
1795 Store->insertAfter(cast<Instruction>(Alloca));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001796 }
1797 }
1798
Igor Laevsky285fe842015-05-19 16:29:43 +00001799 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
Philip Reamesd16a9b12015-02-20 01:06:44 +00001800 "we must have the same allocas with lives");
1801 if (!PromotableAllocas.empty()) {
1802 // apply mem2reg to promote alloca to SSA
1803 PromoteMemToReg(PromotableAllocas, DT);
1804 }
1805
1806#ifndef NDEBUG
Philip Reames704e78b2015-04-10 22:34:56 +00001807 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1808 I++)
Philip Reamesa6ebf072015-03-27 05:53:16 +00001809 if (isa<AllocaInst>(*I))
1810 InitialAllocaNum--;
1811 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
Philip Reamesd16a9b12015-02-20 01:06:44 +00001812#endif
1813}
1814
1815/// Implement a unique function which doesn't require we sort the input
1816/// vector. Doing so has the effect of changing the output of a couple of
1817/// tests in ways which make them less useful in testing fused safepoints.
Philip Reamesd2b66462015-02-20 22:39:41 +00001818template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
Benjamin Kramer258ea0d2015-06-13 19:50:38 +00001819 SmallSet<T, 8> Seen;
1820 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1821 return !Seen.insert(V).second;
1822 }), Vec.end());
Philip Reamesd16a9b12015-02-20 01:06:44 +00001823}
1824
Philip Reamesd16a9b12015-02-20 01:06:44 +00001825/// Insert holders so that each Value is obviously live through the entire
Philip Reamesf209a152015-04-13 20:00:30 +00001826/// lifetime of the call.
Philip Reamesd16a9b12015-02-20 01:06:44 +00001827static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
Philip Reamesf209a152015-04-13 20:00:30 +00001828 SmallVectorImpl<CallInst *> &Holders) {
Philip Reames21142752015-04-13 19:07:47 +00001829 if (Values.empty())
1830 // No values to hold live, might as well not insert the empty holder
1831 return;
1832
Philip Reamesd16a9b12015-02-20 01:06:44 +00001833 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
Philip Reamesf209a152015-04-13 20:00:30 +00001834 // Use a dummy vararg function to actually hold the values live
1835 Function *Func = cast<Function>(M->getOrInsertFunction(
1836 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001837 if (CS.isCall()) {
1838 // For call safepoints insert dummy calls right after safepoint
Philip Reamesf209a152015-04-13 20:00:30 +00001839 BasicBlock::iterator Next(CS.getInstruction());
1840 Next++;
1841 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1842 return;
1843 }
1844 // For invoke safepooints insert dummy calls both in normal and
1845 // exceptional destination blocks
1846 auto *II = cast<InvokeInst>(CS.getInstruction());
1847 Holders.push_back(CallInst::Create(
1848 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1849 Holders.push_back(CallInst::Create(
1850 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
Philip Reamesd16a9b12015-02-20 01:06:44 +00001851}
1852
1853static void findLiveReferences(
Philip Reamesd2b66462015-02-20 22:39:41 +00001854 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1855 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00001856 GCPtrLivenessData OriginalLivenessData;
1857 computeLiveInValues(DT, F, OriginalLivenessData);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001858 for (size_t i = 0; i < records.size(); i++) {
1859 struct PartiallyConstructedSafepointRecord &info = records[i];
Philip Reamesd2b66462015-02-20 22:39:41 +00001860 const CallSite &CS = toUpdate[i];
Philip Reamesdf1ef082015-04-10 22:53:14 +00001861 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
Philip Reamesd16a9b12015-02-20 01:06:44 +00001862 }
1863}
1864
Philip Reames8531d8c2015-04-10 21:48:25 +00001865/// Remove any vector of pointers from the liveset by scalarizing them over the
1866/// statepoint instruction. Adds the scalarized pieces to the liveset. It
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001867/// would be preferable to include the vector in the statepoint itself, but
Philip Reames8531d8c2015-04-10 21:48:25 +00001868/// the lowering code currently does not handle that. Extending it would be
1869/// slightly non-trivial since it requires a format change. Given how rare
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001870/// such cases are (for the moment?) scalarizing is an acceptable compromise.
Philip Reames8531d8c2015-04-10 21:48:25 +00001871static void splitVectorValues(Instruction *StatepointInst,
Philip Reames8fe7f132015-06-26 22:47:37 +00001872 StatepointLiveSetTy &LiveSet,
1873 DenseMap<Value *, Value *>& PointerToBase,
1874 DominatorTree &DT) {
Philip Reames8531d8c2015-04-10 21:48:25 +00001875 SmallVector<Value *, 16> ToSplit;
1876 for (Value *V : LiveSet)
1877 if (isa<VectorType>(V->getType()))
1878 ToSplit.push_back(V);
1879
1880 if (ToSplit.empty())
1881 return;
1882
Philip Reames8fe7f132015-06-26 22:47:37 +00001883 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1884
Philip Reames8531d8c2015-04-10 21:48:25 +00001885 Function &F = *(StatepointInst->getParent()->getParent());
1886
Philip Reames704e78b2015-04-10 22:34:56 +00001887 DenseMap<Value *, AllocaInst *> AllocaMap;
Philip Reames8531d8c2015-04-10 21:48:25 +00001888 // First is normal return, second is exceptional return (invoke only)
Philip Reames704e78b2015-04-10 22:34:56 +00001889 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001890 for (Value *V : ToSplit) {
Philip Reames704e78b2015-04-10 22:34:56 +00001891 AllocaInst *Alloca =
1892 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
Philip Reames8531d8c2015-04-10 21:48:25 +00001893 AllocaMap[V] = Alloca;
1894
1895 VectorType *VT = cast<VectorType>(V->getType());
1896 IRBuilder<> Builder(StatepointInst);
Philip Reames704e78b2015-04-10 22:34:56 +00001897 SmallVector<Value *, 16> Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001898 for (unsigned i = 0; i < VT->getNumElements(); i++)
1899 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
Philip Reames8fe7f132015-06-26 22:47:37 +00001900 ElementMapping[V] = Elements;
Philip Reames8531d8c2015-04-10 21:48:25 +00001901
1902 auto InsertVectorReform = [&](Instruction *IP) {
1903 Builder.SetInsertPoint(IP);
1904 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1905 Value *ResultVec = UndefValue::get(VT);
1906 for (unsigned i = 0; i < VT->getNumElements(); i++)
1907 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1908 Builder.getInt32(i));
1909 return ResultVec;
1910 };
1911
1912 if (isa<CallInst>(StatepointInst)) {
1913 BasicBlock::iterator Next(StatepointInst);
1914 Next++;
1915 Instruction *IP = &*(Next);
1916 Replacements[V].first = InsertVectorReform(IP);
1917 Replacements[V].second = nullptr;
1918 } else {
1919 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1920 // We've already normalized - check that we don't have shared destination
Philip Reames704e78b2015-04-10 22:34:56 +00001921 // blocks
Philip Reames8531d8c2015-04-10 21:48:25 +00001922 BasicBlock *NormalDest = Invoke->getNormalDest();
1923 assert(!isa<PHINode>(NormalDest->begin()));
1924 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1925 assert(!isa<PHINode>(UnwindDest->begin()));
1926 // Insert insert element sequences in both successors
1927 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1928 Replacements[V].first = InsertVectorReform(IP);
1929 IP = &*(UnwindDest->getFirstInsertionPt());
1930 Replacements[V].second = InsertVectorReform(IP);
1931 }
1932 }
Philip Reames8fe7f132015-06-26 22:47:37 +00001933
Philip Reames8531d8c2015-04-10 21:48:25 +00001934 for (Value *V : ToSplit) {
1935 AllocaInst *Alloca = AllocaMap[V];
1936
1937 // Capture all users before we start mutating use lists
Philip Reames704e78b2015-04-10 22:34:56 +00001938 SmallVector<Instruction *, 16> Users;
Philip Reames8531d8c2015-04-10 21:48:25 +00001939 for (User *U : V->users())
1940 Users.push_back(cast<Instruction>(U));
1941
1942 for (Instruction *I : Users) {
1943 if (auto Phi = dyn_cast<PHINode>(I)) {
1944 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1945 if (V == Phi->getIncomingValue(i)) {
Philip Reames704e78b2015-04-10 22:34:56 +00001946 LoadInst *Load = new LoadInst(
1947 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
Philip Reames8531d8c2015-04-10 21:48:25 +00001948 Phi->setIncomingValue(i, Load);
1949 }
1950 } else {
1951 LoadInst *Load = new LoadInst(Alloca, "", I);
1952 I->replaceUsesOfWith(V, Load);
1953 }
1954 }
1955
1956 // Store the original value and the replacement value into the alloca
1957 StoreInst *Store = new StoreInst(V, Alloca);
1958 if (auto I = dyn_cast<Instruction>(V))
1959 Store->insertAfter(I);
1960 else
1961 Store->insertAfter(Alloca);
Philip Reames704e78b2015-04-10 22:34:56 +00001962
Philip Reames8531d8c2015-04-10 21:48:25 +00001963 // Normal return for invoke, or call return
1964 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1965 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1966 // Unwind return for invoke only
1967 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1968 if (Replacement)
1969 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1970 }
1971
1972 // apply mem2reg to promote alloca to SSA
Philip Reames704e78b2015-04-10 22:34:56 +00001973 SmallVector<AllocaInst *, 16> Allocas;
Philip Reames8531d8c2015-04-10 21:48:25 +00001974 for (Value *V : ToSplit)
1975 Allocas.push_back(AllocaMap[V]);
1976 PromoteMemToReg(Allocas, DT);
Philip Reames8fe7f132015-06-26 22:47:37 +00001977
1978 // Update our tracking of live pointers and base mappings to account for the
1979 // changes we just made.
1980 for (Value *V : ToSplit) {
1981 auto &Elements = ElementMapping[V];
1982
1983 LiveSet.erase(V);
1984 LiveSet.insert(Elements.begin(), Elements.end());
1985 // We need to update the base mapping as well.
1986 assert(PointerToBase.count(V));
1987 Value *OldBase = PointerToBase[V];
1988 auto &BaseElements = ElementMapping[OldBase];
1989 PointerToBase.erase(V);
1990 assert(Elements.size() == BaseElements.size());
1991 for (unsigned i = 0; i < Elements.size(); i++) {
1992 Value *Elem = Elements[i];
1993 PointerToBase[Elem] = BaseElements[i];
1994 }
1995 }
Philip Reames8531d8c2015-04-10 21:48:25 +00001996}
1997
Igor Laevskye0317182015-05-19 15:59:05 +00001998// Helper function for the "rematerializeLiveValues". It walks use chain
1999// starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2000// values are visited (currently it is GEP's and casts). Returns true if it
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002001// successfully reached "BaseValue" and false otherwise.
Igor Laevskye0317182015-05-19 15:59:05 +00002002// Fills "ChainToBase" array with all visited values. "BaseValue" is not
2003// recorded.
2004static bool findRematerializableChainToBasePointer(
2005 SmallVectorImpl<Instruction*> &ChainToBase,
2006 Value *CurrentValue, Value *BaseValue) {
2007
2008 // We have found a base value
2009 if (CurrentValue == BaseValue) {
2010 return true;
2011 }
2012
2013 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2014 ChainToBase.push_back(GEP);
2015 return findRematerializableChainToBasePointer(ChainToBase,
2016 GEP->getPointerOperand(),
2017 BaseValue);
2018 }
2019
2020 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2021 Value *Def = CI->stripPointerCasts();
2022
2023 // This two checks are basically similar. First one is here for the
2024 // consistency with findBasePointers logic.
2025 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2026 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2027 return false;
2028
2029 ChainToBase.push_back(CI);
2030 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2031 }
2032
2033 // Not supported instruction in the chain
2034 return false;
2035}
2036
2037// Helper function for the "rematerializeLiveValues". Compute cost of the use
2038// chain we are going to rematerialize.
2039static unsigned
2040chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2041 TargetTransformInfo &TTI) {
2042 unsigned Cost = 0;
2043
2044 for (Instruction *Instr : Chain) {
2045 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2046 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2047 "non noop cast is found during rematerialization");
2048
2049 Type *SrcTy = CI->getOperand(0)->getType();
2050 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2051
2052 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2053 // Cost of the address calculation
2054 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2055 Cost += TTI.getAddressComputationCost(ValTy);
2056
2057 // And cost of the GEP itself
2058 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2059 // allowed for the external usage)
2060 if (!GEP->hasAllConstantIndices())
2061 Cost += 2;
2062
2063 } else {
2064 llvm_unreachable("unsupported instruciton type during rematerialization");
2065 }
2066 }
2067
2068 return Cost;
2069}
2070
2071// From the statepoint liveset pick values that are cheaper to recompute then to
2072// relocate. Remove this values from the liveset, rematerialize them after
2073// statepoint and record them in "Info" structure. Note that similar to
2074// relocated values we don't do any user adjustments here.
2075static void rematerializeLiveValues(CallSite CS,
2076 PartiallyConstructedSafepointRecord &Info,
2077 TargetTransformInfo &TTI) {
Aaron Ballmanff7d4fa2015-05-20 14:53:50 +00002078 const unsigned int ChainLengthThreshold = 10;
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002079
Igor Laevskye0317182015-05-19 15:59:05 +00002080 // Record values we are going to delete from this statepoint live set.
2081 // We can not di this in following loop due to iterator invalidation.
2082 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2083
2084 for (Value *LiveValue: Info.liveset) {
2085 // For each live pointer find it's defining chain
2086 SmallVector<Instruction *, 3> ChainToBase;
Philip Reames74ce2e72015-07-21 16:51:17 +00002087 assert(Info.PointerToBase.count(LiveValue));
Igor Laevskye0317182015-05-19 15:59:05 +00002088 bool FoundChain =
2089 findRematerializableChainToBasePointer(ChainToBase,
2090 LiveValue,
2091 Info.PointerToBase[LiveValue]);
2092 // Nothing to do, or chain is too long
2093 if (!FoundChain ||
2094 ChainToBase.size() == 0 ||
2095 ChainToBase.size() > ChainLengthThreshold)
2096 continue;
2097
2098 // Compute cost of this chain
2099 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2100 // TODO: We can also account for cases when we will be able to remove some
2101 // of the rematerialized values by later optimization passes. I.e if
2102 // we rematerialized several intersecting chains. Or if original values
2103 // don't have any uses besides this statepoint.
2104
2105 // For invokes we need to rematerialize each chain twice - for normal and
2106 // for unwind basic blocks. Model this by multiplying cost by two.
2107 if (CS.isInvoke()) {
2108 Cost *= 2;
2109 }
2110 // If it's too expensive - skip it
2111 if (Cost >= RematerializationThreshold)
2112 continue;
2113
2114 // Remove value from the live set
2115 LiveValuesToBeDeleted.push_back(LiveValue);
2116
2117 // Clone instructions and record them inside "Info" structure
2118
2119 // Walk backwards to visit top-most instructions first
2120 std::reverse(ChainToBase.begin(), ChainToBase.end());
2121
2122 // Utility function which clones all instructions from "ChainToBase"
2123 // and inserts them before "InsertBefore". Returns rematerialized value
2124 // which should be used after statepoint.
2125 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2126 Instruction *LastClonedValue = nullptr;
2127 Instruction *LastValue = nullptr;
2128 for (Instruction *Instr: ChainToBase) {
2129 // Only GEP's and casts are suported as we need to be careful to not
2130 // introduce any new uses of pointers not in the liveset.
2131 // Note that it's fine to introduce new uses of pointers which were
2132 // otherwise not used after this statepoint.
2133 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2134
2135 Instruction *ClonedValue = Instr->clone();
2136 ClonedValue->insertBefore(InsertBefore);
2137 ClonedValue->setName(Instr->getName() + ".remat");
2138
2139 // If it is not first instruction in the chain then it uses previously
2140 // cloned value. We should update it to use cloned value.
2141 if (LastClonedValue) {
2142 assert(LastValue);
2143 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2144#ifndef NDEBUG
Igor Laevskyd83f6972015-05-21 13:02:14 +00002145 // Assert that cloned instruction does not use any instructions from
2146 // this chain other than LastClonedValue
2147 for (auto OpValue : ClonedValue->operand_values()) {
2148 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2149 ChainToBase.end() &&
2150 "incorrect use in rematerialization chain");
Igor Laevskye0317182015-05-19 15:59:05 +00002151 }
2152#endif
2153 }
2154
2155 LastClonedValue = ClonedValue;
2156 LastValue = Instr;
2157 }
2158 assert(LastClonedValue);
2159 return LastClonedValue;
2160 };
2161
2162 // Different cases for calls and invokes. For invokes we need to clone
2163 // instructions both on normal and unwind path.
2164 if (CS.isCall()) {
2165 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2166 assert(InsertBefore);
2167 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2168 Info.RematerializedValues[RematerializedValue] = LiveValue;
2169 } else {
2170 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2171
2172 Instruction *NormalInsertBefore =
2173 Invoke->getNormalDest()->getFirstInsertionPt();
2174 Instruction *UnwindInsertBefore =
2175 Invoke->getUnwindDest()->getFirstInsertionPt();
2176
2177 Instruction *NormalRematerializedValue =
2178 rematerializeChain(NormalInsertBefore);
2179 Instruction *UnwindRematerializedValue =
2180 rematerializeChain(UnwindInsertBefore);
2181
2182 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2183 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2184 }
2185 }
2186
2187 // Remove rematerializaed values from the live set
2188 for (auto LiveValue: LiveValuesToBeDeleted) {
2189 Info.liveset.erase(LiveValue);
2190 }
2191}
2192
Philip Reamesd16a9b12015-02-20 01:06:44 +00002193static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
Philip Reamesd2b66462015-02-20 22:39:41 +00002194 SmallVectorImpl<CallSite> &toUpdate) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002195#ifndef NDEBUG
2196 // sanity check the input
2197 std::set<CallSite> uniqued;
2198 uniqued.insert(toUpdate.begin(), toUpdate.end());
2199 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2200
2201 for (size_t i = 0; i < toUpdate.size(); i++) {
2202 CallSite &CS = toUpdate[i];
2203 assert(CS.getInstruction()->getParent()->getParent() == &F);
2204 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2205 }
2206#endif
2207
Philip Reames69e51ca2015-04-13 18:07:21 +00002208 // When inserting gc.relocates for invokes, we need to be able to insert at
2209 // the top of the successor blocks. See the comment on
2210 // normalForInvokeSafepoint on exactly what is needed. Note that this step
Philip Reamesf209a152015-04-13 20:00:30 +00002211 // may restructure the CFG.
2212 for (CallSite CS : toUpdate) {
2213 if (!CS.isInvoke())
2214 continue;
2215 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2216 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002217 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002218 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002219 DT);
Philip Reamesf209a152015-04-13 20:00:30 +00002220 }
Philip Reames69e51ca2015-04-13 18:07:21 +00002221
Philip Reamesd16a9b12015-02-20 01:06:44 +00002222 // A list of dummy calls added to the IR to keep various values obviously
2223 // live in the IR. We'll remove all of these when done.
Philip Reamesd2b66462015-02-20 22:39:41 +00002224 SmallVector<CallInst *, 64> holders;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002225
2226 // Insert a dummy call with all of the arguments to the vm_state we'll need
2227 // for the actual safepoint insertion. This ensures reference arguments in
2228 // the deopt argument list are considered live through the safepoint (and
2229 // thus makes sure they get relocated.)
2230 for (size_t i = 0; i < toUpdate.size(); i++) {
2231 CallSite &CS = toUpdate[i];
2232 Statepoint StatepointCS(CS);
2233
2234 SmallVector<Value *, 64> DeoptValues;
2235 for (Use &U : StatepointCS.vm_state_args()) {
2236 Value *Arg = cast<Value>(&U);
Philip Reames8531d8c2015-04-10 21:48:25 +00002237 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2238 "support for FCA unimplemented");
2239 if (isHandledGCPointerType(Arg->getType()))
Philip Reamesd16a9b12015-02-20 01:06:44 +00002240 DeoptValues.push_back(Arg);
2241 }
2242 insertUseHolderAfter(CS, DeoptValues, holders);
2243 }
2244
Philip Reamesd2b66462015-02-20 22:39:41 +00002245 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002246 records.reserve(toUpdate.size());
2247 for (size_t i = 0; i < toUpdate.size(); i++) {
2248 struct PartiallyConstructedSafepointRecord info;
2249 records.push_back(info);
2250 }
2251 assert(records.size() == toUpdate.size());
2252
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002253 // A) Identify all gc pointers which are statically live at the given call
Philip Reamesd16a9b12015-02-20 01:06:44 +00002254 // site.
2255 findLiveReferences(F, DT, P, toUpdate, records);
2256
2257 // B) Find the base pointers for each live pointer
2258 /* scope for caching */ {
2259 // Cache the 'defining value' relation used in the computation and
2260 // insertion of base phis and selects. This ensures that we don't insert
2261 // large numbers of duplicate base_phis.
2262 DefiningValueMapTy DVCache;
2263
2264 for (size_t i = 0; i < records.size(); i++) {
2265 struct PartiallyConstructedSafepointRecord &info = records[i];
2266 CallSite &CS = toUpdate[i];
2267 findBasePointers(DT, DVCache, CS, info);
2268 }
2269 } // end of cache scope
2270
2271 // The base phi insertion logic (for any safepoint) may have inserted new
2272 // instructions which are now live at some safepoint. The simplest such
2273 // example is:
2274 // loop:
2275 // phi a <-- will be a new base_phi here
2276 // safepoint 1 <-- that needs to be live here
2277 // gep a + 1
2278 // safepoint 2
2279 // br loop
Philip Reamesd16a9b12015-02-20 01:06:44 +00002280 // We insert some dummy calls after each safepoint to definitely hold live
2281 // the base pointers which were identified for that safepoint. We'll then
2282 // ask liveness for _every_ base inserted to see what is now live. Then we
2283 // remove the dummy calls.
2284 holders.reserve(holders.size() + records.size());
2285 for (size_t i = 0; i < records.size(); i++) {
2286 struct PartiallyConstructedSafepointRecord &info = records[i];
2287 CallSite &CS = toUpdate[i];
2288
2289 SmallVector<Value *, 128> Bases;
Philip Reamesf2041322015-02-20 19:26:04 +00002290 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002291 Bases.push_back(Pair.second);
2292 }
2293 insertUseHolderAfter(CS, Bases, holders);
2294 }
2295
Philip Reamesdf1ef082015-04-10 22:53:14 +00002296 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2297 // need to rerun liveness. We may *also* have inserted new defs, but that's
2298 // not the key issue.
2299 recomputeLiveInValues(F, DT, P, toUpdate, records);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002300
Philip Reamesd16a9b12015-02-20 01:06:44 +00002301 if (PrintBasePointers) {
2302 for (size_t i = 0; i < records.size(); i++) {
2303 struct PartiallyConstructedSafepointRecord &info = records[i];
2304 errs() << "Base Pairs: (w/Relocation)\n";
Philip Reamesf2041322015-02-20 19:26:04 +00002305 for (auto Pair : info.PointerToBase) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002306 errs() << " derived %" << Pair.first->getName() << " base %"
2307 << Pair.second->getName() << "\n";
2308 }
2309 }
2310 }
2311 for (size_t i = 0; i < holders.size(); i++) {
2312 holders[i]->eraseFromParent();
2313 holders[i] = nullptr;
2314 }
2315 holders.clear();
2316
Philip Reames8fe7f132015-06-26 22:47:37 +00002317 // Do a limited scalarization of any live at safepoint vector values which
2318 // contain pointers. This enables this pass to run after vectorization at
2319 // the cost of some possible performance loss. TODO: it would be nice to
2320 // natively support vectors all the way through the backend so we don't need
2321 // to scalarize here.
2322 for (size_t i = 0; i < records.size(); i++) {
2323 struct PartiallyConstructedSafepointRecord &info = records[i];
2324 Instruction *statepoint = toUpdate[i].getInstruction();
2325 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2326 info.PointerToBase, DT);
2327 }
2328
Igor Laevskye0317182015-05-19 15:59:05 +00002329 // In order to reduce live set of statepoint we might choose to rematerialize
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002330 // some values instead of relocating them. This is purely an optimization and
Igor Laevskye0317182015-05-19 15:59:05 +00002331 // does not influence correctness.
2332 TargetTransformInfo &TTI =
2333 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2334
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002335 for (size_t i = 0; i < records.size(); i++) {
Igor Laevskye0317182015-05-19 15:59:05 +00002336 struct PartiallyConstructedSafepointRecord &info = records[i];
2337 CallSite &CS = toUpdate[i];
2338
2339 rematerializeLiveValues(CS, info, TTI);
2340 }
2341
Philip Reamesd16a9b12015-02-20 01:06:44 +00002342 // Now run through and replace the existing statepoints with new ones with
2343 // the live variables listed. We do not yet update uses of the values being
2344 // relocated. We have references to live variables that need to
2345 // survive to the last iteration of this loop. (By construction, the
2346 // previous statepoint can not be a live variable, thus we can and remove
2347 // the old statepoint calls as we go.)
2348 for (size_t i = 0; i < records.size(); i++) {
2349 struct PartiallyConstructedSafepointRecord &info = records[i];
2350 CallSite &CS = toUpdate[i];
2351 makeStatepointExplicit(DT, CS, P, info);
2352 }
2353 toUpdate.clear(); // prevent accident use of invalid CallSites
2354
Philip Reamesd16a9b12015-02-20 01:06:44 +00002355 // Do all the fixups of the original live variables to their relocated selves
Philip Reamesd2b66462015-02-20 22:39:41 +00002356 SmallVector<Value *, 128> live;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002357 for (size_t i = 0; i < records.size(); i++) {
2358 struct PartiallyConstructedSafepointRecord &info = records[i];
2359 // We can't simply save the live set from the original insertion. One of
2360 // the live values might be the result of a call which needs a safepoint.
2361 // That Value* no longer exists and we need to use the new gc_result.
2362 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2363 // we just grab that.
Philip Reames0a3240f2015-02-20 21:34:11 +00002364 Statepoint statepoint(info.StatepointToken);
Philip Reamesd16a9b12015-02-20 01:06:44 +00002365 live.insert(live.end(), statepoint.gc_args_begin(),
2366 statepoint.gc_args_end());
Philip Reames9a2e01d2015-04-13 17:35:55 +00002367#ifndef NDEBUG
2368 // Do some basic sanity checks on our liveness results before performing
2369 // relocation. Relocation can and will turn mistakes in liveness results
2370 // into non-sensical code which is must harder to debug.
2371 // TODO: It would be nice to test consistency as well
2372 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2373 "statepoint must be reachable or liveness is meaningless");
2374 for (Value *V : statepoint.gc_args()) {
2375 if (!isa<Instruction>(V))
2376 // Non-instruction values trivial dominate all possible uses
2377 continue;
2378 auto LiveInst = cast<Instruction>(V);
2379 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2380 "unreachable values should never be live");
2381 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2382 "basic SSA liveness expectation violated by liveness analysis");
2383 }
2384#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002385 }
2386 unique_unsorted(live);
2387
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002388#ifndef NDEBUG
Philip Reamesd16a9b12015-02-20 01:06:44 +00002389 // sanity check
2390 for (auto ptr : live) {
2391 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2392 }
Nick Lewyckyeb3231e2015-02-20 07:14:02 +00002393#endif
Philip Reamesd16a9b12015-02-20 01:06:44 +00002394
2395 relocationViaAlloca(F, DT, live, records);
2396 return !records.empty();
2397}
2398
Sanjoy Das353a19e2015-06-02 22:33:37 +00002399// Handles both return values and arguments for Functions and CallSites.
2400template <typename AttrHolder>
2401static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2402 unsigned Index) {
2403 AttrBuilder R;
2404 if (AH.getDereferenceableBytes(Index))
2405 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2406 AH.getDereferenceableBytes(Index)));
2407 if (AH.getDereferenceableOrNullBytes(Index))
2408 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2409 AH.getDereferenceableOrNullBytes(Index)));
2410
2411 if (!R.empty())
2412 AH.setAttributes(AH.getAttributes().removeAttributes(
2413 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
Vasileios Kalintiris9f77f612015-06-03 08:51:30 +00002414}
Sanjoy Das353a19e2015-06-02 22:33:37 +00002415
2416void
2417RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2418 LLVMContext &Ctx = F.getContext();
2419
2420 for (Argument &A : F.args())
2421 if (isa<PointerType>(A.getType()))
2422 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2423
2424 if (isa<PointerType>(F.getReturnType()))
2425 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2426}
2427
2428void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2429 if (F.empty())
2430 return;
2431
2432 LLVMContext &Ctx = F.getContext();
2433 MDBuilder Builder(Ctx);
2434
Nico Rieck78199512015-08-06 19:10:45 +00002435 for (Instruction &I : instructions(F)) {
Sanjoy Das353a19e2015-06-02 22:33:37 +00002436 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2437 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2438 bool IsImmutableTBAA =
2439 MD->getNumOperands() == 4 &&
2440 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2441
2442 if (!IsImmutableTBAA)
2443 continue; // no work to do, MD_tbaa is already marked mutable
2444
2445 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2446 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2447 uint64_t Offset =
2448 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2449
2450 MDNode *MutableTBAA =
2451 Builder.createTBAAStructTagNode(Base, Access, Offset);
2452 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2453 }
2454
2455 if (CallSite CS = CallSite(&I)) {
2456 for (int i = 0, e = CS.arg_size(); i != e; i++)
2457 if (isa<PointerType>(CS.getArgument(i)->getType()))
2458 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2459 if (isa<PointerType>(CS.getType()))
2460 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2461 }
2462 }
2463}
2464
Philip Reamesd16a9b12015-02-20 01:06:44 +00002465/// Returns true if this function should be rewritten by this pass. The main
2466/// point of this function is as an extension point for custom logic.
2467static bool shouldRewriteStatepointsIn(Function &F) {
2468 // TODO: This should check the GCStrategy
Philip Reames2ef029c2015-02-20 18:56:14 +00002469 if (F.hasGC()) {
NAKAMURA Takumifb3bd712015-05-25 01:43:23 +00002470 const char *FunctionGCName = F.getGC();
2471 const StringRef StatepointExampleName("statepoint-example");
2472 const StringRef CoreCLRName("coreclr");
2473 return (StatepointExampleName == FunctionGCName) ||
NAKAMURA Takumi5582a6a2015-05-25 01:43:34 +00002474 (CoreCLRName == FunctionGCName);
2475 } else
Philip Reames2ef029c2015-02-20 18:56:14 +00002476 return false;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002477}
2478
Sanjoy Das353a19e2015-06-02 22:33:37 +00002479void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2480#ifndef NDEBUG
2481 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2482 "precondition!");
2483#endif
2484
2485 for (Function &F : M)
2486 stripDereferenceabilityInfoFromPrototype(F);
2487
2488 for (Function &F : M)
2489 stripDereferenceabilityInfoFromBody(F);
2490}
2491
Philip Reamesd16a9b12015-02-20 01:06:44 +00002492bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2493 // Nothing to do for declarations.
2494 if (F.isDeclaration() || F.empty())
2495 return false;
2496
2497 // Policy choice says not to rewrite - the most common reason is that we're
2498 // compiling code without a GCStrategy.
2499 if (!shouldRewriteStatepointsIn(F))
2500 return false;
2501
Sanjoy Dasea45f0e2015-06-02 22:33:34 +00002502 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
Philip Reames704e78b2015-04-10 22:34:56 +00002503
Philip Reames85b36a82015-04-10 22:07:04 +00002504 // Gather all the statepoints which need rewritten. Be careful to only
2505 // consider those in reachable code since we need to ask dominance queries
2506 // when rewriting. We'll delete the unreachable ones in a moment.
Philip Reamesd2b66462015-02-20 22:39:41 +00002507 SmallVector<CallSite, 64> ParsePointNeeded;
Philip Reamesf66d7372015-04-10 22:16:58 +00002508 bool HasUnreachableStatepoint = false;
Nico Rieck78199512015-08-06 19:10:45 +00002509 for (Instruction &I : instructions(F)) {
Philip Reamesd16a9b12015-02-20 01:06:44 +00002510 // TODO: only the ones with the flag set!
Philip Reames85b36a82015-04-10 22:07:04 +00002511 if (isStatepoint(I)) {
2512 if (DT.isReachableFromEntry(I.getParent()))
2513 ParsePointNeeded.push_back(CallSite(&I));
2514 else
Philip Reamesf66d7372015-04-10 22:16:58 +00002515 HasUnreachableStatepoint = true;
Philip Reames85b36a82015-04-10 22:07:04 +00002516 }
Philip Reamesd16a9b12015-02-20 01:06:44 +00002517 }
2518
Philip Reames85b36a82015-04-10 22:07:04 +00002519 bool MadeChange = false;
Philip Reames704e78b2015-04-10 22:34:56 +00002520
Philip Reames85b36a82015-04-10 22:07:04 +00002521 // Delete any unreachable statepoints so that we don't have unrewritten
2522 // statepoints surviving this pass. This makes testing easier and the
2523 // resulting IR less confusing to human readers. Rather than be fancy, we
2524 // just reuse a utility function which removes the unreachable blocks.
Philip Reamesf66d7372015-04-10 22:16:58 +00002525 if (HasUnreachableStatepoint)
Philip Reames85b36a82015-04-10 22:07:04 +00002526 MadeChange |= removeUnreachableBlocks(F);
2527
Philip Reamesd16a9b12015-02-20 01:06:44 +00002528 // Return early if no work to do.
2529 if (ParsePointNeeded.empty())
Philip Reames85b36a82015-04-10 22:07:04 +00002530 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002531
Philip Reames85b36a82015-04-10 22:07:04 +00002532 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2533 // These are created by LCSSA. They have the effect of increasing the size
2534 // of liveness sets for no good reason. It may be harder to do this post
2535 // insertion since relocations and base phis can confuse things.
2536 for (BasicBlock &BB : F)
2537 if (BB.getUniquePredecessor()) {
2538 MadeChange = true;
2539 FoldSingleEntryPHINodes(&BB);
2540 }
2541
Philip Reames971dc3a2015-08-12 22:11:45 +00002542 // Before we start introducing relocations, we want to tweak the IR a bit to
2543 // avoid unfortunate code generation effects. The main example is that we
2544 // want to try to make sure the comparison feeding a branch is after any
2545 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2546 // values feeding a branch after relocation. This is semantically correct,
2547 // but results in extra register pressure since both the pre-relocation and
2548 // post-relocation copies must be available in registers. For code without
2549 // relocations this is handled elsewhere, but teaching the scheduler to
2550 // reverse the transform we're about to do would be slightly complex.
2551 // Note: This may extend the live range of the inputs to the icmp and thus
2552 // increase the liveset of any statepoint we move over. This is profitable
2553 // as long as all statepoints are in rare blocks. If we had in-register
2554 // lowering for live values this would be a much safer transform.
2555 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2556 if (auto *BI = dyn_cast<BranchInst>(TI))
2557 if (BI->isConditional())
2558 return dyn_cast<Instruction>(BI->getCondition());
2559 // TODO: Extend this to handle switches
2560 return nullptr;
2561 };
2562 for (BasicBlock &BB : F) {
2563 TerminatorInst *TI = BB.getTerminator();
2564 if (auto *Cond = getConditionInst(TI))
2565 // TODO: Handle more than just ICmps here. We should be able to move
2566 // most instructions without side effects or memory access.
2567 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2568 MadeChange = true;
2569 Cond->moveBefore(TI);
2570 }
2571 }
2572
Philip Reames85b36a82015-04-10 22:07:04 +00002573 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2574 return MadeChange;
Philip Reamesd16a9b12015-02-20 01:06:44 +00002575}
Philip Reamesdf1ef082015-04-10 22:53:14 +00002576
2577// liveness computation via standard dataflow
2578// -------------------------------------------------------------------
2579
2580// TODO: Consider using bitvectors for liveness, the set of potentially
2581// interesting values should be small and easy to pre-compute.
2582
Philip Reamesdf1ef082015-04-10 22:53:14 +00002583/// Compute the live-in set for the location rbegin starting from
2584/// the live-out set of the basic block
2585static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2586 BasicBlock::reverse_iterator rend,
2587 DenseSet<Value *> &LiveTmp) {
2588
2589 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2590 Instruction *I = &*ritr;
2591
2592 // KILL/Def - Remove this definition from LiveIn
2593 LiveTmp.erase(I);
2594
2595 // Don't consider *uses* in PHI nodes, we handle their contribution to
2596 // predecessor blocks when we seed the LiveOut sets
2597 if (isa<PHINode>(I))
2598 continue;
2599
2600 // USE - Add to the LiveIn set for this instruction
2601 for (Value *V : I->operands()) {
2602 assert(!isUnhandledGCPointerType(V->getType()) &&
2603 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002604 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2605 // The choice to exclude all things constant here is slightly subtle.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002606 // There are two independent reasons:
Philip Reames63294cb2015-04-26 19:48:03 +00002607 // - We assume that things which are constant (from LLVM's definition)
2608 // do not move at runtime. For example, the address of a global
2609 // variable is fixed, even though it's contents may not be.
2610 // - Second, we can't disallow arbitrary inttoptr constants even
2611 // if the language frontend does. Optimization passes are free to
2612 // locally exploit facts without respect to global reachability. This
2613 // can create sections of code which are dynamically unreachable and
2614 // contain just about anything. (see constants.ll in tests)
Philip Reamesdf1ef082015-04-10 22:53:14 +00002615 LiveTmp.insert(V);
2616 }
2617 }
2618 }
2619}
2620
2621static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2622
2623 for (BasicBlock *Succ : successors(BB)) {
2624 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2625 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2626 PHINode *Phi = cast<PHINode>(&*I);
2627 Value *V = Phi->getIncomingValueForBlock(BB);
2628 assert(!isUnhandledGCPointerType(V->getType()) &&
2629 "support for FCA unimplemented");
Philip Reames63294cb2015-04-26 19:48:03 +00002630 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002631 LiveTmp.insert(V);
2632 }
2633 }
2634 }
2635}
2636
2637static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2638 DenseSet<Value *> KillSet;
2639 for (Instruction &I : *BB)
2640 if (isHandledGCPointerType(I.getType()))
2641 KillSet.insert(&I);
2642 return KillSet;
2643}
2644
Philip Reames9638ff92015-04-11 00:06:47 +00002645#ifndef NDEBUG
Philip Reamesdf1ef082015-04-10 22:53:14 +00002646/// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2647/// sanity check for the liveness computation.
2648static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2649 TerminatorInst *TI, bool TermOkay = false) {
Philip Reamesdf1ef082015-04-10 22:53:14 +00002650 for (Value *V : Live) {
2651 if (auto *I = dyn_cast<Instruction>(V)) {
2652 // The terminator can be a member of the LiveOut set. LLVM's definition
2653 // of instruction dominance states that V does not dominate itself. As
2654 // such, we need to special case this to allow it.
2655 if (TermOkay && TI == I)
2656 continue;
2657 assert(DT.dominates(I, TI) &&
2658 "basic SSA liveness expectation violated by liveness analysis");
2659 }
2660 }
Philip Reamesdf1ef082015-04-10 22:53:14 +00002661}
2662
2663/// Check that all the liveness sets used during the computation of liveness
2664/// obey basic SSA properties. This is useful for finding cases where we miss
2665/// a def.
2666static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2667 BasicBlock &BB) {
2668 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2669 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2670 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2671}
Philip Reames9638ff92015-04-11 00:06:47 +00002672#endif
Philip Reamesdf1ef082015-04-10 22:53:14 +00002673
2674static void computeLiveInValues(DominatorTree &DT, Function &F,
2675 GCPtrLivenessData &Data) {
2676
Philip Reames4d80ede2015-04-10 23:11:26 +00002677 SmallSetVector<BasicBlock *, 200> Worklist;
Philip Reamesdf1ef082015-04-10 22:53:14 +00002678 auto AddPredsToWorklist = [&](BasicBlock *BB) {
Philip Reames4d80ede2015-04-10 23:11:26 +00002679 // We use a SetVector so that we don't have duplicates in the worklist.
2680 Worklist.insert(pred_begin(BB), pred_end(BB));
Philip Reamesdf1ef082015-04-10 22:53:14 +00002681 };
2682 auto NextItem = [&]() {
2683 BasicBlock *BB = Worklist.back();
2684 Worklist.pop_back();
Philip Reamesdf1ef082015-04-10 22:53:14 +00002685 return BB;
2686 };
2687
2688 // Seed the liveness for each individual block
2689 for (BasicBlock &BB : F) {
2690 Data.KillSet[&BB] = computeKillSet(&BB);
2691 Data.LiveSet[&BB].clear();
2692 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2693
2694#ifndef NDEBUG
2695 for (Value *Kill : Data.KillSet[&BB])
2696 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2697#endif
2698
2699 Data.LiveOut[&BB] = DenseSet<Value *>();
2700 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2701 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2702 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2703 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2704 if (!Data.LiveIn[&BB].empty())
2705 AddPredsToWorklist(&BB);
2706 }
2707
2708 // Propagate that liveness until stable
2709 while (!Worklist.empty()) {
2710 BasicBlock *BB = NextItem();
2711
2712 // Compute our new liveout set, then exit early if it hasn't changed
2713 // despite the contribution of our successor.
2714 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2715 const auto OldLiveOutSize = LiveOut.size();
2716 for (BasicBlock *Succ : successors(BB)) {
2717 assert(Data.LiveIn.count(Succ));
2718 set_union(LiveOut, Data.LiveIn[Succ]);
2719 }
2720 // assert OutLiveOut is a subset of LiveOut
2721 if (OldLiveOutSize == LiveOut.size()) {
2722 // If the sets are the same size, then we didn't actually add anything
2723 // when unioning our successors LiveIn Thus, the LiveIn of this block
2724 // hasn't changed.
2725 continue;
2726 }
2727 Data.LiveOut[BB] = LiveOut;
2728
2729 // Apply the effects of this basic block
2730 DenseSet<Value *> LiveTmp = LiveOut;
2731 set_union(LiveTmp, Data.LiveSet[BB]);
2732 set_subtract(LiveTmp, Data.KillSet[BB]);
2733
2734 assert(Data.LiveIn.count(BB));
2735 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2736 // assert: OldLiveIn is a subset of LiveTmp
2737 if (OldLiveIn.size() != LiveTmp.size()) {
2738 Data.LiveIn[BB] = LiveTmp;
2739 AddPredsToWorklist(BB);
2740 }
2741 } // while( !worklist.empty() )
2742
2743#ifndef NDEBUG
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002744 // Sanity check our output against SSA properties. This helps catch any
Philip Reamesdf1ef082015-04-10 22:53:14 +00002745 // missing kills during the above iteration.
2746 for (BasicBlock &BB : F) {
2747 checkBasicSSA(DT, Data, BB);
2748 }
2749#endif
2750}
2751
2752static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2753 StatepointLiveSetTy &Out) {
2754
2755 BasicBlock *BB = Inst->getParent();
2756
2757 // Note: The copy is intentional and required
2758 assert(Data.LiveOut.count(BB));
2759 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2760
2761 // We want to handle the statepoint itself oddly. It's
2762 // call result is not live (normal), nor are it's arguments
2763 // (unless they're used again later). This adjustment is
2764 // specifically what we need to relocate
2765 BasicBlock::reverse_iterator rend(Inst);
2766 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2767 LiveOut.erase(Inst);
2768 Out.insert(LiveOut.begin(), LiveOut.end());
2769}
2770
2771static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2772 const CallSite &CS,
2773 PartiallyConstructedSafepointRecord &Info) {
2774 Instruction *Inst = CS.getInstruction();
2775 StatepointLiveSetTy Updated;
2776 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2777
2778#ifndef NDEBUG
2779 DenseSet<Value *> Bases;
2780 for (auto KVPair : Info.PointerToBase) {
2781 Bases.insert(KVPair.second);
2782 }
2783#endif
2784 // We may have base pointers which are now live that weren't before. We need
2785 // to update the PointerToBase structure to reflect this.
2786 for (auto V : Updated)
2787 if (!Info.PointerToBase.count(V)) {
2788 assert(Bases.count(V) && "can't find base for unexpected live value");
2789 Info.PointerToBase[V] = V;
2790 continue;
2791 }
2792
2793#ifndef NDEBUG
2794 for (auto V : Updated) {
2795 assert(Info.PointerToBase.count(V) &&
2796 "must be able to find base for live value");
2797 }
2798#endif
2799
2800 // Remove any stale base mappings - this can happen since our liveness is
2801 // more precise then the one inherent in the base pointer analysis
2802 DenseSet<Value *> ToErase;
2803 for (auto KVPair : Info.PointerToBase)
2804 if (!Updated.count(KVPair.first))
2805 ToErase.insert(KVPair.first);
2806 for (auto V : ToErase)
2807 Info.PointerToBase.erase(V);
2808
2809#ifndef NDEBUG
2810 for (auto KVPair : Info.PointerToBase)
2811 assert(Updated.count(KVPair.first) && "record for non-live value");
2812#endif
2813
2814 Info.liveset = Updated;
2815}