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 std::map<Value *, Value *> DefiningValueMapTy;
100 struct PartiallyConstructedSafepointRecord {
101 /// The set of values known to be live accross this safepoint
102 std::set<llvm::Value *> liveset;
104 /// Mapping from live pointers to a base-defining-value
105 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
107 /// Any new values which were added to the IR during base pointer analysis
108 /// for this safepoint
109 DenseSet<llvm::Value *> NewInsertedDefs;
111 /// The bounds of the inserted code for the safepoint
112 std::pair<Instruction *, Instruction *> SafepointBounds;
114 /// Instruction to which exceptional gc relocates are attached
115 /// Makes it easier to iterate through them during relocationViaAlloca.
116 Instruction *UnwindToken;
120 // TODO: Once we can get to the GCStrategy, this becomes
121 // Optional<bool> isGCManagedPointer(const Value *V) const override {
123 static bool isGCPointerType(const Type *T) {
124 if (const PointerType *PT = dyn_cast<PointerType>(T))
125 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
126 // GC managed heap. We know that a pointer into this heap needs to be
127 // updated and that no other pointer does.
128 return (1 == PT->getAddressSpace());
132 /// Return true if the Value is a gc reference type which is potentially used
133 /// after the instruction 'loc'. This is only used with the edge reachability
134 /// liveness code. Note: It is assumed the V dominates loc.
135 static bool isLiveGCReferenceAt(Value &V, Instruction *loc, DominatorTree &DT,
137 if (!isGCPointerType(V.getType()))
143 // Given assumption that V dominates loc, this may be live
148 static bool isAggWhichContainsGCPtrType(Type *Ty) {
149 if (VectorType *VT = dyn_cast<VectorType>(Ty))
150 return isGCPointerType(VT->getScalarType());
151 else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
152 return isGCPointerType(AT->getElementType()) ||
153 isAggWhichContainsGCPtrType(AT->getElementType());
154 } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
155 bool UnsupportedType = false;
156 for (Type *SubType : ST->subtypes())
158 isGCPointerType(SubType) || isAggWhichContainsGCPtrType(SubType);
159 return UnsupportedType;
165 // Conservatively identifies any definitions which might be live at the
166 // given instruction. The analysis is performed immediately before the
167 // given instruction. Values defined by that instruction are not considered
168 // live. Values used by that instruction are considered live.
170 // preconditions: valid IR graph, term is either a terminator instruction or
171 // a call instruction, pred is the basic block of term, DT, LI are valid
173 // side effects: none, does not mutate IR
175 // postconditions: populates liveValues as discussed above
176 static void findLiveGCValuesAtInst(Instruction *term, BasicBlock *pred,
177 DominatorTree &DT, LoopInfo *LI,
178 std::set<llvm::Value *> &liveValues) {
181 assert(isa<CallInst>(term) || isa<InvokeInst>(term) || term->isTerminator());
183 Function *F = pred->getParent();
185 auto is_live_gc_reference =
186 [&](Value &V) { return isLiveGCReferenceAt(V, term, DT, LI); };
188 // Are there any gc pointer arguments live over this point? This needs to be
189 // special cased since arguments aren't defined in basic blocks.
190 for (Argument &arg : F->args()) {
191 assert(!isAggWhichContainsGCPtrType(arg.getType()) &&
192 "support for FCA unimplemented");
194 if (is_live_gc_reference(arg)) {
195 liveValues.insert(&arg);
199 // Walk through all dominating blocks - the ones which can contain
200 // definitions used in this block - and check to see if any of the values
201 // they define are used in locations potentially reachable from the
202 // interesting instruction.
203 BasicBlock *BBI = pred;
206 errs() << "[LSP] Looking at dominating block " << pred->getName() << "\n";
208 assert(DT.dominates(BBI, pred));
209 assert(isPotentiallyReachable(BBI, pred, &DT) &&
210 "dominated block must be reachable");
212 // Walk through the instructions in dominating blocks and keep any
213 // that have a use potentially reachable from the block we're
214 // considering putting the safepoint in
215 for (Instruction &inst : *BBI) {
217 errs() << "[LSP] Looking at instruction ";
221 if (pred == BBI && (&inst) == term) {
223 errs() << "[LSP] stopped because we encountered the safepoint "
227 // If we're in the block which defines the interesting instruction,
228 // we don't want to include any values as live which are defined
229 // _after_ the interesting line or as part of the line itself
230 // i.e. "term" is the call instruction for a call safepoint, the
231 // results of the call should not be considered live in that stackmap
235 assert(!isAggWhichContainsGCPtrType(inst.getType()) &&
236 "support for FCA unimplemented");
238 if (is_live_gc_reference(inst)) {
240 errs() << "[LSP] found live value for this safepoint ";
244 liveValues.insert(&inst);
247 if (!DT.getNode(BBI)->getIDom()) {
248 assert(BBI == &F->getEntryBlock() &&
249 "failed to find a dominator for something other than "
253 BBI = DT.getNode(BBI)->getIDom()->getBlock();
257 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
258 if (a->hasName() && b->hasName()) {
259 return -1 == a->getName().compare(b->getName());
260 } else if (a->hasName() && !b->hasName()) {
262 } else if (!a->hasName() && b->hasName()) {
265 // Better than nothing, but not stable
270 /// Find the initial live set. Note that due to base pointer
271 /// insertion, the live set may be incomplete.
273 analyzeParsePointLiveness(DominatorTree &DT, const CallSite &CS,
274 PartiallyConstructedSafepointRecord &result) {
275 Instruction *inst = CS.getInstruction();
277 BasicBlock *BB = inst->getParent();
278 std::set<Value *> liveset;
279 findLiveGCValuesAtInst(inst, BB, DT, nullptr, liveset);
282 // Note: This output is used by several of the test cases
283 // The order of elemtns in a set is not stable, put them in a vec and sort
285 std::vector<Value *> temp;
286 temp.insert(temp.end(), liveset.begin(), liveset.end());
287 std::sort(temp.begin(), temp.end(), order_by_name);
288 errs() << "Live Variables:\n";
289 for (Value *V : temp) {
290 errs() << " " << V->getName(); // no newline
294 if (PrintLiveSetSize) {
295 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
296 errs() << "Number live values: " << liveset.size() << "\n";
298 result.liveset = liveset;
301 /// True iff this value is the null pointer constant (of any pointer type)
302 static bool isNullConstant(Value *V) {
303 return isa<Constant>(V) && isa<PointerType>(V->getType()) &&
304 cast<Constant>(V)->isNullValue();
307 /// Helper function for findBasePointer - Will return a value which either a)
308 /// defines the base pointer for the input or b) blocks the simple search
309 /// (i.e. a PHI or Select of two derived pointers)
310 static Value *findBaseDefiningValue(Value *I) {
311 assert(I->getType()->isPointerTy() &&
312 "Illegal to ask for the base pointer of a non-pointer type");
314 // There are instructions which can never return gc pointer values. Sanity
316 // that this is actually true.
317 assert(!isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
318 !isa<ShuffleVectorInst>(I) && "Vector types are not gc pointers");
319 assert((!isa<Instruction>(I) || isa<InvokeInst>(I) ||
320 !cast<Instruction>(I)->isTerminator()) &&
321 "With the exception of invoke terminators don't define values");
322 assert(!isa<StoreInst>(I) && !isa<FenceInst>(I) &&
323 "Can't be definitions to start with");
324 assert(!isa<ICmpInst>(I) && !isa<FCmpInst>(I) &&
325 "Comparisons don't give ops");
326 // There's a bunch of instructions which just don't make sense to apply to
327 // a pointer. The only valid reason for this would be pointer bit
328 // twiddling which we're just not going to support.
329 assert((!isa<Instruction>(I) || !cast<Instruction>(I)->isBinaryOp()) &&
330 "Binary ops on pointer values are meaningless. Unless your "
331 "bit-twiddling which we don't support");
333 if (Argument *Arg = dyn_cast<Argument>(I)) {
334 // An incoming argument to the function is a base pointer
335 // We should have never reached here if this argument isn't an gc value
336 assert(Arg->getType()->isPointerTy() &&
337 "Base for pointer must be another pointer");
341 if (GlobalVariable *global = dyn_cast<GlobalVariable>(I)) {
343 assert(global->getType()->isPointerTy() &&
344 "Base for pointer must be another pointer");
348 // inlining could possibly introduce phi node that contains
349 // undef if callee has multiple returns
350 if (UndefValue *undef = dyn_cast<UndefValue>(I)) {
351 assert(undef->getType()->isPointerTy() &&
352 "Base for pointer must be another pointer");
353 return undef; // utterly meaningless, but useful for dealing with
354 // partially optimized code.
357 // Due to inheritance, this must be _after_ the global variable and undef
359 if (Constant *con = dyn_cast<Constant>(I)) {
360 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
361 "order of checks wrong!");
362 // Note: Finding a constant base for something marked for relocation
363 // doesn't really make sense. The most likely case is either a) some
364 // screwed up the address space usage or b) your validating against
365 // compiled C++ code w/o the proper separation. The only real exception
366 // is a null pointer. You could have generic code written to index of
367 // off a potentially null value and have proven it null. We also use
368 // null pointers in dead paths of relocation phis (which we might later
369 // want to find a base pointer for).
370 assert(con->getType()->isPointerTy() &&
371 "Base for pointer must be another pointer");
372 assert(con->isNullValue() && "null is the only case which makes sense");
376 if (CastInst *CI = dyn_cast<CastInst>(I)) {
377 Value *def = CI->stripPointerCasts();
378 assert(def->getType()->isPointerTy() &&
379 "Base for pointer must be another pointer");
380 if (isa<CastInst>(def)) {
381 // If we find a cast instruction here, it means we've found a cast
382 // which is not simply a pointer cast (i.e. an inttoptr). We don't
383 // know how to handle int->ptr conversion.
384 llvm_unreachable("Can not find the base pointers for an inttoptr cast");
386 assert(!isa<CastInst>(def) && "shouldn't find another cast here");
387 return findBaseDefiningValue(def);
390 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
391 if (LI->getType()->isPointerTy()) {
392 Value *Op = LI->getOperand(0);
394 // Has to be a pointer to an gc object, or possibly an array of such?
395 assert(Op->getType()->isPointerTy());
396 return LI; // The value loaded is an gc base itself
399 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
400 Value *Op = GEP->getOperand(0);
401 if (Op->getType()->isPointerTy()) {
402 return findBaseDefiningValue(Op); // The base of this GEP is the base
406 if (AllocaInst *alloc = dyn_cast<AllocaInst>(I)) {
407 // An alloca represents a conceptual stack slot. It's the slot itself
408 // that the GC needs to know about, not the value in the slot.
409 assert(alloc->getType()->isPointerTy() &&
410 "Base for pointer must be another pointer");
414 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
415 switch (II->getIntrinsicID()) {
417 // fall through to general call handling
419 case Intrinsic::experimental_gc_statepoint:
420 case Intrinsic::experimental_gc_result_float:
421 case Intrinsic::experimental_gc_result_int:
422 llvm_unreachable("these don't produce pointers");
423 case Intrinsic::experimental_gc_result_ptr:
424 // This is just a special case of the CallInst check below to handle a
425 // statepoint with deopt args which hasn't been rewritten for GC yet.
426 // TODO: Assert that the statepoint isn't rewritten yet.
428 case Intrinsic::experimental_gc_relocate: {
429 // Rerunning safepoint insertion after safepoints are already
430 // inserted is not supported. It could probably be made to work,
431 // but why are you doing this? There's no good reason.
432 llvm_unreachable("repeat safepoint insertion is not supported");
434 case Intrinsic::gcroot:
435 // Currently, this mechanism hasn't been extended to work with gcroot.
436 // There's no reason it couldn't be, but I haven't thought about the
437 // implications much.
439 "interaction with the gcroot mechanism is not supported");
442 // We assume that functions in the source language only return base
443 // pointers. This should probably be generalized via attributes to support
444 // both source language and internal functions.
445 if (CallInst *call = dyn_cast<CallInst>(I)) {
446 assert(call->getType()->isPointerTy() &&
447 "Base for pointer must be another pointer");
450 if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
451 assert(invoke->getType()->isPointerTy() &&
452 "Base for pointer must be another pointer");
456 // I have absolutely no idea how to implement this part yet. It's not
457 // neccessarily hard, I just haven't really looked at it yet.
458 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
460 if (AtomicCmpXchgInst *cas = dyn_cast<AtomicCmpXchgInst>(I)) {
461 // A CAS is effectively a atomic store and load combined under a
462 // predicate. From the perspective of base pointers, we just treat it
463 // like a load. We loaded a pointer from a address in memory, that value
464 // had better be a valid base pointer.
465 return cas->getPointerOperand();
467 if (AtomicRMWInst *atomic = dyn_cast<AtomicRMWInst>(I)) {
468 assert(AtomicRMWInst::Xchg == atomic->getOperation() &&
469 "All others are binary ops which don't apply to base pointers");
470 // semantically, a load, store pair. Treat it the same as a standard load
471 return atomic->getPointerOperand();
474 // The aggregate ops. Aggregates can either be in the heap or on the
475 // stack, but in either case, this is simply a field load. As a result,
476 // this is a defining definition of the base just like a load is.
477 if (ExtractValueInst *ev = dyn_cast<ExtractValueInst>(I)) {
481 // We should never see an insert vector since that would require we be
482 // tracing back a struct value not a pointer value.
483 assert(!isa<InsertValueInst>(I) &&
484 "Base pointer for a struct is meaningless");
486 // The last two cases here don't return a base pointer. Instead, they
487 // return a value which dynamically selects from amoung several base
488 // derived pointers (each with it's own base potentially). It's the job of
489 // the caller to resolve these.
490 if (SelectInst *select = dyn_cast<SelectInst>(I)) {
493 if (PHINode *phi = dyn_cast<PHINode>(I)) {
497 errs() << "unknown type: " << *I << "\n";
498 llvm_unreachable("unknown type");
502 /// Returns the base defining value for this value.
503 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &cache) {
504 Value *&Cached = cache[I];
506 Cached = findBaseDefiningValue(I);
508 assert(cache[I] != nullptr);
511 errs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
517 /// Return a base pointer for this value if known. Otherwise, return it's
518 /// base defining value.
519 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &cache) {
520 Value *def = findBaseDefiningValueCached(I, cache);
521 auto Found = cache.find(def);
522 if (Found != cache.end()) {
523 // Either a base-of relation, or a self reference. Caller must check.
524 return Found->second;
526 // Only a BDV available
530 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
531 /// is it known to be a base pointer? Or do we need to continue searching.
532 static bool isKnownBaseResult(Value *v) {
533 if (!isa<PHINode>(v) && !isa<SelectInst>(v)) {
534 // no recursion possible
537 if (cast<Instruction>(v)->getMetadata("is_base_value")) {
538 // This is a previously inserted base phi or select. We know
539 // that this is a base value.
543 // We need to keep searching
547 // TODO: find a better name for this
551 enum Status { Unknown, Base, Conflict };
553 PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
554 assert(status != Base || b);
556 PhiState(Value *b) : status(Base), base(b) {}
557 PhiState() : status(Unknown), base(nullptr) {}
558 PhiState(const PhiState &other) : status(other.status), base(other.base) {
559 assert(status != Base || base);
562 Status getStatus() const { return status; }
563 Value *getBase() const { return base; }
565 bool isBase() const { return getStatus() == Base; }
566 bool isUnknown() const { return getStatus() == Unknown; }
567 bool isConflict() const { return getStatus() == Conflict; }
569 bool operator==(const PhiState &other) const {
570 return base == other.base && status == other.status;
573 bool operator!=(const PhiState &other) const { return !(*this == other); }
576 errs() << status << " (" << base << " - "
577 << (base ? base->getName() : "nullptr") << "): ";
582 Value *base; // non null only if status == base
585 // Values of type PhiState form a lattice, and this is a helper
586 // class that implementes the meet operation. The meat of the meet
587 // operation is implemented in MeetPhiStates::pureMeet
588 class MeetPhiStates {
590 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
591 explicit MeetPhiStates(const std::map<Value *, PhiState> &phiStates)
592 : phiStates(phiStates) {}
594 // Destructively meet the current result with the base V. V can
595 // either be a merge instruction (SelectInst / PHINode), in which
596 // case its status is looked up in the phiStates map; or a regular
597 // SSA value, in which case it is assumed to be a base.
598 void meetWith(Value *V) {
599 PhiState otherState = getStateForBDV(V);
600 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
601 MeetPhiStates::pureMeet(currentResult, otherState)) &&
602 "math is wrong: meet does not commute!");
603 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
606 PhiState getResult() const { return currentResult; }
609 const std::map<Value *, PhiState> &phiStates;
610 PhiState currentResult;
612 /// Return a phi state for a base defining value. We'll generate a new
613 /// base state for known bases and expect to find a cached state otherwise
614 PhiState getStateForBDV(Value *baseValue) {
615 if (isKnownBaseResult(baseValue)) {
616 return PhiState(baseValue);
618 return lookupFromMap(baseValue);
622 PhiState lookupFromMap(Value *V) {
623 auto I = phiStates.find(V);
624 assert(I != phiStates.end() && "lookup failed!");
628 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
629 switch (stateA.getStatus()) {
630 case PhiState::Unknown:
634 assert(stateA.getBase() && "can't be null");
635 if (stateB.isUnknown()) {
637 } else if (stateB.isBase()) {
638 if (stateA.getBase() == stateB.getBase()) {
639 assert(stateA == stateB && "equality broken!");
642 return PhiState(PhiState::Conflict);
644 assert(stateB.isConflict() && "only three states!");
645 return PhiState(PhiState::Conflict);
648 case PhiState::Conflict:
651 llvm_unreachable("only three states!");
655 /// For a given value or instruction, figure out what base ptr it's derived
656 /// from. For gc objects, this is simply itself. On success, returns a value
657 /// which is the base pointer. (This is reliable and can be used for
658 /// relocation.) On failure, returns nullptr.
659 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache,
660 DenseSet<llvm::Value *> &NewInsertedDefs) {
661 Value *def = findBaseOrBDV(I, cache);
663 if (isKnownBaseResult(def)) {
667 // Here's the rough algorithm:
668 // - For every SSA value, construct a mapping to either an actual base
669 // pointer or a PHI which obscures the base pointer.
670 // - Construct a mapping from PHI to unknown TOP state. Use an
671 // optimistic algorithm to propagate base pointer information. Lattice
676 // When algorithm terminates, all PHIs will either have a single concrete
677 // base or be in a conflict state.
678 // - For every conflict, insert a dummy PHI node without arguments. Add
679 // these to the base[Instruction] = BasePtr mapping. For every
680 // non-conflict, add the actual base.
681 // - For every conflict, add arguments for the base[a] of each input
684 // Note: A simpler form of this would be to add the conflict form of all
685 // PHIs without running the optimistic algorithm. This would be
686 // analougous to pessimistic data flow and would likely lead to an
687 // overall worse solution.
689 std::map<Value *, PhiState> states;
690 states[def] = PhiState();
691 // Recursively fill in all phis & selects reachable from the initial one
692 // for which we don't already know a definite base value for
693 // PERF: Yes, this is as horribly inefficient as it looks.
697 for (auto Pair : states) {
698 Value *v = Pair.first;
699 assert(!isKnownBaseResult(v) && "why did it get added?");
700 if (PHINode *phi = dyn_cast<PHINode>(v)) {
701 unsigned NumPHIValues = phi->getNumIncomingValues();
702 assert(NumPHIValues > 0 && "zero input phis are illegal");
703 for (unsigned i = 0; i != NumPHIValues; ++i) {
704 Value *InVal = phi->getIncomingValue(i);
705 Value *local = findBaseOrBDV(InVal, cache);
706 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
707 states[local] = PhiState();
711 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
712 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
713 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
714 states[local] = PhiState();
717 local = findBaseOrBDV(sel->getFalseValue(), cache);
718 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
719 states[local] = PhiState();
727 errs() << "States after initialization:\n";
728 for (auto Pair : states) {
729 Instruction *v = cast<Instruction>(Pair.first);
730 PhiState state = Pair.second;
736 // TODO: come back and revisit the state transitions around inputs which
737 // have reached conflict state. The current version seems too conservative.
739 bool progress = true;
742 oldSize = states.size();
744 for (auto Pair : states) {
745 MeetPhiStates calculateMeet(states);
746 Value *v = Pair.first;
747 assert(!isKnownBaseResult(v) && "why did it get added?");
748 assert(isa<SelectInst>(v) || isa<PHINode>(v));
749 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
750 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
751 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
752 } else if (PHINode *phi = dyn_cast<PHINode>(v)) {
753 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
754 calculateMeet.meetWith(
755 findBaseOrBDV(phi->getIncomingValue(i), cache));
758 llvm_unreachable("no such state expected");
761 PhiState oldState = states[v];
762 PhiState newState = calculateMeet.getResult();
763 if (oldState != newState) {
765 states[v] = newState;
769 assert(oldSize <= states.size());
770 assert(oldSize == states.size() || progress);
774 errs() << "States after meet iteration:\n";
775 for (auto Pair : states) {
776 Instruction *v = cast<Instruction>(Pair.first);
777 PhiState state = Pair.second;
783 // Insert Phis for all conflicts
784 for (auto Pair : states) {
785 Instruction *v = cast<Instruction>(Pair.first);
786 PhiState state = Pair.second;
787 assert(!isKnownBaseResult(v) && "why did it get added?");
788 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
789 if (state.isConflict()) {
790 if (isa<PHINode>(v)) {
792 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
793 assert(num_preds > 0 && "how did we reach here");
794 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
795 NewInsertedDefs.insert(phi);
796 // Add metadata marking this as a base value
797 auto *const_1 = ConstantInt::get(
799 v->getParent()->getParent()->getParent()->getContext()),
801 auto MDConst = ConstantAsMetadata::get(const_1);
802 MDNode *md = MDNode::get(
803 v->getParent()->getParent()->getParent()->getContext(), MDConst);
804 phi->setMetadata("is_base_value", md);
805 states[v] = PhiState(PhiState::Conflict, phi);
806 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
807 // The undef will be replaced later
808 UndefValue *undef = UndefValue::get(sel->getType());
809 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
810 undef, "base_select", sel);
811 NewInsertedDefs.insert(basesel);
812 // Add metadata marking this as a base value
813 auto *const_1 = ConstantInt::get(
815 v->getParent()->getParent()->getParent()->getContext()),
817 auto MDConst = ConstantAsMetadata::get(const_1);
818 MDNode *md = MDNode::get(
819 v->getParent()->getParent()->getParent()->getContext(), MDConst);
820 basesel->setMetadata("is_base_value", md);
821 states[v] = PhiState(PhiState::Conflict, basesel);
828 // Fixup all the inputs of the new PHIs
829 for (auto Pair : states) {
830 Instruction *v = cast<Instruction>(Pair.first);
831 PhiState state = Pair.second;
833 assert(!isKnownBaseResult(v) && "why did it get added?");
834 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
835 if (state.isConflict()) {
836 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
837 PHINode *phi = cast<PHINode>(v);
838 unsigned NumPHIValues = phi->getNumIncomingValues();
839 for (unsigned i = 0; i < NumPHIValues; i++) {
840 Value *InVal = phi->getIncomingValue(i);
841 BasicBlock *InBB = phi->getIncomingBlock(i);
843 // If we've already seen InBB, add the same incoming value
844 // we added for it earlier. The IR verifier requires phi
845 // nodes with multiple entries from the same basic block
846 // to have the same incoming value for each of those
847 // entries. If we don't do this check here and basephi
848 // has a different type than base, we'll end up adding two
849 // bitcasts (and hence two distinct values) as incoming
850 // values for the same basic block.
852 int blockIndex = basephi->getBasicBlockIndex(InBB);
853 if (blockIndex != -1) {
854 Value *oldBase = basephi->getIncomingValue(blockIndex);
855 basephi->addIncoming(oldBase, InBB);
857 Value *base = findBaseOrBDV(InVal, cache);
858 if (!isKnownBaseResult(base)) {
859 // Either conflict or base.
860 assert(states.count(base));
861 base = states[base].getBase();
862 assert(base != nullptr && "unknown PhiState!");
863 assert(NewInsertedDefs.count(base) &&
864 "should have already added this in a prev. iteration!");
867 // In essense this assert states: the only way two
868 // values incoming from the same basic block may be
869 // different is by being different bitcasts of the same
870 // value. A cleanup that remains TODO is changing
871 // findBaseOrBDV to return an llvm::Value of the correct
872 // type (and still remain pure). This will remove the
873 // need to add bitcasts.
874 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
875 "sanity -- findBaseOrBDV should be pure!");
880 // Find either the defining value for the PHI or the normal base for
882 Value *base = findBaseOrBDV(InVal, cache);
883 if (!isKnownBaseResult(base)) {
884 // Either conflict or base.
885 assert(states.count(base));
886 base = states[base].getBase();
887 assert(base != nullptr && "unknown PhiState!");
889 assert(base && "can't be null");
890 // Must use original input BB since base may not be Instruction
891 // The cast is needed since base traversal may strip away bitcasts
892 if (base->getType() != basephi->getType()) {
893 base = new BitCastInst(base, basephi->getType(), "cast",
894 InBB->getTerminator());
895 NewInsertedDefs.insert(base);
897 basephi->addIncoming(base, InBB);
899 assert(basephi->getNumIncomingValues() == NumPHIValues);
900 } else if (SelectInst *basesel = dyn_cast<SelectInst>(state.getBase())) {
901 SelectInst *sel = cast<SelectInst>(v);
902 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
903 // something more safe and less hacky.
904 for (int i = 1; i <= 2; i++) {
905 Value *InVal = sel->getOperand(i);
906 // Find either the defining value for the PHI or the normal base for
908 Value *base = findBaseOrBDV(InVal, cache);
909 if (!isKnownBaseResult(base)) {
910 // Either conflict or base.
911 assert(states.count(base));
912 base = states[base].getBase();
913 assert(base != nullptr && "unknown PhiState!");
915 assert(base && "can't be null");
916 // Must use original input BB since base may not be Instruction
917 // The cast is needed since base traversal may strip away bitcasts
918 if (base->getType() != basesel->getType()) {
919 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
920 NewInsertedDefs.insert(base);
922 basesel->setOperand(i, base);
925 assert(false && "unexpected type");
930 // Cache all of our results so we can cheaply reuse them
931 // NOTE: This is actually two caches: one of the base defining value
932 // relation and one of the base pointer relation! FIXME
933 for (auto item : states) {
934 Value *v = item.first;
935 Value *base = item.second.getBase();
937 assert(!isKnownBaseResult(v) && "why did it get added?");
940 std::string fromstr =
941 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
943 errs() << "Updating base value cache"
944 << " for: " << (v->hasName() ? v->getName() : "")
945 << " from: " << fromstr
946 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
949 assert(isKnownBaseResult(base) &&
950 "must be something we 'know' is a base pointer");
951 if (cache.count(v)) {
952 // Once we transition from the BDV relation being store in the cache to
953 // the base relation being stored, it must be stable
954 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
955 "base relation should be stable");
959 assert(cache.find(def) != cache.end());
963 // For a set of live pointers (base and/or derived), identify the base
964 // pointer of the object which they are derived from. This routine will
965 // mutate the IR graph as needed to make the 'base' pointer live at the
966 // definition site of 'derived'. This ensures that any use of 'derived' can
967 // also use 'base'. This may involve the insertion of a number of
968 // additional PHI nodes.
970 // preconditions: live is a set of pointer type Values
972 // side effects: may insert PHI nodes into the existing CFG, will preserve
973 // CFG, will not remove or mutate any existing nodes
975 // post condition: PointerToBase contains one (derived, base) pair for every
976 // pointer in live. Note that derived can be equal to base if the original
977 // pointer was a base pointer.
978 static void findBasePointers(const std::set<llvm::Value *> &live,
979 DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
980 DominatorTree *DT, DefiningValueMapTy &DVCache,
981 DenseSet<llvm::Value *> &NewInsertedDefs) {
982 for (Value *ptr : live) {
983 Value *base = findBasePointer(ptr, DVCache, NewInsertedDefs);
984 assert(base && "failed to find base pointer");
985 PointerToBase[ptr] = base;
986 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
987 DT->dominates(cast<Instruction>(base)->getParent(),
988 cast<Instruction>(ptr)->getParent())) &&
989 "The base we found better dominate the derived pointer");
991 if (isNullConstant(base))
992 // If you see this trip and like to live really dangerously, the code
993 // should be correct, just with idioms the verifier can't handle. You
994 // can try disabling the verifier at your own substaintial risk.
995 llvm_unreachable("the relocation code needs adjustment to handle the"
996 "relocation of a null pointer constant without causing"
997 "false positives in the safepoint ir verifier.");
1001 /// Find the required based pointers (and adjust the live set) for the given
1003 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1005 PartiallyConstructedSafepointRecord &result) {
1006 DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
1007 DenseSet<llvm::Value *> NewInsertedDefs;
1008 findBasePointers(result.liveset, PointerToBase, &DT, DVCache, NewInsertedDefs);
1010 if (PrintBasePointers) {
1011 errs() << "Base Pairs (w/o Relocation):\n";
1012 for (auto Pair : PointerToBase) {
1013 errs() << " derived %" << Pair.first->getName() << " base %"
1014 << Pair.second->getName() << "\n";
1018 result.PointerToBase = PointerToBase;
1019 result.NewInsertedDefs = NewInsertedDefs;
1022 /// Check for liveness of items in the insert defs and add them to the live
1023 /// and base pointer sets
1024 static void fixupLiveness(DominatorTree &DT, const CallSite &CS,
1025 const std::set<Value *> &allInsertedDefs,
1026 PartiallyConstructedSafepointRecord &result) {
1027 Instruction *inst = CS.getInstruction();
1029 auto liveset = result.liveset;
1030 auto PointerToBase = result.PointerToBase;
1032 auto is_live_gc_reference =
1033 [&](Value &V) { return isLiveGCReferenceAt(V, inst, DT, nullptr); };
1035 // For each new definition, check to see if a) the definition dominates the
1036 // instruction we're interested in, and b) one of the uses of that definition
1037 // is edge-reachable from the instruction we're interested in. This is the
1038 // same definition of liveness we used in the intial liveness analysis
1039 for (Value *newDef : allInsertedDefs) {
1040 if (liveset.count(newDef)) {
1041 // already live, no action needed
1045 // PERF: Use DT to check instruction domination might not be good for
1046 // compilation time, and we could change to optimal solution if this
1047 // turn to be a issue
1048 if (!DT.dominates(cast<Instruction>(newDef), inst)) {
1049 // can't possibly be live at inst
1053 if (is_live_gc_reference(*newDef)) {
1054 // Add the live new defs into liveset and PointerToBase
1055 liveset.insert(newDef);
1056 PointerToBase[newDef] = newDef;
1060 result.liveset = liveset;
1061 result.PointerToBase = PointerToBase;
1064 static void fixupLiveReferences(
1065 Function &F, DominatorTree &DT, Pass *P,
1066 const std::set<llvm::Value *> &allInsertedDefs,
1067 std::vector<CallSite> &toUpdate,
1068 std::vector<struct PartiallyConstructedSafepointRecord> &records) {
1069 for (size_t i = 0; i < records.size(); i++) {
1070 struct PartiallyConstructedSafepointRecord &info = records[i];
1071 CallSite &CS = toUpdate[i];
1072 fixupLiveness(DT, CS, allInsertedDefs, info);
1076 // Normalize basic block to make it ready to be target of invoke statepoint.
1077 // It means spliting it to have single predecessor. Return newly created BB
1078 // ready to be successor of invoke statepoint.
1079 static BasicBlock *normalizeBBForInvokeSafepoint(BasicBlock *BB,
1080 BasicBlock *InvokeParent,
1082 BasicBlock *ret = BB;
1084 if (!BB->getUniquePredecessor()) {
1085 ret = SplitBlockPredecessors(BB, InvokeParent, "");
1088 // Another requirement for such basic blocks is to not have any phi nodes.
1089 // Since we just ensured that new BB will have single predecessor,
1090 // all phi nodes in it will have one value. Here it would be naturall place
1092 // remove them all. But we can not do this because we are risking to remove
1093 // one of the values stored in liveset of another statepoint. We will do it
1094 // later after placing all safepoints.
1100 VerifySafepointBounds(const std::pair<Instruction *, Instruction *> &bounds) {
1101 assert(bounds.first->getParent() && bounds.second->getParent() &&
1102 "both must belong to basic blocks");
1103 if (bounds.first->getParent() == bounds.second->getParent()) {
1104 // This is a call safepoint
1105 // TODO: scan the range to find the statepoint
1106 // TODO: check that the following instruction is not a gc_relocate or
1109 // This is an invoke safepoint
1110 InvokeInst *invoke = dyn_cast<InvokeInst>(bounds.first);
1112 assert(invoke && "only continues over invokes!");
1113 assert(invoke->getNormalDest() == bounds.second->getParent() &&
1114 "safepoint should continue into normal exit block");
1118 static int find_index(const SmallVectorImpl<Value *> &livevec, Value *val) {
1119 auto itr = std::find(livevec.begin(), livevec.end(), val);
1120 assert(livevec.end() != itr);
1121 size_t index = std::distance(livevec.begin(), itr);
1122 assert(index < livevec.size());
1126 // Create new attribute set containing only attributes which can be transfered
1127 // from original call to the safepoint.
1128 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1131 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1132 unsigned index = AS.getSlotIndex(Slot);
1134 if (index == AttributeSet::ReturnIndex ||
1135 index == AttributeSet::FunctionIndex) {
1137 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1139 Attribute attr = *it;
1141 // Do not allow certain attributes - just skip them
1142 // Safepoint can not be read only or read none.
1143 if (attr.hasAttribute(Attribute::ReadNone) ||
1144 attr.hasAttribute(Attribute::ReadOnly))
1147 ret = ret.addAttributes(
1148 AS.getContext(), index,
1149 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1153 // Just skip parameter attributes for now
1159 /// Helper function to place all gc relocates necessary for the given
1162 /// liveVariables - list of variables to be relocated.
1163 /// liveStart - index of the first live variable.
1164 /// basePtrs - base pointers.
1165 /// statepointToken - statepoint instruction to which relocates should be
1167 /// Builder - Llvm IR builder to be used to construct new calls.
1168 /// Returns array with newly created relocates.
1169 static std::vector<llvm::Instruction *>
1170 CreateGCRelocates(const SmallVectorImpl<llvm::Value *> &liveVariables,
1171 const int liveStart,
1172 const SmallVectorImpl<llvm::Value *> &basePtrs,
1173 Instruction *statepointToken, IRBuilder<> Builder) {
1175 std::vector<llvm::Instruction *> newDefs;
1177 Module *M = statepointToken->getParent()->getParent()->getParent();
1179 for (unsigned i = 0; i < liveVariables.size(); i++) {
1180 // We generate a (potentially) unique declaration for every pointer type
1181 // combination. This results is some blow up the function declarations in
1182 // the IR, but removes the need for argument bitcasts which shrinks the IR
1183 // greatly and makes it much more readable.
1184 std::vector<Type *> types; // one per 'any' type
1185 types.push_back(liveVariables[i]->getType()); // result type
1186 Value *gc_relocate_decl = Intrinsic::getDeclaration(
1187 M, Intrinsic::experimental_gc_relocate, types);
1189 // Generate the gc.relocate call and save the result
1191 ConstantInt::get(Type::getInt32Ty(M->getContext()),
1192 liveStart + find_index(liveVariables, basePtrs[i]));
1193 Value *liveIdx = ConstantInt::get(
1194 Type::getInt32Ty(M->getContext()),
1195 liveStart + find_index(liveVariables, liveVariables[i]));
1197 // only specify a debug name if we can give a useful one
1198 Value *reloc = Builder.CreateCall3(
1199 gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1200 liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1202 // Trick CodeGen into thinking there are lots of free registers at this
1204 cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1206 newDefs.push_back(cast<Instruction>(reloc));
1208 assert(newDefs.size() == liveVariables.size() &&
1209 "missing or extra redefinition at safepoint");
1215 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1216 const SmallVectorImpl<llvm::Value *> &basePtrs,
1217 const SmallVectorImpl<llvm::Value *> &liveVariables,
1219 PartiallyConstructedSafepointRecord &result) {
1220 assert(basePtrs.size() == liveVariables.size());
1221 assert(isStatepoint(CS) &&
1222 "This method expects to be rewriting a statepoint");
1224 BasicBlock *BB = CS.getInstruction()->getParent();
1226 Function *F = BB->getParent();
1227 assert(F && "must be set");
1228 Module *M = F->getParent();
1230 assert(M && "must be set");
1232 // We're not changing the function signature of the statepoint since the gc
1233 // arguments go into the var args section.
1234 Function *gc_statepoint_decl = CS.getCalledFunction();
1236 // Then go ahead and use the builder do actually do the inserts. We insert
1237 // immediately before the previous instruction under the assumption that all
1238 // arguments will be available here. We can't insert afterwards since we may
1239 // be replacing a terminator.
1240 Instruction *insertBefore = CS.getInstruction();
1241 IRBuilder<> Builder(insertBefore);
1242 // Copy all of the arguments from the original statepoint - this includes the
1243 // target, call args, and deopt args
1244 std::vector<llvm::Value *> args;
1245 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1246 // TODO: Clear the 'needs rewrite' flag
1248 // add all the pointers to be relocated (gc arguments)
1249 // Capture the start of the live variable list for use in the gc_relocates
1250 const int live_start = args.size();
1251 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1253 // Create the statepoint given all the arguments
1254 Instruction *token = nullptr;
1255 AttributeSet return_attributes;
1257 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1259 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1260 call->setTailCall(toReplace->isTailCall());
1261 call->setCallingConv(toReplace->getCallingConv());
1263 // Currently we will fail on parameter attributes and on certain
1264 // function attributes.
1265 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1266 // In case if we can handle this set of sttributes - set up function attrs
1267 // directly on statepoint and return attrs later for gc_result intrinsic.
1268 call->setAttributes(new_attrs.getFnAttributes());
1269 return_attributes = new_attrs.getRetAttributes();
1273 // Put the following gc_result and gc_relocate calls immediately after the
1274 // the old call (which we're about to delete)
1275 BasicBlock::iterator next(toReplace);
1276 assert(BB->end() != next && "not a terminator, must have next");
1278 Instruction *IP = &*(next);
1279 Builder.SetInsertPoint(IP);
1280 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1282 } else if (CS.isInvoke()) {
1283 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1285 // Insert the new invoke into the old block. We'll remove the old one in a
1286 // moment at which point this will become the new terminator for the
1288 InvokeInst *invoke = InvokeInst::Create(
1289 gc_statepoint_decl, toReplace->getNormalDest(),
1290 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1291 invoke->setCallingConv(toReplace->getCallingConv());
1293 // Currently we will fail on parameter attributes and on certain
1294 // function attributes.
1295 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1296 // In case if we can handle this set of sttributes - set up function attrs
1297 // directly on statepoint and return attrs later for gc_result intrinsic.
1298 invoke->setAttributes(new_attrs.getFnAttributes());
1299 return_attributes = new_attrs.getRetAttributes();
1303 // Generate gc relocates in exceptional path
1304 BasicBlock *unwindBlock = normalizeBBForInvokeSafepoint(
1305 toReplace->getUnwindDest(), invoke->getParent(), P);
1307 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1308 Builder.SetInsertPoint(IP);
1309 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1311 // Extract second element from landingpad return value. We will attach
1312 // exceptional gc relocates to it.
1313 const unsigned idx = 1;
1314 Instruction *exceptional_token =
1315 cast<Instruction>(Builder.CreateExtractValue(
1316 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1317 result.UnwindToken = exceptional_token;
1319 // Just throw away return value. We will use the one we got for normal
1321 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1322 exceptional_token, Builder);
1324 // Generate gc relocates and returns for normal block
1325 BasicBlock *normalDest = normalizeBBForInvokeSafepoint(
1326 toReplace->getNormalDest(), invoke->getParent(), P);
1328 IP = &*(normalDest->getFirstInsertionPt());
1329 Builder.SetInsertPoint(IP);
1331 // gc relocates will be generated later as if it were regular call
1334 llvm_unreachable("unexpect type of CallSite");
1338 // Take the name of the original value call if it had one.
1339 token->takeName(CS.getInstruction());
1341 // The GCResult is already inserted, we just need to find it
1342 Instruction *gc_result = nullptr;
1344 Instruction *toReplace = CS.getInstruction();
1345 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1346 "only valid use before rewrite is gc.result");
1347 if (toReplace->hasOneUse()) {
1348 Instruction *GCResult = cast<Instruction>(*toReplace->user_begin());
1349 assert(isGCResult(GCResult));
1350 gc_result = GCResult;
1354 // Update the gc.result of the original statepoint (if any) to use the newly
1355 // inserted statepoint. This is safe to do here since the token can't be
1356 // considered a live reference.
1357 CS.getInstruction()->replaceAllUsesWith(token);
1359 // Second, create a gc.relocate for every live variable
1360 std::vector<llvm::Instruction *> newDefs =
1361 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1363 // Need to pass through the last part of the safepoint block so that we
1364 // don't accidentally update uses in a following gc.relocate which is
1365 // still conceptually part of the same safepoint. Gah.
1366 Instruction *last = nullptr;
1367 if (!newDefs.empty()) {
1368 last = newDefs.back();
1369 } else if (gc_result) {
1374 assert(last && "can't be null");
1375 const auto bounds = std::make_pair(token, last);
1377 // Sanity check our results - this is slightly non-trivial due to invokes
1378 VerifySafepointBounds(bounds);
1380 result.SafepointBounds = bounds;
1384 struct name_ordering {
1387 bool operator()(name_ordering const &a, name_ordering const &b) {
1388 return -1 == a.derived->getName().compare(b.derived->getName());
1392 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1393 SmallVectorImpl<Value *> &livevec) {
1394 assert(basevec.size() == livevec.size());
1396 std::vector<name_ordering> temp;
1397 for (size_t i = 0; i < basevec.size(); i++) {
1399 v.base = basevec[i];
1400 v.derived = livevec[i];
1403 std::sort(temp.begin(), temp.end(), name_ordering());
1404 for (size_t i = 0; i < basevec.size(); i++) {
1405 basevec[i] = temp[i].base;
1406 livevec[i] = temp[i].derived;
1410 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1411 // which make the relocations happening at this safepoint explicit.
1413 // WARNING: Does not do any fixup to adjust users of the original live
1414 // values. That's the callers responsibility.
1416 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1417 PartiallyConstructedSafepointRecord &result) {
1418 auto liveset = result.liveset;
1419 auto PointerToBase = result.PointerToBase;
1421 // Convert to vector for efficient cross referencing.
1422 SmallVector<Value *, 64> basevec, livevec;
1423 livevec.reserve(liveset.size());
1424 basevec.reserve(liveset.size());
1425 for (Value *L : liveset) {
1426 livevec.push_back(L);
1428 assert(PointerToBase.find(L) != PointerToBase.end());
1429 Value *base = PointerToBase[L];
1430 basevec.push_back(base);
1432 assert(livevec.size() == basevec.size());
1434 // To make the output IR slightly more stable (for use in diffs), ensure a
1435 // fixed order of the values in the safepoint (by sorting the value name).
1436 // The order is otherwise meaningless.
1437 stablize_order(basevec, livevec);
1439 // Do the actual rewriting and delete the old statepoint
1440 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1441 CS.getInstruction()->eraseFromParent();
1444 // Helper function for the relocationViaAlloca.
1445 // It receives iterator to the statepoint gc relocates and emits store to the
1447 // location (via allocaMap) for the each one of them.
1448 // Add visited values into the visitedLiveValues set we will later use them
1449 // for sanity check.
1451 insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1452 DenseMap<Value *, Value *> &allocaMap,
1453 DenseSet<Value *> &visitedLiveValues) {
1455 for (User *U : gcRelocs) {
1456 if (!isa<IntrinsicInst>(U))
1459 IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1461 // We only care about relocates
1462 if (relocatedValue->getIntrinsicID() !=
1463 Intrinsic::experimental_gc_relocate) {
1467 GCRelocateOperands relocateOperands(relocatedValue);
1468 Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1469 assert(allocaMap.count(originalValue));
1470 Value *alloca = allocaMap[originalValue];
1472 // Emit store into the related alloca
1473 StoreInst *store = new StoreInst(relocatedValue, alloca);
1474 store->insertAfter(relocatedValue);
1477 visitedLiveValues.insert(originalValue);
1482 /// do all the relocation update via allocas and mem2reg
1483 static void relocationViaAlloca(
1484 Function &F, DominatorTree &DT, const std::vector<Value *> &live,
1485 const std::vector<struct PartiallyConstructedSafepointRecord> &records) {
1487 int initialAllocaNum = 0;
1489 // record initial number of allocas
1490 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1492 if (isa<AllocaInst>(*itr))
1497 // TODO-PERF: change data structures, reserve
1498 DenseMap<Value *, Value *> allocaMap;
1499 SmallVector<AllocaInst *, 200> PromotableAllocas;
1500 PromotableAllocas.reserve(live.size());
1502 // emit alloca for each live gc pointer
1503 for (unsigned i = 0; i < live.size(); i++) {
1504 Value *liveValue = live[i];
1505 AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1506 F.getEntryBlock().getFirstNonPHI());
1507 allocaMap[liveValue] = alloca;
1508 PromotableAllocas.push_back(alloca);
1511 // The next two loops are part of the same conceptual operation. We need to
1512 // insert a store to the alloca after the original def and at each
1513 // redefinition. We need to insert a load before each use. These are split
1514 // into distinct loops for performance reasons.
1516 // update gc pointer after each statepoint
1517 // either store a relocated value or null (if no relocated value found for
1518 // this gc pointer and it is not a gc_result)
1519 // this must happen before we update the statepoint with load of alloca
1520 // otherwise we lose the link between statepoint and old def
1521 for (size_t i = 0; i < records.size(); i++) {
1522 const struct PartiallyConstructedSafepointRecord &info = records[i];
1523 Value *statepoint = info.SafepointBounds.first;
1525 // This will be used for consistency check
1526 DenseSet<Value *> visitedLiveValues;
1528 // Insert stores for normal statepoint gc relocates
1529 insertRelocationStores(statepoint->users(), allocaMap, visitedLiveValues);
1531 // In case if it was invoke statepoint
1532 // we will insert stores for exceptional path gc relocates.
1533 if (isa<InvokeInst>(statepoint)) {
1534 insertRelocationStores(info.UnwindToken->users(),
1535 allocaMap, visitedLiveValues);
1539 // As a debuging aid, pretend that an unrelocated pointer becomes null at
1540 // the gc.statepoint. This will turn some subtle GC problems into slightly
1541 // easy to debug SEGVs
1542 for (auto Pair : allocaMap) {
1543 Value *def = Pair.first;
1544 Value *alloca = Pair.second;
1546 // This value was relocated
1547 if (visitedLiveValues.count(def)) {
1551 auto PT = cast<PointerType>(def->getType());
1552 Constant *CPN = ConstantPointerNull::get(PT);
1553 StoreInst *store = new StoreInst(CPN, alloca);
1554 store->insertBefore(info.SafepointBounds.second);
1558 // update use with load allocas and add store for gc_relocated
1559 for (auto Pair : allocaMap) {
1560 Value *def = Pair.first;
1561 Value *alloca = Pair.second;
1563 // we pre-record the uses of allocas so that we dont have to worry about
1565 // that change the user information.
1566 SmallVector<Instruction *, 20> uses;
1567 // PERF: trade a linear scan for repeated reallocation
1568 uses.reserve(std::distance(def->user_begin(), def->user_end()));
1569 for (User *U : def->users()) {
1570 if (!isa<ConstantExpr>(U)) {
1571 // If the def has a ConstantExpr use, then the def is either a
1572 // ConstantExpr use itself or null. In either case
1573 // (recursively in the first, directly in the second), the oop
1574 // it is ultimately dependent on is null and this particular
1575 // use does not need to be fixed up.
1576 uses.push_back(cast<Instruction>(U));
1580 std::sort(uses.begin(), uses.end());
1581 auto last = std::unique(uses.begin(), uses.end());
1582 uses.erase(last, uses.end());
1584 for (Instruction *use : uses) {
1585 if (isa<PHINode>(use)) {
1586 PHINode *phi = cast<PHINode>(use);
1587 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1588 if (def == phi->getIncomingValue(i)) {
1589 LoadInst *load = new LoadInst(
1590 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1591 phi->setIncomingValue(i, load);
1595 LoadInst *load = new LoadInst(alloca, "", use);
1596 use->replaceUsesOfWith(def, load);
1600 // emit store for the initial gc value
1601 // store must be inserted after load, otherwise store will be in alloca's
1602 // use list and an extra load will be inserted before it
1603 StoreInst *store = new StoreInst(def, alloca);
1604 if (isa<Instruction>(def)) {
1605 store->insertAfter(cast<Instruction>(def));
1607 assert((isa<Argument>(def) || isa<GlobalVariable>(def) ||
1608 (isa<Constant>(def) && cast<Constant>(def)->isNullValue())) &&
1609 "Must be argument or global");
1610 store->insertAfter(cast<Instruction>(alloca));
1614 assert(PromotableAllocas.size() == live.size() &&
1615 "we must have the same allocas with lives");
1616 if (!PromotableAllocas.empty()) {
1617 // apply mem2reg to promote alloca to SSA
1618 PromoteMemToReg(PromotableAllocas, DT);
1622 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1624 if (isa<AllocaInst>(*itr))
1627 assert(initialAllocaNum == 0 && "We must not introduce any extra allocas");
1631 /// Implement a unique function which doesn't require we sort the input
1632 /// vector. Doing so has the effect of changing the output of a couple of
1633 /// tests in ways which make them less useful in testing fused safepoints.
1634 template <typename T> static void unique_unsorted(std::vector<T> &vec) {
1637 vec.reserve(vec.size());
1638 std::swap(tmp, vec);
1639 for (auto V : tmp) {
1640 if (seen.insert(V).second) {
1646 static Function *getUseHolder(Module &M) {
1647 FunctionType *ftype =
1648 FunctionType::get(Type::getVoidTy(M.getContext()), true);
1649 Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype));
1653 /// Insert holders so that each Value is obviously live through the entire
1654 /// liftetime of the call.
1655 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1656 std::vector<CallInst *> &holders) {
1657 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1658 Function *Func = getUseHolder(*M);
1660 // For call safepoints insert dummy calls right after safepoint
1661 BasicBlock::iterator next(CS.getInstruction());
1663 CallInst *base_holder = CallInst::Create(Func, Values, "", next);
1664 holders.push_back(base_holder);
1665 } else if (CS.isInvoke()) {
1666 // For invoke safepooints insert dummy calls both in normal and
1667 // exceptional destination blocks
1668 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1669 CallInst *normal_holder = CallInst::Create(
1670 Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt());
1671 CallInst *unwind_holder = CallInst::Create(
1672 Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt());
1673 holders.push_back(normal_holder);
1674 holders.push_back(unwind_holder);
1676 assert(false && "Unsupported");
1680 static void findLiveReferences(
1681 Function &F, DominatorTree &DT, Pass *P, std::vector<CallSite> &toUpdate,
1682 std::vector<struct PartiallyConstructedSafepointRecord> &records) {
1683 for (size_t i = 0; i < records.size(); i++) {
1684 struct PartiallyConstructedSafepointRecord &info = records[i];
1685 CallSite &CS = toUpdate[i];
1686 analyzeParsePointLiveness(DT, CS, info);
1690 static void addBasesAsLiveValues(std::set<Value *> &liveset,
1691 DenseMap<Value *, Value *> &PointerToBase) {
1692 // Identify any base pointers which are used in this safepoint, but not
1693 // themselves relocated. We need to relocate them so that later inserted
1694 // safepoints can get the properly relocated base register.
1695 DenseSet<Value *> missing;
1696 for (Value *L : liveset) {
1697 assert(PointerToBase.find(L) != PointerToBase.end());
1698 Value *base = PointerToBase[L];
1700 if (liveset.find(base) == liveset.end()) {
1701 assert(PointerToBase.find(base) == PointerToBase.end());
1702 // uniqued by set insert
1703 missing.insert(base);
1707 // Note that we want these at the end of the list, otherwise
1708 // register placement gets screwed up once we lower to STATEPOINT
1709 // instructions. This is an utter hack, but there doesn't seem to be a
1711 for (Value *base : missing) {
1713 liveset.insert(base);
1714 PointerToBase[base] = base;
1716 assert(liveset.size() == PointerToBase.size());
1719 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
1720 std::vector<CallSite> &toUpdate) {
1722 // sanity check the input
1723 std::set<CallSite> uniqued;
1724 uniqued.insert(toUpdate.begin(), toUpdate.end());
1725 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1727 for (size_t i = 0; i < toUpdate.size(); i++) {
1728 CallSite &CS = toUpdate[i];
1729 assert(CS.getInstruction()->getParent()->getParent() == &F);
1730 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1734 // A list of dummy calls added to the IR to keep various values obviously
1735 // live in the IR. We'll remove all of these when done.
1736 std::vector<CallInst *> holders;
1738 // Insert a dummy call with all of the arguments to the vm_state we'll need
1739 // for the actual safepoint insertion. This ensures reference arguments in
1740 // the deopt argument list are considered live through the safepoint (and
1741 // thus makes sure they get relocated.)
1742 for (size_t i = 0; i < toUpdate.size(); i++) {
1743 CallSite &CS = toUpdate[i];
1744 Statepoint StatepointCS(CS);
1746 SmallVector<Value *, 64> DeoptValues;
1747 for (Use &U : StatepointCS.vm_state_args()) {
1748 Value *Arg = cast<Value>(&U);
1749 if (isGCPointerType(Arg->getType()))
1750 DeoptValues.push_back(Arg);
1752 insertUseHolderAfter(CS, DeoptValues, holders);
1755 std::vector<struct PartiallyConstructedSafepointRecord> records;
1756 records.reserve(toUpdate.size());
1757 for (size_t i = 0; i < toUpdate.size(); i++) {
1758 struct PartiallyConstructedSafepointRecord info;
1759 records.push_back(info);
1761 assert(records.size() == toUpdate.size());
1763 // A) Identify all gc pointers which are staticly live at the given call
1765 findLiveReferences(F, DT, P, toUpdate, records);
1767 // B) Find the base pointers for each live pointer
1768 /* scope for caching */ {
1769 // Cache the 'defining value' relation used in the computation and
1770 // insertion of base phis and selects. This ensures that we don't insert
1771 // large numbers of duplicate base_phis.
1772 DefiningValueMapTy DVCache;
1774 for (size_t i = 0; i < records.size(); i++) {
1775 struct PartiallyConstructedSafepointRecord &info = records[i];
1776 CallSite &CS = toUpdate[i];
1777 findBasePointers(DT, DVCache, CS, info);
1779 } // end of cache scope
1781 // The base phi insertion logic (for any safepoint) may have inserted new
1782 // instructions which are now live at some safepoint. The simplest such
1785 // phi a <-- will be a new base_phi here
1786 // safepoint 1 <-- that needs to be live here
1790 std::set<llvm::Value *> allInsertedDefs;
1791 for (size_t i = 0; i < records.size(); i++) {
1792 struct PartiallyConstructedSafepointRecord &info = records[i];
1793 allInsertedDefs.insert(info.NewInsertedDefs.begin(),
1794 info.NewInsertedDefs.end());
1797 // We insert some dummy calls after each safepoint to definitely hold live
1798 // the base pointers which were identified for that safepoint. We'll then
1799 // ask liveness for _every_ base inserted to see what is now live. Then we
1800 // remove the dummy calls.
1801 holders.reserve(holders.size() + records.size());
1802 for (size_t i = 0; i < records.size(); i++) {
1803 struct PartiallyConstructedSafepointRecord &info = records[i];
1804 CallSite &CS = toUpdate[i];
1806 SmallVector<Value *, 128> Bases;
1807 for (auto Pair : info.PointerToBase) {
1808 Bases.push_back(Pair.second);
1810 insertUseHolderAfter(CS, Bases, holders);
1813 // Add the bases explicitly to the live vector set. This may result in a few
1814 // extra relocations, but the base has to be available whenever a pointer
1815 // derived from it is used. Thus, we need it to be part of the statepoint's
1816 // gc arguments list. TODO: Introduce an explicit notion (in the following
1817 // code) of the GC argument list as seperate from the live Values at a
1818 // given statepoint.
1819 for (size_t i = 0; i < records.size(); i++) {
1820 struct PartiallyConstructedSafepointRecord &info = records[i];
1821 addBasesAsLiveValues(info.liveset, info.PointerToBase);
1824 // If we inserted any new values, we need to adjust our notion of what is
1825 // live at a particular safepoint.
1826 if (!allInsertedDefs.empty()) {
1827 fixupLiveReferences(F, DT, P, allInsertedDefs, toUpdate, records);
1829 if (PrintBasePointers) {
1830 for (size_t i = 0; i < records.size(); i++) {
1831 struct PartiallyConstructedSafepointRecord &info = records[i];
1832 errs() << "Base Pairs: (w/Relocation)\n";
1833 for (auto Pair : info.PointerToBase) {
1834 errs() << " derived %" << Pair.first->getName() << " base %"
1835 << Pair.second->getName() << "\n";
1839 for (size_t i = 0; i < holders.size(); i++) {
1840 holders[i]->eraseFromParent();
1841 holders[i] = nullptr;
1845 // Now run through and replace the existing statepoints with new ones with
1846 // the live variables listed. We do not yet update uses of the values being
1847 // relocated. We have references to live variables that need to
1848 // survive to the last iteration of this loop. (By construction, the
1849 // previous statepoint can not be a live variable, thus we can and remove
1850 // the old statepoint calls as we go.)
1851 for (size_t i = 0; i < records.size(); i++) {
1852 struct PartiallyConstructedSafepointRecord &info = records[i];
1853 CallSite &CS = toUpdate[i];
1854 makeStatepointExplicit(DT, CS, P, info);
1856 toUpdate.clear(); // prevent accident use of invalid CallSites
1858 // In case if we inserted relocates in a different basic block than the
1859 // original safepoint (this can happen for invokes). We need to be sure that
1860 // original values were not used in any of the phi nodes at the
1861 // beginning of basic block containing them. Because we know that all such
1862 // blocks will have single predecessor we can safely assume that all phi
1863 // nodes have single entry (because of normalizeBBForInvokeSafepoint).
1864 // Just remove them all here.
1865 for (size_t i = 0; i < records.size(); i++) {
1866 Instruction *I = records[i].SafepointBounds.first;
1868 if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
1869 FoldSingleEntryPHINodes(invoke->getNormalDest());
1870 assert(!isa<PHINode>(invoke->getNormalDest()->begin()));
1872 FoldSingleEntryPHINodes(invoke->getUnwindDest());
1873 assert(!isa<PHINode>(invoke->getUnwindDest()->begin()));
1877 // Do all the fixups of the original live variables to their relocated selves
1878 std::vector<Value *> live;
1879 for (size_t i = 0; i < records.size(); i++) {
1880 struct PartiallyConstructedSafepointRecord &info = records[i];
1881 // We can't simply save the live set from the original insertion. One of
1882 // the live values might be the result of a call which needs a safepoint.
1883 // That Value* no longer exists and we need to use the new gc_result.
1884 // Thankfully, the liveset is embedded in the statepoint (and updated), so
1885 // we just grab that.
1886 Statepoint statepoint(info.SafepointBounds.first);
1887 live.insert(live.end(), statepoint.gc_args_begin(),
1888 statepoint.gc_args_end());
1890 unique_unsorted(live);
1894 for (auto ptr : live) {
1895 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1899 relocationViaAlloca(F, DT, live, records);
1900 return !records.empty();
1903 /// Returns true if this function should be rewritten by this pass. The main
1904 /// point of this function is as an extension point for custom logic.
1905 static bool shouldRewriteStatepointsIn(Function &F) {
1906 // TODO: This should check the GCStrategy
1908 const std::string StatepointExampleName("statepoint-example");
1909 return StatepointExampleName == F.getGC();
1914 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1915 // Nothing to do for declarations.
1916 if (F.isDeclaration() || F.empty())
1919 // Policy choice says not to rewrite - the most common reason is that we're
1920 // compiling code without a GCStrategy.
1921 if (!shouldRewriteStatepointsIn(F))
1924 // Gather all the statepoints which need rewritten.
1925 std::vector<CallSite> ParsePointNeeded;
1926 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1928 // TODO: only the ones with the flag set!
1929 if (isStatepoint(*itr))
1930 ParsePointNeeded.push_back(CallSite(&*itr));
1933 // Return early if no work to do.
1934 if (ParsePointNeeded.empty())
1937 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1938 return insertParsePoints(F, DT, this, ParsePointNeeded);