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/TargetTransformInfo.h"
18 #include "llvm/ADT/SetOperations.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstIterator.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/MDBuilder.h"
34 #include "llvm/IR/Statepoint.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Transforms/Scalar.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/Cloning.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
45 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
49 // Print tracing output
50 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
53 // Print the liveset found at the insert location
54 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
56 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
58 // Print out the base pointers for debugging
59 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
62 // Cost threshold measuring when it is profitable to rematerialize value instead
64 static cl::opt<unsigned>
65 RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden,
69 static bool ClobberNonLive = true;
71 static bool ClobberNonLive = false;
73 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
74 cl::location(ClobberNonLive),
78 struct RewriteStatepointsForGC : public ModulePass {
79 static char ID; // Pass identification, replacement for typeid
81 RewriteStatepointsForGC() : ModulePass(ID) {
82 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
84 bool runOnFunction(Function &F);
85 bool runOnModule(Module &M) override {
88 Changed |= runOnFunction(F);
91 // stripDereferenceabilityInfo asserts that shouldRewriteStatepointsIn
92 // returns true for at least one function in the module. Since at least
93 // one function changed, we know that the precondition is satisfied.
94 stripDereferenceabilityInfo(M);
100 void getAnalysisUsage(AnalysisUsage &AU) const override {
101 // We add and rewrite a bunch of instructions, but don't really do much
102 // else. We could in theory preserve a lot more analyses here.
103 AU.addRequired<DominatorTreeWrapperPass>();
104 AU.addRequired<TargetTransformInfoWrapperPass>();
107 /// The IR fed into RewriteStatepointsForGC may have had attributes implying
108 /// dereferenceability that are no longer valid/correct after
109 /// RewriteStatepointsForGC has run. This is because semantically, after
110 /// RewriteStatepointsForGC runs, all calls to gc.statepoint "free" the entire
111 /// heap. stripDereferenceabilityInfo (conservatively) restores correctness
112 /// by erasing all attributes in the module that externally imply
113 /// dereferenceability.
115 void stripDereferenceabilityInfo(Module &M);
117 // Helpers for stripDereferenceabilityInfo
118 void stripDereferenceabilityInfoFromBody(Function &F);
119 void stripDereferenceabilityInfoFromPrototype(Function &F);
123 char RewriteStatepointsForGC::ID = 0;
125 ModulePass *llvm::createRewriteStatepointsForGCPass() {
126 return new RewriteStatepointsForGC();
129 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
130 "Make relocations explicit at statepoints", false, false)
131 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
132 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
133 "Make relocations explicit at statepoints", false, false)
136 struct GCPtrLivenessData {
137 /// Values defined in this block.
138 DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
139 /// Values used in this block (and thus live); does not included values
140 /// killed within this block.
141 DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
143 /// Values live into this basic block (i.e. used by any
144 /// instruction in this basic block or ones reachable from here)
145 DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
147 /// Values live out of this basic block (i.e. live into
148 /// any successor block)
149 DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
152 // The type of the internal cache used inside the findBasePointers family
153 // of functions. From the callers perspective, this is an opaque type and
154 // should not be inspected.
156 // In the actual implementation this caches two relations:
157 // - The base relation itself (i.e. this pointer is based on that one)
158 // - The base defining value relation (i.e. before base_phi insertion)
159 // Generally, after the execution of a full findBasePointer call, only the
160 // base relation will remain. Internally, we add a mixture of the two
161 // types, then update all the second type to the first type
162 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
163 typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
164 typedef DenseMap<Instruction *, Value *> RematerializedValueMapTy;
166 struct PartiallyConstructedSafepointRecord {
167 /// The set of values known to be live across this safepoint
168 StatepointLiveSetTy liveset;
170 /// Mapping from live pointers to a base-defining-value
171 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
173 /// The *new* gc.statepoint instruction itself. This produces the token
174 /// that normal path gc.relocates and the gc.result are tied to.
175 Instruction *StatepointToken;
177 /// Instruction to which exceptional gc relocates are attached
178 /// Makes it easier to iterate through them during relocationViaAlloca.
179 Instruction *UnwindToken;
181 /// Record live values we are rematerialized instead of relocating.
182 /// They are not included into 'liveset' field.
183 /// Maps rematerialized copy to it's original value.
184 RematerializedValueMapTy RematerializedValues;
188 /// Compute the live-in set for every basic block in the function
189 static void computeLiveInValues(DominatorTree &DT, Function &F,
190 GCPtrLivenessData &Data);
192 /// Given results from the dataflow liveness computation, find the set of live
193 /// Values at a particular instruction.
194 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
195 StatepointLiveSetTy &out);
197 // TODO: Once we can get to the GCStrategy, this becomes
198 // Optional<bool> isGCManagedPointer(const Value *V) const override {
200 static bool isGCPointerType(Type *T) {
201 if (auto *PT = dyn_cast<PointerType>(T))
202 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
203 // GC managed heap. We know that a pointer into this heap needs to be
204 // updated and that no other pointer does.
205 return (1 == PT->getAddressSpace());
209 // Return true if this type is one which a) is a gc pointer or contains a GC
210 // pointer and b) is of a type this code expects to encounter as a live value.
211 // (The insertion code will assert that a type which matches (a) and not (b)
212 // is not encountered.)
213 static bool isHandledGCPointerType(Type *T) {
214 // We fully support gc pointers
215 if (isGCPointerType(T))
217 // We partially support vectors of gc pointers. The code will assert if it
218 // can't handle something.
219 if (auto VT = dyn_cast<VectorType>(T))
220 if (isGCPointerType(VT->getElementType()))
226 /// Returns true if this type contains a gc pointer whether we know how to
227 /// handle that type or not.
228 static bool containsGCPtrType(Type *Ty) {
229 if (isGCPointerType(Ty))
231 if (VectorType *VT = dyn_cast<VectorType>(Ty))
232 return isGCPointerType(VT->getScalarType());
233 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
234 return containsGCPtrType(AT->getElementType());
235 if (StructType *ST = dyn_cast<StructType>(Ty))
237 ST->subtypes().begin(), ST->subtypes().end(),
238 [](Type *SubType) { return containsGCPtrType(SubType); });
242 // Returns true if this is a type which a) is a gc pointer or contains a GC
243 // pointer and b) is of a type which the code doesn't expect (i.e. first class
244 // aggregates). Used to trip assertions.
245 static bool isUnhandledGCPointerType(Type *Ty) {
246 return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
250 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
251 if (a->hasName() && b->hasName()) {
252 return -1 == a->getName().compare(b->getName());
253 } else if (a->hasName() && !b->hasName()) {
255 } else if (!a->hasName() && b->hasName()) {
258 // Better than nothing, but not stable
263 // Conservatively identifies any definitions which might be live at the
264 // given instruction. The analysis is performed immediately before the
265 // given instruction. Values defined by that instruction are not considered
266 // live. Values used by that instruction are considered live.
267 static void analyzeParsePointLiveness(
268 DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
269 const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
270 Instruction *inst = CS.getInstruction();
272 StatepointLiveSetTy liveset;
273 findLiveSetAtInst(inst, OriginalLivenessData, liveset);
276 // Note: This output is used by several of the test cases
277 // The order of elements in a set is not stable, put them in a vec and sort
279 SmallVector<Value *, 64> temp;
280 temp.insert(temp.end(), liveset.begin(), liveset.end());
281 std::sort(temp.begin(), temp.end(), order_by_name);
282 errs() << "Live Variables:\n";
283 for (Value *V : temp) {
284 errs() << " " << V->getName(); // no newline
288 if (PrintLiveSetSize) {
289 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
290 errs() << "Number live values: " << liveset.size() << "\n";
292 result.liveset = liveset;
295 static Value *findBaseDefiningValue(Value *I);
297 /// Return a base defining value for the 'Index' element of the given vector
298 /// instruction 'I'. If Index is null, returns a BDV for the entire vector
299 /// 'I'. As an optimization, this method will try to determine when the
300 /// element is known to already be a base pointer. If this can be established,
301 /// the second value in the returned pair will be true. Note that either a
302 /// vector or a pointer typed value can be returned. For the former, the
303 /// vector returned is a BDV (and possibly a base) of the entire vector 'I'.
304 /// If the later, the return pointer is a BDV (or possibly a base) for the
305 /// particular element in 'I'.
306 static std::pair<Value *, bool>
307 findBaseDefiningValueOfVector(Value *I, Value *Index = nullptr) {
308 assert(I->getType()->isVectorTy() &&
309 cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
310 "Illegal to ask for the base pointer of a non-pointer type");
312 // Each case parallels findBaseDefiningValue below, see that code for
313 // detailed motivation.
315 if (isa<Argument>(I))
316 // An incoming argument to the function is a base pointer
317 return std::make_pair(I, true);
319 // We shouldn't see the address of a global as a vector value?
320 assert(!isa<GlobalVariable>(I) &&
321 "unexpected global variable found in base of vector");
323 // inlining could possibly introduce phi node that contains
324 // undef if callee has multiple returns
325 if (isa<UndefValue>(I))
326 // utterly meaningless, but useful for dealing with partially optimized
328 return std::make_pair(I, true);
330 // Due to inheritance, this must be _after_ the global variable and undef
332 if (Constant *Con = dyn_cast<Constant>(I)) {
333 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
334 "order of checks wrong!");
335 assert(Con->isNullValue() && "null is the only case which makes sense");
336 return std::make_pair(Con, true);
339 if (isa<LoadInst>(I))
340 return std::make_pair(I, true);
342 // For an insert element, we might be able to look through it if we know
343 // something about the indexes.
344 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(I)) {
346 Value *InsertIndex = IEI->getOperand(2);
347 // This index is inserting the value, look for its BDV
348 if (InsertIndex == Index)
349 return std::make_pair(findBaseDefiningValue(IEI->getOperand(1)), false);
350 // Both constant, and can't be equal per above. This insert is definitely
351 // not relevant, look back at the rest of the vector and keep trying.
352 if (isa<ConstantInt>(Index) && isa<ConstantInt>(InsertIndex))
353 return findBaseDefiningValueOfVector(IEI->getOperand(0), Index);
356 // We don't know whether this vector contains entirely base pointers or
357 // not. To be conservatively correct, we treat it as a BDV and will
358 // duplicate code as needed to construct a parallel vector of bases.
359 return std::make_pair(IEI, false);
362 if (isa<ShuffleVectorInst>(I))
363 // We don't know whether this vector contains entirely base pointers or
364 // not. To be conservatively correct, we treat it as a BDV and will
365 // duplicate code as needed to construct a parallel vector of bases.
366 // TODO: There a number of local optimizations which could be applied here
367 // for particular sufflevector patterns.
368 return std::make_pair(I, false);
370 // A PHI or Select is a base defining value. The outer findBasePointer
371 // algorithm is responsible for constructing a base value for this BDV.
372 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
373 "unknown vector instruction - no base found for vector element");
374 return std::make_pair(I, false);
377 static bool isKnownBaseResult(Value *V);
379 /// Helper function for findBasePointer - Will return a value which either a)
380 /// defines the base pointer for the input, b) blocks the simple search
381 /// (i.e. a PHI or Select of two derived pointers), or c) involves a change
382 /// from pointer to vector type or back.
383 static Value *findBaseDefiningValue(Value *I) {
384 if (I->getType()->isVectorTy())
385 return findBaseDefiningValueOfVector(I).first;
387 assert(I->getType()->isPointerTy() &&
388 "Illegal to ask for the base pointer of a non-pointer type");
390 if (isa<Argument>(I))
391 // An incoming argument to the function is a base pointer
392 // We should have never reached here if this argument isn't an gc value
395 if (isa<GlobalVariable>(I))
399 // inlining could possibly introduce phi node that contains
400 // undef if callee has multiple returns
401 if (isa<UndefValue>(I))
402 // utterly meaningless, but useful for dealing with
403 // partially optimized code.
406 // Due to inheritance, this must be _after_ the global variable and undef
408 if (Constant *Con = dyn_cast<Constant>(I)) {
409 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
410 "order of checks wrong!");
411 // Note: Finding a constant base for something marked for relocation
412 // doesn't really make sense. The most likely case is either a) some
413 // screwed up the address space usage or b) your validating against
414 // compiled C++ code w/o the proper separation. The only real exception
415 // is a null pointer. You could have generic code written to index of
416 // off a potentially null value and have proven it null. We also use
417 // null pointers in dead paths of relocation phis (which we might later
418 // want to find a base pointer for).
419 assert(isa<ConstantPointerNull>(Con) &&
420 "null is the only case which makes sense");
424 if (CastInst *CI = dyn_cast<CastInst>(I)) {
425 Value *Def = CI->stripPointerCasts();
426 // If we find a cast instruction here, it means we've found a cast which is
427 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
428 // handle int->ptr conversion.
429 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
430 return findBaseDefiningValue(Def);
433 if (isa<LoadInst>(I))
434 return I; // The value loaded is an gc base itself
436 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
437 // The base of this GEP is the base
438 return findBaseDefiningValue(GEP->getPointerOperand());
440 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
441 switch (II->getIntrinsicID()) {
442 case Intrinsic::experimental_gc_result_ptr:
444 // fall through to general call handling
446 case Intrinsic::experimental_gc_statepoint:
447 case Intrinsic::experimental_gc_result_float:
448 case Intrinsic::experimental_gc_result_int:
449 llvm_unreachable("these don't produce pointers");
450 case Intrinsic::experimental_gc_relocate: {
451 // Rerunning safepoint insertion after safepoints are already
452 // inserted is not supported. It could probably be made to work,
453 // but why are you doing this? There's no good reason.
454 llvm_unreachable("repeat safepoint insertion is not supported");
456 case Intrinsic::gcroot:
457 // Currently, this mechanism hasn't been extended to work with gcroot.
458 // There's no reason it couldn't be, but I haven't thought about the
459 // implications much.
461 "interaction with the gcroot mechanism is not supported");
464 // We assume that functions in the source language only return base
465 // pointers. This should probably be generalized via attributes to support
466 // both source language and internal functions.
467 if (isa<CallInst>(I) || isa<InvokeInst>(I))
470 // I have absolutely no idea how to implement this part yet. It's not
471 // necessarily hard, I just haven't really looked at it yet.
472 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
474 if (isa<AtomicCmpXchgInst>(I))
475 // A CAS is effectively a atomic store and load combined under a
476 // predicate. From the perspective of base pointers, we just treat it
480 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
481 "binary ops which don't apply to pointers");
483 // The aggregate ops. Aggregates can either be in the heap or on the
484 // stack, but in either case, this is simply a field load. As a result,
485 // this is a defining definition of the base just like a load is.
486 if (isa<ExtractValueInst>(I))
489 // We should never see an insert vector since that would require we be
490 // tracing back a struct value not a pointer value.
491 assert(!isa<InsertValueInst>(I) &&
492 "Base pointer for a struct is meaningless");
494 // An extractelement produces a base result exactly when it's input does.
495 // We may need to insert a parallel instruction to extract the appropriate
496 // element out of the base vector corresponding to the input. Given this,
497 // it's analogous to the phi and select case even though it's not a merge.
498 if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
499 Value *VectorOperand = EEI->getVectorOperand();
500 Value *Index = EEI->getIndexOperand();
501 std::pair<Value *, bool> pair =
502 findBaseDefiningValueOfVector(VectorOperand, Index);
503 Value *VectorBase = pair.first;
504 if (VectorBase->getType()->isPointerTy())
505 // We found a BDV for this specific element with the vector. This is an
506 // optimization, but in practice it covers most of the useful cases
507 // created via scalarization. Note: The peephole optimization here is
508 // currently needed for correctness since the general algorithm doesn't
509 // yet handle insertelements. That will change shortly.
512 assert(VectorBase->getType()->isVectorTy());
513 // Otherwise, we have an instruction which potentially produces a
514 // derived pointer and we need findBasePointers to clone code for us
515 // such that we can create an instruction which produces the
516 // accompanying base pointer.
521 // The last two cases here don't return a base pointer. Instead, they
522 // return a value which dynamically selects from among several base
523 // derived pointers (each with it's own base potentially). It's the job of
524 // the caller to resolve these.
525 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
526 "missing instruction case in findBaseDefiningValing");
530 /// Returns the base defining value for this value.
531 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
532 Value *&Cached = Cache[I];
534 Cached = findBaseDefiningValue(I);
535 DEBUG(dbgs() << "fBDV-cached: " << I->getName() << " -> "
536 << Cached->getName() << "\n");
538 assert(Cache[I] != nullptr);
542 /// Return a base pointer for this value if known. Otherwise, return it's
543 /// base defining value.
544 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
545 Value *Def = findBaseDefiningValueCached(I, Cache);
546 auto Found = Cache.find(Def);
547 if (Found != Cache.end()) {
548 // Either a base-of relation, or a self reference. Caller must check.
549 return Found->second;
551 // Only a BDV available
555 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
556 /// is it known to be a base pointer? Or do we need to continue searching.
557 static bool isKnownBaseResult(Value *V) {
558 if (!isa<PHINode>(V) && !isa<SelectInst>(V) && !isa<ExtractElementInst>(V)) {
559 // no recursion possible
562 if (isa<Instruction>(V) &&
563 cast<Instruction>(V)->getMetadata("is_base_value")) {
564 // This is a previously inserted base phi or select. We know
565 // that this is a base value.
569 // We need to keep searching
574 /// Models the state of a single base defining value in the findBasePointer
575 /// algorithm for determining where a new instruction is needed to propagate
576 /// the base of this BDV.
579 enum Status { Unknown, Base, Conflict };
581 BDVState(Status s, Value *b = nullptr) : status(s), base(b) {
582 assert(status != Base || b);
584 explicit BDVState(Value *b) : status(Base), base(b) {}
585 BDVState() : status(Unknown), base(nullptr) {}
587 Status getStatus() const { return status; }
588 Value *getBase() const { return base; }
590 bool isBase() const { return getStatus() == Base; }
591 bool isUnknown() const { return getStatus() == Unknown; }
592 bool isConflict() const { return getStatus() == Conflict; }
594 bool operator==(const BDVState &other) const {
595 return base == other.base && status == other.status;
598 bool operator!=(const BDVState &other) const { return !(*this == other); }
601 void dump() const { print(dbgs()); dbgs() << '\n'; }
603 void print(raw_ostream &OS) const {
604 OS << status << " (" << base << " - "
605 << (base ? base->getName() : "nullptr") << "): ";
610 Value *base; // non null only if status == base
613 inline raw_ostream &operator<<(raw_ostream &OS, const BDVState &State) {
619 typedef DenseMap<Value *, BDVState> ConflictStateMapTy;
620 // Values of type BDVState form a lattice, and this is a helper
621 // class that implementes the meet operation. The meat of the meet
622 // operation is implemented in MeetBDVStates::pureMeet
623 class MeetBDVStates {
625 /// Initializes the currentResult to the TOP state so that if can be met with
626 /// any other state to produce that state.
629 // Destructively meet the current result with the given BDVState
630 void meetWith(BDVState otherState) {
631 currentResult = meet(otherState, currentResult);
634 BDVState getResult() const { return currentResult; }
637 BDVState currentResult;
639 /// Perform a meet operation on two elements of the BDVState lattice.
640 static BDVState meet(BDVState LHS, BDVState RHS) {
641 assert((pureMeet(LHS, RHS) == pureMeet(RHS, LHS)) &&
642 "math is wrong: meet does not commute!");
643 BDVState Result = pureMeet(LHS, RHS);
644 DEBUG(dbgs() << "meet of " << LHS << " with " << RHS
645 << " produced " << Result << "\n");
649 static BDVState pureMeet(const BDVState &stateA, const BDVState &stateB) {
650 switch (stateA.getStatus()) {
651 case BDVState::Unknown:
655 assert(stateA.getBase() && "can't be null");
656 if (stateB.isUnknown())
659 if (stateB.isBase()) {
660 if (stateA.getBase() == stateB.getBase()) {
661 assert(stateA == stateB && "equality broken!");
664 return BDVState(BDVState::Conflict);
666 assert(stateB.isConflict() && "only three states!");
667 return BDVState(BDVState::Conflict);
669 case BDVState::Conflict:
672 llvm_unreachable("only three states!");
676 /// For a given value or instruction, figure out what base ptr it's derived
677 /// from. For gc objects, this is simply itself. On success, returns a value
678 /// which is the base pointer. (This is reliable and can be used for
679 /// relocation.) On failure, returns nullptr.
680 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
681 Value *def = findBaseOrBDV(I, cache);
683 if (isKnownBaseResult(def)) {
687 // Here's the rough algorithm:
688 // - For every SSA value, construct a mapping to either an actual base
689 // pointer or a PHI which obscures the base pointer.
690 // - Construct a mapping from PHI to unknown TOP state. Use an
691 // optimistic algorithm to propagate base pointer information. Lattice
696 // When algorithm terminates, all PHIs will either have a single concrete
697 // base or be in a conflict state.
698 // - For every conflict, insert a dummy PHI node without arguments. Add
699 // these to the base[Instruction] = BasePtr mapping. For every
700 // non-conflict, add the actual base.
701 // - For every conflict, add arguments for the base[a] of each input
704 // Note: A simpler form of this would be to add the conflict form of all
705 // PHIs without running the optimistic algorithm. This would be
706 // analogous to pessimistic data flow and would likely lead to an
707 // overall worse solution.
710 auto isExpectedBDVType = [](Value *BDV) {
711 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) || isa<ExtractElementInst>(BDV);
715 // Once populated, will contain a mapping from each potentially non-base BDV
716 // to a lattice value (described above) which corresponds to that BDV.
717 ConflictStateMapTy states;
718 // Recursively fill in all phis & selects reachable from the initial one
719 // for which we don't already know a definite base value for
721 DenseSet<Value *> Visited;
722 SmallVector<Value*, 16> Worklist;
723 Worklist.push_back(def);
725 while (!Worklist.empty()) {
726 Value *Current = Worklist.pop_back_val();
727 assert(!isKnownBaseResult(Current) && "why did it get added?");
729 auto visitIncomingValue = [&](Value *InVal) {
730 Value *Base = findBaseOrBDV(InVal, cache);
731 if (isKnownBaseResult(Base))
732 // Known bases won't need new instructions introduced and can be
735 assert(isExpectedBDVType(Base) && "the only non-base values "
736 "we see should be base defining values");
737 if (Visited.insert(Base).second)
738 Worklist.push_back(Base);
740 if (PHINode *Phi = dyn_cast<PHINode>(Current)) {
741 for (Value *InVal : Phi->incoming_values())
742 visitIncomingValue(InVal);
743 } else if (SelectInst *Sel = dyn_cast<SelectInst>(Current)) {
744 visitIncomingValue(Sel->getTrueValue());
745 visitIncomingValue(Sel->getFalseValue());
746 } else if (auto *EE = dyn_cast<ExtractElementInst>(Current)) {
747 visitIncomingValue(EE->getVectorOperand());
749 // There are two classes of instructions we know we don't handle.
750 assert(isa<ShuffleVectorInst>(Current) ||
751 isa<InsertElementInst>(Current));
752 llvm_unreachable("unimplemented instruction case");
755 // The frontier of visited instructions are the ones we might need to
756 // duplicate, so fill in the starting state for the optimistic algorithm
758 for (Value *BDV : Visited) {
759 states[BDV] = BDVState();
764 errs() << "States after initialization:\n";
765 for (auto Pair : states)
766 dbgs() << " " << Pair.second << " for " << *Pair.first << "\n";
769 // TODO: come back and revisit the state transitions around inputs which
770 // have reached conflict state. The current version seems too conservative.
772 // Return a phi state for a base defining value. We'll generate a new
773 // base state for known bases and expect to find a cached state otherwise.
774 auto getStateForBDV = [&](Value *baseValue) {
775 if (isKnownBaseResult(baseValue))
776 return BDVState(baseValue);
777 auto I = states.find(baseValue);
778 assert(I != states.end() && "lookup failed!");
782 bool progress = true;
785 size_t oldSize = states.size();
788 // We're only changing keys in this loop, thus safe to keep iterators
789 for (auto Pair : states) {
790 Value *v = Pair.first;
791 assert(!isKnownBaseResult(v) && "why did it get added?");
793 // Given an input value for the current instruction, return a BDVState
794 // instance which represents the BDV of that value.
795 auto getStateForInput = [&](Value *V) mutable {
796 Value *BDV = findBaseOrBDV(V, cache);
797 return getStateForBDV(BDV);
800 MeetBDVStates calculateMeet;
801 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
802 calculateMeet.meetWith(getStateForInput(select->getTrueValue()));
803 calculateMeet.meetWith(getStateForInput(select->getFalseValue()));
804 } else if (PHINode *Phi = dyn_cast<PHINode>(v)) {
805 for (Value *Val : Phi->incoming_values())
806 calculateMeet.meetWith(getStateForInput(Val));
808 // The 'meet' for an extractelement is slightly trivial, but it's still
809 // useful in that it drives us to conflict if our input is.
810 auto *EE = cast<ExtractElementInst>(v);
811 calculateMeet.meetWith(getStateForInput(EE->getVectorOperand()));
815 BDVState oldState = states[v];
816 BDVState newState = calculateMeet.getResult();
817 if (oldState != newState) {
819 states[v] = newState;
823 assert(oldSize <= states.size());
824 assert(oldSize == states.size() || progress);
828 errs() << "States after meet iteration:\n";
829 for (auto Pair : states)
830 dbgs() << " " << Pair.second << " for " << *Pair.first << "\n";
833 // Insert Phis for all conflicts
834 // We want to keep naming deterministic in the loop that follows, so
835 // sort the keys before iteration. This is useful in allowing us to
836 // write stable tests. Note that there is no invalidation issue here.
837 SmallVector<Value *, 16> Keys;
838 Keys.reserve(states.size());
839 for (auto Pair : states) {
840 Value *V = Pair.first;
843 std::sort(Keys.begin(), Keys.end(), order_by_name);
844 // TODO: adjust naming patterns to avoid this order of iteration dependency
845 for (Value *V : Keys) {
846 Instruction *I = cast<Instruction>(V);
847 BDVState State = states[I];
848 assert(!isKnownBaseResult(I) && "why did it get added?");
849 assert(!State.isUnknown() && "Optimistic algorithm didn't complete!");
851 // extractelement instructions are a bit special in that we may need to
852 // insert an extract even when we know an exact base for the instruction.
853 // The problem is that we need to convert from a vector base to a scalar
854 // base for the particular indice we're interested in.
855 if (State.isBase() && isa<ExtractElementInst>(I) &&
856 isa<VectorType>(State.getBase()->getType())) {
857 auto *EE = cast<ExtractElementInst>(I);
858 // TODO: In many cases, the new instruction is just EE itself. We should
859 // exploit this, but can't do it here since it would break the invariant
860 // about the BDV not being known to be a base.
861 auto *BaseInst = ExtractElementInst::Create(State.getBase(),
862 EE->getIndexOperand(),
864 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
865 states[I] = BDVState(BDVState::Base, BaseInst);
868 if (!State.isConflict())
871 /// Create and insert a new instruction which will represent the base of
872 /// the given instruction 'I'.
873 auto MakeBaseInstPlaceholder = [](Instruction *I) -> Instruction* {
874 if (isa<PHINode>(I)) {
875 BasicBlock *BB = I->getParent();
876 int NumPreds = std::distance(pred_begin(BB), pred_end(BB));
877 assert(NumPreds > 0 && "how did we reach here");
878 std::string Name = I->hasName() ?
879 (I->getName() + ".base").str() : "base_phi";
880 return PHINode::Create(I->getType(), NumPreds, Name, I);
881 } else if (SelectInst *Sel = dyn_cast<SelectInst>(I)) {
882 // The undef will be replaced later
883 UndefValue *Undef = UndefValue::get(Sel->getType());
884 std::string Name = I->hasName() ?
885 (I->getName() + ".base").str() : "base_select";
886 return SelectInst::Create(Sel->getCondition(), Undef,
889 auto *EE = cast<ExtractElementInst>(I);
890 UndefValue *Undef = UndefValue::get(EE->getVectorOperand()->getType());
891 std::string Name = I->hasName() ?
892 (I->getName() + ".base").str() : "base_ee";
893 return ExtractElementInst::Create(Undef, EE->getIndexOperand(), Name,
897 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
898 // Add metadata marking this as a base value
899 BaseInst->setMetadata("is_base_value", MDNode::get(I->getContext(), {}));
900 states[I] = BDVState(BDVState::Conflict, BaseInst);
903 // Fixup all the inputs of the new PHIs
904 for (auto Pair : states) {
905 Instruction *v = cast<Instruction>(Pair.first);
906 BDVState state = Pair.second;
908 assert(!isKnownBaseResult(v) && "why did it get added?");
909 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
910 if (!state.isConflict())
913 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
914 PHINode *phi = cast<PHINode>(v);
915 unsigned NumPHIValues = phi->getNumIncomingValues();
916 for (unsigned i = 0; i < NumPHIValues; i++) {
917 Value *InVal = phi->getIncomingValue(i);
918 BasicBlock *InBB = phi->getIncomingBlock(i);
920 // If we've already seen InBB, add the same incoming value
921 // we added for it earlier. The IR verifier requires phi
922 // nodes with multiple entries from the same basic block
923 // to have the same incoming value for each of those
924 // entries. If we don't do this check here and basephi
925 // has a different type than base, we'll end up adding two
926 // bitcasts (and hence two distinct values) as incoming
927 // values for the same basic block.
929 int blockIndex = basephi->getBasicBlockIndex(InBB);
930 if (blockIndex != -1) {
931 Value *oldBase = basephi->getIncomingValue(blockIndex);
932 basephi->addIncoming(oldBase, InBB);
934 Value *base = findBaseOrBDV(InVal, cache);
935 if (!isKnownBaseResult(base)) {
936 // Either conflict or base.
937 assert(states.count(base));
938 base = states[base].getBase();
939 assert(base != nullptr && "unknown BDVState!");
942 // In essence this assert states: the only way two
943 // values incoming from the same basic block may be
944 // different is by being different bitcasts of the same
945 // value. A cleanup that remains TODO is changing
946 // findBaseOrBDV to return an llvm::Value of the correct
947 // type (and still remain pure). This will remove the
948 // need to add bitcasts.
949 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
950 "sanity -- findBaseOrBDV should be pure!");
955 // Find either the defining value for the PHI or the normal base for
957 Value *base = findBaseOrBDV(InVal, cache);
958 if (!isKnownBaseResult(base)) {
959 // Either conflict or base.
960 assert(states.count(base));
961 base = states[base].getBase();
962 assert(base != nullptr && "unknown BDVState!");
964 assert(base && "can't be null");
965 // Must use original input BB since base may not be Instruction
966 // The cast is needed since base traversal may strip away bitcasts
967 if (base->getType() != basephi->getType()) {
968 base = new BitCastInst(base, basephi->getType(), "cast",
969 InBB->getTerminator());
971 basephi->addIncoming(base, InBB);
973 assert(basephi->getNumIncomingValues() == NumPHIValues);
974 } else if (SelectInst *basesel = dyn_cast<SelectInst>(state.getBase())) {
975 SelectInst *sel = cast<SelectInst>(v);
976 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
977 // something more safe and less hacky.
978 for (int i = 1; i <= 2; i++) {
979 Value *InVal = sel->getOperand(i);
980 // Find either the defining value for the PHI or the normal base for
982 Value *base = findBaseOrBDV(InVal, cache);
983 if (!isKnownBaseResult(base)) {
984 // Either conflict or base.
985 assert(states.count(base));
986 base = states[base].getBase();
987 assert(base != nullptr && "unknown BDVState!");
989 assert(base && "can't be null");
990 // Must use original input BB since base may not be Instruction
991 // The cast is needed since base traversal may strip away bitcasts
992 if (base->getType() != basesel->getType()) {
993 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
995 basesel->setOperand(i, base);
998 auto *BaseEE = cast<ExtractElementInst>(state.getBase());
999 Value *InVal = cast<ExtractElementInst>(v)->getVectorOperand();
1000 Value *Base = findBaseOrBDV(InVal, cache);
1001 if (!isKnownBaseResult(Base)) {
1002 // Either conflict or base.
1003 assert(states.count(Base));
1004 Base = states[Base].getBase();
1005 assert(Base != nullptr && "unknown BDVState!");
1007 assert(Base && "can't be null");
1008 BaseEE->setOperand(0, Base);
1012 // Cache all of our results so we can cheaply reuse them
1013 // NOTE: This is actually two caches: one of the base defining value
1014 // relation and one of the base pointer relation! FIXME
1015 for (auto item : states) {
1016 Value *v = item.first;
1017 Value *base = item.second.getBase();
1019 assert(!isKnownBaseResult(v) && "why did it get added?");
1022 std::string fromstr =
1023 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
1025 errs() << "Updating base value cache"
1026 << " for: " << (v->hasName() ? v->getName() : "")
1027 << " from: " << fromstr
1028 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
1031 assert(isKnownBaseResult(base) &&
1032 "must be something we 'know' is a base pointer");
1033 if (cache.count(v)) {
1034 // Once we transition from the BDV relation being store in the cache to
1035 // the base relation being stored, it must be stable
1036 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
1037 "base relation should be stable");
1041 assert(cache.find(def) != cache.end());
1045 // For a set of live pointers (base and/or derived), identify the base
1046 // pointer of the object which they are derived from. This routine will
1047 // mutate the IR graph as needed to make the 'base' pointer live at the
1048 // definition site of 'derived'. This ensures that any use of 'derived' can
1049 // also use 'base'. This may involve the insertion of a number of
1050 // additional PHI nodes.
1052 // preconditions: live is a set of pointer type Values
1054 // side effects: may insert PHI nodes into the existing CFG, will preserve
1055 // CFG, will not remove or mutate any existing nodes
1057 // post condition: PointerToBase contains one (derived, base) pair for every
1058 // pointer in live. Note that derived can be equal to base if the original
1059 // pointer was a base pointer.
1061 findBasePointers(const StatepointLiveSetTy &live,
1062 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
1063 DominatorTree *DT, DefiningValueMapTy &DVCache) {
1064 // For the naming of values inserted to be deterministic - which makes for
1065 // much cleaner and more stable tests - we need to assign an order to the
1066 // live values. DenseSets do not provide a deterministic order across runs.
1067 SmallVector<Value *, 64> Temp;
1068 Temp.insert(Temp.end(), live.begin(), live.end());
1069 std::sort(Temp.begin(), Temp.end(), order_by_name);
1070 for (Value *ptr : Temp) {
1071 Value *base = findBasePointer(ptr, DVCache);
1072 assert(base && "failed to find base pointer");
1073 PointerToBase[ptr] = base;
1074 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1075 DT->dominates(cast<Instruction>(base)->getParent(),
1076 cast<Instruction>(ptr)->getParent())) &&
1077 "The base we found better dominate the derived pointer");
1079 // If you see this trip and like to live really dangerously, the code should
1080 // be correct, just with idioms the verifier can't handle. You can try
1081 // disabling the verifier at your own substantial risk.
1082 assert(!isa<ConstantPointerNull>(base) &&
1083 "the relocation code needs adjustment to handle the relocation of "
1084 "a null pointer constant without causing false positives in the "
1085 "safepoint ir verifier.");
1089 /// Find the required based pointers (and adjust the live set) for the given
1091 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1093 PartiallyConstructedSafepointRecord &result) {
1094 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1095 findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
1097 if (PrintBasePointers) {
1098 // Note: Need to print these in a stable order since this is checked in
1100 errs() << "Base Pairs (w/o Relocation):\n";
1101 SmallVector<Value *, 64> Temp;
1102 Temp.reserve(PointerToBase.size());
1103 for (auto Pair : PointerToBase) {
1104 Temp.push_back(Pair.first);
1106 std::sort(Temp.begin(), Temp.end(), order_by_name);
1107 for (Value *Ptr : Temp) {
1108 Value *Base = PointerToBase[Ptr];
1109 errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
1114 result.PointerToBase = PointerToBase;
1117 /// Given an updated version of the dataflow liveness results, update the
1118 /// liveset and base pointer maps for the call site CS.
1119 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
1121 PartiallyConstructedSafepointRecord &result);
1123 static void recomputeLiveInValues(
1124 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1125 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1126 // TODO-PERF: reuse the original liveness, then simply run the dataflow
1127 // again. The old values are still live and will help it stabilize quickly.
1128 GCPtrLivenessData RevisedLivenessData;
1129 computeLiveInValues(DT, F, RevisedLivenessData);
1130 for (size_t i = 0; i < records.size(); i++) {
1131 struct PartiallyConstructedSafepointRecord &info = records[i];
1132 const CallSite &CS = toUpdate[i];
1133 recomputeLiveInValues(RevisedLivenessData, CS, info);
1137 // When inserting gc.relocate calls, we need to ensure there are no uses
1138 // of the original value between the gc.statepoint and the gc.relocate call.
1139 // One case which can arise is a phi node starting one of the successor blocks.
1140 // We also need to be able to insert the gc.relocates only on the path which
1141 // goes through the statepoint. We might need to split an edge to make this
1144 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent,
1145 DominatorTree &DT) {
1146 BasicBlock *Ret = BB;
1147 if (!BB->getUniquePredecessor()) {
1148 Ret = SplitBlockPredecessors(BB, InvokeParent, "", &DT);
1151 // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1153 FoldSingleEntryPHINodes(Ret);
1154 assert(!isa<PHINode>(Ret->begin()));
1156 // At this point, we can safely insert a gc.relocate as the first instruction
1157 // in Ret if needed.
1161 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1162 auto itr = std::find(livevec.begin(), livevec.end(), val);
1163 assert(livevec.end() != itr);
1164 size_t index = std::distance(livevec.begin(), itr);
1165 assert(index < livevec.size());
1169 // Create new attribute set containing only attributes which can be transferred
1170 // from original call to the safepoint.
1171 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1174 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1175 unsigned index = AS.getSlotIndex(Slot);
1177 if (index == AttributeSet::ReturnIndex ||
1178 index == AttributeSet::FunctionIndex) {
1180 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1182 Attribute attr = *it;
1184 // Do not allow certain attributes - just skip them
1185 // Safepoint can not be read only or read none.
1186 if (attr.hasAttribute(Attribute::ReadNone) ||
1187 attr.hasAttribute(Attribute::ReadOnly))
1190 ret = ret.addAttributes(
1191 AS.getContext(), index,
1192 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1196 // Just skip parameter attributes for now
1202 /// Helper function to place all gc relocates necessary for the given
1205 /// liveVariables - list of variables to be relocated.
1206 /// liveStart - index of the first live variable.
1207 /// basePtrs - base pointers.
1208 /// statepointToken - statepoint instruction to which relocates should be
1210 /// Builder - Llvm IR builder to be used to construct new calls.
1211 static void CreateGCRelocates(ArrayRef<llvm::Value *> LiveVariables,
1212 const int LiveStart,
1213 ArrayRef<llvm::Value *> BasePtrs,
1214 Instruction *StatepointToken,
1215 IRBuilder<> Builder) {
1216 if (LiveVariables.empty())
1219 // All gc_relocate are set to i8 addrspace(1)* type. We originally generated
1220 // unique declarations for each pointer type, but this proved problematic
1221 // because the intrinsic mangling code is incomplete and fragile. Since
1222 // we're moving towards a single unified pointer type anyways, we can just
1223 // cast everything to an i8* of the right address space. A bitcast is added
1224 // later to convert gc_relocate to the actual value's type.
1225 Module *M = StatepointToken->getModule();
1226 auto AS = cast<PointerType>(LiveVariables[0]->getType())->getAddressSpace();
1227 Type *Types[] = {Type::getInt8PtrTy(M->getContext(), AS)};
1228 Value *GCRelocateDecl =
1229 Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
1231 for (unsigned i = 0; i < LiveVariables.size(); i++) {
1232 // Generate the gc.relocate call and save the result
1234 Builder.getInt32(LiveStart + find_index(LiveVariables, BasePtrs[i]));
1236 Builder.getInt32(LiveStart + find_index(LiveVariables, LiveVariables[i]));
1238 // only specify a debug name if we can give a useful one
1239 CallInst *Reloc = Builder.CreateCall(
1240 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1241 LiveVariables[i]->hasName() ? LiveVariables[i]->getName() + ".relocated"
1243 // Trick CodeGen into thinking there are lots of free registers at this
1245 Reloc->setCallingConv(CallingConv::Cold);
1250 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1251 const SmallVectorImpl<llvm::Value *> &basePtrs,
1252 const SmallVectorImpl<llvm::Value *> &liveVariables,
1254 PartiallyConstructedSafepointRecord &result) {
1255 assert(basePtrs.size() == liveVariables.size());
1256 assert(isStatepoint(CS) &&
1257 "This method expects to be rewriting a statepoint");
1259 BasicBlock *BB = CS.getInstruction()->getParent();
1261 Function *F = BB->getParent();
1262 assert(F && "must be set");
1263 Module *M = F->getParent();
1265 assert(M && "must be set");
1267 // We're not changing the function signature of the statepoint since the gc
1268 // arguments go into the var args section.
1269 Function *gc_statepoint_decl = CS.getCalledFunction();
1271 // Then go ahead and use the builder do actually do the inserts. We insert
1272 // immediately before the previous instruction under the assumption that all
1273 // arguments will be available here. We can't insert afterwards since we may
1274 // be replacing a terminator.
1275 Instruction *insertBefore = CS.getInstruction();
1276 IRBuilder<> Builder(insertBefore);
1277 // Copy all of the arguments from the original statepoint - this includes the
1278 // target, call args, and deopt args
1279 SmallVector<llvm::Value *, 64> args;
1280 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1281 // TODO: Clear the 'needs rewrite' flag
1283 // add all the pointers to be relocated (gc arguments)
1284 // Capture the start of the live variable list for use in the gc_relocates
1285 const int live_start = args.size();
1286 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1288 // Create the statepoint given all the arguments
1289 Instruction *token = nullptr;
1290 AttributeSet return_attributes;
1292 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1294 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1295 call->setTailCall(toReplace->isTailCall());
1296 call->setCallingConv(toReplace->getCallingConv());
1298 // Currently we will fail on parameter attributes and on certain
1299 // function attributes.
1300 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1301 // In case if we can handle this set of attributes - set up function attrs
1302 // directly on statepoint and return attrs later for gc_result intrinsic.
1303 call->setAttributes(new_attrs.getFnAttributes());
1304 return_attributes = new_attrs.getRetAttributes();
1308 // Put the following gc_result and gc_relocate calls immediately after the
1309 // the old call (which we're about to delete)
1310 BasicBlock::iterator next(toReplace);
1311 assert(BB->end() != next && "not a terminator, must have next");
1313 Instruction *IP = &*(next);
1314 Builder.SetInsertPoint(IP);
1315 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1318 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1320 // Insert the new invoke into the old block. We'll remove the old one in a
1321 // moment at which point this will become the new terminator for the
1323 InvokeInst *invoke = InvokeInst::Create(
1324 gc_statepoint_decl, toReplace->getNormalDest(),
1325 toReplace->getUnwindDest(), args, "statepoint_token", toReplace->getParent());
1326 invoke->setCallingConv(toReplace->getCallingConv());
1328 // Currently we will fail on parameter attributes and on certain
1329 // function attributes.
1330 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1331 // In case if we can handle this set of attributes - set up function attrs
1332 // directly on statepoint and return attrs later for gc_result intrinsic.
1333 invoke->setAttributes(new_attrs.getFnAttributes());
1334 return_attributes = new_attrs.getRetAttributes();
1338 // Generate gc relocates in exceptional path
1339 BasicBlock *unwindBlock = toReplace->getUnwindDest();
1340 assert(!isa<PHINode>(unwindBlock->begin()) &&
1341 unwindBlock->getUniquePredecessor() &&
1342 "can't safely insert in this block!");
1344 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1345 Builder.SetInsertPoint(IP);
1346 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1348 // Extract second element from landingpad return value. We will attach
1349 // exceptional gc relocates to it.
1350 const unsigned idx = 1;
1351 Instruction *exceptional_token =
1352 cast<Instruction>(Builder.CreateExtractValue(
1353 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1354 result.UnwindToken = exceptional_token;
1356 CreateGCRelocates(liveVariables, live_start, basePtrs,
1357 exceptional_token, Builder);
1359 // Generate gc relocates and returns for normal block
1360 BasicBlock *normalDest = toReplace->getNormalDest();
1361 assert(!isa<PHINode>(normalDest->begin()) &&
1362 normalDest->getUniquePredecessor() &&
1363 "can't safely insert in this block!");
1365 IP = &*(normalDest->getFirstInsertionPt());
1366 Builder.SetInsertPoint(IP);
1368 // gc relocates will be generated later as if it were regular call
1373 // Take the name of the original value call if it had one.
1374 token->takeName(CS.getInstruction());
1376 // The GCResult is already inserted, we just need to find it
1378 Instruction *toReplace = CS.getInstruction();
1379 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1380 "only valid use before rewrite is gc.result");
1381 assert(!toReplace->hasOneUse() ||
1382 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1385 // Update the gc.result of the original statepoint (if any) to use the newly
1386 // inserted statepoint. This is safe to do here since the token can't be
1387 // considered a live reference.
1388 CS.getInstruction()->replaceAllUsesWith(token);
1390 result.StatepointToken = token;
1392 // Second, create a gc.relocate for every live variable
1393 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1397 struct name_ordering {
1400 bool operator()(name_ordering const &a, name_ordering const &b) {
1401 return -1 == a.derived->getName().compare(b.derived->getName());
1405 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1406 SmallVectorImpl<Value *> &livevec) {
1407 assert(basevec.size() == livevec.size());
1409 SmallVector<name_ordering, 64> temp;
1410 for (size_t i = 0; i < basevec.size(); i++) {
1412 v.base = basevec[i];
1413 v.derived = livevec[i];
1416 std::sort(temp.begin(), temp.end(), name_ordering());
1417 for (size_t i = 0; i < basevec.size(); i++) {
1418 basevec[i] = temp[i].base;
1419 livevec[i] = temp[i].derived;
1423 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1424 // which make the relocations happening at this safepoint explicit.
1426 // WARNING: Does not do any fixup to adjust users of the original live
1427 // values. That's the callers responsibility.
1429 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1430 PartiallyConstructedSafepointRecord &result) {
1431 auto liveset = result.liveset;
1432 auto PointerToBase = result.PointerToBase;
1434 // Convert to vector for efficient cross referencing.
1435 SmallVector<Value *, 64> basevec, livevec;
1436 livevec.reserve(liveset.size());
1437 basevec.reserve(liveset.size());
1438 for (Value *L : liveset) {
1439 livevec.push_back(L);
1440 assert(PointerToBase.count(L));
1441 Value *base = PointerToBase[L];
1442 basevec.push_back(base);
1444 assert(livevec.size() == basevec.size());
1446 // To make the output IR slightly more stable (for use in diffs), ensure a
1447 // fixed order of the values in the safepoint (by sorting the value name).
1448 // The order is otherwise meaningless.
1449 stablize_order(basevec, livevec);
1451 // Do the actual rewriting and delete the old statepoint
1452 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1453 CS.getInstruction()->eraseFromParent();
1456 // Helper function for the relocationViaAlloca.
1457 // It receives iterator to the statepoint gc relocates and emits store to the
1459 // location (via allocaMap) for the each one of them.
1460 // Add visited values into the visitedLiveValues set we will later use them
1461 // for sanity check.
1463 insertRelocationStores(iterator_range<Value::user_iterator> GCRelocs,
1464 DenseMap<Value *, Value *> &AllocaMap,
1465 DenseSet<Value *> &VisitedLiveValues) {
1467 for (User *U : GCRelocs) {
1468 if (!isa<IntrinsicInst>(U))
1471 IntrinsicInst *RelocatedValue = cast<IntrinsicInst>(U);
1473 // We only care about relocates
1474 if (RelocatedValue->getIntrinsicID() !=
1475 Intrinsic::experimental_gc_relocate) {
1479 GCRelocateOperands RelocateOperands(RelocatedValue);
1480 Value *OriginalValue =
1481 const_cast<Value *>(RelocateOperands.getDerivedPtr());
1482 assert(AllocaMap.count(OriginalValue));
1483 Value *Alloca = AllocaMap[OriginalValue];
1485 // Emit store into the related alloca
1486 // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1487 // the correct type according to alloca.
1488 assert(RelocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1489 IRBuilder<> Builder(RelocatedValue->getNextNode());
1490 Value *CastedRelocatedValue =
1491 Builder.CreateBitCast(RelocatedValue, cast<AllocaInst>(Alloca)->getAllocatedType(),
1492 RelocatedValue->hasName() ? RelocatedValue->getName() + ".casted" : "");
1494 StoreInst *Store = new StoreInst(CastedRelocatedValue, Alloca);
1495 Store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1498 VisitedLiveValues.insert(OriginalValue);
1503 // Helper function for the "relocationViaAlloca". Similar to the
1504 // "insertRelocationStores" but works for rematerialized values.
1506 insertRematerializationStores(
1507 RematerializedValueMapTy RematerializedValues,
1508 DenseMap<Value *, Value *> &AllocaMap,
1509 DenseSet<Value *> &VisitedLiveValues) {
1511 for (auto RematerializedValuePair: RematerializedValues) {
1512 Instruction *RematerializedValue = RematerializedValuePair.first;
1513 Value *OriginalValue = RematerializedValuePair.second;
1515 assert(AllocaMap.count(OriginalValue) &&
1516 "Can not find alloca for rematerialized value");
1517 Value *Alloca = AllocaMap[OriginalValue];
1519 StoreInst *Store = new StoreInst(RematerializedValue, Alloca);
1520 Store->insertAfter(RematerializedValue);
1523 VisitedLiveValues.insert(OriginalValue);
1528 /// do all the relocation update via allocas and mem2reg
1529 static void relocationViaAlloca(
1530 Function &F, DominatorTree &DT, ArrayRef<Value *> Live,
1531 ArrayRef<struct PartiallyConstructedSafepointRecord> Records) {
1533 // record initial number of (static) allocas; we'll check we have the same
1534 // number when we get done.
1535 int InitialAllocaNum = 0;
1536 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1538 if (isa<AllocaInst>(*I))
1542 // TODO-PERF: change data structures, reserve
1543 DenseMap<Value *, Value *> AllocaMap;
1544 SmallVector<AllocaInst *, 200> PromotableAllocas;
1545 // Used later to chack that we have enough allocas to store all values
1546 std::size_t NumRematerializedValues = 0;
1547 PromotableAllocas.reserve(Live.size());
1549 // Emit alloca for "LiveValue" and record it in "allocaMap" and
1550 // "PromotableAllocas"
1551 auto emitAllocaFor = [&](Value *LiveValue) {
1552 AllocaInst *Alloca = new AllocaInst(LiveValue->getType(), "",
1553 F.getEntryBlock().getFirstNonPHI());
1554 AllocaMap[LiveValue] = Alloca;
1555 PromotableAllocas.push_back(Alloca);
1558 // emit alloca for each live gc pointer
1559 for (unsigned i = 0; i < Live.size(); i++) {
1560 emitAllocaFor(Live[i]);
1563 // emit allocas for rematerialized values
1564 for (size_t i = 0; i < Records.size(); i++) {
1565 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1567 for (auto RematerializedValuePair : Info.RematerializedValues) {
1568 Value *OriginalValue = RematerializedValuePair.second;
1569 if (AllocaMap.count(OriginalValue) != 0)
1572 emitAllocaFor(OriginalValue);
1573 ++NumRematerializedValues;
1577 // The next two loops are part of the same conceptual operation. We need to
1578 // insert a store to the alloca after the original def and at each
1579 // redefinition. We need to insert a load before each use. These are split
1580 // into distinct loops for performance reasons.
1582 // update gc pointer after each statepoint
1583 // either store a relocated value or null (if no relocated value found for
1584 // this gc pointer and it is not a gc_result)
1585 // this must happen before we update the statepoint with load of alloca
1586 // otherwise we lose the link between statepoint and old def
1587 for (size_t i = 0; i < Records.size(); i++) {
1588 const struct PartiallyConstructedSafepointRecord &Info = Records[i];
1589 Value *Statepoint = Info.StatepointToken;
1591 // This will be used for consistency check
1592 DenseSet<Value *> VisitedLiveValues;
1594 // Insert stores for normal statepoint gc relocates
1595 insertRelocationStores(Statepoint->users(), AllocaMap, VisitedLiveValues);
1597 // In case if it was invoke statepoint
1598 // we will insert stores for exceptional path gc relocates.
1599 if (isa<InvokeInst>(Statepoint)) {
1600 insertRelocationStores(Info.UnwindToken->users(), AllocaMap,
1604 // Do similar thing with rematerialized values
1605 insertRematerializationStores(Info.RematerializedValues, AllocaMap,
1608 if (ClobberNonLive) {
1609 // As a debugging aid, pretend that an unrelocated pointer becomes null at
1610 // the gc.statepoint. This will turn some subtle GC problems into
1611 // slightly easier to debug SEGVs. Note that on large IR files with
1612 // lots of gc.statepoints this is extremely costly both memory and time
1614 SmallVector<AllocaInst *, 64> ToClobber;
1615 for (auto Pair : AllocaMap) {
1616 Value *Def = Pair.first;
1617 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1619 // This value was relocated
1620 if (VisitedLiveValues.count(Def)) {
1623 ToClobber.push_back(Alloca);
1626 auto InsertClobbersAt = [&](Instruction *IP) {
1627 for (auto *AI : ToClobber) {
1628 auto AIType = cast<PointerType>(AI->getType());
1629 auto PT = cast<PointerType>(AIType->getElementType());
1630 Constant *CPN = ConstantPointerNull::get(PT);
1631 StoreInst *Store = new StoreInst(CPN, AI);
1632 Store->insertBefore(IP);
1636 // Insert the clobbering stores. These may get intermixed with the
1637 // gc.results and gc.relocates, but that's fine.
1638 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1639 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1640 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1642 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1644 InsertClobbersAt(Next);
1648 // update use with load allocas and add store for gc_relocated
1649 for (auto Pair : AllocaMap) {
1650 Value *Def = Pair.first;
1651 Value *Alloca = Pair.second;
1653 // we pre-record the uses of allocas so that we dont have to worry about
1655 // that change the user information.
1656 SmallVector<Instruction *, 20> Uses;
1657 // PERF: trade a linear scan for repeated reallocation
1658 Uses.reserve(std::distance(Def->user_begin(), Def->user_end()));
1659 for (User *U : Def->users()) {
1660 if (!isa<ConstantExpr>(U)) {
1661 // If the def has a ConstantExpr use, then the def is either a
1662 // ConstantExpr use itself or null. In either case
1663 // (recursively in the first, directly in the second), the oop
1664 // it is ultimately dependent on is null and this particular
1665 // use does not need to be fixed up.
1666 Uses.push_back(cast<Instruction>(U));
1670 std::sort(Uses.begin(), Uses.end());
1671 auto Last = std::unique(Uses.begin(), Uses.end());
1672 Uses.erase(Last, Uses.end());
1674 for (Instruction *Use : Uses) {
1675 if (isa<PHINode>(Use)) {
1676 PHINode *Phi = cast<PHINode>(Use);
1677 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++) {
1678 if (Def == Phi->getIncomingValue(i)) {
1679 LoadInst *Load = new LoadInst(
1680 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1681 Phi->setIncomingValue(i, Load);
1685 LoadInst *Load = new LoadInst(Alloca, "", Use);
1686 Use->replaceUsesOfWith(Def, Load);
1690 // emit store for the initial gc value
1691 // store must be inserted after load, otherwise store will be in alloca's
1692 // use list and an extra load will be inserted before it
1693 StoreInst *Store = new StoreInst(Def, Alloca);
1694 if (Instruction *Inst = dyn_cast<Instruction>(Def)) {
1695 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1696 // InvokeInst is a TerminatorInst so the store need to be inserted
1697 // into its normal destination block.
1698 BasicBlock *NormalDest = Invoke->getNormalDest();
1699 Store->insertBefore(NormalDest->getFirstNonPHI());
1701 assert(!Inst->isTerminator() &&
1702 "The only TerminatorInst that can produce a value is "
1703 "InvokeInst which is handled above.");
1704 Store->insertAfter(Inst);
1707 assert(isa<Argument>(Def));
1708 Store->insertAfter(cast<Instruction>(Alloca));
1712 assert(PromotableAllocas.size() == Live.size() + NumRematerializedValues &&
1713 "we must have the same allocas with lives");
1714 if (!PromotableAllocas.empty()) {
1715 // apply mem2reg to promote alloca to SSA
1716 PromoteMemToReg(PromotableAllocas, DT);
1720 for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1722 if (isa<AllocaInst>(*I))
1724 assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1728 /// Implement a unique function which doesn't require we sort the input
1729 /// vector. Doing so has the effect of changing the output of a couple of
1730 /// tests in ways which make them less useful in testing fused safepoints.
1731 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1732 SmallSet<T, 8> Seen;
1733 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), [&](const T &V) {
1734 return !Seen.insert(V).second;
1738 /// Insert holders so that each Value is obviously live through the entire
1739 /// lifetime of the call.
1740 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1741 SmallVectorImpl<CallInst *> &Holders) {
1743 // No values to hold live, might as well not insert the empty holder
1746 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1747 // Use a dummy vararg function to actually hold the values live
1748 Function *Func = cast<Function>(M->getOrInsertFunction(
1749 "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1751 // For call safepoints insert dummy calls right after safepoint
1752 BasicBlock::iterator Next(CS.getInstruction());
1754 Holders.push_back(CallInst::Create(Func, Values, "", Next));
1757 // For invoke safepooints insert dummy calls both in normal and
1758 // exceptional destination blocks
1759 auto *II = cast<InvokeInst>(CS.getInstruction());
1760 Holders.push_back(CallInst::Create(
1761 Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1762 Holders.push_back(CallInst::Create(
1763 Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
1766 static void findLiveReferences(
1767 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1768 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1769 GCPtrLivenessData OriginalLivenessData;
1770 computeLiveInValues(DT, F, OriginalLivenessData);
1771 for (size_t i = 0; i < records.size(); i++) {
1772 struct PartiallyConstructedSafepointRecord &info = records[i];
1773 const CallSite &CS = toUpdate[i];
1774 analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1778 /// Remove any vector of pointers from the liveset by scalarizing them over the
1779 /// statepoint instruction. Adds the scalarized pieces to the liveset. It
1780 /// would be preferable to include the vector in the statepoint itself, but
1781 /// the lowering code currently does not handle that. Extending it would be
1782 /// slightly non-trivial since it requires a format change. Given how rare
1783 /// such cases are (for the moment?) scalarizing is an acceptable compromise.
1784 static void splitVectorValues(Instruction *StatepointInst,
1785 StatepointLiveSetTy &LiveSet,
1786 DenseMap<Value *, Value *>& PointerToBase,
1787 DominatorTree &DT) {
1788 SmallVector<Value *, 16> ToSplit;
1789 for (Value *V : LiveSet)
1790 if (isa<VectorType>(V->getType()))
1791 ToSplit.push_back(V);
1793 if (ToSplit.empty())
1796 DenseMap<Value *, SmallVector<Value *, 16>> ElementMapping;
1798 Function &F = *(StatepointInst->getParent()->getParent());
1800 DenseMap<Value *, AllocaInst *> AllocaMap;
1801 // First is normal return, second is exceptional return (invoke only)
1802 DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1803 for (Value *V : ToSplit) {
1804 AllocaInst *Alloca =
1805 new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1806 AllocaMap[V] = Alloca;
1808 VectorType *VT = cast<VectorType>(V->getType());
1809 IRBuilder<> Builder(StatepointInst);
1810 SmallVector<Value *, 16> Elements;
1811 for (unsigned i = 0; i < VT->getNumElements(); i++)
1812 Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1813 ElementMapping[V] = Elements;
1815 auto InsertVectorReform = [&](Instruction *IP) {
1816 Builder.SetInsertPoint(IP);
1817 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1818 Value *ResultVec = UndefValue::get(VT);
1819 for (unsigned i = 0; i < VT->getNumElements(); i++)
1820 ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1821 Builder.getInt32(i));
1825 if (isa<CallInst>(StatepointInst)) {
1826 BasicBlock::iterator Next(StatepointInst);
1828 Instruction *IP = &*(Next);
1829 Replacements[V].first = InsertVectorReform(IP);
1830 Replacements[V].second = nullptr;
1832 InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1833 // We've already normalized - check that we don't have shared destination
1835 BasicBlock *NormalDest = Invoke->getNormalDest();
1836 assert(!isa<PHINode>(NormalDest->begin()));
1837 BasicBlock *UnwindDest = Invoke->getUnwindDest();
1838 assert(!isa<PHINode>(UnwindDest->begin()));
1839 // Insert insert element sequences in both successors
1840 Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1841 Replacements[V].first = InsertVectorReform(IP);
1842 IP = &*(UnwindDest->getFirstInsertionPt());
1843 Replacements[V].second = InsertVectorReform(IP);
1847 for (Value *V : ToSplit) {
1848 AllocaInst *Alloca = AllocaMap[V];
1850 // Capture all users before we start mutating use lists
1851 SmallVector<Instruction *, 16> Users;
1852 for (User *U : V->users())
1853 Users.push_back(cast<Instruction>(U));
1855 for (Instruction *I : Users) {
1856 if (auto Phi = dyn_cast<PHINode>(I)) {
1857 for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1858 if (V == Phi->getIncomingValue(i)) {
1859 LoadInst *Load = new LoadInst(
1860 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1861 Phi->setIncomingValue(i, Load);
1864 LoadInst *Load = new LoadInst(Alloca, "", I);
1865 I->replaceUsesOfWith(V, Load);
1869 // Store the original value and the replacement value into the alloca
1870 StoreInst *Store = new StoreInst(V, Alloca);
1871 if (auto I = dyn_cast<Instruction>(V))
1872 Store->insertAfter(I);
1874 Store->insertAfter(Alloca);
1876 // Normal return for invoke, or call return
1877 Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1878 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1879 // Unwind return for invoke only
1880 Replacement = cast_or_null<Instruction>(Replacements[V].second);
1882 (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1885 // apply mem2reg to promote alloca to SSA
1886 SmallVector<AllocaInst *, 16> Allocas;
1887 for (Value *V : ToSplit)
1888 Allocas.push_back(AllocaMap[V]);
1889 PromoteMemToReg(Allocas, DT);
1891 // Update our tracking of live pointers and base mappings to account for the
1892 // changes we just made.
1893 for (Value *V : ToSplit) {
1894 auto &Elements = ElementMapping[V];
1897 LiveSet.insert(Elements.begin(), Elements.end());
1898 // We need to update the base mapping as well.
1899 assert(PointerToBase.count(V));
1900 Value *OldBase = PointerToBase[V];
1901 auto &BaseElements = ElementMapping[OldBase];
1902 PointerToBase.erase(V);
1903 assert(Elements.size() == BaseElements.size());
1904 for (unsigned i = 0; i < Elements.size(); i++) {
1905 Value *Elem = Elements[i];
1906 PointerToBase[Elem] = BaseElements[i];
1911 // Helper function for the "rematerializeLiveValues". It walks use chain
1912 // starting from the "CurrentValue" until it meets "BaseValue". Only "simple"
1913 // values are visited (currently it is GEP's and casts). Returns true if it
1914 // successfully reached "BaseValue" and false otherwise.
1915 // Fills "ChainToBase" array with all visited values. "BaseValue" is not
1917 static bool findRematerializableChainToBasePointer(
1918 SmallVectorImpl<Instruction*> &ChainToBase,
1919 Value *CurrentValue, Value *BaseValue) {
1921 // We have found a base value
1922 if (CurrentValue == BaseValue) {
1926 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurrentValue)) {
1927 ChainToBase.push_back(GEP);
1928 return findRematerializableChainToBasePointer(ChainToBase,
1929 GEP->getPointerOperand(),
1933 if (CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1934 Value *Def = CI->stripPointerCasts();
1936 // This two checks are basically similar. First one is here for the
1937 // consistency with findBasePointers logic.
1938 assert(!isa<CastInst>(Def) && "not a pointer cast found");
1939 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1942 ChainToBase.push_back(CI);
1943 return findRematerializableChainToBasePointer(ChainToBase, Def, BaseValue);
1946 // Not supported instruction in the chain
1950 // Helper function for the "rematerializeLiveValues". Compute cost of the use
1951 // chain we are going to rematerialize.
1953 chainToBasePointerCost(SmallVectorImpl<Instruction*> &Chain,
1954 TargetTransformInfo &TTI) {
1957 for (Instruction *Instr : Chain) {
1958 if (CastInst *CI = dyn_cast<CastInst>(Instr)) {
1959 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1960 "non noop cast is found during rematerialization");
1962 Type *SrcTy = CI->getOperand(0)->getType();
1963 Cost += TTI.getCastInstrCost(CI->getOpcode(), CI->getType(), SrcTy);
1965 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Instr)) {
1966 // Cost of the address calculation
1967 Type *ValTy = GEP->getPointerOperandType()->getPointerElementType();
1968 Cost += TTI.getAddressComputationCost(ValTy);
1970 // And cost of the GEP itself
1971 // TODO: Use TTI->getGEPCost here (it exists, but appears to be not
1972 // allowed for the external usage)
1973 if (!GEP->hasAllConstantIndices())
1977 llvm_unreachable("unsupported instruciton type during rematerialization");
1984 // From the statepoint liveset pick values that are cheaper to recompute then to
1985 // relocate. Remove this values from the liveset, rematerialize them after
1986 // statepoint and record them in "Info" structure. Note that similar to
1987 // relocated values we don't do any user adjustments here.
1988 static void rematerializeLiveValues(CallSite CS,
1989 PartiallyConstructedSafepointRecord &Info,
1990 TargetTransformInfo &TTI) {
1991 const unsigned int ChainLengthThreshold = 10;
1993 // Record values we are going to delete from this statepoint live set.
1994 // We can not di this in following loop due to iterator invalidation.
1995 SmallVector<Value *, 32> LiveValuesToBeDeleted;
1997 for (Value *LiveValue: Info.liveset) {
1998 // For each live pointer find it's defining chain
1999 SmallVector<Instruction *, 3> ChainToBase;
2000 assert(Info.PointerToBase.count(LiveValue));
2002 findRematerializableChainToBasePointer(ChainToBase,
2004 Info.PointerToBase[LiveValue]);
2005 // Nothing to do, or chain is too long
2007 ChainToBase.size() == 0 ||
2008 ChainToBase.size() > ChainLengthThreshold)
2011 // Compute cost of this chain
2012 unsigned Cost = chainToBasePointerCost(ChainToBase, TTI);
2013 // TODO: We can also account for cases when we will be able to remove some
2014 // of the rematerialized values by later optimization passes. I.e if
2015 // we rematerialized several intersecting chains. Or if original values
2016 // don't have any uses besides this statepoint.
2018 // For invokes we need to rematerialize each chain twice - for normal and
2019 // for unwind basic blocks. Model this by multiplying cost by two.
2020 if (CS.isInvoke()) {
2023 // If it's too expensive - skip it
2024 if (Cost >= RematerializationThreshold)
2027 // Remove value from the live set
2028 LiveValuesToBeDeleted.push_back(LiveValue);
2030 // Clone instructions and record them inside "Info" structure
2032 // Walk backwards to visit top-most instructions first
2033 std::reverse(ChainToBase.begin(), ChainToBase.end());
2035 // Utility function which clones all instructions from "ChainToBase"
2036 // and inserts them before "InsertBefore". Returns rematerialized value
2037 // which should be used after statepoint.
2038 auto rematerializeChain = [&ChainToBase](Instruction *InsertBefore) {
2039 Instruction *LastClonedValue = nullptr;
2040 Instruction *LastValue = nullptr;
2041 for (Instruction *Instr: ChainToBase) {
2042 // Only GEP's and casts are suported as we need to be careful to not
2043 // introduce any new uses of pointers not in the liveset.
2044 // Note that it's fine to introduce new uses of pointers which were
2045 // otherwise not used after this statepoint.
2046 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2048 Instruction *ClonedValue = Instr->clone();
2049 ClonedValue->insertBefore(InsertBefore);
2050 ClonedValue->setName(Instr->getName() + ".remat");
2052 // If it is not first instruction in the chain then it uses previously
2053 // cloned value. We should update it to use cloned value.
2054 if (LastClonedValue) {
2056 ClonedValue->replaceUsesOfWith(LastValue, LastClonedValue);
2058 // Assert that cloned instruction does not use any instructions from
2059 // this chain other than LastClonedValue
2060 for (auto OpValue : ClonedValue->operand_values()) {
2061 assert(std::find(ChainToBase.begin(), ChainToBase.end(), OpValue) ==
2062 ChainToBase.end() &&
2063 "incorrect use in rematerialization chain");
2068 LastClonedValue = ClonedValue;
2071 assert(LastClonedValue);
2072 return LastClonedValue;
2075 // Different cases for calls and invokes. For invokes we need to clone
2076 // instructions both on normal and unwind path.
2078 Instruction *InsertBefore = CS.getInstruction()->getNextNode();
2079 assert(InsertBefore);
2080 Instruction *RematerializedValue = rematerializeChain(InsertBefore);
2081 Info.RematerializedValues[RematerializedValue] = LiveValue;
2083 InvokeInst *Invoke = cast<InvokeInst>(CS.getInstruction());
2085 Instruction *NormalInsertBefore =
2086 Invoke->getNormalDest()->getFirstInsertionPt();
2087 Instruction *UnwindInsertBefore =
2088 Invoke->getUnwindDest()->getFirstInsertionPt();
2090 Instruction *NormalRematerializedValue =
2091 rematerializeChain(NormalInsertBefore);
2092 Instruction *UnwindRematerializedValue =
2093 rematerializeChain(UnwindInsertBefore);
2095 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2096 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2100 // Remove rematerializaed values from the live set
2101 for (auto LiveValue: LiveValuesToBeDeleted) {
2102 Info.liveset.erase(LiveValue);
2106 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
2107 SmallVectorImpl<CallSite> &toUpdate) {
2109 // sanity check the input
2110 std::set<CallSite> uniqued;
2111 uniqued.insert(toUpdate.begin(), toUpdate.end());
2112 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
2114 for (size_t i = 0; i < toUpdate.size(); i++) {
2115 CallSite &CS = toUpdate[i];
2116 assert(CS.getInstruction()->getParent()->getParent() == &F);
2117 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
2121 // When inserting gc.relocates for invokes, we need to be able to insert at
2122 // the top of the successor blocks. See the comment on
2123 // normalForInvokeSafepoint on exactly what is needed. Note that this step
2124 // may restructure the CFG.
2125 for (CallSite CS : toUpdate) {
2128 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
2129 normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
2131 normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
2135 // A list of dummy calls added to the IR to keep various values obviously
2136 // live in the IR. We'll remove all of these when done.
2137 SmallVector<CallInst *, 64> holders;
2139 // Insert a dummy call with all of the arguments to the vm_state we'll need
2140 // for the actual safepoint insertion. This ensures reference arguments in
2141 // the deopt argument list are considered live through the safepoint (and
2142 // thus makes sure they get relocated.)
2143 for (size_t i = 0; i < toUpdate.size(); i++) {
2144 CallSite &CS = toUpdate[i];
2145 Statepoint StatepointCS(CS);
2147 SmallVector<Value *, 64> DeoptValues;
2148 for (Use &U : StatepointCS.vm_state_args()) {
2149 Value *Arg = cast<Value>(&U);
2150 assert(!isUnhandledGCPointerType(Arg->getType()) &&
2151 "support for FCA unimplemented");
2152 if (isHandledGCPointerType(Arg->getType()))
2153 DeoptValues.push_back(Arg);
2155 insertUseHolderAfter(CS, DeoptValues, holders);
2158 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
2159 records.reserve(toUpdate.size());
2160 for (size_t i = 0; i < toUpdate.size(); i++) {
2161 struct PartiallyConstructedSafepointRecord info;
2162 records.push_back(info);
2164 assert(records.size() == toUpdate.size());
2166 // A) Identify all gc pointers which are statically live at the given call
2168 findLiveReferences(F, DT, P, toUpdate, records);
2170 // B) Find the base pointers for each live pointer
2171 /* scope for caching */ {
2172 // Cache the 'defining value' relation used in the computation and
2173 // insertion of base phis and selects. This ensures that we don't insert
2174 // large numbers of duplicate base_phis.
2175 DefiningValueMapTy DVCache;
2177 for (size_t i = 0; i < records.size(); i++) {
2178 struct PartiallyConstructedSafepointRecord &info = records[i];
2179 CallSite &CS = toUpdate[i];
2180 findBasePointers(DT, DVCache, CS, info);
2182 } // end of cache scope
2184 // The base phi insertion logic (for any safepoint) may have inserted new
2185 // instructions which are now live at some safepoint. The simplest such
2188 // phi a <-- will be a new base_phi here
2189 // safepoint 1 <-- that needs to be live here
2193 // We insert some dummy calls after each safepoint to definitely hold live
2194 // the base pointers which were identified for that safepoint. We'll then
2195 // ask liveness for _every_ base inserted to see what is now live. Then we
2196 // remove the dummy calls.
2197 holders.reserve(holders.size() + records.size());
2198 for (size_t i = 0; i < records.size(); i++) {
2199 struct PartiallyConstructedSafepointRecord &info = records[i];
2200 CallSite &CS = toUpdate[i];
2202 SmallVector<Value *, 128> Bases;
2203 for (auto Pair : info.PointerToBase) {
2204 Bases.push_back(Pair.second);
2206 insertUseHolderAfter(CS, Bases, holders);
2209 // By selecting base pointers, we've effectively inserted new uses. Thus, we
2210 // need to rerun liveness. We may *also* have inserted new defs, but that's
2211 // not the key issue.
2212 recomputeLiveInValues(F, DT, P, toUpdate, records);
2214 if (PrintBasePointers) {
2215 for (size_t i = 0; i < records.size(); i++) {
2216 struct PartiallyConstructedSafepointRecord &info = records[i];
2217 errs() << "Base Pairs: (w/Relocation)\n";
2218 for (auto Pair : info.PointerToBase) {
2219 errs() << " derived %" << Pair.first->getName() << " base %"
2220 << Pair.second->getName() << "\n";
2224 for (size_t i = 0; i < holders.size(); i++) {
2225 holders[i]->eraseFromParent();
2226 holders[i] = nullptr;
2230 // Do a limited scalarization of any live at safepoint vector values which
2231 // contain pointers. This enables this pass to run after vectorization at
2232 // the cost of some possible performance loss. TODO: it would be nice to
2233 // natively support vectors all the way through the backend so we don't need
2234 // to scalarize here.
2235 for (size_t i = 0; i < records.size(); i++) {
2236 struct PartiallyConstructedSafepointRecord &info = records[i];
2237 Instruction *statepoint = toUpdate[i].getInstruction();
2238 splitVectorValues(cast<Instruction>(statepoint), info.liveset,
2239 info.PointerToBase, DT);
2242 // In order to reduce live set of statepoint we might choose to rematerialize
2243 // some values instead of relocating them. This is purely an optimization and
2244 // does not influence correctness.
2245 TargetTransformInfo &TTI =
2246 P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2248 for (size_t i = 0; i < records.size(); i++) {
2249 struct PartiallyConstructedSafepointRecord &info = records[i];
2250 CallSite &CS = toUpdate[i];
2252 rematerializeLiveValues(CS, info, TTI);
2255 // Now run through and replace the existing statepoints with new ones with
2256 // the live variables listed. We do not yet update uses of the values being
2257 // relocated. We have references to live variables that need to
2258 // survive to the last iteration of this loop. (By construction, the
2259 // previous statepoint can not be a live variable, thus we can and remove
2260 // the old statepoint calls as we go.)
2261 for (size_t i = 0; i < records.size(); i++) {
2262 struct PartiallyConstructedSafepointRecord &info = records[i];
2263 CallSite &CS = toUpdate[i];
2264 makeStatepointExplicit(DT, CS, P, info);
2266 toUpdate.clear(); // prevent accident use of invalid CallSites
2268 // Do all the fixups of the original live variables to their relocated selves
2269 SmallVector<Value *, 128> live;
2270 for (size_t i = 0; i < records.size(); i++) {
2271 struct PartiallyConstructedSafepointRecord &info = records[i];
2272 // We can't simply save the live set from the original insertion. One of
2273 // the live values might be the result of a call which needs a safepoint.
2274 // That Value* no longer exists and we need to use the new gc_result.
2275 // Thankfully, the liveset is embedded in the statepoint (and updated), so
2276 // we just grab that.
2277 Statepoint statepoint(info.StatepointToken);
2278 live.insert(live.end(), statepoint.gc_args_begin(),
2279 statepoint.gc_args_end());
2281 // Do some basic sanity checks on our liveness results before performing
2282 // relocation. Relocation can and will turn mistakes in liveness results
2283 // into non-sensical code which is must harder to debug.
2284 // TODO: It would be nice to test consistency as well
2285 assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
2286 "statepoint must be reachable or liveness is meaningless");
2287 for (Value *V : statepoint.gc_args()) {
2288 if (!isa<Instruction>(V))
2289 // Non-instruction values trivial dominate all possible uses
2291 auto LiveInst = cast<Instruction>(V);
2292 assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
2293 "unreachable values should never be live");
2294 assert(DT.dominates(LiveInst, info.StatepointToken) &&
2295 "basic SSA liveness expectation violated by liveness analysis");
2299 unique_unsorted(live);
2303 for (auto ptr : live) {
2304 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
2308 relocationViaAlloca(F, DT, live, records);
2309 return !records.empty();
2312 // Handles both return values and arguments for Functions and CallSites.
2313 template <typename AttrHolder>
2314 static void RemoveDerefAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH,
2317 if (AH.getDereferenceableBytes(Index))
2318 R.addAttribute(Attribute::get(Ctx, Attribute::Dereferenceable,
2319 AH.getDereferenceableBytes(Index)));
2320 if (AH.getDereferenceableOrNullBytes(Index))
2321 R.addAttribute(Attribute::get(Ctx, Attribute::DereferenceableOrNull,
2322 AH.getDereferenceableOrNullBytes(Index)));
2325 AH.setAttributes(AH.getAttributes().removeAttributes(
2326 Ctx, Index, AttributeSet::get(Ctx, Index, R)));
2330 RewriteStatepointsForGC::stripDereferenceabilityInfoFromPrototype(Function &F) {
2331 LLVMContext &Ctx = F.getContext();
2333 for (Argument &A : F.args())
2334 if (isa<PointerType>(A.getType()))
2335 RemoveDerefAttrAtIndex(Ctx, F, A.getArgNo() + 1);
2337 if (isa<PointerType>(F.getReturnType()))
2338 RemoveDerefAttrAtIndex(Ctx, F, AttributeSet::ReturnIndex);
2341 void RewriteStatepointsForGC::stripDereferenceabilityInfoFromBody(Function &F) {
2345 LLVMContext &Ctx = F.getContext();
2346 MDBuilder Builder(Ctx);
2348 for (Instruction &I : instructions(F)) {
2349 if (const MDNode *MD = I.getMetadata(LLVMContext::MD_tbaa)) {
2350 assert(MD->getNumOperands() < 5 && "unrecognized metadata shape!");
2351 bool IsImmutableTBAA =
2352 MD->getNumOperands() == 4 &&
2353 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2355 if (!IsImmutableTBAA)
2356 continue; // no work to do, MD_tbaa is already marked mutable
2358 MDNode *Base = cast<MDNode>(MD->getOperand(0));
2359 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2361 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2363 MDNode *MutableTBAA =
2364 Builder.createTBAAStructTagNode(Base, Access, Offset);
2365 I.setMetadata(LLVMContext::MD_tbaa, MutableTBAA);
2368 if (CallSite CS = CallSite(&I)) {
2369 for (int i = 0, e = CS.arg_size(); i != e; i++)
2370 if (isa<PointerType>(CS.getArgument(i)->getType()))
2371 RemoveDerefAttrAtIndex(Ctx, CS, i + 1);
2372 if (isa<PointerType>(CS.getType()))
2373 RemoveDerefAttrAtIndex(Ctx, CS, AttributeSet::ReturnIndex);
2378 /// Returns true if this function should be rewritten by this pass. The main
2379 /// point of this function is as an extension point for custom logic.
2380 static bool shouldRewriteStatepointsIn(Function &F) {
2381 // TODO: This should check the GCStrategy
2383 const char *FunctionGCName = F.getGC();
2384 const StringRef StatepointExampleName("statepoint-example");
2385 const StringRef CoreCLRName("coreclr");
2386 return (StatepointExampleName == FunctionGCName) ||
2387 (CoreCLRName == FunctionGCName);
2392 void RewriteStatepointsForGC::stripDereferenceabilityInfo(Module &M) {
2394 assert(std::any_of(M.begin(), M.end(), shouldRewriteStatepointsIn) &&
2398 for (Function &F : M)
2399 stripDereferenceabilityInfoFromPrototype(F);
2401 for (Function &F : M)
2402 stripDereferenceabilityInfoFromBody(F);
2405 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
2406 // Nothing to do for declarations.
2407 if (F.isDeclaration() || F.empty())
2410 // Policy choice says not to rewrite - the most common reason is that we're
2411 // compiling code without a GCStrategy.
2412 if (!shouldRewriteStatepointsIn(F))
2415 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
2417 // Gather all the statepoints which need rewritten. Be careful to only
2418 // consider those in reachable code since we need to ask dominance queries
2419 // when rewriting. We'll delete the unreachable ones in a moment.
2420 SmallVector<CallSite, 64> ParsePointNeeded;
2421 bool HasUnreachableStatepoint = false;
2422 for (Instruction &I : instructions(F)) {
2423 // TODO: only the ones with the flag set!
2424 if (isStatepoint(I)) {
2425 if (DT.isReachableFromEntry(I.getParent()))
2426 ParsePointNeeded.push_back(CallSite(&I));
2428 HasUnreachableStatepoint = true;
2432 bool MadeChange = false;
2434 // Delete any unreachable statepoints so that we don't have unrewritten
2435 // statepoints surviving this pass. This makes testing easier and the
2436 // resulting IR less confusing to human readers. Rather than be fancy, we
2437 // just reuse a utility function which removes the unreachable blocks.
2438 if (HasUnreachableStatepoint)
2439 MadeChange |= removeUnreachableBlocks(F);
2441 // Return early if no work to do.
2442 if (ParsePointNeeded.empty())
2445 // As a prepass, go ahead and aggressively destroy single entry phi nodes.
2446 // These are created by LCSSA. They have the effect of increasing the size
2447 // of liveness sets for no good reason. It may be harder to do this post
2448 // insertion since relocations and base phis can confuse things.
2449 for (BasicBlock &BB : F)
2450 if (BB.getUniquePredecessor()) {
2452 FoldSingleEntryPHINodes(&BB);
2455 MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
2459 // liveness computation via standard dataflow
2460 // -------------------------------------------------------------------
2462 // TODO: Consider using bitvectors for liveness, the set of potentially
2463 // interesting values should be small and easy to pre-compute.
2465 /// Compute the live-in set for the location rbegin starting from
2466 /// the live-out set of the basic block
2467 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
2468 BasicBlock::reverse_iterator rend,
2469 DenseSet<Value *> &LiveTmp) {
2471 for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
2472 Instruction *I = &*ritr;
2474 // KILL/Def - Remove this definition from LiveIn
2477 // Don't consider *uses* in PHI nodes, we handle their contribution to
2478 // predecessor blocks when we seed the LiveOut sets
2479 if (isa<PHINode>(I))
2482 // USE - Add to the LiveIn set for this instruction
2483 for (Value *V : I->operands()) {
2484 assert(!isUnhandledGCPointerType(V->getType()) &&
2485 "support for FCA unimplemented");
2486 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2487 // The choice to exclude all things constant here is slightly subtle.
2488 // There are two independent reasons:
2489 // - We assume that things which are constant (from LLVM's definition)
2490 // do not move at runtime. For example, the address of a global
2491 // variable is fixed, even though it's contents may not be.
2492 // - Second, we can't disallow arbitrary inttoptr constants even
2493 // if the language frontend does. Optimization passes are free to
2494 // locally exploit facts without respect to global reachability. This
2495 // can create sections of code which are dynamically unreachable and
2496 // contain just about anything. (see constants.ll in tests)
2503 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2505 for (BasicBlock *Succ : successors(BB)) {
2506 const BasicBlock::iterator E(Succ->getFirstNonPHI());
2507 for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2508 PHINode *Phi = cast<PHINode>(&*I);
2509 Value *V = Phi->getIncomingValueForBlock(BB);
2510 assert(!isUnhandledGCPointerType(V->getType()) &&
2511 "support for FCA unimplemented");
2512 if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2519 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2520 DenseSet<Value *> KillSet;
2521 for (Instruction &I : *BB)
2522 if (isHandledGCPointerType(I.getType()))
2528 /// Check that the items in 'Live' dominate 'TI'. This is used as a basic
2529 /// sanity check for the liveness computation.
2530 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2531 TerminatorInst *TI, bool TermOkay = false) {
2532 for (Value *V : Live) {
2533 if (auto *I = dyn_cast<Instruction>(V)) {
2534 // The terminator can be a member of the LiveOut set. LLVM's definition
2535 // of instruction dominance states that V does not dominate itself. As
2536 // such, we need to special case this to allow it.
2537 if (TermOkay && TI == I)
2539 assert(DT.dominates(I, TI) &&
2540 "basic SSA liveness expectation violated by liveness analysis");
2545 /// Check that all the liveness sets used during the computation of liveness
2546 /// obey basic SSA properties. This is useful for finding cases where we miss
2548 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2550 checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2551 checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2552 checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2556 static void computeLiveInValues(DominatorTree &DT, Function &F,
2557 GCPtrLivenessData &Data) {
2559 SmallSetVector<BasicBlock *, 200> Worklist;
2560 auto AddPredsToWorklist = [&](BasicBlock *BB) {
2561 // We use a SetVector so that we don't have duplicates in the worklist.
2562 Worklist.insert(pred_begin(BB), pred_end(BB));
2564 auto NextItem = [&]() {
2565 BasicBlock *BB = Worklist.back();
2566 Worklist.pop_back();
2570 // Seed the liveness for each individual block
2571 for (BasicBlock &BB : F) {
2572 Data.KillSet[&BB] = computeKillSet(&BB);
2573 Data.LiveSet[&BB].clear();
2574 computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2577 for (Value *Kill : Data.KillSet[&BB])
2578 assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2581 Data.LiveOut[&BB] = DenseSet<Value *>();
2582 computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2583 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2584 set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2585 set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2586 if (!Data.LiveIn[&BB].empty())
2587 AddPredsToWorklist(&BB);
2590 // Propagate that liveness until stable
2591 while (!Worklist.empty()) {
2592 BasicBlock *BB = NextItem();
2594 // Compute our new liveout set, then exit early if it hasn't changed
2595 // despite the contribution of our successor.
2596 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2597 const auto OldLiveOutSize = LiveOut.size();
2598 for (BasicBlock *Succ : successors(BB)) {
2599 assert(Data.LiveIn.count(Succ));
2600 set_union(LiveOut, Data.LiveIn[Succ]);
2602 // assert OutLiveOut is a subset of LiveOut
2603 if (OldLiveOutSize == LiveOut.size()) {
2604 // If the sets are the same size, then we didn't actually add anything
2605 // when unioning our successors LiveIn Thus, the LiveIn of this block
2609 Data.LiveOut[BB] = LiveOut;
2611 // Apply the effects of this basic block
2612 DenseSet<Value *> LiveTmp = LiveOut;
2613 set_union(LiveTmp, Data.LiveSet[BB]);
2614 set_subtract(LiveTmp, Data.KillSet[BB]);
2616 assert(Data.LiveIn.count(BB));
2617 const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2618 // assert: OldLiveIn is a subset of LiveTmp
2619 if (OldLiveIn.size() != LiveTmp.size()) {
2620 Data.LiveIn[BB] = LiveTmp;
2621 AddPredsToWorklist(BB);
2623 } // while( !worklist.empty() )
2626 // Sanity check our output against SSA properties. This helps catch any
2627 // missing kills during the above iteration.
2628 for (BasicBlock &BB : F) {
2629 checkBasicSSA(DT, Data, BB);
2634 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2635 StatepointLiveSetTy &Out) {
2637 BasicBlock *BB = Inst->getParent();
2639 // Note: The copy is intentional and required
2640 assert(Data.LiveOut.count(BB));
2641 DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2643 // We want to handle the statepoint itself oddly. It's
2644 // call result is not live (normal), nor are it's arguments
2645 // (unless they're used again later). This adjustment is
2646 // specifically what we need to relocate
2647 BasicBlock::reverse_iterator rend(Inst);
2648 computeLiveInValues(BB->rbegin(), rend, LiveOut);
2649 LiveOut.erase(Inst);
2650 Out.insert(LiveOut.begin(), LiveOut.end());
2653 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2655 PartiallyConstructedSafepointRecord &Info) {
2656 Instruction *Inst = CS.getInstruction();
2657 StatepointLiveSetTy Updated;
2658 findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2661 DenseSet<Value *> Bases;
2662 for (auto KVPair : Info.PointerToBase) {
2663 Bases.insert(KVPair.second);
2666 // We may have base pointers which are now live that weren't before. We need
2667 // to update the PointerToBase structure to reflect this.
2668 for (auto V : Updated)
2669 if (!Info.PointerToBase.count(V)) {
2670 assert(Bases.count(V) && "can't find base for unexpected live value");
2671 Info.PointerToBase[V] = V;
2676 for (auto V : Updated) {
2677 assert(Info.PointerToBase.count(V) &&
2678 "must be able to find base for live value");
2682 // Remove any stale base mappings - this can happen since our liveness is
2683 // more precise then the one inherent in the base pointer analysis
2684 DenseSet<Value *> ToErase;
2685 for (auto KVPair : Info.PointerToBase)
2686 if (!Updated.count(KVPair.first))
2687 ToErase.insert(KVPair.first);
2688 for (auto V : ToErase)
2689 Info.PointerToBase.erase(V);
2692 for (auto KVPair : Info.PointerToBase)
2693 assert(Updated.count(KVPair.first) && "record for non-live value");
2696 Info.liveset = Updated;