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/ADT/SetOperations.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/InstIterator.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Statepoint.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
41 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
45 // Print tracing output
46 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
49 // Print the liveset found at the insert location
50 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
52 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size",
53 cl::Hidden, cl::init(false));
54 // Print out the base pointers for debugging
55 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers",
56 cl::Hidden, cl::init(false));
59 struct RewriteStatepointsForGC : public FunctionPass {
60 static char ID; // Pass identification, replacement for typeid
62 RewriteStatepointsForGC() : FunctionPass(ID) {
63 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
65 bool runOnFunction(Function &F) override;
67 void getAnalysisUsage(AnalysisUsage &AU) const override {
68 // We add and rewrite a bunch of instructions, but don't really do much
69 // else. We could in theory preserve a lot more analyses here.
70 AU.addRequired<DominatorTreeWrapperPass>();
75 char RewriteStatepointsForGC::ID = 0;
77 FunctionPass *llvm::createRewriteStatepointsForGCPass() {
78 return new RewriteStatepointsForGC();
81 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
82 "Make relocations explicit at statepoints", false, false)
83 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
84 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
85 "Make relocations explicit at statepoints", false, false)
88 // The type of the internal cache used inside the findBasePointers family
89 // of functions. From the callers perspective, this is an opaque type and
90 // should not be inspected.
92 // In the actual implementation this caches two relations:
93 // - The base relation itself (i.e. this pointer is based on that one)
94 // - The base defining value relation (i.e. before base_phi insertion)
95 // Generally, after the execution of a full findBasePointer call, only the
96 // base relation will remain. Internally, we add a mixture of the two
97 // types, then update all the second type to the first type
98 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
99 typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
101 struct PartiallyConstructedSafepointRecord {
102 /// The set of values known to be live accross this safepoint
103 StatepointLiveSetTy liveset;
105 /// Mapping from live pointers to a base-defining-value
106 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
108 /// Any new values which were added to the IR during base pointer analysis
109 /// for this safepoint
110 DenseSet<llvm::Value *> NewInsertedDefs;
112 /// The *new* gc.statepoint instruction itself. This produces the token
113 /// that normal path gc.relocates and the gc.result are tied to.
114 Instruction *StatepointToken;
116 /// Instruction to which exceptional gc relocates are attached
117 /// Makes it easier to iterate through them during relocationViaAlloca.
118 Instruction *UnwindToken;
122 // TODO: Once we can get to the GCStrategy, this becomes
123 // Optional<bool> isGCManagedPointer(const Value *V) const override {
125 static bool isGCPointerType(const Type *T) {
126 if (const PointerType *PT = dyn_cast<PointerType>(T))
127 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
128 // GC managed heap. We know that a pointer into this heap needs to be
129 // updated and that no other pointer does.
130 return (1 == PT->getAddressSpace());
134 /// Return true if the Value is a gc reference type which is potentially used
135 /// after the instruction 'loc'. This is only used with the edge reachability
136 /// liveness code. Note: It is assumed the V dominates loc.
137 static bool isLiveGCReferenceAt(Value &V, Instruction *loc, DominatorTree &DT,
139 if (!isGCPointerType(V.getType()))
145 // Given assumption that V dominates loc, this may be live
150 static bool isAggWhichContainsGCPtrType(Type *Ty) {
151 if (VectorType *VT = dyn_cast<VectorType>(Ty))
152 return isGCPointerType(VT->getScalarType());
153 if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
154 return isGCPointerType(AT->getElementType()) ||
155 isAggWhichContainsGCPtrType(AT->getElementType());
156 if (StructType *ST = dyn_cast<StructType>(Ty))
157 return std::any_of(ST->subtypes().begin(), ST->subtypes().end(),
159 return isGCPointerType(SubType) ||
160 isAggWhichContainsGCPtrType(SubType);
166 // Conservatively identifies any definitions which might be live at the
167 // given instruction. The analysis is performed immediately before the
168 // given instruction. Values defined by that instruction are not considered
169 // live. Values used by that instruction are considered live.
171 // preconditions: valid IR graph, term is either a terminator instruction or
172 // a call instruction, pred is the basic block of term, DT, LI are valid
174 // side effects: none, does not mutate IR
176 // postconditions: populates liveValues as discussed above
177 static void findLiveGCValuesAtInst(Instruction *term, BasicBlock *pred,
178 DominatorTree &DT, LoopInfo *LI,
179 StatepointLiveSetTy &liveValues) {
182 assert(isa<CallInst>(term) || isa<InvokeInst>(term) || term->isTerminator());
184 Function *F = pred->getParent();
186 auto is_live_gc_reference =
187 [&](Value &V) { return isLiveGCReferenceAt(V, term, DT, LI); };
189 // Are there any gc pointer arguments live over this point? This needs to be
190 // special cased since arguments aren't defined in basic blocks.
191 for (Argument &arg : F->args()) {
192 assert(!isAggWhichContainsGCPtrType(arg.getType()) &&
193 "support for FCA unimplemented");
195 if (is_live_gc_reference(arg)) {
196 liveValues.insert(&arg);
200 // Walk through all dominating blocks - the ones which can contain
201 // definitions used in this block - and check to see if any of the values
202 // they define are used in locations potentially reachable from the
203 // interesting instruction.
204 BasicBlock *BBI = pred;
207 errs() << "[LSP] Looking at dominating block " << pred->getName() << "\n";
209 assert(DT.dominates(BBI, pred));
210 assert(isPotentiallyReachable(BBI, pred, &DT) &&
211 "dominated block must be reachable");
213 // Walk through the instructions in dominating blocks and keep any
214 // that have a use potentially reachable from the block we're
215 // considering putting the safepoint in
216 for (Instruction &inst : *BBI) {
218 errs() << "[LSP] Looking at instruction ";
222 if (pred == BBI && (&inst) == term) {
224 errs() << "[LSP] stopped because we encountered the safepoint "
228 // If we're in the block which defines the interesting instruction,
229 // we don't want to include any values as live which are defined
230 // _after_ the interesting line or as part of the line itself
231 // i.e. "term" is the call instruction for a call safepoint, the
232 // results of the call should not be considered live in that stackmap
236 assert(!isAggWhichContainsGCPtrType(inst.getType()) &&
237 "support for FCA unimplemented");
239 if (is_live_gc_reference(inst)) {
241 errs() << "[LSP] found live value for this safepoint ";
245 liveValues.insert(&inst);
248 if (!DT.getNode(BBI)->getIDom()) {
249 assert(BBI == &F->getEntryBlock() &&
250 "failed to find a dominator for something other than "
254 BBI = DT.getNode(BBI)->getIDom()->getBlock();
258 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
259 if (a->hasName() && b->hasName()) {
260 return -1 == a->getName().compare(b->getName());
261 } else if (a->hasName() && !b->hasName()) {
263 } else if (!a->hasName() && b->hasName()) {
266 // Better than nothing, but not stable
271 /// Find the initial live set. Note that due to base pointer
272 /// insertion, the live set may be incomplete.
274 analyzeParsePointLiveness(DominatorTree &DT, const CallSite &CS,
275 PartiallyConstructedSafepointRecord &result) {
276 Instruction *inst = CS.getInstruction();
278 BasicBlock *BB = inst->getParent();
279 StatepointLiveSetTy liveset;
280 findLiveGCValuesAtInst(inst, BB, DT, nullptr, liveset);
283 // Note: This output is used by several of the test cases
284 // The order of elemtns in a set is not stable, put them in a vec and sort
286 SmallVector<Value *, 64> temp;
287 temp.insert(temp.end(), liveset.begin(), liveset.end());
288 std::sort(temp.begin(), temp.end(), order_by_name);
289 errs() << "Live Variables:\n";
290 for (Value *V : temp) {
291 errs() << " " << V->getName(); // no newline
295 if (PrintLiveSetSize) {
296 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
297 errs() << "Number live values: " << liveset.size() << "\n";
299 result.liveset = liveset;
302 /// True iff this value is the null pointer constant (of any pointer type)
303 static bool LLVM_ATTRIBUTE_UNUSED isNullConstant(Value *V) {
304 return isa<Constant>(V) && isa<PointerType>(V->getType()) &&
305 cast<Constant>(V)->isNullValue();
308 /// Helper function for findBasePointer - Will return a value which either a)
309 /// defines the base pointer for the input or b) blocks the simple search
310 /// (i.e. a PHI or Select of two derived pointers)
311 static Value *findBaseDefiningValue(Value *I) {
312 assert(I->getType()->isPointerTy() &&
313 "Illegal to ask for the base pointer of a non-pointer type");
315 // There are instructions which can never return gc pointer values. Sanity
316 // check that this is actually true.
317 assert(!isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
318 !isa<ShuffleVectorInst>(I) && "Vector types are not gc pointers");
320 if (isa<Argument>(I))
321 // An incoming argument to the function is a base pointer
322 // We should have never reached here if this argument isn't an gc value
325 if (isa<GlobalVariable>(I))
329 // inlining could possibly introduce phi node that contains
330 // undef if callee has multiple returns
331 if (isa<UndefValue>(I))
332 // utterly meaningless, but useful for dealing with
333 // partially optimized code.
336 // Due to inheritance, this must be _after_ the global variable and undef
338 if (Constant *Con = dyn_cast<Constant>(I)) {
339 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
340 "order of checks wrong!");
341 // Note: Finding a constant base for something marked for relocation
342 // doesn't really make sense. The most likely case is either a) some
343 // screwed up the address space usage or b) your validating against
344 // compiled C++ code w/o the proper separation. The only real exception
345 // is a null pointer. You could have generic code written to index of
346 // off a potentially null value and have proven it null. We also use
347 // null pointers in dead paths of relocation phis (which we might later
348 // want to find a base pointer for).
349 assert(Con->getType()->isPointerTy() &&
350 "Base for pointer must be another pointer");
351 assert(Con->isNullValue() && "null is the only case which makes sense");
355 if (CastInst *CI = dyn_cast<CastInst>(I)) {
356 Value *Def = CI->stripPointerCasts();
357 // If we find a cast instruction here, it means we've found a cast which is
358 // not simply a pointer cast (i.e. an inttoptr). We don't know how to
359 // handle int->ptr conversion.
360 assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
361 return findBaseDefiningValue(Def);
364 if (isa<LoadInst>(I))
365 return I; // The value loaded is an gc base itself
367 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
368 // The base of this GEP is the base
369 return findBaseDefiningValue(GEP->getPointerOperand());
371 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
372 switch (II->getIntrinsicID()) {
373 case Intrinsic::experimental_gc_result_ptr:
375 // fall through to general call handling
377 case Intrinsic::experimental_gc_statepoint:
378 case Intrinsic::experimental_gc_result_float:
379 case Intrinsic::experimental_gc_result_int:
380 llvm_unreachable("these don't produce pointers");
381 case Intrinsic::experimental_gc_relocate: {
382 // Rerunning safepoint insertion after safepoints are already
383 // inserted is not supported. It could probably be made to work,
384 // but why are you doing this? There's no good reason.
385 llvm_unreachable("repeat safepoint insertion is not supported");
387 case Intrinsic::gcroot:
388 // Currently, this mechanism hasn't been extended to work with gcroot.
389 // There's no reason it couldn't be, but I haven't thought about the
390 // implications much.
392 "interaction with the gcroot mechanism is not supported");
395 // We assume that functions in the source language only return base
396 // pointers. This should probably be generalized via attributes to support
397 // both source language and internal functions.
398 if (isa<CallInst>(I) || isa<InvokeInst>(I))
401 // I have absolutely no idea how to implement this part yet. It's not
402 // neccessarily hard, I just haven't really looked at it yet.
403 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
405 if (isa<AtomicCmpXchgInst>(I))
406 // A CAS is effectively a atomic store and load combined under a
407 // predicate. From the perspective of base pointers, we just treat it
411 assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
412 "binary ops which don't apply to pointers");
414 // The aggregate ops. Aggregates can either be in the heap or on the
415 // stack, but in either case, this is simply a field load. As a result,
416 // this is a defining definition of the base just like a load is.
417 if (isa<ExtractValueInst>(I))
420 // We should never see an insert vector since that would require we be
421 // tracing back a struct value not a pointer value.
422 assert(!isa<InsertValueInst>(I) &&
423 "Base pointer for a struct is meaningless");
425 // The last two cases here don't return a base pointer. Instead, they
426 // return a value which dynamically selects from amoung several base
427 // derived pointers (each with it's own base potentially). It's the job of
428 // the caller to resolve these.
429 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
430 "missing instruction case in findBaseDefiningValing");
434 /// Returns the base defining value for this value.
435 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &cache) {
436 Value *&Cached = cache[I];
438 Cached = findBaseDefiningValue(I);
440 assert(cache[I] != nullptr);
443 errs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
449 /// Return a base pointer for this value if known. Otherwise, return it's
450 /// base defining value.
451 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &cache) {
452 Value *def = findBaseDefiningValueCached(I, cache);
453 auto Found = cache.find(def);
454 if (Found != cache.end()) {
455 // Either a base-of relation, or a self reference. Caller must check.
456 return Found->second;
458 // Only a BDV available
462 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
463 /// is it known to be a base pointer? Or do we need to continue searching.
464 static bool isKnownBaseResult(Value *v) {
465 if (!isa<PHINode>(v) && !isa<SelectInst>(v)) {
466 // no recursion possible
469 if (cast<Instruction>(v)->getMetadata("is_base_value")) {
470 // This is a previously inserted base phi or select. We know
471 // that this is a base value.
475 // We need to keep searching
479 // TODO: find a better name for this
483 enum Status { Unknown, Base, Conflict };
485 PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
486 assert(status != Base || b);
488 PhiState(Value *b) : status(Base), base(b) {}
489 PhiState() : status(Unknown), base(nullptr) {}
491 Status getStatus() const { return status; }
492 Value *getBase() const { return base; }
494 bool isBase() const { return getStatus() == Base; }
495 bool isUnknown() const { return getStatus() == Unknown; }
496 bool isConflict() const { return getStatus() == Conflict; }
498 bool operator==(const PhiState &other) const {
499 return base == other.base && status == other.status;
502 bool operator!=(const PhiState &other) const { return !(*this == other); }
505 errs() << status << " (" << base << " - "
506 << (base ? base->getName() : "nullptr") << "): ";
511 Value *base; // non null only if status == base
514 typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
515 // Values of type PhiState form a lattice, and this is a helper
516 // class that implementes the meet operation. The meat of the meet
517 // operation is implemented in MeetPhiStates::pureMeet
518 class MeetPhiStates {
520 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
521 explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
522 : phiStates(phiStates) {}
524 // Destructively meet the current result with the base V. V can
525 // either be a merge instruction (SelectInst / PHINode), in which
526 // case its status is looked up in the phiStates map; or a regular
527 // SSA value, in which case it is assumed to be a base.
528 void meetWith(Value *V) {
529 PhiState otherState = getStateForBDV(V);
530 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
531 MeetPhiStates::pureMeet(currentResult, otherState)) &&
532 "math is wrong: meet does not commute!");
533 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
536 PhiState getResult() const { return currentResult; }
539 const ConflictStateMapTy &phiStates;
540 PhiState currentResult;
542 /// Return a phi state for a base defining value. We'll generate a new
543 /// base state for known bases and expect to find a cached state otherwise
544 PhiState getStateForBDV(Value *baseValue) {
545 if (isKnownBaseResult(baseValue)) {
546 return PhiState(baseValue);
548 return lookupFromMap(baseValue);
552 PhiState lookupFromMap(Value *V) {
553 auto I = phiStates.find(V);
554 assert(I != phiStates.end() && "lookup failed!");
558 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
559 switch (stateA.getStatus()) {
560 case PhiState::Unknown:
564 assert(stateA.getBase() && "can't be null");
565 if (stateB.isUnknown())
568 if (stateB.isBase()) {
569 if (stateA.getBase() == stateB.getBase()) {
570 assert(stateA == stateB && "equality broken!");
573 return PhiState(PhiState::Conflict);
575 assert(stateB.isConflict() && "only three states!");
576 return PhiState(PhiState::Conflict);
578 case PhiState::Conflict:
581 llvm_unreachable("only three states!");
585 /// For a given value or instruction, figure out what base ptr it's derived
586 /// from. For gc objects, this is simply itself. On success, returns a value
587 /// which is the base pointer. (This is reliable and can be used for
588 /// relocation.) On failure, returns nullptr.
589 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache,
590 DenseSet<llvm::Value *> &NewInsertedDefs) {
591 Value *def = findBaseOrBDV(I, cache);
593 if (isKnownBaseResult(def)) {
597 // Here's the rough algorithm:
598 // - For every SSA value, construct a mapping to either an actual base
599 // pointer or a PHI which obscures the base pointer.
600 // - Construct a mapping from PHI to unknown TOP state. Use an
601 // optimistic algorithm to propagate base pointer information. Lattice
606 // When algorithm terminates, all PHIs will either have a single concrete
607 // base or be in a conflict state.
608 // - For every conflict, insert a dummy PHI node without arguments. Add
609 // these to the base[Instruction] = BasePtr mapping. For every
610 // non-conflict, add the actual base.
611 // - For every conflict, add arguments for the base[a] of each input
614 // Note: A simpler form of this would be to add the conflict form of all
615 // PHIs without running the optimistic algorithm. This would be
616 // analougous to pessimistic data flow and would likely lead to an
617 // overall worse solution.
619 ConflictStateMapTy states;
620 states[def] = PhiState();
621 // Recursively fill in all phis & selects reachable from the initial one
622 // for which we don't already know a definite base value for
623 // TODO: This should be rewritten with a worklist
627 // Since we're adding elements to 'states' as we run, we can't keep
628 // iterators into the set.
629 SmallVector<Value*, 16> Keys;
630 Keys.reserve(states.size());
631 for (auto Pair : states) {
632 Value *V = Pair.first;
635 for (Value *v : Keys) {
636 assert(!isKnownBaseResult(v) && "why did it get added?");
637 if (PHINode *phi = dyn_cast<PHINode>(v)) {
638 assert(phi->getNumIncomingValues() > 0 &&
639 "zero input phis are illegal");
640 for (Value *InVal : phi->incoming_values()) {
641 Value *local = findBaseOrBDV(InVal, cache);
642 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
643 states[local] = PhiState();
647 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
648 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
649 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
650 states[local] = PhiState();
653 local = findBaseOrBDV(sel->getFalseValue(), cache);
654 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
655 states[local] = PhiState();
663 errs() << "States after initialization:\n";
664 for (auto Pair : states) {
665 Instruction *v = cast<Instruction>(Pair.first);
666 PhiState state = Pair.second;
672 // TODO: come back and revisit the state transitions around inputs which
673 // have reached conflict state. The current version seems too conservative.
675 bool progress = true;
678 size_t oldSize = states.size();
681 // We're only changing keys in this loop, thus safe to keep iterators
682 for (auto Pair : states) {
683 MeetPhiStates calculateMeet(states);
684 Value *v = Pair.first;
685 assert(!isKnownBaseResult(v) && "why did it get added?");
686 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
687 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
688 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
690 for (Value *Val : cast<PHINode>(v)->incoming_values())
691 calculateMeet.meetWith(findBaseOrBDV(Val, cache));
693 PhiState oldState = states[v];
694 PhiState newState = calculateMeet.getResult();
695 if (oldState != newState) {
697 states[v] = newState;
701 assert(oldSize <= states.size());
702 assert(oldSize == states.size() || progress);
706 errs() << "States after meet iteration:\n";
707 for (auto Pair : states) {
708 Instruction *v = cast<Instruction>(Pair.first);
709 PhiState state = Pair.second;
715 // Insert Phis for all conflicts
716 // We want to keep naming deterministic in the loop that follows, so
717 // sort the keys before iteration. This is useful in allowing us to
718 // write stable tests. Note that there is no invalidation issue here.
719 SmallVector<Value*, 16> Keys;
720 Keys.reserve(states.size());
721 for (auto Pair : states) {
722 Value *V = Pair.first;
725 std::sort(Keys.begin(), Keys.end(), order_by_name);
726 // TODO: adjust naming patterns to avoid this order of iteration dependency
727 for (Value *V : Keys) {
728 Instruction *v = cast<Instruction>(V);
729 PhiState state = states[V];
730 assert(!isKnownBaseResult(v) && "why did it get added?");
731 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
732 if (!state.isConflict())
735 if (isa<PHINode>(v)) {
737 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
738 assert(num_preds > 0 && "how did we reach here");
739 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
740 NewInsertedDefs.insert(phi);
741 // Add metadata marking this as a base value
742 auto *const_1 = ConstantInt::get(
744 v->getParent()->getParent()->getParent()->getContext()),
746 auto MDConst = ConstantAsMetadata::get(const_1);
747 MDNode *md = MDNode::get(
748 v->getParent()->getParent()->getParent()->getContext(), MDConst);
749 phi->setMetadata("is_base_value", md);
750 states[v] = PhiState(PhiState::Conflict, phi);
752 SelectInst *sel = cast<SelectInst>(v);
753 // The undef will be replaced later
754 UndefValue *undef = UndefValue::get(sel->getType());
755 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
756 undef, "base_select", sel);
757 NewInsertedDefs.insert(basesel);
758 // Add metadata marking this as a base value
759 auto *const_1 = ConstantInt::get(
761 v->getParent()->getParent()->getParent()->getContext()),
763 auto MDConst = ConstantAsMetadata::get(const_1);
764 MDNode *md = MDNode::get(
765 v->getParent()->getParent()->getParent()->getContext(), MDConst);
766 basesel->setMetadata("is_base_value", md);
767 states[v] = PhiState(PhiState::Conflict, basesel);
771 // Fixup all the inputs of the new PHIs
772 for (auto Pair : states) {
773 Instruction *v = cast<Instruction>(Pair.first);
774 PhiState state = Pair.second;
776 assert(!isKnownBaseResult(v) && "why did it get added?");
777 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
778 if (!state.isConflict())
781 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
782 PHINode *phi = cast<PHINode>(v);
783 unsigned NumPHIValues = phi->getNumIncomingValues();
784 for (unsigned i = 0; i < NumPHIValues; i++) {
785 Value *InVal = phi->getIncomingValue(i);
786 BasicBlock *InBB = phi->getIncomingBlock(i);
788 // If we've already seen InBB, add the same incoming value
789 // we added for it earlier. The IR verifier requires phi
790 // nodes with multiple entries from the same basic block
791 // to have the same incoming value for each of those
792 // entries. If we don't do this check here and basephi
793 // has a different type than base, we'll end up adding two
794 // bitcasts (and hence two distinct values) as incoming
795 // values for the same basic block.
797 int blockIndex = basephi->getBasicBlockIndex(InBB);
798 if (blockIndex != -1) {
799 Value *oldBase = basephi->getIncomingValue(blockIndex);
800 basephi->addIncoming(oldBase, InBB);
802 Value *base = findBaseOrBDV(InVal, cache);
803 if (!isKnownBaseResult(base)) {
804 // Either conflict or base.
805 assert(states.count(base));
806 base = states[base].getBase();
807 assert(base != nullptr && "unknown PhiState!");
808 assert(NewInsertedDefs.count(base) &&
809 "should have already added this in a prev. iteration!");
812 // In essense this assert states: the only way two
813 // values incoming from the same basic block may be
814 // different is by being different bitcasts of the same
815 // value. A cleanup that remains TODO is changing
816 // findBaseOrBDV to return an llvm::Value of the correct
817 // type (and still remain pure). This will remove the
818 // need to add bitcasts.
819 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
820 "sanity -- findBaseOrBDV should be pure!");
825 // Find either the defining value for the PHI or the normal base for
827 Value *base = findBaseOrBDV(InVal, cache);
828 if (!isKnownBaseResult(base)) {
829 // Either conflict or base.
830 assert(states.count(base));
831 base = states[base].getBase();
832 assert(base != nullptr && "unknown PhiState!");
834 assert(base && "can't be null");
835 // Must use original input BB since base may not be Instruction
836 // The cast is needed since base traversal may strip away bitcasts
837 if (base->getType() != basephi->getType()) {
838 base = new BitCastInst(base, basephi->getType(), "cast",
839 InBB->getTerminator());
840 NewInsertedDefs.insert(base);
842 basephi->addIncoming(base, InBB);
844 assert(basephi->getNumIncomingValues() == NumPHIValues);
846 SelectInst *basesel = cast<SelectInst>(state.getBase());
847 SelectInst *sel = cast<SelectInst>(v);
848 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
849 // something more safe and less hacky.
850 for (int i = 1; i <= 2; i++) {
851 Value *InVal = sel->getOperand(i);
852 // Find either the defining value for the PHI or the normal base for
854 Value *base = findBaseOrBDV(InVal, cache);
855 if (!isKnownBaseResult(base)) {
856 // Either conflict or base.
857 assert(states.count(base));
858 base = states[base].getBase();
859 assert(base != nullptr && "unknown PhiState!");
861 assert(base && "can't be null");
862 // Must use original input BB since base may not be Instruction
863 // The cast is needed since base traversal may strip away bitcasts
864 if (base->getType() != basesel->getType()) {
865 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
866 NewInsertedDefs.insert(base);
868 basesel->setOperand(i, base);
873 // Cache all of our results so we can cheaply reuse them
874 // NOTE: This is actually two caches: one of the base defining value
875 // relation and one of the base pointer relation! FIXME
876 for (auto item : states) {
877 Value *v = item.first;
878 Value *base = item.second.getBase();
880 assert(!isKnownBaseResult(v) && "why did it get added?");
883 std::string fromstr =
884 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
886 errs() << "Updating base value cache"
887 << " for: " << (v->hasName() ? v->getName() : "")
888 << " from: " << fromstr
889 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
892 assert(isKnownBaseResult(base) &&
893 "must be something we 'know' is a base pointer");
894 if (cache.count(v)) {
895 // Once we transition from the BDV relation being store in the cache to
896 // the base relation being stored, it must be stable
897 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
898 "base relation should be stable");
902 assert(cache.find(def) != cache.end());
906 // For a set of live pointers (base and/or derived), identify the base
907 // pointer of the object which they are derived from. This routine will
908 // mutate the IR graph as needed to make the 'base' pointer live at the
909 // definition site of 'derived'. This ensures that any use of 'derived' can
910 // also use 'base'. This may involve the insertion of a number of
911 // additional PHI nodes.
913 // preconditions: live is a set of pointer type Values
915 // side effects: may insert PHI nodes into the existing CFG, will preserve
916 // CFG, will not remove or mutate any existing nodes
918 // post condition: PointerToBase contains one (derived, base) pair for every
919 // pointer in live. Note that derived can be equal to base if the original
920 // pointer was a base pointer.
921 static void findBasePointers(const StatepointLiveSetTy &live,
922 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
923 DominatorTree *DT, DefiningValueMapTy &DVCache,
924 DenseSet<llvm::Value *> &NewInsertedDefs) {
925 // For the naming of values inserted to be deterministic - which makes for
926 // much cleaner and more stable tests - we need to assign an order to the
927 // live values. DenseSets do not provide a deterministic order across runs.
928 SmallVector<Value*, 64> Temp;
929 Temp.insert(Temp.end(), live.begin(), live.end());
930 std::sort(Temp.begin(), Temp.end(), order_by_name);
931 for (Value *ptr : Temp) {
932 Value *base = findBasePointer(ptr, DVCache, NewInsertedDefs);
933 assert(base && "failed to find base pointer");
934 PointerToBase[ptr] = base;
935 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
936 DT->dominates(cast<Instruction>(base)->getParent(),
937 cast<Instruction>(ptr)->getParent())) &&
938 "The base we found better dominate the derived pointer");
940 // If you see this trip and like to live really dangerously, the code should
941 // be correct, just with idioms the verifier can't handle. You can try
942 // disabling the verifier at your own substaintial risk.
943 assert(!isNullConstant(base) && "the relocation code needs adjustment to "
944 "handle the relocation of a null pointer "
945 "constant without causing false positives "
946 "in the safepoint ir verifier.");
950 /// Find the required based pointers (and adjust the live set) for the given
952 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
954 PartiallyConstructedSafepointRecord &result) {
955 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
956 DenseSet<llvm::Value *> NewInsertedDefs;
957 findBasePointers(result.liveset, PointerToBase, &DT, DVCache, NewInsertedDefs);
959 if (PrintBasePointers) {
960 // Note: Need to print these in a stable order since this is checked in
962 errs() << "Base Pairs (w/o Relocation):\n";
963 SmallVector<Value*, 64> Temp;
964 Temp.reserve(PointerToBase.size());
965 for (auto Pair : PointerToBase) {
966 Temp.push_back(Pair.first);
968 std::sort(Temp.begin(), Temp.end(), order_by_name);
969 for (Value *Ptr : Temp) {
970 Value *Base = PointerToBase[Ptr];
971 errs() << " derived %" << Ptr->getName() << " base %"
972 << Base->getName() << "\n";
976 result.PointerToBase = PointerToBase;
977 result.NewInsertedDefs = NewInsertedDefs;
980 /// Check for liveness of items in the insert defs and add them to the live
981 /// and base pointer sets
982 static void fixupLiveness(DominatorTree &DT, const CallSite &CS,
983 const DenseSet<Value *> &allInsertedDefs,
984 PartiallyConstructedSafepointRecord &result) {
985 Instruction *inst = CS.getInstruction();
987 auto liveset = result.liveset;
988 auto PointerToBase = result.PointerToBase;
990 auto is_live_gc_reference =
991 [&](Value &V) { return isLiveGCReferenceAt(V, inst, DT, nullptr); };
993 // For each new definition, check to see if a) the definition dominates the
994 // instruction we're interested in, and b) one of the uses of that definition
995 // is edge-reachable from the instruction we're interested in. This is the
996 // same definition of liveness we used in the intial liveness analysis
997 for (Value *newDef : allInsertedDefs) {
998 if (liveset.count(newDef)) {
999 // already live, no action needed
1003 // PERF: Use DT to check instruction domination might not be good for
1004 // compilation time, and we could change to optimal solution if this
1005 // turn to be a issue
1006 if (!DT.dominates(cast<Instruction>(newDef), inst)) {
1007 // can't possibly be live at inst
1011 if (is_live_gc_reference(*newDef)) {
1012 // Add the live new defs into liveset and PointerToBase
1013 liveset.insert(newDef);
1014 PointerToBase[newDef] = newDef;
1018 result.liveset = liveset;
1019 result.PointerToBase = PointerToBase;
1022 static void fixupLiveReferences(
1023 Function &F, DominatorTree &DT, Pass *P,
1024 const DenseSet<llvm::Value *> &allInsertedDefs,
1025 ArrayRef<CallSite> toUpdate,
1026 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1027 for (size_t i = 0; i < records.size(); i++) {
1028 struct PartiallyConstructedSafepointRecord &info = records[i];
1029 const CallSite &CS = toUpdate[i];
1030 fixupLiveness(DT, CS, allInsertedDefs, info);
1034 // Normalize basic block to make it ready to be target of invoke statepoint.
1035 // It means spliting it to have single predecessor. Return newly created BB
1036 // ready to be successor of invoke statepoint.
1037 static BasicBlock *normalizeBBForInvokeSafepoint(BasicBlock *BB,
1038 BasicBlock *InvokeParent,
1040 BasicBlock *ret = BB;
1042 if (!BB->getUniquePredecessor()) {
1043 ret = SplitBlockPredecessors(BB, InvokeParent, "");
1046 // Another requirement for such basic blocks is to not have any phi nodes.
1047 // Since we just ensured that new BB will have single predecessor,
1048 // all phi nodes in it will have one value. Here it would be naturall place
1050 // remove them all. But we can not do this because we are risking to remove
1051 // one of the values stored in liveset of another statepoint. We will do it
1052 // later after placing all safepoints.
1057 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1058 auto itr = std::find(livevec.begin(), livevec.end(), val);
1059 assert(livevec.end() != itr);
1060 size_t index = std::distance(livevec.begin(), itr);
1061 assert(index < livevec.size());
1065 // Create new attribute set containing only attributes which can be transfered
1066 // from original call to the safepoint.
1067 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1070 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1071 unsigned index = AS.getSlotIndex(Slot);
1073 if (index == AttributeSet::ReturnIndex ||
1074 index == AttributeSet::FunctionIndex) {
1076 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1078 Attribute attr = *it;
1080 // Do not allow certain attributes - just skip them
1081 // Safepoint can not be read only or read none.
1082 if (attr.hasAttribute(Attribute::ReadNone) ||
1083 attr.hasAttribute(Attribute::ReadOnly))
1086 ret = ret.addAttributes(
1087 AS.getContext(), index,
1088 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1092 // Just skip parameter attributes for now
1098 /// Helper function to place all gc relocates necessary for the given
1101 /// liveVariables - list of variables to be relocated.
1102 /// liveStart - index of the first live variable.
1103 /// basePtrs - base pointers.
1104 /// statepointToken - statepoint instruction to which relocates should be
1106 /// Builder - Llvm IR builder to be used to construct new calls.
1107 static void CreateGCRelocates(ArrayRef<llvm::Value *> liveVariables,
1108 const int liveStart,
1109 ArrayRef<llvm::Value *> basePtrs,
1110 Instruction *statepointToken,
1111 IRBuilder<> Builder) {
1112 SmallVector<Instruction *, 64> NewDefs;
1113 NewDefs.reserve(liveVariables.size());
1115 Module *M = statepointToken->getParent()->getParent()->getParent();
1117 for (unsigned i = 0; i < liveVariables.size(); i++) {
1118 // We generate a (potentially) unique declaration for every pointer type
1119 // combination. This results is some blow up the function declarations in
1120 // the IR, but removes the need for argument bitcasts which shrinks the IR
1121 // greatly and makes it much more readable.
1122 SmallVector<Type *, 1> types; // one per 'any' type
1123 types.push_back(liveVariables[i]->getType()); // result type
1124 Value *gc_relocate_decl = Intrinsic::getDeclaration(
1125 M, Intrinsic::experimental_gc_relocate, types);
1127 // Generate the gc.relocate call and save the result
1129 ConstantInt::get(Type::getInt32Ty(M->getContext()),
1130 liveStart + find_index(liveVariables, basePtrs[i]));
1131 Value *liveIdx = ConstantInt::get(
1132 Type::getInt32Ty(M->getContext()),
1133 liveStart + find_index(liveVariables, liveVariables[i]));
1135 // only specify a debug name if we can give a useful one
1136 Value *reloc = Builder.CreateCall3(
1137 gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1138 liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1140 // Trick CodeGen into thinking there are lots of free registers at this
1142 cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1144 NewDefs.push_back(cast<Instruction>(reloc));
1146 assert(NewDefs.size() == liveVariables.size() &&
1147 "missing or extra redefinition at safepoint");
1151 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1152 const SmallVectorImpl<llvm::Value *> &basePtrs,
1153 const SmallVectorImpl<llvm::Value *> &liveVariables,
1155 PartiallyConstructedSafepointRecord &result) {
1156 assert(basePtrs.size() == liveVariables.size());
1157 assert(isStatepoint(CS) &&
1158 "This method expects to be rewriting a statepoint");
1160 BasicBlock *BB = CS.getInstruction()->getParent();
1162 Function *F = BB->getParent();
1163 assert(F && "must be set");
1164 Module *M = F->getParent();
1166 assert(M && "must be set");
1168 // We're not changing the function signature of the statepoint since the gc
1169 // arguments go into the var args section.
1170 Function *gc_statepoint_decl = CS.getCalledFunction();
1172 // Then go ahead and use the builder do actually do the inserts. We insert
1173 // immediately before the previous instruction under the assumption that all
1174 // arguments will be available here. We can't insert afterwards since we may
1175 // be replacing a terminator.
1176 Instruction *insertBefore = CS.getInstruction();
1177 IRBuilder<> Builder(insertBefore);
1178 // Copy all of the arguments from the original statepoint - this includes the
1179 // target, call args, and deopt args
1180 SmallVector<llvm::Value *, 64> args;
1181 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1182 // TODO: Clear the 'needs rewrite' flag
1184 // add all the pointers to be relocated (gc arguments)
1185 // Capture the start of the live variable list for use in the gc_relocates
1186 const int live_start = args.size();
1187 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1189 // Create the statepoint given all the arguments
1190 Instruction *token = nullptr;
1191 AttributeSet return_attributes;
1193 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1195 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1196 call->setTailCall(toReplace->isTailCall());
1197 call->setCallingConv(toReplace->getCallingConv());
1199 // Currently we will fail on parameter attributes and on certain
1200 // function attributes.
1201 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1202 // In case if we can handle this set of sttributes - set up function attrs
1203 // directly on statepoint and return attrs later for gc_result intrinsic.
1204 call->setAttributes(new_attrs.getFnAttributes());
1205 return_attributes = new_attrs.getRetAttributes();
1209 // Put the following gc_result and gc_relocate calls immediately after the
1210 // the old call (which we're about to delete)
1211 BasicBlock::iterator next(toReplace);
1212 assert(BB->end() != next && "not a terminator, must have next");
1214 Instruction *IP = &*(next);
1215 Builder.SetInsertPoint(IP);
1216 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1219 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1221 // Insert the new invoke into the old block. We'll remove the old one in a
1222 // moment at which point this will become the new terminator for the
1224 InvokeInst *invoke = InvokeInst::Create(
1225 gc_statepoint_decl, toReplace->getNormalDest(),
1226 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1227 invoke->setCallingConv(toReplace->getCallingConv());
1229 // Currently we will fail on parameter attributes and on certain
1230 // function attributes.
1231 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1232 // In case if we can handle this set of sttributes - set up function attrs
1233 // directly on statepoint and return attrs later for gc_result intrinsic.
1234 invoke->setAttributes(new_attrs.getFnAttributes());
1235 return_attributes = new_attrs.getRetAttributes();
1239 // Generate gc relocates in exceptional path
1240 BasicBlock *unwindBlock = normalizeBBForInvokeSafepoint(
1241 toReplace->getUnwindDest(), invoke->getParent(), P);
1243 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1244 Builder.SetInsertPoint(IP);
1245 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1247 // Extract second element from landingpad return value. We will attach
1248 // exceptional gc relocates to it.
1249 const unsigned idx = 1;
1250 Instruction *exceptional_token =
1251 cast<Instruction>(Builder.CreateExtractValue(
1252 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1253 result.UnwindToken = exceptional_token;
1255 // Just throw away return value. We will use the one we got for normal
1257 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1258 exceptional_token, Builder);
1260 // Generate gc relocates and returns for normal block
1261 BasicBlock *normalDest = normalizeBBForInvokeSafepoint(
1262 toReplace->getNormalDest(), invoke->getParent(), P);
1264 IP = &*(normalDest->getFirstInsertionPt());
1265 Builder.SetInsertPoint(IP);
1267 // gc relocates will be generated later as if it were regular call
1272 // Take the name of the original value call if it had one.
1273 token->takeName(CS.getInstruction());
1275 // The GCResult is already inserted, we just need to find it
1277 Instruction *toReplace = CS.getInstruction();
1278 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1279 "only valid use before rewrite is gc.result");
1280 assert(!toReplace->hasOneUse() ||
1281 isGCResult(cast<Instruction>(*toReplace->user_begin())));
1284 // Update the gc.result of the original statepoint (if any) to use the newly
1285 // inserted statepoint. This is safe to do here since the token can't be
1286 // considered a live reference.
1287 CS.getInstruction()->replaceAllUsesWith(token);
1289 result.StatepointToken = token;
1291 // Second, create a gc.relocate for every live variable
1292 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1297 struct name_ordering {
1300 bool operator()(name_ordering const &a, name_ordering const &b) {
1301 return -1 == a.derived->getName().compare(b.derived->getName());
1305 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1306 SmallVectorImpl<Value *> &livevec) {
1307 assert(basevec.size() == livevec.size());
1309 SmallVector<name_ordering, 64> temp;
1310 for (size_t i = 0; i < basevec.size(); i++) {
1312 v.base = basevec[i];
1313 v.derived = livevec[i];
1316 std::sort(temp.begin(), temp.end(), name_ordering());
1317 for (size_t i = 0; i < basevec.size(); i++) {
1318 basevec[i] = temp[i].base;
1319 livevec[i] = temp[i].derived;
1323 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1324 // which make the relocations happening at this safepoint explicit.
1326 // WARNING: Does not do any fixup to adjust users of the original live
1327 // values. That's the callers responsibility.
1329 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1330 PartiallyConstructedSafepointRecord &result) {
1331 auto liveset = result.liveset;
1332 auto PointerToBase = result.PointerToBase;
1334 // Convert to vector for efficient cross referencing.
1335 SmallVector<Value *, 64> basevec, livevec;
1336 livevec.reserve(liveset.size());
1337 basevec.reserve(liveset.size());
1338 for (Value *L : liveset) {
1339 livevec.push_back(L);
1341 assert(PointerToBase.find(L) != PointerToBase.end());
1342 Value *base = PointerToBase[L];
1343 basevec.push_back(base);
1345 assert(livevec.size() == basevec.size());
1347 // To make the output IR slightly more stable (for use in diffs), ensure a
1348 // fixed order of the values in the safepoint (by sorting the value name).
1349 // The order is otherwise meaningless.
1350 stablize_order(basevec, livevec);
1352 // Do the actual rewriting and delete the old statepoint
1353 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1354 CS.getInstruction()->eraseFromParent();
1357 // Helper function for the relocationViaAlloca.
1358 // It receives iterator to the statepoint gc relocates and emits store to the
1360 // location (via allocaMap) for the each one of them.
1361 // Add visited values into the visitedLiveValues set we will later use them
1362 // for sanity check.
1364 insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1365 DenseMap<Value *, Value *> &allocaMap,
1366 DenseSet<Value *> &visitedLiveValues) {
1368 for (User *U : gcRelocs) {
1369 if (!isa<IntrinsicInst>(U))
1372 IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1374 // We only care about relocates
1375 if (relocatedValue->getIntrinsicID() !=
1376 Intrinsic::experimental_gc_relocate) {
1380 GCRelocateOperands relocateOperands(relocatedValue);
1381 Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1382 assert(allocaMap.count(originalValue));
1383 Value *alloca = allocaMap[originalValue];
1385 // Emit store into the related alloca
1386 StoreInst *store = new StoreInst(relocatedValue, alloca);
1387 store->insertAfter(relocatedValue);
1390 visitedLiveValues.insert(originalValue);
1395 /// do all the relocation update via allocas and mem2reg
1396 static void relocationViaAlloca(
1397 Function &F, DominatorTree &DT, ArrayRef<Value *> live,
1398 ArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1400 int initialAllocaNum = 0;
1402 // record initial number of allocas
1403 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1405 if (isa<AllocaInst>(*itr))
1410 // TODO-PERF: change data structures, reserve
1411 DenseMap<Value *, Value *> allocaMap;
1412 SmallVector<AllocaInst *, 200> PromotableAllocas;
1413 PromotableAllocas.reserve(live.size());
1415 // emit alloca for each live gc pointer
1416 for (unsigned i = 0; i < live.size(); i++) {
1417 Value *liveValue = live[i];
1418 AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1419 F.getEntryBlock().getFirstNonPHI());
1420 allocaMap[liveValue] = alloca;
1421 PromotableAllocas.push_back(alloca);
1424 // The next two loops are part of the same conceptual operation. We need to
1425 // insert a store to the alloca after the original def and at each
1426 // redefinition. We need to insert a load before each use. These are split
1427 // into distinct loops for performance reasons.
1429 // update gc pointer after each statepoint
1430 // either store a relocated value or null (if no relocated value found for
1431 // this gc pointer and it is not a gc_result)
1432 // this must happen before we update the statepoint with load of alloca
1433 // otherwise we lose the link between statepoint and old def
1434 for (size_t i = 0; i < records.size(); i++) {
1435 const struct PartiallyConstructedSafepointRecord &info = records[i];
1436 Value *Statepoint = info.StatepointToken;
1438 // This will be used for consistency check
1439 DenseSet<Value *> visitedLiveValues;
1441 // Insert stores for normal statepoint gc relocates
1442 insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues);
1444 // In case if it was invoke statepoint
1445 // we will insert stores for exceptional path gc relocates.
1446 if (isa<InvokeInst>(Statepoint)) {
1447 insertRelocationStores(info.UnwindToken->users(),
1448 allocaMap, visitedLiveValues);
1452 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1453 // the gc.statepoint. This will turn some subtle GC problems into slightly
1454 // easier to debug SEGVs
1455 SmallVector<AllocaInst *, 64> ToClobber;
1456 for (auto Pair : allocaMap) {
1457 Value *Def = Pair.first;
1458 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1460 // This value was relocated
1461 if (visitedLiveValues.count(Def)) {
1464 ToClobber.push_back(Alloca);
1467 auto InsertClobbersAt = [&](Instruction *IP) {
1468 for (auto *AI : ToClobber) {
1469 auto AIType = cast<PointerType>(AI->getType());
1470 auto PT = cast<PointerType>(AIType->getElementType());
1471 Constant *CPN = ConstantPointerNull::get(PT);
1472 StoreInst *store = new StoreInst(CPN, AI);
1473 store->insertBefore(IP);
1477 // Insert the clobbering stores. These may get intermixed with the
1478 // gc.results and gc.relocates, but that's fine.
1479 if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1480 InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1481 InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1483 BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1485 InsertClobbersAt(Next);
1489 // update use with load allocas and add store for gc_relocated
1490 for (auto Pair : allocaMap) {
1491 Value *def = Pair.first;
1492 Value *alloca = Pair.second;
1494 // we pre-record the uses of allocas so that we dont have to worry about
1496 // that change the user information.
1497 SmallVector<Instruction *, 20> uses;
1498 // PERF: trade a linear scan for repeated reallocation
1499 uses.reserve(std::distance(def->user_begin(), def->user_end()));
1500 for (User *U : def->users()) {
1501 if (!isa<ConstantExpr>(U)) {
1502 // If the def has a ConstantExpr use, then the def is either a
1503 // ConstantExpr use itself or null. In either case
1504 // (recursively in the first, directly in the second), the oop
1505 // it is ultimately dependent on is null and this particular
1506 // use does not need to be fixed up.
1507 uses.push_back(cast<Instruction>(U));
1511 std::sort(uses.begin(), uses.end());
1512 auto last = std::unique(uses.begin(), uses.end());
1513 uses.erase(last, uses.end());
1515 for (Instruction *use : uses) {
1516 if (isa<PHINode>(use)) {
1517 PHINode *phi = cast<PHINode>(use);
1518 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1519 if (def == phi->getIncomingValue(i)) {
1520 LoadInst *load = new LoadInst(
1521 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1522 phi->setIncomingValue(i, load);
1526 LoadInst *load = new LoadInst(alloca, "", use);
1527 use->replaceUsesOfWith(def, load);
1531 // emit store for the initial gc value
1532 // store must be inserted after load, otherwise store will be in alloca's
1533 // use list and an extra load will be inserted before it
1534 StoreInst *store = new StoreInst(def, alloca);
1535 if (Instruction *inst = dyn_cast<Instruction>(def)) {
1536 if (InvokeInst *invoke = dyn_cast<InvokeInst>(inst)) {
1537 // InvokeInst is a TerminatorInst so the store need to be inserted
1538 // into its normal destination block.
1539 BasicBlock *normalDest = invoke->getNormalDest();
1540 store->insertBefore(normalDest->getFirstNonPHI());
1542 assert(!inst->isTerminator() &&
1543 "The only TerminatorInst that can produce a value is "
1544 "InvokeInst which is handled above.");
1545 store->insertAfter(inst);
1548 assert((isa<Argument>(def) || isa<GlobalVariable>(def) ||
1549 (isa<Constant>(def) && cast<Constant>(def)->isNullValue())) &&
1550 "Must be argument or global");
1551 store->insertAfter(cast<Instruction>(alloca));
1555 assert(PromotableAllocas.size() == live.size() &&
1556 "we must have the same allocas with lives");
1557 if (!PromotableAllocas.empty()) {
1558 // apply mem2reg to promote alloca to SSA
1559 PromoteMemToReg(PromotableAllocas, DT);
1563 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1565 if (isa<AllocaInst>(*itr))
1568 assert(initialAllocaNum == 0 && "We must not introduce any extra allocas");
1572 /// Implement a unique function which doesn't require we sort the input
1573 /// vector. Doing so has the effect of changing the output of a couple of
1574 /// tests in ways which make them less useful in testing fused safepoints.
1575 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1577 SmallVector<T, 128> TempVec;
1578 TempVec.reserve(Vec.size());
1579 for (auto Element : Vec)
1580 TempVec.push_back(Element);
1582 for (auto V : TempVec) {
1583 if (Seen.insert(V).second) {
1589 static Function *getUseHolder(Module &M) {
1590 FunctionType *ftype =
1591 FunctionType::get(Type::getVoidTy(M.getContext()), true);
1592 Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype));
1596 /// Insert holders so that each Value is obviously live through the entire
1597 /// liftetime of the call.
1598 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1599 SmallVectorImpl<CallInst *> &holders) {
1600 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1601 Function *Func = getUseHolder(*M);
1603 // For call safepoints insert dummy calls right after safepoint
1604 BasicBlock::iterator next(CS.getInstruction());
1606 CallInst *base_holder = CallInst::Create(Func, Values, "", next);
1607 holders.push_back(base_holder);
1608 } else if (CS.isInvoke()) {
1609 // For invoke safepooints insert dummy calls both in normal and
1610 // exceptional destination blocks
1611 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1612 CallInst *normal_holder = CallInst::Create(
1613 Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt());
1614 CallInst *unwind_holder = CallInst::Create(
1615 Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt());
1616 holders.push_back(normal_holder);
1617 holders.push_back(unwind_holder);
1619 llvm_unreachable("unsupported call type");
1622 static void findLiveReferences(
1623 Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1624 MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1625 for (size_t i = 0; i < records.size(); i++) {
1626 struct PartiallyConstructedSafepointRecord &info = records[i];
1627 const CallSite &CS = toUpdate[i];
1628 analyzeParsePointLiveness(DT, CS, info);
1632 static void addBasesAsLiveValues(StatepointLiveSetTy &liveset,
1633 DenseMap<Value *, Value *> &PointerToBase) {
1634 // Identify any base pointers which are used in this safepoint, but not
1635 // themselves relocated. We need to relocate them so that later inserted
1636 // safepoints can get the properly relocated base register.
1637 DenseSet<Value *> missing;
1638 for (Value *L : liveset) {
1639 assert(PointerToBase.find(L) != PointerToBase.end());
1640 Value *base = PointerToBase[L];
1642 if (liveset.find(base) == liveset.end()) {
1643 assert(PointerToBase.find(base) == PointerToBase.end());
1644 // uniqued by set insert
1645 missing.insert(base);
1649 // Note that we want these at the end of the list, otherwise
1650 // register placement gets screwed up once we lower to STATEPOINT
1651 // instructions. This is an utter hack, but there doesn't seem to be a
1653 for (Value *base : missing) {
1655 liveset.insert(base);
1656 PointerToBase[base] = base;
1658 assert(liveset.size() == PointerToBase.size());
1661 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
1662 SmallVectorImpl<CallSite> &toUpdate) {
1664 // sanity check the input
1665 std::set<CallSite> uniqued;
1666 uniqued.insert(toUpdate.begin(), toUpdate.end());
1667 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1669 for (size_t i = 0; i < toUpdate.size(); i++) {
1670 CallSite &CS = toUpdate[i];
1671 assert(CS.getInstruction()->getParent()->getParent() == &F);
1672 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1676 // A list of dummy calls added to the IR to keep various values obviously
1677 // live in the IR. We'll remove all of these when done.
1678 SmallVector<CallInst *, 64> holders;
1680 // Insert a dummy call with all of the arguments to the vm_state we'll need
1681 // for the actual safepoint insertion. This ensures reference arguments in
1682 // the deopt argument list are considered live through the safepoint (and
1683 // thus makes sure they get relocated.)
1684 for (size_t i = 0; i < toUpdate.size(); i++) {
1685 CallSite &CS = toUpdate[i];
1686 Statepoint StatepointCS(CS);
1688 SmallVector<Value *, 64> DeoptValues;
1689 for (Use &U : StatepointCS.vm_state_args()) {
1690 Value *Arg = cast<Value>(&U);
1691 if (isGCPointerType(Arg->getType()))
1692 DeoptValues.push_back(Arg);
1694 insertUseHolderAfter(CS, DeoptValues, holders);
1697 SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
1698 records.reserve(toUpdate.size());
1699 for (size_t i = 0; i < toUpdate.size(); i++) {
1700 struct PartiallyConstructedSafepointRecord info;
1701 records.push_back(info);
1703 assert(records.size() == toUpdate.size());
1705 // A) Identify all gc pointers which are staticly live at the given call
1707 findLiveReferences(F, DT, P, toUpdate, records);
1709 // B) Find the base pointers for each live pointer
1710 /* scope for caching */ {
1711 // Cache the 'defining value' relation used in the computation and
1712 // insertion of base phis and selects. This ensures that we don't insert
1713 // large numbers of duplicate base_phis.
1714 DefiningValueMapTy DVCache;
1716 for (size_t i = 0; i < records.size(); i++) {
1717 struct PartiallyConstructedSafepointRecord &info = records[i];
1718 CallSite &CS = toUpdate[i];
1719 findBasePointers(DT, DVCache, CS, info);
1721 } // end of cache scope
1723 // The base phi insertion logic (for any safepoint) may have inserted new
1724 // instructions which are now live at some safepoint. The simplest such
1727 // phi a <-- will be a new base_phi here
1728 // safepoint 1 <-- that needs to be live here
1732 DenseSet<llvm::Value *> allInsertedDefs;
1733 for (size_t i = 0; i < records.size(); i++) {
1734 struct PartiallyConstructedSafepointRecord &info = records[i];
1735 allInsertedDefs.insert(info.NewInsertedDefs.begin(),
1736 info.NewInsertedDefs.end());
1739 // We insert some dummy calls after each safepoint to definitely hold live
1740 // the base pointers which were identified for that safepoint. We'll then
1741 // ask liveness for _every_ base inserted to see what is now live. Then we
1742 // remove the dummy calls.
1743 holders.reserve(holders.size() + records.size());
1744 for (size_t i = 0; i < records.size(); i++) {
1745 struct PartiallyConstructedSafepointRecord &info = records[i];
1746 CallSite &CS = toUpdate[i];
1748 SmallVector<Value *, 128> Bases;
1749 for (auto Pair : info.PointerToBase) {
1750 Bases.push_back(Pair.second);
1752 insertUseHolderAfter(CS, Bases, holders);
1755 // Add the bases explicitly to the live vector set. This may result in a few
1756 // extra relocations, but the base has to be available whenever a pointer
1757 // derived from it is used. Thus, we need it to be part of the statepoint's
1758 // gc arguments list. TODO: Introduce an explicit notion (in the following
1759 // code) of the GC argument list as seperate from the live Values at a
1760 // given statepoint.
1761 for (size_t i = 0; i < records.size(); i++) {
1762 struct PartiallyConstructedSafepointRecord &info = records[i];
1763 addBasesAsLiveValues(info.liveset, info.PointerToBase);
1766 // If we inserted any new values, we need to adjust our notion of what is
1767 // live at a particular safepoint.
1768 if (!allInsertedDefs.empty()) {
1769 fixupLiveReferences(F, DT, P, allInsertedDefs, toUpdate, records);
1771 if (PrintBasePointers) {
1772 for (size_t i = 0; i < records.size(); i++) {
1773 struct PartiallyConstructedSafepointRecord &info = records[i];
1774 errs() << "Base Pairs: (w/Relocation)\n";
1775 for (auto Pair : info.PointerToBase) {
1776 errs() << " derived %" << Pair.first->getName() << " base %"
1777 << Pair.second->getName() << "\n";
1781 for (size_t i = 0; i < holders.size(); i++) {
1782 holders[i]->eraseFromParent();
1783 holders[i] = nullptr;
1787 // Now run through and replace the existing statepoints with new ones with
1788 // the live variables listed. We do not yet update uses of the values being
1789 // relocated. We have references to live variables that need to
1790 // survive to the last iteration of this loop. (By construction, the
1791 // previous statepoint can not be a live variable, thus we can and remove
1792 // the old statepoint calls as we go.)
1793 for (size_t i = 0; i < records.size(); i++) {
1794 struct PartiallyConstructedSafepointRecord &info = records[i];
1795 CallSite &CS = toUpdate[i];
1796 makeStatepointExplicit(DT, CS, P, info);
1798 toUpdate.clear(); // prevent accident use of invalid CallSites
1800 // In case if we inserted relocates in a different basic block than the
1801 // original safepoint (this can happen for invokes). We need to be sure that
1802 // original values were not used in any of the phi nodes at the
1803 // beginning of basic block containing them. Because we know that all such
1804 // blocks will have single predecessor we can safely assume that all phi
1805 // nodes have single entry (because of normalizeBBForInvokeSafepoint).
1806 // Just remove them all here.
1807 for (size_t i = 0; i < records.size(); i++) {
1808 Instruction *I = records[i].StatepointToken;
1810 if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
1811 FoldSingleEntryPHINodes(invoke->getNormalDest());
1812 assert(!isa<PHINode>(invoke->getNormalDest()->begin()));
1814 FoldSingleEntryPHINodes(invoke->getUnwindDest());
1815 assert(!isa<PHINode>(invoke->getUnwindDest()->begin()));
1819 // Do all the fixups of the original live variables to their relocated selves
1820 SmallVector<Value *, 128> live;
1821 for (size_t i = 0; i < records.size(); i++) {
1822 struct PartiallyConstructedSafepointRecord &info = records[i];
1823 // We can't simply save the live set from the original insertion. One of
1824 // the live values might be the result of a call which needs a safepoint.
1825 // That Value* no longer exists and we need to use the new gc_result.
1826 // Thankfully, the liveset is embedded in the statepoint (and updated), so
1827 // we just grab that.
1828 Statepoint statepoint(info.StatepointToken);
1829 live.insert(live.end(), statepoint.gc_args_begin(),
1830 statepoint.gc_args_end());
1832 unique_unsorted(live);
1836 for (auto ptr : live) {
1837 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1841 relocationViaAlloca(F, DT, live, records);
1842 return !records.empty();
1845 /// Returns true if this function should be rewritten by this pass. The main
1846 /// point of this function is as an extension point for custom logic.
1847 static bool shouldRewriteStatepointsIn(Function &F) {
1848 // TODO: This should check the GCStrategy
1850 const std::string StatepointExampleName("statepoint-example");
1851 return StatepointExampleName == F.getGC();
1856 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1857 // Nothing to do for declarations.
1858 if (F.isDeclaration() || F.empty())
1861 // Policy choice says not to rewrite - the most common reason is that we're
1862 // compiling code without a GCStrategy.
1863 if (!shouldRewriteStatepointsIn(F))
1866 // Gather all the statepoints which need rewritten.
1867 SmallVector<CallSite, 64> ParsePointNeeded;
1868 for (Instruction &I : inst_range(F)) {
1869 // TODO: only the ones with the flag set!
1870 if (isStatepoint(I))
1871 ParsePointNeeded.push_back(CallSite(&I));
1874 // Return early if no work to do.
1875 if (ParsePointNeeded.empty())
1878 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1879 return insertParsePoints(F, DT, this, ParsePointNeeded);