1 //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Rewrite an existing set of gc.statepoints such that they make potential
11 // relocations performed by the garbage collector explicit in the IR.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Pass.h"
16 #include "llvm/Analysis/CFG.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/TargetTransformInfo.h"
19 #include "llvm/ADT/SetOperations.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/MapVector.h"
25 #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"
35 #include "llvm/IR/MDBuilder.h"
36 #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"
47 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
51 // Print the liveset found at the insert location
52 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
54 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
56 // Print out the base pointers for debugging
57 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
60 // Cost threshold measuring when it is profitable to rematerialize value instead
62 static cl::opt<unsigned>
63 RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
67 static bool ClobberNonLive = true;
69 static bool ClobberNonLive = false;
71 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
72 cl::location(ClobberNonLive),
76 struct RewriteStatepointsForGC : public ModulePass {
77 static char ID; // Pass identification, replacement for typeid
79 RewriteStatepointsForGC() : ModulePass(ID) {
80 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
82 bool runOnFunction(Function &F);
83 bool runOnModule(Module &M) override {
86 Changed |= runOnFunction(F);
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);
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>();
102 AU.addRequired<TargetTransformInfoWrapperPass>();
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.
113 void stripDereferenceabilityInfo(Module &M);
115 // Helpers for stripDereferenceabilityInfo
116 void stripDereferenceabilityInfoFromBody(Function &F);
117 void stripDereferenceabilityInfoFromPrototype(Function &F);
121 char RewriteStatepointsForGC::ID = 0;
123 ModulePass *llvm::createRewriteStatepointsForGCPass() {
124 return new RewriteStatepointsForGC();
127 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
128 "Make relocations explicit at statepoints", false, false)
129 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
130 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
131 "Make relocations explicit at statepoints", false, false)
134 struct 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;
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;
145 /// Values live out of this basic block (i.e. live into
146 /// any successor block)
147 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
150 // 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.
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
160 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
161 typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
162 typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
164 struct PartiallyConstructedSafepointRecord {
165 /// The set of values known to be live across this safepoint
166 StatepointLiveSetTy liveset;
168 /// Mapping from live pointers to a base-defining-value
169 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
171 /// 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;
175 /// Instruction to which exceptional gc relocates are attached
176 /// Makes it easier to iterate through them during relocationViaAlloca.
177 Instruction *UnwindToken;
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;
186 /// Compute the live-in set for every basic block in the function
187 static void computeLiveInValues(DominatorTree &DT, Function &F,
188 GCPtrLivenessData &Data);
190 /// Given results from the dataflow liveness computation, find the set of live
191 /// Values at a particular instruction.
192 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
193 StatepointLiveSetTy &out);
195 // TODO: Once we can get to the GCStrategy, this becomes
196 // Optional<bool> isGCManagedPointer(const Value *V) const override {
198 static bool isGCPointerType(Type *T) {
199 if (auto *PT = dyn_cast<PointerType>(T))
200 // 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());
207 // 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)
210 // is not encountered.)
211 static bool isHandledGCPointerType(Type *T) {
212 // We fully support gc pointers
213 if (isGCPointerType(T))
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()))
224 /// Returns true if this type contains a gc pointer whether we know how to
225 /// handle that type or not.
226 static bool containsGCPtrType(Type *Ty) {
227 if (isGCPointerType(Ty))
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))
235 ST->subtypes().begin(), ST->subtypes().end(),
236 [](Type *SubType) { return containsGCPtrType(SubType); });
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.
243 static bool isUnhandledGCPointerType(Type *Ty) {
244 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
248 static 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()) {
253 } else if (!a->hasName() && b->hasName()) {
256 // Better than nothing, but not stable
261 // 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.
265 static void analyzeParsePointLiveness(
266 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
267 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
268 Instruction *inst = CS.getInstruction();
270 StatepointLiveSetTy liveset;
271 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
274 // Note: This output is used by several of the test cases
275 // The order of elements in a set is not stable, put them in a vec and sort
277 SmallVector<Value *, 64> Temp;
278 Temp.insert(Temp.end(), liveset.begin(), liveset.end());
279 std::sort(Temp.begin(), Temp.end(), order_by_name);
280 errs() << "Live Variables:\n";
281 for (Value *V : Temp)
282 dbgs() << " " << V->getName() << " " << *V << "\n";
284 if (PrintLiveSetSize) {
285 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
286 errs() << "Number live values: " << liveset.size() << "\n";
288 result.liveset = liveset;
291 static bool isKnownBaseResult(Value *V);
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.
301 struct BaseDefiningValueResult {
302 /// Contains the value which is the base defining value.
304 /// True if the base defining value is also known to be an actual base
306 const bool IsKnownBase;
307 BaseDefiningValueResult(Value *BDV, bool IsKnownBase)
308 : BDV(BDV), IsKnownBase(IsKnownBase) {
310 // Check consistency between new and old means of checking whether a BDV is
312 bool MustBeBase = isKnownBaseResult(BDV);
313 assert(!MustBeBase || MustBeBase == IsKnownBase);
319 static BaseDefiningValueResult findBaseDefiningValue(Value *I);
321 /// 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'.
330 static BaseDefiningValueResult
331 findBaseDefiningValueOfVector(Value *I) {
332 assert(I->getType()->isVectorTy() &&
333 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
334 "Illegal to ask for the base pointer of a non-pointer type");
336 // Each case parallels findBaseDefiningValue below, see that code for
337 // detailed motivation.
339 if (isa<Argument>(I))
340 // An incoming argument to the function is a base pointer
341 return BaseDefiningValueResult(I, true);
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");
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
352 return BaseDefiningValueResult(I, true);
354 // Due to inheritance, this must be _after_ the global variable and undef
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");
360 return BaseDefiningValueResult(Con, true);
363 if (isa<LoadInst>(I))
364 return BaseDefiningValueResult(I, true);
366 if (isa<InsertElementInst>(I))
367 // We don't know whether this vector contains entirely base pointers or
368 // not. To be conservatively correct, we treat it as a BDV and will
369 // duplicate code as needed to construct a parallel vector of bases.
370 return BaseDefiningValueResult(I, false);
372 if (isa<ShuffleVectorInst>(I))
373 // We don't know whether this vector contains entirely base pointers or
374 // not. To be conservatively correct, we treat it as a BDV and will
375 // duplicate code as needed to construct a parallel vector of bases.
376 // TODO: There a number of local optimizations which could be applied here
377 // for particular sufflevector patterns.
378 return BaseDefiningValueResult(I, false);
380 // A PHI or Select is a base defining value. The outer findBasePointer
381 // algorithm is responsible for constructing a base value for this BDV.
382 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
383 "unknown vector instruction - no base found for vector element");
384 return BaseDefiningValueResult(I, false);
387 /// Helper function for findBasePointer - Will return a value which either a)
388 /// defines the base pointer for the input, b) blocks the simple search
389 /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
390 /// from pointer to vector type or back.
391 static BaseDefiningValueResult findBaseDefiningValue(Value *I) {
392 if (I->getType()->isVectorTy())
393 return findBaseDefiningValueOfVector(I);
395 assert(I->getType()->isPointerTy() &&
396 "Illegal to ask for the base pointer of a non-pointer type");
398 if (isa<Argument>(I))
399 // An incoming argument to the function is a base pointer
400 // We should have never reached here if this argument isn't an gc value
401 return BaseDefiningValueResult(I, true);
403 if (isa<GlobalVariable>(I))
405 return BaseDefiningValueResult(I, true);
407 // inlining could possibly introduce phi node that contains
408 // undef if callee has multiple returns
409 if (isa<UndefValue>(I))
410 // utterly meaningless, but useful for dealing with
411 // partially optimized code.
412 return BaseDefiningValueResult(I, true);
414 // Due to inheritance, this must be _after_ the global variable and undef
416 if (isa<Constant>(I)) {
417 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
418 "order of checks wrong!");
419 // Note: Finding a constant base for something marked for relocation
420 // doesn't really make sense. The most likely case is either a) some
421 // screwed up the address space usage or b) your validating against
422 // compiled C++ code w/o the proper separation. The only real exception
423 // is a null pointer. You could have generic code written to index of
424 // off a potentially null value and have proven it null. We also use
425 // null pointers in dead paths of relocation phis (which we might later
426 // want to find a base pointer for).
427 assert(isa<ConstantPointerNull>(I) &&
428 "null is the only case which makes sense");
429 return BaseDefiningValueResult(I, true);
432 if (CastInst *CI = dyn_cast<CastInst>(I)) {
433 Value *Def = CI->stripPointerCasts();
434 // If we find a cast instruction here, it means we've found a cast which is
435 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
436 // handle int->ptr conversion.
437 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
438 return findBaseDefiningValue(Def);
441 if (isa<LoadInst>(I))
442 // The value loaded is an gc base itself
443 return BaseDefiningValueResult(I, true);
446 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
447 // The base of this GEP is the base
448 return findBaseDefiningValue(GEP->getPointerOperand());
450 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
451 switch (II->getIntrinsicID()) {
452 case Intrinsic::experimental_gc_result_ptr:
454 // fall through to general call handling
456 case Intrinsic::experimental_gc_statepoint:
457 case Intrinsic::experimental_gc_result_float:
458 case Intrinsic::experimental_gc_result_int:
459 llvm_unreachable("these don't produce pointers");
460 case Intrinsic::experimental_gc_relocate: {
461 // Rerunning safepoint insertion after safepoints are already
462 // inserted is not supported. It could probably be made to work,
463 // but why are you doing this? There's no good reason.
464 llvm_unreachable("repeat safepoint insertion is not supported");
466 case Intrinsic::gcroot:
467 // Currently, this mechanism hasn't been extended to work with gcroot.
468 // There's no reason it couldn't be, but I haven't thought about the
469 // implications much.
471 "interaction with the gcroot mechanism is not supported");
474 // We assume that functions in the source language only return base
475 // pointers. This should probably be generalized via attributes to support
476 // both source language and internal functions.
477 if (isa<CallInst>(I) || isa<InvokeInst>(I))
478 return BaseDefiningValueResult(I, true);
480 // I have absolutely no idea how to implement this part yet. It's not
481 // necessarily hard, I just haven't really looked at it yet.
482 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
484 if (isa<AtomicCmpXchgInst>(I))
485 // A CAS is effectively a atomic store and load combined under a
486 // predicate. From the perspective of base pointers, we just treat it
488 return BaseDefiningValueResult(I, true);
490 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
491 "binary ops which don't apply to pointers");
493 // The aggregate ops. Aggregates can either be in the heap or on the
494 // stack, but in either case, this is simply a field load. As a result,
495 // this is a defining definition of the base just like a load is.
496 if (isa<ExtractValueInst>(I))
497 return BaseDefiningValueResult(I, true);
499 // We should never see an insert vector since that would require we be
500 // tracing back a struct value not a pointer value.
501 assert(!isa<InsertValueInst>(I) &&
502 "Base pointer for a struct is meaningless");
504 // An extractelement produces a base result exactly when it's input does.
505 // We may need to insert a parallel instruction to extract the appropriate
506 // element out of the base vector corresponding to the input. Given this,
507 // it's analogous to the phi and select case even though it's not a merge.
508 if (isa<ExtractElementInst>(I))
509 // Note: There a lot of obvious peephole cases here. This are deliberately
510 // handled after the main base pointer inference algorithm to make writing
511 // test cases to exercise that code easier.
512 return BaseDefiningValueResult(I, false);
514 // The last two cases here don't return a base pointer. Instead, they
515 // return a value which dynamically selects from among several base
516 // derived pointers (each with it's own base potentially). It's the job of
517 // the caller to resolve these.
518 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
519 "missing instruction case in findBaseDefiningValing");
520 return BaseDefiningValueResult(I, false);
523 /// Returns the base defining value for this value.
524 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
525 Value *&Cached = Cache[I];
527 Cached = findBaseDefiningValue(I).BDV;
528 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
529 << Cached->getName() << "\n");
531 assert(Cache[I] != nullptr);
535 /// Return a base pointer for this value if known. Otherwise, return it's
536 /// base defining value.
537 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
538 Value *Def = findBaseDefiningValueCached(I, Cache);
539 auto Found = Cache.find(Def);
540 if (Found != Cache.end()) {
541 // Either a base-of relation, or a self reference. Caller must check.
542 return Found->second;
544 // Only a BDV available
548 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
549 /// is it known to be a base pointer? Or do we need to continue searching.
550 static bool isKnownBaseResult(Value *V) {
551 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
552 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
553 !isa<ShuffleVectorInst>(V)) {
554 // no recursion possible
557 if (isa<Instruction>(V) &&
558 cast<Instruction>(V)->getMetadata("is_base_value")) {
559 // This is a previously inserted base phi or select. We know
560 // that this is a base value.
564 // We need to keep searching
569 /// Models the state of a single base defining value in the findBasePointer
570 /// algorithm for determining where a new instruction is needed to propagate
571 /// the base of this BDV.
574 enum Status { Unknown, Base, Conflict };
576 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
577 assert(status != Base || b);
579 explicit BDVState(Value *b) : status(Base), base(b) {}
580 BDVState() : status(Unknown), base(nullptr) {}
582 Status getStatus() const { return status; }
583 Value *getBase() const { return base; }
585 bool isBase() const { return getStatus() == Base; }
586 bool isUnknown() const { return getStatus() == Unknown; }
587 bool isConflict() const { return getStatus() == Conflict; }
589 bool operator==(const BDVState &other) const {
590 return base == other.base && status == other.status;
593 bool operator!=(const BDVState &other) const { return !(*this == other); }
596 void dump() const { print(dbgs()); dbgs() << '\n'; }
598 void print(raw_ostream &OS) const {
610 OS << " (" << base << " - "
611 << (base ? base->getName() : "nullptr") << "): ";
616 Value *base; // non null only if status == base
621 static raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
628 // Values of type BDVState form a lattice, and this is a helper
629 // class that implementes the meet operation. The meat of the meet
630 // operation is implemented in MeetBDVStates::pureMeet
631 class MeetBDVStates {
633 /// Initializes the currentResult to the TOP state so that if can be met with
634 /// any other state to produce that state.
637 // Destructively meet the current result with the given BDVState
638 void meetWith(BDVState otherState) {
639 currentResult = meet(otherState, currentResult);
642 BDVState getResult() const { return currentResult; }
645 BDVState currentResult;
647 /// Perform a meet operation on two elements of the BDVState lattice.
648 static BDVState meet(BDVState LHS, BDVState RHS) {
649 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
650 "math is wrong: meet does not commute!");
651 BDVState Result = pureMeet(LHS, RHS);
652 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
653 << " produced " << Result << "\n");
657 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
658 switch (stateA.getStatus()) {
659 case BDVState::Unknown:
663 assert(stateA.getBase() && "can't be null");
664 if (stateB.isUnknown())
667 if (stateB.isBase()) {
668 if (stateA.getBase() == stateB.getBase()) {
669 assert(stateA == stateB && "equality broken!");
672 return BDVState(BDVState::Conflict);
674 assert(stateB.isConflict() && "only three states!");
675 return BDVState(BDVState::Conflict);
677 case BDVState::Conflict:
680 llvm_unreachable("only three states!");
686 /// For a given value or instruction, figure out what base ptr it's derived
687 /// from. For gc objects, this is simply itself. On success, returns a value
688 /// which is the base pointer. (This is reliable and can be used for
689 /// relocation.) On failure, returns nullptr.
690 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
691 Value *def = findBaseOrBDV(I, cache);
693 if (isKnownBaseResult(def)) {
697 // Here's the rough algorithm:
698 // - For every SSA value, construct a mapping to either an actual base
699 // pointer or a PHI which obscures the base pointer.
700 // - Construct a mapping from PHI to unknown TOP state. Use an
701 // optimistic algorithm to propagate base pointer information. Lattice
706 // When algorithm terminates, all PHIs will either have a single concrete
707 // base or be in a conflict state.
708 // - For every conflict, insert a dummy PHI node without arguments. Add
709 // these to the base[Instruction] = BasePtr mapping. For every
710 // non-conflict, add the actual base.
711 // - For every conflict, add arguments for the base[a] of each input
714 // Note: A simpler form of this would be to add the conflict form of all
715 // PHIs without running the optimistic algorithm. This would be
716 // analogous to pessimistic data flow and would likely lead to an
717 // overall worse solution.
720 auto isExpectedBDVType = [](Value *BDV) {
721 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
722 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV);
726 // Once populated, will contain a mapping from each potentially non-base BDV
727 // to a lattice value (described above) which corresponds to that BDV.
728 // We use the order of insertion (DFS over the def/use graph) to provide a
729 // stable deterministic ordering for visiting DenseMaps (which are unordered)
730 // below. This is important for deterministic compilation.
731 MapVector<Value *, BDVState> states;
733 // Recursively fill in all base defining values reachable from the initial
734 // one for which we don't already know a definite base value for
736 SmallVector<Value*, 16> Worklist;
737 Worklist.push_back(def);
738 states.insert(std::make_pair(def, BDVState()));
739 while (!Worklist.empty()) {
740 Value *Current = Worklist.pop_back_val();
741 assert(!isKnownBaseResult(Current) && "why did it get added?");
743 auto visitIncomingValue = [&](Value *InVal) {
744 Value *Base = findBaseOrBDV(InVal, cache);
745 if (isKnownBaseResult(Base))
746 // Known bases won't need new instructions introduced and can be
749 assert(isExpectedBDVType(Base) && "the only non-base values "
750 "we see should be base defining values");
751 if (states.insert(std::make_pair(Base, BDVState())).second)
752 Worklist.push_back(Base);
754 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
755 for (Value *InVal : Phi->incoming_values())
756 visitIncomingValue(InVal);
757 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
758 visitIncomingValue(Sel->getTrueValue());
759 visitIncomingValue(Sel->getFalseValue());
760 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
761 visitIncomingValue(EE->getVectorOperand());
762 } else if (auto *IE = dyn_cast<InsertElementInst>(Current)) {
763 visitIncomingValue(IE->getOperand(0)); // vector operand
764 visitIncomingValue(IE->getOperand(1)); // scalar operand
766 // There is one known class of instructions we know we don't handle.
767 assert(isa<ShuffleVectorInst>(Current));
768 llvm_unreachable("unimplemented instruction case");
774 DEBUG(dbgs() << "States after initialization:\n");
775 for (auto Pair : states) {
776 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
780 // Return a phi state for a base defining value. We'll generate a new
781 // base state for known bases and expect to find a cached state otherwise.
782 auto getStateForBDV = [&](Value *baseValue) {
783 if (isKnownBaseResult(baseValue))
784 return BDVState(baseValue);
785 auto I = states.find(baseValue);
786 assert(I != states.end() && "lookup failed!");
790 bool progress = true;
793 size_t oldSize = states.size();
796 // We're only changing values in this loop, thus safe to keep iterators.
797 // Since this is computing a fixed point, the order of visit does not
798 // effect the result. TODO: We could use a worklist here and make this run
800 for (auto Pair : states) {
801 Value *v = Pair.first;
802 assert(!isKnownBaseResult(v) && "why did it get added?");
804 // Given an input value for the current instruction, return a BDVState
805 // instance which represents the BDV of that value.
806 auto getStateForInput = [&](Value *V) mutable {
807 Value *BDV = findBaseOrBDV(V, cache);
808 return getStateForBDV(BDV);
811 MeetBDVStates calculateMeet;
812 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
813 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
814 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
815 } else if (PHINode *Phi = dyn_cast<PHINode>(v)) {
816 for (Value *Val : Phi->incoming_values())
817 calculateMeet.meetWith(getStateForInput(Val));
818 } else if (auto *EE = dyn_cast<ExtractElementInst>(v)) {
819 // The 'meet' for an extractelement is slightly trivial, but it's still
820 // useful in that it drives us to conflict if our input is.
821 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
823 // Given there's a inherent type mismatch between the operands, will
824 // *always* produce Conflict.
825 auto *IE = cast<InsertElementInst>(v);
826 calculateMeet.meetWith(getStateForInput(IE->getOperand(0)));
827 calculateMeet.meetWith(getStateForInput(IE->getOperand(1)));
830 BDVState oldState = states[v];
831 BDVState newState = calculateMeet.getResult();
832 if (oldState != newState) {
834 states[v] = newState;
838 assert(oldSize <= states.size());
839 assert(oldSize == states.size() || progress);
843 DEBUG(dbgs() << "States after meet iteration:\n");
844 for (auto Pair : states) {
845 DEBUG(dbgs() << " " << Pair.second << " for " << *Pair.first << "\n");
849 // Insert Phis for all conflicts
850 // TODO: adjust naming patterns to avoid this order of iteration dependency
851 for (auto Pair : states) {
852 Instruction *I = cast<Instruction>(Pair.first);
853 BDVState State = Pair.second;
854 assert(!isKnownBaseResult(I) && "why did it get added?");
855 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
857 // extractelement instructions are a bit special in that we may need to
858 // insert an extract even when we know an exact base for the instruction.
859 // The problem is that we need to convert from a vector base to a scalar
860 // base for the particular indice we're interested in.
861 if (State.isBase() && isa<ExtractElementInst>(I) &&
862 isa<VectorType>(State.getBase()->getType())) {
863 auto *EE = cast<ExtractElementInst>(I);
864 // TODO: In many cases, the new instruction is just EE itself. We should
865 // exploit this, but can't do it here since it would break the invariant
866 // about the BDV not being known to be a base.
867 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
868 EE->getIndexOperand(),
870 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
871 states[I] = BDVState(BDVState::Base, BaseInst);
874 // Since we're joining a vector and scalar base, they can never be the
875 // same. As a result, we should always see insert element having reached
876 // the conflict state.
877 if (isa<InsertElementInst>(I)) {
878 assert(State.isConflict());
881 if (!State.isConflict())
884 /// Create and insert a new instruction which will represent the base of
885 /// the given instruction 'I'.
886 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
887 if (isa<PHINode>(I)) {
888 BasicBlock *BB = I->getParent();
889 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
890 assert(NumPreds > 0 && "how did we reach here");
891 std::string Name = I->hasName() ?
892 (I->getName() + ".base").str() : "base_phi";
893 return PHINode::Create(I->getType(), NumPreds, Name, I);
894 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
895 // The undef will be replaced later
896 UndefValue *Undef = UndefValue::get(Sel->getType());
897 std::string Name = I->hasName() ?
898 (I->getName() + ".base").str() : "base_select";
899 return SelectInst::Create(Sel->getCondition(), Undef,
901 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
902 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
903 std::string Name = I->hasName() ?
904 (I->getName() + ".base").str() : "base_ee";
905 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
908 auto *IE = cast<InsertElementInst>(I);
909 UndefValue *VecUndef = UndefValue::get(IE->getOperand(0)->getType());
910 UndefValue *ScalarUndef = UndefValue::get(IE->getOperand(1)->getType());
911 std::string Name = I->hasName() ?
912 (I->getName() + ".base").str() : "base_ie";
913 return InsertElementInst::Create(VecUndef, ScalarUndef,
914 IE->getOperand(2), Name, IE);
918 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
919 // Add metadata marking this as a base value
920 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
921 states[I] = BDVState(BDVState::Conflict, BaseInst);
924 // Returns a instruction which produces the base pointer for a given
925 // instruction. The instruction is assumed to be an input to one of the BDVs
926 // seen in the inference algorithm above. As such, we must either already
927 // know it's base defining value is a base, or have inserted a new
928 // instruction to propagate the base of it's BDV and have entered that newly
929 // introduced instruction into the state table. In either case, we are
930 // assured to be able to determine an instruction which produces it's base
932 auto getBaseForInput = [&](Value *Input, Instruction *InsertPt) {
933 Value *BDV = findBaseOrBDV(Input, cache);
934 Value *Base = nullptr;
935 if (isKnownBaseResult(BDV)) {
938 // Either conflict or base.
939 assert(states.count(BDV));
940 Base = states[BDV].getBase();
942 assert(Base && "can't be null");
943 // The cast is needed since base traversal may strip away bitcasts
944 if (Base->getType() != Input->getType() &&
946 Base = new BitCastInst(Base, Input->getType(), "cast",
952 // Fixup all the inputs of the new PHIs. Visit order needs to be
953 // deterministic and predictable because we're naming newly created
955 for (auto Pair : states) {
956 Instruction *v = cast<Instruction>(Pair.first);
957 BDVState state = Pair.second;
959 assert(!isKnownBaseResult(v) && "why did it get added?");
960 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
961 if (!state.isConflict())
964 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
965 PHINode *phi = cast<PHINode>(v);
966 unsigned NumPHIValues = phi->getNumIncomingValues();
967 for (unsigned i = 0; i < NumPHIValues; i++) {
968 Value *InVal = phi->getIncomingValue(i);
969 BasicBlock *InBB = phi->getIncomingBlock(i);
971 // If we've already seen InBB, add the same incoming value
972 // we added for it earlier. The IR verifier requires phi
973 // nodes with multiple entries from the same basic block
974 // to have the same incoming value for each of those
975 // entries. If we don't do this check here and basephi
976 // has a different type than base, we'll end up adding two
977 // bitcasts (and hence two distinct values) as incoming
978 // values for the same basic block.
980 int blockIndex = basephi->getBasicBlockIndex(InBB);
981 if (blockIndex != -1) {
982 Value *oldBase = basephi->getIncomingValue(blockIndex);
983 basephi->addIncoming(oldBase, InBB);
986 Value *Base = getBaseForInput(InVal, nullptr);
987 // In essence this assert states: the only way two
988 // values incoming from the same basic block may be
989 // different is by being different bitcasts of the same
990 // value. A cleanup that remains TODO is changing
991 // findBaseOrBDV to return an llvm::Value of the correct
992 // type (and still remain pure). This will remove the
993 // need to add bitcasts.
994 assert(Base->stripPointerCasts() == oldBase->stripPointerCasts() &&
995 "sanity -- findBaseOrBDV should be pure!");
1000 // Find the instruction which produces the base for each input. We may
1001 // need to insert a bitcast in the incoming block.
1002 // TODO: Need to split critical edges if insertion is needed
1003 Value *Base = getBaseForInput(InVal, InBB->getTerminator());
1004 basephi->addIncoming(Base, InBB);
1006 assert(basephi->getNumIncomingValues() == NumPHIValues);
1007 } else if (SelectInst *BaseSel = dyn_cast<SelectInst>(state.getBase())) {
1008 SelectInst *Sel = cast<SelectInst>(v);
1009 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
1010 // something more safe and less hacky.
1011 for (int i = 1; i <= 2; i++) {
1012 Value *InVal = Sel->getOperand(i);
1013 // Find the instruction which produces the base for each input. We may
1014 // need to insert a bitcast.
1015 Value *Base = getBaseForInput(InVal, BaseSel);
1016 BaseSel->setOperand(i, Base);
1018 } else if (auto *BaseEE = dyn_cast<ExtractElementInst>(state.getBase())) {
1019 Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
1020 // Find the instruction which produces the base for each input. We may
1021 // need to insert a bitcast.
1022 Value *Base = getBaseForInput(InVal, BaseEE);
1023 BaseEE->setOperand(0, Base);
1025 auto *BaseIE = cast<InsertElementInst>(state.getBase());
1026 auto *BdvIE = cast<InsertElementInst>(v);
1027 auto UpdateOperand = [&](int OperandIdx) {
1028 Value *InVal = BdvIE->getOperand(OperandIdx);
1029 Value *Base = findBaseOrBDV(InVal, cache);
1030 if (!isKnownBaseResult(Base)) {
1031 // Either conflict or base.
1032 assert(states.count(Base));
1033 Base = states[Base].getBase();
1034 assert(Base != nullptr && "unknown BDVState!");
1036 assert(Base && "can't be null");
1037 BaseIE->setOperand(OperandIdx, Base);
1039 UpdateOperand(0); // vector operand
1040 UpdateOperand(1); // scalar operand
1045 // Now that we're done with the algorithm, see if we can optimize the
1046 // results slightly by reducing the number of new instructions needed.
1047 // Arguably, this should be integrated into the algorithm above, but
1048 // doing as a post process step is easier to reason about for the moment.
1049 DenseMap<Value *, Value *> ReverseMap;
1050 SmallPtrSet<Instruction *, 16> NewInsts;
1051 SmallSetVector<AssertingVH<Instruction>, 16> Worklist;
1052 // Note: We need to visit the states in a deterministic order. We uses the
1053 // Keys we sorted above for this purpose. Note that we are papering over a
1054 // bigger problem with the algorithm above - it's visit order is not
1055 // deterministic. A larger change is needed to fix this.
1056 for (auto Pair : states) {
1057 auto *BDV = Pair.first;
1058 auto State = Pair.second;
1059 Value *Base = State.getBase();
1060 assert(BDV && Base);
1061 assert(!isKnownBaseResult(BDV) && "why did it get added?");
1062 assert(isKnownBaseResult(Base) &&
1063 "must be something we 'know' is a base pointer");
1064 if (!State.isConflict())
1067 ReverseMap[Base] = BDV;
1068 if (auto *BaseI = dyn_cast<Instruction>(Base)) {
1069 NewInsts.insert(BaseI);
1070 Worklist.insert(BaseI);
1073 auto ReplaceBaseInstWith = [&](Value *BDV, Instruction *BaseI,
1074 Value *Replacement) {
1075 // Add users which are new instructions (excluding self references)
1076 for (User *U : BaseI->users())
1077 if (auto *UI = dyn_cast<Instruction>(U))
1078 if (NewInsts.count(UI) && UI != BaseI)
1079 Worklist.insert(UI);
1080 // Then do the actual replacement
1081 NewInsts.erase(BaseI);
1082 ReverseMap.erase(BaseI);
1083 BaseI->replaceAllUsesWith(Replacement);
1084 BaseI->eraseFromParent();
1085 assert(states.count(BDV));
1086 assert(states[BDV].isConflict() && states[BDV].getBase() == BaseI);
1087 states[BDV] = BDVState(BDVState::Conflict, Replacement);
1089 const DataLayout &DL = cast<Instruction>(def)->getModule()->getDataLayout();
1090 while (!Worklist.empty()) {
1091 Instruction *BaseI = Worklist.pop_back_val();
1092 assert(NewInsts.count(BaseI));
1093 Value *Bdv = ReverseMap[BaseI];
1094 if (auto *BdvI = dyn_cast<Instruction>(Bdv))
1095 if (BaseI->isIdenticalTo(BdvI)) {
1096 DEBUG(dbgs() << "Identical Base: " << *BaseI << "\n");
1097 ReplaceBaseInstWith(Bdv, BaseI, Bdv);
1100 if (Value *V = SimplifyInstruction(BaseI, DL)) {
1101 DEBUG(dbgs() << "Base " << *BaseI << " simplified to " << *V << "\n");
1102 ReplaceBaseInstWith(Bdv, BaseI, V);
1107 // Cache all of our results so we can cheaply reuse them
1108 // NOTE: This is actually two caches: one of the base defining value
1109 // relation and one of the base pointer relation! FIXME
1110 for (auto Pair : states) {
1111 auto *BDV = Pair.first;
1112 Value *base = Pair.second.getBase();
1113 assert(BDV && base);
1115 std::string fromstr =
1116 cache.count(BDV) ? (cache[BDV]->hasName() ? cache[BDV]->getName() : "")
1118 DEBUG(dbgs() << "Updating base value cache"
1119 << " for: " << (BDV->hasName() ? BDV->getName() : "")
1120 << " from: " << fromstr
1121 << " to: " << (base->hasName() ? base->getName() : "") << "\n");
1123 if (cache.count(BDV)) {
1124 // Once we transition from the BDV relation being store in the cache to
1125 // the base relation being stored, it must be stable
1126 assert((!isKnownBaseResult(cache[BDV]) || cache[BDV] == base) &&
1127 "base relation should be stable");
1131 assert(cache.find(def) != cache.end());
1135 // For a set of live pointers (base and/or derived), identify the base
1136 // pointer of the object which they are derived from. This routine will
1137 // mutate the IR graph as needed to make the 'base' pointer live at the
1138 // definition site of 'derived'. This ensures that any use of 'derived' can
1139 // also use 'base'. This may involve the insertion of a number of
1140 // additional PHI nodes.
1142 // preconditions: live is a set of pointer type Values
1144 // side effects: may insert PHI nodes into the existing CFG, will preserve
1145 // CFG, will not remove or mutate any existing nodes
1147 // post condition: PointerToBase contains one (derived, base) pair for every
1148 // pointer in live. Note that derived can be equal to base if the original
1149 // pointer was a base pointer.
1151 findBasePointers(const StatepointLiveSetTy &live,
1152 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
1153 DominatorTree *DT, DefiningValueMapTy &DVCache) {
1154 // For the naming of values inserted to be deterministic - which makes for
1155 // much cleaner and more stable tests - we need to assign an order to the
1156 // live values. DenseSets do not provide a deterministic order across runs.
1157 SmallVector<Value *, 64> Temp;
1158 Temp.insert(Temp.end(), live.begin(), live.end());
1159 std::sort(Temp.begin(), Temp.end(), order_by_name);
1160 for (Value *ptr : Temp) {
1161 Value *base = findBasePointer(ptr, DVCache);
1162 assert(base && "failed to find base pointer");
1163 PointerToBase[ptr] = base;
1164 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1165 DT->dominates(cast<Instruction>(base)->getParent(),
1166 cast<Instruction>(ptr)->getParent())) &&
1167 "The base we found better dominate the derived pointer");
1169 // If you see this trip and like to live really dangerously, the code should
1170 // be correct, just with idioms the verifier can't handle. You can try
1171 // disabling the verifier at your own substantial risk.
1172 assert(!isa<ConstantPointerNull>(base) &&
1173 "the relocation code needs adjustment to handle the relocation of "
1174 "a null pointer constant without causing false positives in the "
1175 "safepoint ir verifier.");
1179 /// Find the required based pointers (and adjust the live set) for the given
1181 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1183 PartiallyConstructedSafepointRecord &result) {
1184 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1185 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
1187 if (PrintBasePointers) {
1188 // Note: Need to print these in a stable order since this is checked in
1190 errs() << "Base Pairs (w/o Relocation):\n";
1191 SmallVector<Value *, 64> Temp;
1192 Temp.reserve(PointerToBase.size());
1193 for (auto Pair : PointerToBase) {
1194 Temp.push_back(Pair.first);
1196 std::sort(Temp.begin(), Temp.end(), order_by_name);
1197 for (Value *Ptr : Temp) {
1198 Value *Base = PointerToBase[Ptr];
1199 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1204 result.PointerToBase = PointerToBase;
1207 /// Given an updated version of the dataflow liveness results, update the
1208 /// liveset and base pointer maps for the call site CS.
1209 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1211 PartiallyConstructedSafepointRecord &result);
1213 static void recomputeLiveInValues(
1214 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1215 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1216 // TODO-PERF: reuse the original liveness, then simply run the dataflow
1217 // again. The old values are still live and will help it stabilize quickly.
1218 GCPtrLivenessData RevisedLivenessData;
1219 computeLiveInValues(DT, F, RevisedLivenessData);
1220 for (size_t i = 0; i < records.size(); i++) {
1221 struct PartiallyConstructedSafepointRecord &info = records[i];
1222 const CallSite &CS = toUpdate[i];
1223 recomputeLiveInValues(RevisedLivenessData, CS, info);
1227 // When inserting gc.relocate calls, we need to ensure there are no uses
1228 // of the original value between the gc.statepoint and the gc.relocate call.
1229 // One case which can arise is a phi node starting one of the successor blocks.
1230 // We also need to be able to insert the gc.relocates only on the path which
1231 // goes through the statepoint. We might need to split an edge to make this
1234 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1235 DominatorTree &DT) {
1236 BasicBlock *Ret = BB;
1237 if (!BB->getUniquePredecessor()) {
1238 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1241 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1243 FoldSingleEntryPHINodes(Ret);
1244 assert(!isa<PHINode>(Ret->begin()));
1246 // At this point, we can safely insert a gc.relocate as the first instruction
1247 // in Ret if needed.
1251 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1252 auto itr = std::find(livevec.begin(), livevec.end(), val);
1253 assert(livevec.end() != itr);
1254 size_t index = std::distance(livevec.begin(), itr);
1255 assert(index < livevec.size());
1259 // Create new attribute set containing only attributes which can be transferred
1260 // from original call to the safepoint.
1261 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1264 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1265 unsigned index = AS.getSlotIndex(Slot);
1267 if (index == AttributeSet::ReturnIndex ||
1268 index == AttributeSet::FunctionIndex) {
1270 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1272 Attribute attr = *it;
1274 // Do not allow certain attributes - just skip them
1275 // Safepoint can not be read only or read none.
1276 if (attr.hasAttribute(Attribute::ReadNone) ||
1277 attr.hasAttribute(Attribute::ReadOnly))
1280 ret = ret.addAttributes(
1281 AS.getContext(), index,
1282 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1286 // Just skip parameter attributes for now
1292 /// Helper function to place all gc relocates necessary for the given
1295 /// liveVariables - list of variables to be relocated.
1296 /// liveStart - index of the first live variable.
1297 /// basePtrs - base pointers.
1298 /// statepointToken - statepoint instruction to which relocates should be
1300 /// Builder - Llvm IR builder to be used to construct new calls.
1301 static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1302 const int LiveStart,
1303 ArrayRef<llvm::Value *> BasePtrs,
1304 Instruction *StatepointToken,
1305 IRBuilder<> Builder) {
1306 if (LiveVariables.empty())
1309 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1310 // unique declarations for each pointer type, but this proved problematic
1311 // because the intrinsic mangling code is incomplete and fragile. Since
1312 // we're moving towards a single unified pointer type anyways, we can just
1313 // cast everything to an i8* of the right address space. A bitcast is added
1314 // later to convert gc_relocate to the actual value's type.
1315 Module *M = StatepointToken->getModule();
1316 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1317 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1318 Value *GCRelocateDecl =
1319 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
1321 for (unsigned i = 0; i < LiveVariables.size(); i++) {
1322 // Generate the gc.relocate call and save the result
1324 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1326 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
1328 // only specify a debug name if we can give a useful one
1329 CallInst *Reloc = Builder.CreateCall(
1330 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1331 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
1333 // Trick CodeGen into thinking there are lots of free registers at this
1335 Reloc->setCallingConv(CallingConv::Cold);
1340 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1341 const SmallVectorImpl<llvm::Value *> &basePtrs,
1342 const SmallVectorImpl<llvm::Value *> &liveVariables,
1344 PartiallyConstructedSafepointRecord &result) {
1345 assert(basePtrs.size() == liveVariables.size());
1346 assert(isStatepoint(CS) &&
1347 "This method expects to be rewriting a statepoint");
1349 BasicBlock *BB = CS.getInstruction()->getParent();
1351 Function *F = BB->getParent();
1352 assert(F && "must be set");
1353 Module *M = F->getParent();
1355 assert(M && "must be set");
1357 // We're not changing the function signature of the statepoint since the gc
1358 // arguments go into the var args section.
1359 Function *gc_statepoint_decl = CS.getCalledFunction();
1361 // Then go ahead and use the builder do actually do the inserts. We insert
1362 // immediately before the previous instruction under the assumption that all
1363 // arguments will be available here. We can't insert afterwards since we may
1364 // be replacing a terminator.
1365 Instruction *insertBefore = CS.getInstruction();
1366 IRBuilder<> Builder(insertBefore);
1367 // Copy all of the arguments from the original statepoint - this includes the
1368 // target, call args, and deopt args
1369 SmallVector<llvm::Value *, 64> args;
1370 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1371 // TODO: Clear the 'needs rewrite' flag
1373 // add all the pointers to be relocated (gc arguments)
1374 // Capture the start of the live variable list for use in the gc_relocates
1375 const int live_start = args.size();
1376 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1378 // Create the statepoint given all the arguments
1379 Instruction *token = nullptr;
1380 AttributeSet return_attributes;
1382 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1384 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1385 call->setTailCall(toReplace->isTailCall());
1386 call->setCallingConv(toReplace->getCallingConv());
1388 // Currently we will fail on parameter attributes and on certain
1389 // function attributes.
1390 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1391 // In case if we can handle this set of attributes - set up function attrs
1392 // directly on statepoint and return attrs later for gc_result intrinsic.
1393 call->setAttributes(new_attrs.getFnAttributes());
1394 return_attributes = new_attrs.getRetAttributes();
1398 // Put the following gc_result and gc_relocate calls immediately after the
1399 // the old call (which we're about to delete)
1400 BasicBlock::iterator next(toReplace);
1401 assert(BB->end() != next && "not a terminator, must have next");
1403 Instruction *IP = &*(next);
1404 Builder.SetInsertPoint(IP);
1405 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1408 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1410 // Insert the new invoke into the old block. We'll remove the old one in a
1411 // moment at which point this will become the new terminator for the
1413 InvokeInst *invoke = InvokeInst::Create(
1414 gc_statepoint_decl, toReplace->getNormalDest(),
1415 toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
1416 invoke->setCallingConv(toReplace->getCallingConv());
1418 // Currently we will fail on parameter attributes and on certain
1419 // function attributes.
1420 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1421 // In case if we can handle this set of attributes - set up function attrs
1422 // directly on statepoint and return attrs later for gc_result intrinsic.
1423 invoke->setAttributes(new_attrs.getFnAttributes());
1424 return_attributes = new_attrs.getRetAttributes();
1428 // Generate gc relocates in exceptional path
1429 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1430 assert(!isa<PHINode>(unwindBlock->begin()) &&
1431 unwindBlock->getUniquePredecessor() &&
1432 "can't safely insert in this block!");
1434 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1435 Builder.SetInsertPoint(IP);
1436 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1438 // Extract second element from landingpad return value. We will attach
1439 // exceptional gc relocates to it.
1440 const unsigned idx = 1;
1441 Instruction *exceptional_token =
1442 cast<Instruction>(Builder.CreateExtractValue(
1443 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1444 result.UnwindToken = exceptional_token;
1446 CreateGCRelocates(liveVariables, live_start, basePtrs,
1447 exceptional_token, Builder);
1449 // Generate gc relocates and returns for normal block
1450 BasicBlock *normalDest = toReplace->getNormalDest();
1451 assert(!isa<PHINode>(normalDest->begin()) &&
1452 normalDest->getUniquePredecessor() &&
1453 "can't safely insert in this block!");
1455 IP = &*(normalDest->getFirstInsertionPt());
1456 Builder.SetInsertPoint(IP);
1458 // gc relocates will be generated later as if it were regular call
1463 // Take the name of the original value call if it had one.
1464 token->takeName(CS.getInstruction());
1466 // The GCResult is already inserted, we just need to find it
1468 Instruction *toReplace = CS.getInstruction();
1469 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1470 "only valid use before rewrite is gc.result");
1471 assert(!toReplace->hasOneUse() ||
1472 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1475 // Update the gc.result of the original statepoint (if any) to use the newly
1476 // inserted statepoint. This is safe to do here since the token can't be
1477 // considered a live reference.
1478 CS.getInstruction()->replaceAllUsesWith(token);
1480 result.StatepointToken = token;
1482 // Second, create a gc.relocate for every live variable
1483 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1487 struct name_ordering {
1490 bool operator()(name_ordering const &a, name_ordering const &b) {
1491 return -1 == a.derived->getName().compare(b.derived->getName());
1495 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1496 SmallVectorImpl<Value *> &livevec) {
1497 assert(basevec.size() == livevec.size());
1499 SmallVector<name_ordering, 64> temp;
1500 for (size_t i = 0; i < basevec.size(); i++) {
1502 v.base = basevec[i];
1503 v.derived = livevec[i];
1506 std::sort(temp.begin(), temp.end(), name_ordering());
1507 for (size_t i = 0; i < basevec.size(); i++) {
1508 basevec[i] = temp[i].base;
1509 livevec[i] = temp[i].derived;
1513 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1514 // which make the relocations happening at this safepoint explicit.
1516 // WARNING: Does not do any fixup to adjust users of the original live
1517 // values. That's the callers responsibility.
1519 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1520 PartiallyConstructedSafepointRecord &result) {
1521 auto liveset = result.liveset;
1522 auto PointerToBase = result.PointerToBase;
1524 // Convert to vector for efficient cross referencing.
1525 SmallVector<Value *, 64> basevec, livevec;
1526 livevec.reserve(liveset.size());
1527 basevec.reserve(liveset.size());
1528 for (Value *L : liveset) {
1529 livevec.push_back(L);
1530 assert(PointerToBase.count(L));
1531 Value *base = PointerToBase[L];
1532 basevec.push_back(base);
1534 assert(livevec.size() == basevec.size());
1536 // To make the output IR slightly more stable (for use in diffs), ensure a
1537 // fixed order of the values in the safepoint (by sorting the value name).
1538 // The order is otherwise meaningless.
1539 stablize_order(basevec, livevec);
1541 // Do the actual rewriting and delete the old statepoint
1542 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1543 CS.getInstruction()->eraseFromParent();
1546 // Helper function for the relocationViaAlloca.
1547 // It receives iterator to the statepoint gc relocates and emits store to the
1549 // location (via allocaMap) for the each one of them.
1550 // Add visited values into the visitedLiveValues set we will later use them
1551 // for sanity check.
1553 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1554 DenseMap<Value *, Value *> &AllocaMap,
1555 DenseSet<Value *> &VisitedLiveValues) {
1557 for (User *U : GCRelocs) {
1558 if (!isa<IntrinsicInst>(U))
1561 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
1563 // We only care about relocates
1564 if (RelocatedValue->getIntrinsicID() !=
1565 Intrinsic::experimental_gc_relocate) {
1569 GCRelocateOperands RelocateOperands(RelocatedValue);
1570 Value *OriginalValue =
1571 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1572 assert(AllocaMap.count(OriginalValue));
1573 Value *Alloca = AllocaMap[OriginalValue];
1575 // Emit store into the related alloca
1576 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1577 // the correct type according to alloca.
1578 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1579 IRBuilder<> Builder(RelocatedValue->getNextNode());
1580 Value *CastedRelocatedValue =
1581 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1582 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
1584 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1585 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1588 VisitedLiveValues.insert(OriginalValue);
1593 // Helper function for the "relocationViaAlloca". Similar to the
1594 // "insertRelocationStores" but works for rematerialized values.
1596 insertRematerializationStores(
1597 RematerializedValueMapTy RematerializedValues,
1598 DenseMap<Value *, Value *> &AllocaMap,
1599 DenseSet<Value *> &VisitedLiveValues) {
1601 for (auto RematerializedValuePair: RematerializedValues) {
1602 Instruction *RematerializedValue = RematerializedValuePair.first;
1603 Value *OriginalValue = RematerializedValuePair.second;
1605 assert(AllocaMap.count(OriginalValue) &&
1606 "Can not find alloca for rematerialized value");
1607 Value *Alloca = AllocaMap[OriginalValue];
1609 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1610 Store->insertAfter(RematerializedValue);
1613 VisitedLiveValues.insert(OriginalValue);
1618 /// do all the relocation update via allocas and mem2reg
1619 static void relocationViaAlloca(
1620 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1621 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
1623 // record initial number of (static) allocas; we'll check we have the same
1624 // number when we get done.
1625 int InitialAllocaNum = 0;
1626 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1628 if (isa<AllocaInst>(*I))
1632 // TODO-PERF: change data structures, reserve
1633 DenseMap<Value *, Value *> AllocaMap;
1634 SmallVector<AllocaInst *, 200> PromotableAllocas;
1635 // Used later to chack that we have enough allocas to store all values
1636 std::size_t NumRematerializedValues = 0;
1637 PromotableAllocas.reserve(Live.size());
1639 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1640 // "PromotableAllocas"
1641 auto emitAllocaFor = [&](Value *LiveValue) {
1642 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1643 F.getEntryBlock().getFirstNonPHI());
1644 AllocaMap[LiveValue] = Alloca;
1645 PromotableAllocas.push_back(Alloca);
1648 // emit alloca for each live gc pointer
1649 for (unsigned i = 0; i < Live.size(); i++) {
1650 emitAllocaFor(Live[i]);
1653 // emit allocas for rematerialized values
1654 for (size_t i = 0; i < Records.size(); i++) {
1655 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1657 for (auto RematerializedValuePair : Info.RematerializedValues) {
1658 Value *OriginalValue = RematerializedValuePair.second;
1659 if (AllocaMap.count(OriginalValue) != 0)
1662 emitAllocaFor(OriginalValue);
1663 ++NumRematerializedValues;
1667 // The next two loops are part of the same conceptual operation. We need to
1668 // insert a store to the alloca after the original def and at each
1669 // redefinition. We need to insert a load before each use. These are split
1670 // into distinct loops for performance reasons.
1672 // update gc pointer after each statepoint
1673 // either store a relocated value or null (if no relocated value found for
1674 // this gc pointer and it is not a gc_result)
1675 // this must happen before we update the statepoint with load of alloca
1676 // otherwise we lose the link between statepoint and old def
1677 for (size_t i = 0; i < Records.size(); i++) {
1678 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1679 Value *Statepoint = Info.StatepointToken;
1681 // This will be used for consistency check
1682 DenseSet<Value *> VisitedLiveValues;
1684 // Insert stores for normal statepoint gc relocates
1685 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1687 // In case if it was invoke statepoint
1688 // we will insert stores for exceptional path gc relocates.
1689 if (isa<InvokeInst>(Statepoint)) {
1690 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1694 // Do similar thing with rematerialized values
1695 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1698 if (ClobberNonLive) {
1699 // As a debugging aid, pretend that an unrelocated pointer becomes null at
1700 // the gc.statepoint. This will turn some subtle GC problems into
1701 // slightly easier to debug SEGVs. Note that on large IR files with
1702 // lots of gc.statepoints this is extremely costly both memory and time
1704 SmallVector<AllocaInst *, 64> ToClobber;
1705 for (auto Pair : AllocaMap) {
1706 Value *Def = Pair.first;
1707 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1709 // This value was relocated
1710 if (VisitedLiveValues.count(Def)) {
1713 ToClobber.push_back(Alloca);
1716 auto InsertClobbersAt = [&](Instruction *IP) {
1717 for (auto *AI : ToClobber) {
1718 auto AIType = cast<PointerType>(AI->getType());
1719 auto PT = cast<PointerType>(AIType->getElementType());
1720 Constant *CPN = ConstantPointerNull::get(PT);
1721 StoreInst *Store = new StoreInst(CPN, AI);
1722 Store->insertBefore(IP);
1726 // Insert the clobbering stores. These may get intermixed with the
1727 // gc.results and gc.relocates, but that's fine.
1728 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1729 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1730 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1732 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1734 InsertClobbersAt(Next);
1738 // update use with load allocas and add store for gc_relocated
1739 for (auto Pair : AllocaMap) {
1740 Value *Def = Pair.first;
1741 Value *Alloca = Pair.second;
1743 // we pre-record the uses of allocas so that we dont have to worry about
1745 // that change the user information.
1746 SmallVector<Instruction *, 20> Uses;
1747 // PERF: trade a linear scan for repeated reallocation
1748 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1749 for (User *U : Def->users()) {
1750 if (!isa<ConstantExpr>(U)) {
1751 // If the def has a ConstantExpr use, then the def is either a
1752 // ConstantExpr use itself or null. In either case
1753 // (recursively in the first, directly in the second), the oop
1754 // it is ultimately dependent on is null and this particular
1755 // use does not need to be fixed up.
1756 Uses.push_back(cast<Instruction>(U));
1760 std::sort(Uses.begin(), Uses.end());
1761 auto Last = std::unique(Uses.begin(), Uses.end());
1762 Uses.erase(Last, Uses.end());
1764 for (Instruction *Use : Uses) {
1765 if (isa<PHINode>(Use)) {
1766 PHINode *Phi = cast<PHINode>(Use);
1767 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1768 if (Def == Phi->getIncomingValue(i)) {
1769 LoadInst *Load = new LoadInst(
1770 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1771 Phi->setIncomingValue(i, Load);
1775 LoadInst *Load = new LoadInst(Alloca, "", Use);
1776 Use->replaceUsesOfWith(Def, Load);
1780 // emit store for the initial gc value
1781 // store must be inserted after load, otherwise store will be in alloca's
1782 // use list and an extra load will be inserted before it
1783 StoreInst *Store = new StoreInst(Def, Alloca);
1784 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1785 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1786 // InvokeInst is a TerminatorInst so the store need to be inserted
1787 // into its normal destination block.
1788 BasicBlock *NormalDest = Invoke->getNormalDest();
1789 Store->insertBefore(NormalDest->getFirstNonPHI());
1791 assert(!Inst->isTerminator() &&
1792 "The only TerminatorInst that can produce a value is "
1793 "InvokeInst which is handled above.");
1794 Store->insertAfter(Inst);
1797 assert(isa<Argument>(Def));
1798 Store->insertAfter(cast<Instruction>(Alloca));
1802 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1803 "we must have the same allocas with lives");
1804 if (!PromotableAllocas.empty()) {
1805 // apply mem2reg to promote alloca to SSA
1806 PromoteMemToReg(PromotableAllocas, DT);
1810 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1812 if (isa<AllocaInst>(*I))
1814 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1818 /// Implement a unique function which doesn't require we sort the input
1819 /// vector. Doing so has the effect of changing the output of a couple of
1820 /// tests in ways which make them less useful in testing fused safepoints.
1821 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1822 SmallSet<T, 8> Seen;
1823 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1824 return !Seen.insert(V).second;
1828 /// Insert holders so that each Value is obviously live through the entire
1829 /// lifetime of the call.
1830 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1831 SmallVectorImpl<CallInst *> &Holders) {
1833 // No values to hold live, might as well not insert the empty holder
1836 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1837 // Use a dummy vararg function to actually hold the values live
1838 Function *Func = cast<Function>(M->getOrInsertFunction(
1839 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1841 // For call safepoints insert dummy calls right after safepoint
1842 BasicBlock::iterator Next(CS.getInstruction());
1844 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1847 // For invoke safepooints insert dummy calls both in normal and
1848 // exceptional destination blocks
1849 auto *II = cast<InvokeInst>(CS.getInstruction());
1850 Holders.push_back(CallInst::Create(
1851 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1852 Holders.push_back(CallInst::Create(
1853 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
1856 static void findLiveReferences(
1857 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1858 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1859 GCPtrLivenessData OriginalLivenessData;
1860 computeLiveInValues(DT, F, OriginalLivenessData);
1861 for (size_t i = 0; i < records.size(); i++) {
1862 struct PartiallyConstructedSafepointRecord &info = records[i];
1863 const CallSite &CS = toUpdate[i];
1864 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1868 /// Remove any vector of pointers from the liveset by scalarizing them over the
1869 /// statepoint instruction. Adds the scalarized pieces to the liveset. It
1870 /// would be preferable to include the vector in the statepoint itself, but
1871 /// the lowering code currently does not handle that. Extending it would be
1872 /// slightly non-trivial since it requires a format change. Given how rare
1873 /// such cases are (for the moment?) scalarizing is an acceptable compromise.
1874 static void splitVectorValues(Instruction *StatepointInst,
1875 StatepointLiveSetTy &LiveSet,
1876 DenseMap<Value *, Value *>& PointerToBase,
1877 DominatorTree &DT) {
1878 SmallVector<Value *, 16> ToSplit;
1879 for (Value *V : LiveSet)
1880 if (isa<VectorType>(V->getType()))
1881 ToSplit.push_back(V);
1883 if (ToSplit.empty())
1886 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1888 Function &F = *(StatepointInst->getParent()->getParent());
1890 DenseMap<Value *, AllocaInst *> AllocaMap;
1891 // First is normal return, second is exceptional return (invoke only)
1892 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1893 for (Value *V : ToSplit) {
1894 AllocaInst *Alloca =
1895 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1896 AllocaMap[V] = Alloca;
1898 VectorType *VT = cast<VectorType>(V->getType());
1899 IRBuilder<> Builder(StatepointInst);
1900 SmallVector<Value *, 16> Elements;
1901 for (unsigned i = 0; i < VT->getNumElements(); i++)
1902 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1903 ElementMapping[V] = Elements;
1905 auto InsertVectorReform = [&](Instruction *IP) {
1906 Builder.SetInsertPoint(IP);
1907 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1908 Value *ResultVec = UndefValue::get(VT);
1909 for (unsigned i = 0; i < VT->getNumElements(); i++)
1910 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1911 Builder.getInt32(i));
1915 if (isa<CallInst>(StatepointInst)) {
1916 BasicBlock::iterator Next(StatepointInst);
1918 Instruction *IP = &*(Next);
1919 Replacements[V].first = InsertVectorReform(IP);
1920 Replacements[V].second = nullptr;
1922 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1923 // We've already normalized - check that we don't have shared destination
1925 BasicBlock *NormalDest = Invoke->getNormalDest();
1926 assert(!isa<PHINode>(NormalDest->begin()));
1927 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1928 assert(!isa<PHINode>(UnwindDest->begin()));
1929 // Insert insert element sequences in both successors
1930 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1931 Replacements[V].first = InsertVectorReform(IP);
1932 IP = &*(UnwindDest->getFirstInsertionPt());
1933 Replacements[V].second = InsertVectorReform(IP);
1937 for (Value *V : ToSplit) {
1938 AllocaInst *Alloca = AllocaMap[V];
1940 // Capture all users before we start mutating use lists
1941 SmallVector<Instruction *, 16> Users;
1942 for (User *U : V->users())
1943 Users.push_back(cast<Instruction>(U));
1945 for (Instruction *I : Users) {
1946 if (auto Phi = dyn_cast<PHINode>(I)) {
1947 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1948 if (V == Phi->getIncomingValue(i)) {
1949 LoadInst *Load = new LoadInst(
1950 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1951 Phi->setIncomingValue(i, Load);
1954 LoadInst *Load = new LoadInst(Alloca, "", I);
1955 I->replaceUsesOfWith(V, Load);
1959 // Store the original value and the replacement value into the alloca
1960 StoreInst *Store = new StoreInst(V, Alloca);
1961 if (auto I = dyn_cast<Instruction>(V))
1962 Store->insertAfter(I);
1964 Store->insertAfter(Alloca);
1966 // Normal return for invoke, or call return
1967 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1968 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1969 // Unwind return for invoke only
1970 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1972 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1975 // apply mem2reg to promote alloca to SSA
1976 SmallVector<AllocaInst *, 16> Allocas;
1977 for (Value *V : ToSplit)
1978 Allocas.push_back(AllocaMap[V]);
1979 PromoteMemToReg(Allocas, DT);
1981 // Update our tracking of live pointers and base mappings to account for the
1982 // changes we just made.
1983 for (Value *V : ToSplit) {
1984 auto &Elements = ElementMapping[V];
1987 LiveSet.insert(Elements.begin(), Elements.end());
1988 // We need to update the base mapping as well.
1989 assert(PointerToBase.count(V));
1990 Value *OldBase = PointerToBase[V];
1991 auto &BaseElements = ElementMapping[OldBase];
1992 PointerToBase.erase(V);
1993 assert(Elements.size() == BaseElements.size());
1994 for (unsigned i = 0; i < Elements.size(); i++) {
1995 Value *Elem = Elements[i];
1996 PointerToBase[Elem] = BaseElements[i];
2001 // Helper function for the "rematerializeLiveValues". It walks use chain
2002 // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
2003 // values are visited (currently it is GEP's and casts). Returns true if it
2004 // successfully reached "BaseValue" and false otherwise.
2005 // Fills "ChainToBase" array with all visited values. "BaseValue" is not
2007 static bool findRematerializableChainToBasePointer(
2008 SmallVectorImpl<Instruction*> &ChainToBase,
2009 Value *CurrentValue, Value *BaseValue) {
2011 // We have found a base value
2012 if (CurrentValue == BaseValue) {
2016 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
2017 ChainToBase.push_back(GEP);
2018 return findRematerializableChainToBasePointer(ChainToBase,
2019 GEP->getPointerOperand(),
2023 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
2024 Value *Def = CI->stripPointerCasts();
2026 // This two checks are basically similar. First one is here for the
2027 // consistency with findBasePointers logic.
2028 assert(!isa<CastInst>(Def) && "not a pointer cast found");
2029 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
2032 ChainToBase.push_back(CI);
2033 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
2036 // Not supported instruction in the chain
2040 // Helper function for the "rematerializeLiveValues". Compute cost of the use
2041 // chain we are going to rematerialize.
2043 chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
2044 TargetTransformInfo &TTI) {
2047 for (Instruction *Instr : Chain) {
2048 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
2049 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
2050 "non noop cast is found during rematerialization");
2052 Type *SrcTy = CI->getOperand(0)->getType();
2053 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
2055 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
2056 // Cost of the address calculation
2057 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
2058 Cost += TTI.getAddressComputationCost(ValTy);
2060 // And cost of the GEP itself
2061 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
2062 // allowed for the external usage)
2063 if (!GEP->hasAllConstantIndices())
2067 llvm_unreachable("unsupported instruciton type during rematerialization");
2074 // From the statepoint liveset pick values that are cheaper to recompute then to
2075 // relocate. Remove this values from the liveset, rematerialize them after
2076 // statepoint and record them in "Info" structure. Note that similar to
2077 // relocated values we don't do any user adjustments here.
2078 static void rematerializeLiveValues(CallSite CS,
2079 PartiallyConstructedSafepointRecord &Info,
2080 TargetTransformInfo &TTI) {
2081 const unsigned int ChainLengthThreshold = 10;
2083 // Record values we are going to delete from this statepoint live set.
2084 // We can not di this in following loop due to iterator invalidation.
2085 SmallVector<Value *, 32> LiveValuesToBeDeleted;
2087 for (Value *LiveValue: Info.liveset) {
2088 // For each live pointer find it's defining chain
2089 SmallVector<Instruction *, 3> ChainToBase;
2090 assert(Info.PointerToBase.count(LiveValue));
2092 findRematerializableChainToBasePointer(ChainToBase,
2094 Info.PointerToBase[LiveValue]);
2095 // Nothing to do, or chain is too long
2097 ChainToBase.size() == 0 ||
2098 ChainToBase.size() > ChainLengthThreshold)
2101 // Compute cost of this chain
2102 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2103 // TODO: We can also account for cases when we will be able to remove some
2104 // of the rematerialized values by later optimization passes. I.e if
2105 // we rematerialized several intersecting chains. Or if original values
2106 // don't have any uses besides this statepoint.
2108 // For invokes we need to rematerialize each chain twice - for normal and
2109 // for unwind basic blocks. Model this by multiplying cost by two.
2110 if (CS.isInvoke()) {
2113 // If it's too expensive - skip it
2114 if (Cost >= RematerializationThreshold)
2117 // Remove value from the live set
2118 LiveValuesToBeDeleted.push_back(LiveValue);
2120 // Clone instructions and record them inside "Info" structure
2122 // Walk backwards to visit top-most instructions first
2123 std::reverse(ChainToBase.begin(), ChainToBase.end());
2125 // Utility function which clones all instructions from "ChainToBase"
2126 // and inserts them before "InsertBefore". Returns rematerialized value
2127 // which should be used after statepoint.
2128 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2129 Instruction *LastClonedValue = nullptr;
2130 Instruction *LastValue = nullptr;
2131 for (Instruction *Instr: ChainToBase) {
2132 // Only GEP's and casts are suported as we need to be careful to not
2133 // introduce any new uses of pointers not in the liveset.
2134 // Note that it's fine to introduce new uses of pointers which were
2135 // otherwise not used after this statepoint.
2136 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2138 Instruction *ClonedValue = Instr->clone();
2139 ClonedValue->insertBefore(InsertBefore);
2140 ClonedValue->setName(Instr->getName() + ".remat");
2142 // If it is not first instruction in the chain then it uses previously
2143 // cloned value. We should update it to use cloned value.
2144 if (LastClonedValue) {
2146 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2148 // Assert that cloned instruction does not use any instructions from
2149 // this chain other than LastClonedValue
2150 for (auto OpValue : ClonedValue->operand_values()) {
2151 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2152 ChainToBase.end() &&
2153 "incorrect use in rematerialization chain");
2158 LastClonedValue = ClonedValue;
2161 assert(LastClonedValue);
2162 return LastClonedValue;
2165 // Different cases for calls and invokes. For invokes we need to clone
2166 // instructions both on normal and unwind path.
2168 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2169 assert(InsertBefore);
2170 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2171 Info.RematerializedValues[RematerializedValue] = LiveValue;
2173 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2175 Instruction *NormalInsertBefore =
2176 Invoke->getNormalDest()->getFirstInsertionPt();
2177 Instruction *UnwindInsertBefore =
2178 Invoke->getUnwindDest()->getFirstInsertionPt();
2180 Instruction *NormalRematerializedValue =
2181 rematerializeChain(NormalInsertBefore);
2182 Instruction *UnwindRematerializedValue =
2183 rematerializeChain(UnwindInsertBefore);
2185 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2186 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2190 // Remove rematerializaed values from the live set
2191 for (auto LiveValue: LiveValuesToBeDeleted) {
2192 Info.liveset.erase(LiveValue);
2196 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
2197 SmallVectorImpl<CallSite> &toUpdate) {
2199 // sanity check the input
2200 std::set<CallSite> uniqued;
2201 uniqued.insert(toUpdate.begin(), toUpdate.end());
2202 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2204 for (size_t i = 0; i < toUpdate.size(); i++) {
2205 CallSite &CS = toUpdate[i];
2206 assert(CS.getInstruction()->getParent()->getParent() == &F);
2207 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2211 // When inserting gc.relocates for invokes, we need to be able to insert at
2212 // the top of the successor blocks. See the comment on
2213 // normalForInvokeSafepoint on exactly what is needed. Note that this step
2214 // may restructure the CFG.
2215 for (CallSite CS : toUpdate) {
2218 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2219 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
2221 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
2225 // A list of dummy calls added to the IR to keep various values obviously
2226 // live in the IR. We'll remove all of these when done.
2227 SmallVector<CallInst *, 64> holders;
2229 // Insert a dummy call with all of the arguments to the vm_state we'll need
2230 // for the actual safepoint insertion. This ensures reference arguments in
2231 // the deopt argument list are considered live through the safepoint (and
2232 // thus makes sure they get relocated.)
2233 for (size_t i = 0; i < toUpdate.size(); i++) {
2234 CallSite &CS = toUpdate[i];
2235 Statepoint StatepointCS(CS);
2237 SmallVector<Value *, 64> DeoptValues;
2238 for (Use &U : StatepointCS.vm_state_args()) {
2239 Value *Arg = cast<Value>(&U);
2240 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2241 "support for FCA unimplemented");
2242 if (isHandledGCPointerType(Arg->getType()))
2243 DeoptValues.push_back(Arg);
2245 insertUseHolderAfter(CS, DeoptValues, holders);
2248 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
2249 records.reserve(toUpdate.size());
2250 for (size_t i = 0; i < toUpdate.size(); i++) {
2251 struct PartiallyConstructedSafepointRecord info;
2252 records.push_back(info);
2254 assert(records.size() == toUpdate.size());
2256 // A) Identify all gc pointers which are statically live at the given call
2258 findLiveReferences(F, DT, P, toUpdate, records);
2260 // B) Find the base pointers for each live pointer
2261 /* scope for caching */ {
2262 // Cache the 'defining value' relation used in the computation and
2263 // insertion of base phis and selects. This ensures that we don't insert
2264 // large numbers of duplicate base_phis.
2265 DefiningValueMapTy DVCache;
2267 for (size_t i = 0; i < records.size(); i++) {
2268 struct PartiallyConstructedSafepointRecord &info = records[i];
2269 CallSite &CS = toUpdate[i];
2270 findBasePointers(DT, DVCache, CS, info);
2272 } // end of cache scope
2274 // The base phi insertion logic (for any safepoint) may have inserted new
2275 // instructions which are now live at some safepoint. The simplest such
2278 // phi a <-- will be a new base_phi here
2279 // safepoint 1 <-- that needs to be live here
2283 // We insert some dummy calls after each safepoint to definitely hold live
2284 // the base pointers which were identified for that safepoint. We'll then
2285 // ask liveness for _every_ base inserted to see what is now live. Then we
2286 // remove the dummy calls.
2287 holders.reserve(holders.size() + records.size());
2288 for (size_t i = 0; i < records.size(); i++) {
2289 struct PartiallyConstructedSafepointRecord &info = records[i];
2290 CallSite &CS = toUpdate[i];
2292 SmallVector<Value *, 128> Bases;
2293 for (auto Pair : info.PointerToBase) {
2294 Bases.push_back(Pair.second);
2296 insertUseHolderAfter(CS, Bases, holders);
2299 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2300 // need to rerun liveness. We may *also* have inserted new defs, but that's
2301 // not the key issue.
2302 recomputeLiveInValues(F, DT, P, toUpdate, records);
2304 if (PrintBasePointers) {
2305 for (size_t i = 0; i < records.size(); i++) {
2306 struct PartiallyConstructedSafepointRecord &info = records[i];
2307 errs() << "Base Pairs: (w/Relocation)\n";
2308 for (auto Pair : info.PointerToBase) {
2309 errs() << " derived %" << Pair.first->getName() << " base %"
2310 << Pair.second->getName() << "\n";
2314 for (size_t i = 0; i < holders.size(); i++) {
2315 holders[i]->eraseFromParent();
2316 holders[i] = nullptr;
2320 // Do a limited scalarization of any live at safepoint vector values which
2321 // contain pointers. This enables this pass to run after vectorization at
2322 // the cost of some possible performance loss. TODO: it would be nice to
2323 // natively support vectors all the way through the backend so we don't need
2324 // to scalarize here.
2325 for (size_t i = 0; i < records.size(); i++) {
2326 struct PartiallyConstructedSafepointRecord &info = records[i];
2327 Instruction *statepoint = toUpdate[i].getInstruction();
2328 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2329 info.PointerToBase, DT);
2332 // In order to reduce live set of statepoint we might choose to rematerialize
2333 // some values instead of relocating them. This is purely an optimization and
2334 // does not influence correctness.
2335 TargetTransformInfo &TTI =
2336 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2338 for (size_t i = 0; i < records.size(); i++) {
2339 struct PartiallyConstructedSafepointRecord &info = records[i];
2340 CallSite &CS = toUpdate[i];
2342 rematerializeLiveValues(CS, info, TTI);
2345 // Now run through and replace the existing statepoints with new ones with
2346 // the live variables listed. We do not yet update uses of the values being
2347 // relocated. We have references to live variables that need to
2348 // survive to the last iteration of this loop. (By construction, the
2349 // previous statepoint can not be a live variable, thus we can and remove
2350 // the old statepoint calls as we go.)
2351 for (size_t i = 0; i < records.size(); i++) {
2352 struct PartiallyConstructedSafepointRecord &info = records[i];
2353 CallSite &CS = toUpdate[i];
2354 makeStatepointExplicit(DT, CS, P, info);
2356 toUpdate.clear(); // prevent accident use of invalid CallSites
2358 // Do all the fixups of the original live variables to their relocated selves
2359 SmallVector<Value *, 128> live;
2360 for (size_t i = 0; i < records.size(); i++) {
2361 struct PartiallyConstructedSafepointRecord &info = records[i];
2362 // We can't simply save the live set from the original insertion. One of
2363 // the live values might be the result of a call which needs a safepoint.
2364 // That Value* no longer exists and we need to use the new gc_result.
2365 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2366 // we just grab that.
2367 Statepoint statepoint(info.StatepointToken);
2368 live.insert(live.end(), statepoint.gc_args_begin(),
2369 statepoint.gc_args_end());
2371 // Do some basic sanity checks on our liveness results before performing
2372 // relocation. Relocation can and will turn mistakes in liveness results
2373 // into non-sensical code which is must harder to debug.
2374 // TODO: It would be nice to test consistency as well
2375 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2376 "statepoint must be reachable or liveness is meaningless");
2377 for (Value *V : statepoint.gc_args()) {
2378 if (!isa<Instruction>(V))
2379 // Non-instruction values trivial dominate all possible uses
2381 auto LiveInst = cast<Instruction>(V);
2382 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2383 "unreachable values should never be live");
2384 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2385 "basic SSA liveness expectation violated by liveness analysis");
2389 unique_unsorted(live);
2393 for (auto ptr : live) {
2394 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2398 relocationViaAlloca(F, DT, live, records);
2399 return !records.empty();
2402 // Handles both return values and arguments for Functions and CallSites.
2403 template <typename AttrHolder>
2404 static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2407 if (AH.getDereferenceableBytes(Index))
2408 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2409 AH.getDereferenceableBytes(Index)));
2410 if (AH.getDereferenceableOrNullBytes(Index))
2411 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2412 AH.getDereferenceableOrNullBytes(Index)));
2415 AH.setAttributes(AH.getAttributes().removeAttributes(
2416 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
2420 RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2421 LLVMContext &Ctx = F.getContext();
2423 for (Argument &A : F.args())
2424 if (isa<PointerType>(A.getType()))
2425 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2427 if (isa<PointerType>(F.getReturnType()))
2428 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2431 void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2435 LLVMContext &Ctx = F.getContext();
2436 MDBuilder Builder(Ctx);
2438 for (Instruction &I : instructions(F)) {
2439 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2440 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2441 bool IsImmutableTBAA =
2442 MD->getNumOperands() == 4 &&
2443 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2445 if (!IsImmutableTBAA)
2446 continue; // no work to do, MD_tbaa is already marked mutable
2448 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2449 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2451 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2453 MDNode *MutableTBAA =
2454 Builder.createTBAAStructTagNode(Base, Access, Offset);
2455 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2458 if (CallSite CS = CallSite(&I)) {
2459 for (int i = 0, e = CS.arg_size(); i != e; i++)
2460 if (isa<PointerType>(CS.getArgument(i)->getType()))
2461 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2462 if (isa<PointerType>(CS.getType()))
2463 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2468 /// Returns true if this function should be rewritten by this pass. The main
2469 /// point of this function is as an extension point for custom logic.
2470 static bool shouldRewriteStatepointsIn(Function &F) {
2471 // TODO: This should check the GCStrategy
2473 const char *FunctionGCName = F.getGC();
2474 const StringRef StatepointExampleName("statepoint-example");
2475 const StringRef CoreCLRName("coreclr");
2476 return (StatepointExampleName == FunctionGCName) ||
2477 (CoreCLRName == FunctionGCName);
2482 void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2484 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2488 for (Function &F : M)
2489 stripDereferenceabilityInfoFromPrototype(F);
2491 for (Function &F : M)
2492 stripDereferenceabilityInfoFromBody(F);
2495 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2496 // Nothing to do for declarations.
2497 if (F.isDeclaration() || F.empty())
2500 // Policy choice says not to rewrite - the most common reason is that we're
2501 // compiling code without a GCStrategy.
2502 if (!shouldRewriteStatepointsIn(F))
2505 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2507 // Gather all the statepoints which need rewritten. Be careful to only
2508 // consider those in reachable code since we need to ask dominance queries
2509 // when rewriting. We'll delete the unreachable ones in a moment.
2510 SmallVector<CallSite, 64> ParsePointNeeded;
2511 bool HasUnreachableStatepoint = false;
2512 for (Instruction &I : instructions(F)) {
2513 // TODO: only the ones with the flag set!
2514 if (isStatepoint(I)) {
2515 if (DT.isReachableFromEntry(I.getParent()))
2516 ParsePointNeeded.push_back(CallSite(&I));
2518 HasUnreachableStatepoint = true;
2522 bool MadeChange = false;
2524 // Delete any unreachable statepoints so that we don't have unrewritten
2525 // statepoints surviving this pass. This makes testing easier and the
2526 // resulting IR less confusing to human readers. Rather than be fancy, we
2527 // just reuse a utility function which removes the unreachable blocks.
2528 if (HasUnreachableStatepoint)
2529 MadeChange |= removeUnreachableBlocks(F);
2531 // Return early if no work to do.
2532 if (ParsePointNeeded.empty())
2535 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2536 // These are created by LCSSA. They have the effect of increasing the size
2537 // of liveness sets for no good reason. It may be harder to do this post
2538 // insertion since relocations and base phis can confuse things.
2539 for (BasicBlock &BB : F)
2540 if (BB.getUniquePredecessor()) {
2542 FoldSingleEntryPHINodes(&BB);
2545 // Before we start introducing relocations, we want to tweak the IR a bit to
2546 // avoid unfortunate code generation effects. The main example is that we
2547 // want to try to make sure the comparison feeding a branch is after any
2548 // safepoints. Otherwise, we end up with a comparison of pre-relocation
2549 // values feeding a branch after relocation. This is semantically correct,
2550 // but results in extra register pressure since both the pre-relocation and
2551 // post-relocation copies must be available in registers. For code without
2552 // relocations this is handled elsewhere, but teaching the scheduler to
2553 // reverse the transform we're about to do would be slightly complex.
2554 // Note: This may extend the live range of the inputs to the icmp and thus
2555 // increase the liveset of any statepoint we move over. This is profitable
2556 // as long as all statepoints are in rare blocks. If we had in-register
2557 // lowering for live values this would be a much safer transform.
2558 auto getConditionInst = [](TerminatorInst *TI) -> Instruction* {
2559 if (auto *BI = dyn_cast<BranchInst>(TI))
2560 if (BI->isConditional())
2561 return dyn_cast<Instruction>(BI->getCondition());
2562 // TODO: Extend this to handle switches
2565 for (BasicBlock &BB : F) {
2566 TerminatorInst *TI = BB.getTerminator();
2567 if (auto *Cond = getConditionInst(TI))
2568 // TODO: Handle more than just ICmps here. We should be able to move
2569 // most instructions without side effects or memory access.
2570 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2572 Cond->moveBefore(TI);
2576 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2580 // liveness computation via standard dataflow
2581 // -------------------------------------------------------------------
2583 // TODO: Consider using bitvectors for liveness, the set of potentially
2584 // interesting values should be small and easy to pre-compute.
2586 /// Compute the live-in set for the location rbegin starting from
2587 /// the live-out set of the basic block
2588 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2589 BasicBlock::reverse_iterator rend,
2590 DenseSet<Value *> &LiveTmp) {
2592 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2593 Instruction *I = &*ritr;
2595 // KILL/Def - Remove this definition from LiveIn
2598 // Don't consider *uses* in PHI nodes, we handle their contribution to
2599 // predecessor blocks when we seed the LiveOut sets
2600 if (isa<PHINode>(I))
2603 // USE - Add to the LiveIn set for this instruction
2604 for (Value *V : I->operands()) {
2605 assert(!isUnhandledGCPointerType(V->getType()) &&
2606 "support for FCA unimplemented");
2607 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2608 // The choice to exclude all things constant here is slightly subtle.
2609 // There are two independent reasons:
2610 // - We assume that things which are constant (from LLVM's definition)
2611 // do not move at runtime. For example, the address of a global
2612 // variable is fixed, even though it's contents may not be.
2613 // - Second, we can't disallow arbitrary inttoptr constants even
2614 // if the language frontend does. Optimization passes are free to
2615 // locally exploit facts without respect to global reachability. This
2616 // can create sections of code which are dynamically unreachable and
2617 // contain just about anything. (see constants.ll in tests)
2624 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2626 for (BasicBlock *Succ : successors(BB)) {
2627 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2628 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2629 PHINode *Phi = cast<PHINode>(&*I);
2630 Value *V = Phi->getIncomingValueForBlock(BB);
2631 assert(!isUnhandledGCPointerType(V->getType()) &&
2632 "support for FCA unimplemented");
2633 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2640 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2641 DenseSet<Value *> KillSet;
2642 for (Instruction &I : *BB)
2643 if (isHandledGCPointerType(I.getType()))
2649 /// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2650 /// sanity check for the liveness computation.
2651 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2652 TerminatorInst *TI, bool TermOkay = false) {
2653 for (Value *V : Live) {
2654 if (auto *I = dyn_cast<Instruction>(V)) {
2655 // The terminator can be a member of the LiveOut set. LLVM's definition
2656 // of instruction dominance states that V does not dominate itself. As
2657 // such, we need to special case this to allow it.
2658 if (TermOkay && TI == I)
2660 assert(DT.dominates(I, TI) &&
2661 "basic SSA liveness expectation violated by liveness analysis");
2666 /// Check that all the liveness sets used during the computation of liveness
2667 /// obey basic SSA properties. This is useful for finding cases where we miss
2669 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2671 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2672 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2673 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2677 static void computeLiveInValues(DominatorTree &DT, Function &F,
2678 GCPtrLivenessData &Data) {
2680 SmallSetVector<BasicBlock *, 200> Worklist;
2681 auto AddPredsToWorklist = [&](BasicBlock *BB) {
2682 // We use a SetVector so that we don't have duplicates in the worklist.
2683 Worklist.insert(pred_begin(BB), pred_end(BB));
2685 auto NextItem = [&]() {
2686 BasicBlock *BB = Worklist.back();
2687 Worklist.pop_back();
2691 // Seed the liveness for each individual block
2692 for (BasicBlock &BB : F) {
2693 Data.KillSet[&BB] = computeKillSet(&BB);
2694 Data.LiveSet[&BB].clear();
2695 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2698 for (Value *Kill : Data.KillSet[&BB])
2699 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2702 Data.LiveOut[&BB] = DenseSet<Value *>();
2703 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2704 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2705 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2706 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2707 if (!Data.LiveIn[&BB].empty())
2708 AddPredsToWorklist(&BB);
2711 // Propagate that liveness until stable
2712 while (!Worklist.empty()) {
2713 BasicBlock *BB = NextItem();
2715 // Compute our new liveout set, then exit early if it hasn't changed
2716 // despite the contribution of our successor.
2717 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2718 const auto OldLiveOutSize = LiveOut.size();
2719 for (BasicBlock *Succ : successors(BB)) {
2720 assert(Data.LiveIn.count(Succ));
2721 set_union(LiveOut, Data.LiveIn[Succ]);
2723 // assert OutLiveOut is a subset of LiveOut
2724 if (OldLiveOutSize == LiveOut.size()) {
2725 // If the sets are the same size, then we didn't actually add anything
2726 // when unioning our successors LiveIn Thus, the LiveIn of this block
2730 Data.LiveOut[BB] = LiveOut;
2732 // Apply the effects of this basic block
2733 DenseSet<Value *> LiveTmp = LiveOut;
2734 set_union(LiveTmp, Data.LiveSet[BB]);
2735 set_subtract(LiveTmp, Data.KillSet[BB]);
2737 assert(Data.LiveIn.count(BB));
2738 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2739 // assert: OldLiveIn is a subset of LiveTmp
2740 if (OldLiveIn.size() != LiveTmp.size()) {
2741 Data.LiveIn[BB] = LiveTmp;
2742 AddPredsToWorklist(BB);
2744 } // while( !worklist.empty() )
2747 // Sanity check our output against SSA properties. This helps catch any
2748 // missing kills during the above iteration.
2749 for (BasicBlock &BB : F) {
2750 checkBasicSSA(DT, Data, BB);
2755 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2756 StatepointLiveSetTy &Out) {
2758 BasicBlock *BB = Inst->getParent();
2760 // Note: The copy is intentional and required
2761 assert(Data.LiveOut.count(BB));
2762 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2764 // We want to handle the statepoint itself oddly. It's
2765 // call result is not live (normal), nor are it's arguments
2766 // (unless they're used again later). This adjustment is
2767 // specifically what we need to relocate
2768 BasicBlock::reverse_iterator rend(Inst);
2769 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2770 LiveOut.erase(Inst);
2771 Out.insert(LiveOut.begin(), LiveOut.end());
2774 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2776 PartiallyConstructedSafepointRecord &Info) {
2777 Instruction *Inst = CS.getInstruction();
2778 StatepointLiveSetTy Updated;
2779 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2782 DenseSet<Value *> Bases;
2783 for (auto KVPair : Info.PointerToBase) {
2784 Bases.insert(KVPair.second);
2787 // We may have base pointers which are now live that weren't before. We need
2788 // to update the PointerToBase structure to reflect this.
2789 for (auto V : Updated)
2790 if (!Info.PointerToBase.count(V)) {
2791 assert(Bases.count(V) && "can't find base for unexpected live value");
2792 Info.PointerToBase[V] = V;
2797 for (auto V : Updated) {
2798 assert(Info.PointerToBase.count(V) &&
2799 "must be able to find base for live value");
2803 // Remove any stale base mappings - this can happen since our liveness is
2804 // more precise then the one inherent in the base pointer analysis
2805 DenseSet<Value *> ToErase;
2806 for (auto KVPair : Info.PointerToBase)
2807 if (!Updated.count(KVPair.first))
2808 ToErase.insert(KVPair.first);
2809 for (auto V : ToErase)
2810 Info.PointerToBase.erase(V);
2813 for (auto KVPair : Info.PointerToBase)
2814 assert(Updated.count(KVPair.first) && "record for non-live value");
2817 Info.liveset = Updated;