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));
58 struct RewriteStatepointsForGC : public FunctionPass {
59 static char ID; // Pass identification, replacement for typeid
61 RewriteStatepointsForGC() : FunctionPass(ID) {
62 initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
64 bool runOnFunction(Function &F) override;
66 void getAnalysisUsage(AnalysisUsage &AU) const override {
67 // We add and rewrite a bunch of instructions, but don't really do much
68 // else. We could in theory preserve a lot more analyses here.
69 AU.addRequired<DominatorTreeWrapperPass>();
73 char RewriteStatepointsForGC::ID = 0;
75 FunctionPass *llvm::createRewriteStatepointsForGCPass() {
76 return new RewriteStatepointsForGC();
79 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
80 "Make relocations explicit at statepoints", false, false)
81 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
82 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
83 "Make relocations explicit at statepoints", false, false)
86 // The type of the internal cache used inside the findBasePointers family
87 // of functions. From the callers perspective, this is an opaque type and
88 // should not be inspected.
90 // In the actual implementation this caches two relations:
91 // - The base relation itself (i.e. this pointer is based on that one)
92 // - The base defining value relation (i.e. before base_phi insertion)
93 // Generally, after the execution of a full findBasePointer call, only the
94 // base relation will remain. Internally, we add a mixture of the two
95 // types, then update all the second type to the first type
96 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 std::map<llvm::Value *, llvm::Value *> base_pairs;
107 /// Any new values which were added to the IR during base pointer analysis
108 /// for this safepoint
109 std::set<llvm::Value *> newInsertedDefs;
111 /// The bounds of the inserted code for the safepoint
112 std::pair<Instruction *, Instruction *> safepoint;
114 // Instruction to which exceptional gc relocates are attached
115 // Makes it easier to iterate through them during relocationViaAlloca.
116 Instruction *exceptional_relocates_token;
118 /// The result of the safepointing call (or nullptr)
123 // TODO: Once we can get to the GCStrategy, this becomes
124 // Optional<bool> isGCManagedPointer(const Value *V) const override {
126 static bool isGCPointerType(const Type *T) {
127 if (const PointerType *PT = dyn_cast<PointerType>(T))
128 // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
129 // GC managed heap. We know that a pointer into this heap needs to be
130 // updated and that no other pointer does.
131 return (1 == PT->getAddressSpace());
135 /// Return true if the Value is a gc reference type which is potentially used
136 /// after the instruction 'loc'. This is only used with the edge reachability
137 /// liveness code. Note: It is assumed the V dominates loc.
138 static bool isLiveGCReferenceAt(Value &V, Instruction *loc, DominatorTree &DT,
140 if (!isGCPointerType(V.getType()))
146 // Given assumption that V dominates loc, this may be live
151 static bool isAggWhichContainsGCPtrType(Type *Ty) {
152 if (VectorType *VT = dyn_cast<VectorType>(Ty))
153 return isGCPointerType(VT->getScalarType());
154 else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
155 return isGCPointerType(AT->getElementType()) ||
156 isAggWhichContainsGCPtrType(AT->getElementType());
157 } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
158 bool UnsupportedType = false;
159 for (Type *SubType : ST->subtypes())
161 isGCPointerType(SubType) || isAggWhichContainsGCPtrType(SubType);
162 return UnsupportedType;
168 // Conservatively identifies any definitions which might be live at the
169 // given instruction. The analysis is performed immediately before the
170 // given instruction. Values defined by that instruction are not considered
171 // live. Values used by that instruction are considered live.
173 // preconditions: valid IR graph, term is either a terminator instruction or
174 // a call instruction, pred is the basic block of term, DT, LI are valid
176 // side effects: none, does not mutate IR
178 // postconditions: populates liveValues as discussed above
179 static void findLiveGCValuesAtInst(Instruction *term, BasicBlock *pred,
180 DominatorTree &DT, LoopInfo *LI,
181 std::set<llvm::Value *> &liveValues) {
184 assert(isa<CallInst>(term) || isa<InvokeInst>(term) || term->isTerminator());
186 Function *F = pred->getParent();
188 auto is_live_gc_reference =
189 [&](Value &V) { return isLiveGCReferenceAt(V, term, DT, LI); };
191 // Are there any gc pointer arguments live over this point? This needs to be
192 // special cased since arguments aren't defined in basic blocks.
193 for (Argument &arg : F->args()) {
194 assert(!isAggWhichContainsGCPtrType(arg.getType()) &&
195 "support for FCA unimplemented");
197 if (is_live_gc_reference(arg)) {
198 liveValues.insert(&arg);
202 // Walk through all dominating blocks - the ones which can contain
203 // definitions used in this block - and check to see if any of the values
204 // they define are used in locations potentially reachable from the
205 // interesting instruction.
206 BasicBlock *BBI = pred;
209 errs() << "[LSP] Looking at dominating block " << pred->getName() << "\n";
211 assert(DT.dominates(BBI, pred));
212 assert(isPotentiallyReachable(BBI, pred, &DT) &&
213 "dominated block must be reachable");
215 // Walk through the instructions in dominating blocks and keep any
216 // that have a use potentially reachable from the block we're
217 // considering putting the safepoint in
218 for (Instruction &inst : *BBI) {
220 errs() << "[LSP] Looking at instruction ";
224 if (pred == BBI && (&inst) == term) {
226 errs() << "[LSP] stopped because we encountered the safepoint "
230 // If we're in the block which defines the interesting instruction,
231 // we don't want to include any values as live which are defined
232 // _after_ the interesting line or as part of the line itself
233 // i.e. "term" is the call instruction for a call safepoint, the
234 // results of the call should not be considered live in that stackmap
238 assert(!isAggWhichContainsGCPtrType(inst.getType()) &&
239 "support for FCA unimplemented");
241 if (is_live_gc_reference(inst)) {
243 errs() << "[LSP] found live value for this safepoint ";
247 liveValues.insert(&inst);
250 if (!DT.getNode(BBI)->getIDom()) {
251 assert(BBI == &F->getEntryBlock() &&
252 "failed to find a dominator for something other than "
256 BBI = DT.getNode(BBI)->getIDom()->getBlock();
260 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
261 if (a->hasName() && b->hasName()) {
262 return -1 == a->getName().compare(b->getName());
263 } else if (a->hasName() && !b->hasName()) {
265 } else if (!a->hasName() && b->hasName()) {
268 // Better than nothing, but not stable
273 /// Find the initial live set. Note that due to base pointer
274 /// insertion, the live set may be incomplete.
276 analyzeParsePointLiveness(DominatorTree &DT, const CallSite &CS,
277 PartiallyConstructedSafepointRecord &result) {
278 Instruction *inst = CS.getInstruction();
280 BasicBlock *BB = inst->getParent();
281 std::set<Value *> liveset;
282 findLiveGCValuesAtInst(inst, BB, DT, nullptr, liveset);
285 // Note: This output is used by several of the test cases
286 // The order of elemtns in a set is not stable, put them in a vec and sort
288 std::vector<Value *> temp;
289 temp.insert(temp.end(), liveset.begin(), liveset.end());
290 std::sort(temp.begin(), temp.end(), order_by_name);
291 errs() << "Live Variables:\n";
292 for (Value *V : temp) {
293 errs() << " " << V->getName(); // no newline
297 if (PrintLiveSetSize) {
298 errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
299 errs() << "Number live values: " << liveset.size() << "\n";
301 result.liveset = liveset;
304 /// True iff this value is the null pointer constant (of any pointer type)
305 static bool isNullConstant(Value *V) {
306 return isa<Constant>(V) && isa<PointerType>(V->getType()) &&
307 cast<Constant>(V)->isNullValue();
310 /// Helper function for findBasePointer - Will return a value which either a)
311 /// defines the base pointer for the input or b) blocks the simple search
312 /// (i.e. a PHI or Select of two derived pointers)
313 static Value *findBaseDefiningValue(Value *I) {
314 assert(I->getType()->isPointerTy() &&
315 "Illegal to ask for the base pointer of a non-pointer type");
317 // There are instructions which can never return gc pointer values. Sanity
319 // that this is actually true.
320 assert(!isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
321 !isa<ShuffleVectorInst>(I) && "Vector types are not gc pointers");
322 assert((!isa<Instruction>(I) || isa<InvokeInst>(I) ||
323 !cast<Instruction>(I)->isTerminator()) &&
324 "With the exception of invoke terminators don't define values");
325 assert(!isa<StoreInst>(I) && !isa<FenceInst>(I) &&
326 "Can't be definitions to start with");
327 assert(!isa<ICmpInst>(I) && !isa<FCmpInst>(I) &&
328 "Comparisons don't give ops");
329 // There's a bunch of instructions which just don't make sense to apply to
330 // a pointer. The only valid reason for this would be pointer bit
331 // twiddling which we're just not going to support.
332 assert((!isa<Instruction>(I) || !cast<Instruction>(I)->isBinaryOp()) &&
333 "Binary ops on pointer values are meaningless. Unless your "
334 "bit-twiddling which we don't support");
336 if (Argument *Arg = dyn_cast<Argument>(I)) {
337 // An incoming argument to the function is a base pointer
338 // We should have never reached here if this argument isn't an gc value
339 assert(Arg->getType()->isPointerTy() &&
340 "Base for pointer must be another pointer");
344 if (GlobalVariable *global = dyn_cast<GlobalVariable>(I)) {
346 assert(global->getType()->isPointerTy() &&
347 "Base for pointer must be another pointer");
351 // inlining could possibly introduce phi node that contains
352 // undef if callee has multiple returns
353 if (UndefValue *undef = dyn_cast<UndefValue>(I)) {
354 assert(undef->getType()->isPointerTy() &&
355 "Base for pointer must be another pointer");
356 return undef; // utterly meaningless, but useful for dealing with
357 // partially optimized code.
360 // Due to inheritance, this must be _after_ the global variable and undef
362 if (Constant *con = dyn_cast<Constant>(I)) {
363 assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
364 "order of checks wrong!");
365 // Note: Finding a constant base for something marked for relocation
366 // doesn't really make sense. The most likely case is either a) some
367 // screwed up the address space usage or b) your validating against
368 // compiled C++ code w/o the proper separation. The only real exception
369 // is a null pointer. You could have generic code written to index of
370 // off a potentially null value and have proven it null. We also use
371 // null pointers in dead paths of relocation phis (which we might later
372 // want to find a base pointer for).
373 assert(con->getType()->isPointerTy() &&
374 "Base for pointer must be another pointer");
375 assert(con->isNullValue() && "null is the only case which makes sense");
379 if (CastInst *CI = dyn_cast<CastInst>(I)) {
380 Value *def = CI->stripPointerCasts();
381 assert(def->getType()->isPointerTy() &&
382 "Base for pointer must be another pointer");
383 if (isa<CastInst>(def)) {
384 // If we find a cast instruction here, it means we've found a cast
385 // which is not simply a pointer cast (i.e. an inttoptr). We don't
386 // know how to handle int->ptr conversion.
387 llvm_unreachable("Can not find the base pointers for an inttoptr cast");
389 assert(!isa<CastInst>(def) && "shouldn't find another cast here");
390 return findBaseDefiningValue(def);
393 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
394 if (LI->getType()->isPointerTy()) {
395 Value *Op = LI->getOperand(0);
397 // Has to be a pointer to an gc object, or possibly an array of such?
398 assert(Op->getType()->isPointerTy());
399 return LI; // The value loaded is an gc base itself
402 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
403 Value *Op = GEP->getOperand(0);
404 if (Op->getType()->isPointerTy()) {
405 return findBaseDefiningValue(Op); // The base of this GEP is the base
409 if (AllocaInst *alloc = dyn_cast<AllocaInst>(I)) {
410 // An alloca represents a conceptual stack slot. It's the slot itself
411 // that the GC needs to know about, not the value in the slot.
412 assert(alloc->getType()->isPointerTy() &&
413 "Base for pointer must be another pointer");
417 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
418 switch (II->getIntrinsicID()) {
420 // fall through to general call handling
422 case Intrinsic::experimental_gc_statepoint:
423 case Intrinsic::experimental_gc_result_float:
424 case Intrinsic::experimental_gc_result_int:
425 llvm_unreachable("these don't produce pointers");
426 case Intrinsic::experimental_gc_result_ptr:
427 // This is just a special case of the CallInst check below to handle a
428 // statepoint with deopt args which hasn't been rewritten for GC yet.
429 // TODO: Assert that the statepoint isn't rewritten yet.
431 case Intrinsic::experimental_gc_relocate: {
432 // Rerunning safepoint insertion after safepoints are already
433 // inserted is not supported. It could probably be made to work,
434 // but why are you doing this? There's no good reason.
435 llvm_unreachable("repeat safepoint insertion is not supported");
437 case Intrinsic::gcroot:
438 // Currently, this mechanism hasn't been extended to work with gcroot.
439 // There's no reason it couldn't be, but I haven't thought about the
440 // implications much.
442 "interaction with the gcroot mechanism is not supported");
445 // We assume that functions in the source language only return base
446 // pointers. This should probably be generalized via attributes to support
447 // both source language and internal functions.
448 if (CallInst *call = dyn_cast<CallInst>(I)) {
449 assert(call->getType()->isPointerTy() &&
450 "Base for pointer must be another pointer");
453 if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
454 assert(invoke->getType()->isPointerTy() &&
455 "Base for pointer must be another pointer");
459 // I have absolutely no idea how to implement this part yet. It's not
460 // neccessarily hard, I just haven't really looked at it yet.
461 assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
463 if (AtomicCmpXchgInst *cas = dyn_cast<AtomicCmpXchgInst>(I)) {
464 // A CAS is effectively a atomic store and load combined under a
465 // predicate. From the perspective of base pointers, we just treat it
466 // like a load. We loaded a pointer from a address in memory, that value
467 // had better be a valid base pointer.
468 return cas->getPointerOperand();
470 if (AtomicRMWInst *atomic = dyn_cast<AtomicRMWInst>(I)) {
471 assert(AtomicRMWInst::Xchg == atomic->getOperation() &&
472 "All others are binary ops which don't apply to base pointers");
473 // semantically, a load, store pair. Treat it the same as a standard load
474 return atomic->getPointerOperand();
477 // The aggregate ops. Aggregates can either be in the heap or on the
478 // stack, but in either case, this is simply a field load. As a result,
479 // this is a defining definition of the base just like a load is.
480 if (ExtractValueInst *ev = dyn_cast<ExtractValueInst>(I)) {
484 // We should never see an insert vector since that would require we be
485 // tracing back a struct value not a pointer value.
486 assert(!isa<InsertValueInst>(I) &&
487 "Base pointer for a struct is meaningless");
489 // The last two cases here don't return a base pointer. Instead, they
490 // return a value which dynamically selects from amoung several base
491 // derived pointers (each with it's own base potentially). It's the job of
492 // the caller to resolve these.
493 if (SelectInst *select = dyn_cast<SelectInst>(I)) {
496 if (PHINode *phi = dyn_cast<PHINode>(I)) {
500 errs() << "unknown type: " << *I << "\n";
501 llvm_unreachable("unknown type");
505 /// Returns the base defining value for this value.
506 Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &cache) {
507 if (cache.find(I) == cache.end()) {
508 cache[I] = findBaseDefiningValue(I);
510 assert(cache.find(I) != cache.end());
513 errs() << "fBDV-cached: " << I->getName() << " -> " << cache[I]->getName()
519 /// Return a base pointer for this value if known. Otherwise, return it's
520 /// base defining value.
521 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &cache) {
522 Value *def = findBaseDefiningValueCached(I, cache);
523 if (cache.count(def)) {
524 // Either a base-of relation, or a self reference. Caller must check.
527 // Only a BDV available
531 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
532 /// is it known to be a base pointer? Or do we need to continue searching.
533 static bool isKnownBaseResult(Value *v) {
534 if (!isa<PHINode>(v) && !isa<SelectInst>(v)) {
535 // no recursion possible
538 if (cast<Instruction>(v)->getMetadata("is_base_value")) {
539 // This is a previously inserted base phi or select. We know
540 // that this is a base value.
544 // We need to keep searching
548 // TODO: find a better name for this
552 enum Status { Unknown, Base, Conflict };
554 PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
555 assert(status != Base || b);
557 PhiState(Value *b) : status(Base), base(b) {}
558 PhiState() : status(Unknown), base(nullptr) {}
559 PhiState(const PhiState &other) : status(other.status), base(other.base) {
560 assert(status != Base || base);
563 Status getStatus() const { return status; }
564 Value *getBase() const { return base; }
566 bool isBase() const { return getStatus() == Base; }
567 bool isUnknown() const { return getStatus() == Unknown; }
568 bool isConflict() const { return getStatus() == Conflict; }
570 bool operator==(const PhiState &other) const {
571 return base == other.base && status == other.status;
574 bool operator!=(const PhiState &other) const { return !(*this == other); }
577 errs() << status << " (" << base << " - "
578 << (base ? base->getName() : "nullptr") << "): ";
583 Value *base; // non null only if status == base
586 // Values of type PhiState form a lattice, and this is a helper
587 // class that implementes the meet operation. The meat of the meet
588 // operation is implemented in MeetPhiStates::pureMeet
589 class MeetPhiStates {
591 // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
592 explicit MeetPhiStates(const std::map<Value *, PhiState> &phiStates)
593 : phiStates(phiStates) {}
595 // Destructively meet the current result with the base V. V can
596 // either be a merge instruction (SelectInst / PHINode), in which
597 // case its status is looked up in the phiStates map; or a regular
598 // SSA value, in which case it is assumed to be a base.
599 void meetWith(Value *V) {
600 PhiState otherState = getStateForBDV(V);
601 assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
602 MeetPhiStates::pureMeet(currentResult, otherState)) &&
603 "math is wrong: meet does not commute!");
604 currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
607 PhiState getResult() const { return currentResult; }
610 const std::map<Value *, PhiState> &phiStates;
611 PhiState currentResult;
613 /// Return a phi state for a base defining value. We'll generate a new
614 /// base state for known bases and expect to find a cached state otherwise
615 PhiState getStateForBDV(Value *baseValue) {
616 if (isKnownBaseResult(baseValue)) {
617 return PhiState(baseValue);
619 return lookupFromMap(baseValue);
623 PhiState lookupFromMap(Value *V) {
624 auto I = phiStates.find(V);
625 assert(I != phiStates.end() && "lookup failed!");
629 static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
630 switch (stateA.getStatus()) {
631 case PhiState::Unknown:
635 assert(stateA.getBase() && "can't be null");
636 if (stateB.isUnknown()) {
638 } else if (stateB.isBase()) {
639 if (stateA.getBase() == stateB.getBase()) {
640 assert(stateA == stateB && "equality broken!");
643 return PhiState(PhiState::Conflict);
645 assert(stateB.isConflict() && "only three states!");
646 return PhiState(PhiState::Conflict);
649 case PhiState::Conflict:
652 assert(false && "only three states!");
656 /// For a given value or instruction, figure out what base ptr it's derived
657 /// from. For gc objects, this is simply itself. On success, returns a value
658 /// which is the base pointer. (This is reliable and can be used for
659 /// relocation.) On failure, returns nullptr.
660 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache,
661 std::set<llvm::Value *> &newInsertedDefs) {
662 Value *def = findBaseOrBDV(I, cache);
664 if (isKnownBaseResult(def)) {
668 // Here's the rough algorithm:
669 // - For every SSA value, construct a mapping to either an actual base
670 // pointer or a PHI which obscures the base pointer.
671 // - Construct a mapping from PHI to unknown TOP state. Use an
672 // optimistic algorithm to propagate base pointer information. Lattice
677 // When algorithm terminates, all PHIs will either have a single concrete
678 // base or be in a conflict state.
679 // - For every conflict, insert a dummy PHI node without arguments. Add
680 // these to the base[Instruction] = BasePtr mapping. For every
681 // non-conflict, add the actual base.
682 // - For every conflict, add arguments for the base[a] of each input
685 // Note: A simpler form of this would be to add the conflict form of all
686 // PHIs without running the optimistic algorithm. This would be
687 // analougous to pessimistic data flow and would likely lead to an
688 // overall worse solution.
690 std::map<Value *, PhiState> states;
691 states[def] = PhiState();
692 // Recursively fill in all phis & selects reachable from the initial one
693 // for which we don't already know a definite base value for
694 // PERF: Yes, this is as horribly inefficient as it looks.
698 for (auto Pair : states) {
699 Value *v = Pair.first;
700 assert(!isKnownBaseResult(v) && "why did it get added?");
701 if (PHINode *phi = dyn_cast<PHINode>(v)) {
702 unsigned NumPHIValues = phi->getNumIncomingValues();
703 assert(NumPHIValues > 0 && "zero input phis are illegal");
704 for (unsigned i = 0; i != NumPHIValues; ++i) {
705 Value *InVal = phi->getIncomingValue(i);
706 Value *local = findBaseOrBDV(InVal, cache);
707 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
708 states[local] = PhiState();
712 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
713 Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
714 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
715 states[local] = PhiState();
718 local = findBaseOrBDV(sel->getFalseValue(), cache);
719 if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
720 states[local] = PhiState();
728 errs() << "States after initialization:\n";
729 for (auto Pair : states) {
730 Instruction *v = cast<Instruction>(Pair.first);
731 PhiState state = Pair.second;
737 // TODO: come back and revisit the state transitions around inputs which
738 // have reached conflict state. The current version seems too conservative.
740 bool progress = true;
743 oldSize = states.size();
745 for (auto Pair : states) {
746 MeetPhiStates calculateMeet(states);
747 Value *v = Pair.first;
748 assert(!isKnownBaseResult(v) && "why did it get added?");
749 assert(isa<SelectInst>(v) || isa<PHINode>(v));
750 if (SelectInst *select = dyn_cast<SelectInst>(v)) {
751 calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
752 calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
753 } else if (PHINode *phi = dyn_cast<PHINode>(v)) {
754 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
755 calculateMeet.meetWith(
756 findBaseOrBDV(phi->getIncomingValue(i), cache));
759 llvm_unreachable("no such state expected");
762 PhiState oldState = states[v];
763 PhiState newState = calculateMeet.getResult();
764 if (oldState != newState) {
766 states[v] = newState;
770 assert(oldSize <= states.size());
771 assert(oldSize == states.size() || progress);
775 errs() << "States after meet iteration:\n";
776 for (auto Pair : states) {
777 Instruction *v = cast<Instruction>(Pair.first);
778 PhiState state = Pair.second;
784 // Insert Phis for all conflicts
785 for (auto Pair : states) {
786 Instruction *v = cast<Instruction>(Pair.first);
787 PhiState state = Pair.second;
788 assert(!isKnownBaseResult(v) && "why did it get added?");
789 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
790 if (state.isConflict()) {
791 if (isa<PHINode>(v)) {
793 std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
794 assert(num_preds > 0 && "how did we reach here");
795 PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
796 newInsertedDefs.insert(phi);
797 // Add metadata marking this as a base value
798 auto *const_1 = ConstantInt::get(
800 v->getParent()->getParent()->getParent()->getContext()),
802 auto MDConst = ConstantAsMetadata::get(const_1);
803 MDNode *md = MDNode::get(
804 v->getParent()->getParent()->getParent()->getContext(), MDConst);
805 phi->setMetadata("is_base_value", md);
806 states[v] = PhiState(PhiState::Conflict, phi);
807 } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
808 // The undef will be replaced later
809 UndefValue *undef = UndefValue::get(sel->getType());
810 SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
811 undef, "base_select", sel);
812 newInsertedDefs.insert(basesel);
813 // Add metadata marking this as a base value
814 auto *const_1 = ConstantInt::get(
816 v->getParent()->getParent()->getParent()->getContext()),
818 auto MDConst = ConstantAsMetadata::get(const_1);
819 MDNode *md = MDNode::get(
820 v->getParent()->getParent()->getParent()->getContext(), MDConst);
821 basesel->setMetadata("is_base_value", md);
822 states[v] = PhiState(PhiState::Conflict, basesel);
829 // Fixup all the inputs of the new PHIs
830 for (auto Pair : states) {
831 Instruction *v = cast<Instruction>(Pair.first);
832 PhiState state = Pair.second;
834 assert(!isKnownBaseResult(v) && "why did it get added?");
835 assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
836 if (state.isConflict()) {
837 if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
838 PHINode *phi = cast<PHINode>(v);
839 unsigned NumPHIValues = phi->getNumIncomingValues();
840 for (unsigned i = 0; i < NumPHIValues; i++) {
841 Value *InVal = phi->getIncomingValue(i);
842 BasicBlock *InBB = phi->getIncomingBlock(i);
844 // If we've already seen InBB, add the same incoming value
845 // we added for it earlier. The IR verifier requires phi
846 // nodes with multiple entries from the same basic block
847 // to have the same incoming value for each of those
848 // entries. If we don't do this check here and basephi
849 // has a different type than base, we'll end up adding two
850 // bitcasts (and hence two distinct values) as incoming
851 // values for the same basic block.
853 int blockIndex = basephi->getBasicBlockIndex(InBB);
854 if (blockIndex != -1) {
855 Value *oldBase = basephi->getIncomingValue(blockIndex);
856 basephi->addIncoming(oldBase, InBB);
858 Value *base = findBaseOrBDV(InVal, cache);
859 if (!isKnownBaseResult(base)) {
860 // Either conflict or base.
861 assert(states.count(base));
862 base = states[base].getBase();
863 assert(base != nullptr && "unknown PhiState!");
864 assert(newInsertedDefs.count(base) &&
865 "should have already added this in a prev. iteration!");
868 // In essense this assert states: the only way two
869 // values incoming from the same basic block may be
870 // different is by being different bitcasts of the same
871 // value. A cleanup that remains TODO is changing
872 // findBaseOrBDV to return an llvm::Value of the correct
873 // type (and still remain pure). This will remove the
874 // need to add bitcasts.
875 assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
876 "sanity -- findBaseOrBDV should be pure!");
881 // Find either the defining value for the PHI or the normal base for
883 Value *base = findBaseOrBDV(InVal, cache);
884 if (!isKnownBaseResult(base)) {
885 // Either conflict or base.
886 assert(states.count(base));
887 base = states[base].getBase();
888 assert(base != nullptr && "unknown PhiState!");
890 assert(base && "can't be null");
891 // Must use original input BB since base may not be Instruction
892 // The cast is needed since base traversal may strip away bitcasts
893 if (base->getType() != basephi->getType()) {
894 base = new BitCastInst(base, basephi->getType(), "cast",
895 InBB->getTerminator());
896 newInsertedDefs.insert(base);
898 basephi->addIncoming(base, InBB);
900 assert(basephi->getNumIncomingValues() == NumPHIValues);
901 } else if (SelectInst *basesel = dyn_cast<SelectInst>(state.getBase())) {
902 SelectInst *sel = cast<SelectInst>(v);
903 // Operand 1 & 2 are true, false path respectively. TODO: refactor to
904 // something more safe and less hacky.
905 for (int i = 1; i <= 2; i++) {
906 Value *InVal = sel->getOperand(i);
907 // Find either the defining value for the PHI or the normal base for
909 Value *base = findBaseOrBDV(InVal, cache);
910 if (!isKnownBaseResult(base)) {
911 // Either conflict or base.
912 assert(states.count(base));
913 base = states[base].getBase();
914 assert(base != nullptr && "unknown PhiState!");
916 assert(base && "can't be null");
917 // Must use original input BB since base may not be Instruction
918 // The cast is needed since base traversal may strip away bitcasts
919 if (base->getType() != basesel->getType()) {
920 base = new BitCastInst(base, basesel->getType(), "cast", basesel);
921 newInsertedDefs.insert(base);
923 basesel->setOperand(i, base);
926 assert(false && "unexpected type");
931 // Cache all of our results so we can cheaply reuse them
932 // NOTE: This is actually two caches: one of the base defining value
933 // relation and one of the base pointer relation! FIXME
934 for (auto item : states) {
935 Value *v = item.first;
936 Value *base = item.second.getBase();
938 assert(!isKnownBaseResult(v) && "why did it get added?");
941 std::string fromstr =
942 cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
944 errs() << "Updating base value cache"
945 << " for: " << (v->hasName() ? v->getName() : "")
946 << " from: " << fromstr
947 << " to: " << (base->hasName() ? base->getName() : "") << "\n";
950 assert(isKnownBaseResult(base) &&
951 "must be something we 'know' is a base pointer");
952 if (cache.count(v)) {
953 // Once we transition from the BDV relation being store in the cache to
954 // the base relation being stored, it must be stable
955 assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
956 "base relation should be stable");
960 assert(cache.find(def) != cache.end());
964 // For a set of live pointers (base and/or derived), identify the base
965 // pointer of the object which they are derived from. This routine will
966 // mutate the IR graph as needed to make the 'base' pointer live at the
967 // definition site of 'derived'. This ensures that any use of 'derived' can
968 // also use 'base'. This may involve the insertion of a number of
969 // additional PHI nodes.
971 // preconditions: live is a set of pointer type Values
973 // side effects: may insert PHI nodes into the existing CFG, will preserve
974 // CFG, will not remove or mutate any existing nodes
976 // post condition: base_pairs contains one (derived, base) pair for every
977 // pointer in live. Note that derived can be equal to base if the original
978 // pointer was a base pointer.
979 static void findBasePointers(const std::set<llvm::Value *> &live,
980 std::map<llvm::Value *, llvm::Value *> &base_pairs,
981 DominatorTree *DT, DefiningValueMapTy &DVCache,
982 std::set<llvm::Value *> &newInsertedDefs) {
983 for (Value *ptr : live) {
984 Value *base = findBasePointer(ptr, DVCache, newInsertedDefs);
985 assert(base && "failed to find base pointer");
986 base_pairs[ptr] = base;
987 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
988 DT->dominates(cast<Instruction>(base)->getParent(),
989 cast<Instruction>(ptr)->getParent())) &&
990 "The base we found better dominate the derived pointer");
992 if (isNullConstant(base))
993 // If you see this trip and like to live really dangerously, the code
994 // should be correct, just with idioms the verifier can't handle. You
995 // can try disabling the verifier at your own substaintial risk.
996 llvm_unreachable("the relocation code needs adjustment to handle the"
997 "relocation of a null pointer constant without causing"
998 "false positives in the safepoint ir verifier.");
1002 /// Find the required based pointers (and adjust the live set) for the given
1004 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
1006 PartiallyConstructedSafepointRecord &result) {
1007 std::map<llvm::Value *, llvm::Value *> base_pairs;
1008 std::set<llvm::Value *> newInsertedDefs;
1009 findBasePointers(result.liveset, base_pairs, &DT, DVCache, newInsertedDefs);
1011 if (PrintBasePointers) {
1012 errs() << "Base Pairs (w/o Relocation):\n";
1013 for (auto Pair : base_pairs) {
1014 errs() << " derived %" << Pair.first->getName() << " base %"
1015 << Pair.second->getName() << "\n";
1019 result.base_pairs = base_pairs;
1020 result.newInsertedDefs = newInsertedDefs;
1023 /// Check for liveness of items in the insert defs and add them to the live
1024 /// and base pointer sets
1025 static void fixupLiveness(DominatorTree &DT, const CallSite &CS,
1026 const std::set<Value *> &allInsertedDefs,
1027 PartiallyConstructedSafepointRecord &result) {
1028 Instruction *inst = CS.getInstruction();
1030 std::set<llvm::Value *> liveset = result.liveset;
1031 std::map<llvm::Value *, llvm::Value *> base_pairs = result.base_pairs;
1033 auto is_live_gc_reference =
1034 [&](Value &V) { return isLiveGCReferenceAt(V, inst, DT, nullptr); };
1036 // For each new definition, check to see if a) the definition dominates the
1037 // instruction we're interested in, and b) one of the uses of that definition
1038 // is edge-reachable from the instruction we're interested in. This is the
1039 // same definition of liveness we used in the intial liveness analysis
1040 for (Value *newDef : allInsertedDefs) {
1041 if (liveset.count(newDef)) {
1042 // already live, no action needed
1046 // PERF: Use DT to check instruction domination might not be good for
1047 // compilation time, and we could change to optimal solution if this
1048 // turn to be a issue
1049 if (!DT.dominates(cast<Instruction>(newDef), inst)) {
1050 // can't possibly be live at inst
1054 if (is_live_gc_reference(*newDef)) {
1055 // Add the live new defs into liveset and base_pairs
1056 liveset.insert(newDef);
1057 base_pairs[newDef] = newDef;
1061 result.liveset = liveset;
1062 result.base_pairs = base_pairs;
1065 static void fixupLiveReferences(
1066 Function &F, DominatorTree &DT, Pass *P,
1067 const std::set<llvm::Value *> &allInsertedDefs,
1068 std::vector<CallSite> &toUpdate,
1069 std::vector<struct PartiallyConstructedSafepointRecord> &records) {
1070 for (size_t i = 0; i < records.size(); i++) {
1071 struct PartiallyConstructedSafepointRecord &info = records[i];
1072 CallSite &CS = toUpdate[i];
1073 fixupLiveness(DT, CS, allInsertedDefs, info);
1077 // Normalize basic block to make it ready to be target of invoke statepoint.
1078 // It means spliting it to have single predecessor. Return newly created BB
1079 // ready to be successor of invoke statepoint.
1080 static BasicBlock *normalizeBBForInvokeSafepoint(BasicBlock *BB,
1081 BasicBlock *InvokeParent,
1083 BasicBlock *ret = BB;
1085 if (!BB->getUniquePredecessor()) {
1086 ret = SplitBlockPredecessors(BB, InvokeParent, "");
1089 // Another requirement for such basic blocks is to not have any phi nodes.
1090 // Since we just ensured that new BB will have single predecessor,
1091 // all phi nodes in it will have one value. Here it would be naturall place
1093 // remove them all. But we can not do this because we are risking to remove
1094 // one of the values stored in liveset of another statepoint. We will do it
1095 // later after placing all safepoints.
1101 VerifySafepointBounds(const std::pair<Instruction *, Instruction *> &bounds) {
1102 assert(bounds.first->getParent() && bounds.second->getParent() &&
1103 "both must belong to basic blocks");
1104 if (bounds.first->getParent() == bounds.second->getParent()) {
1105 // This is a call safepoint
1106 // TODO: scan the range to find the statepoint
1107 // TODO: check that the following instruction is not a gc_relocate or
1110 // This is an invoke safepoint
1111 InvokeInst *invoke = dyn_cast<InvokeInst>(bounds.first);
1113 assert(invoke && "only continues over invokes!");
1114 assert(invoke->getNormalDest() == bounds.second->getParent() &&
1115 "safepoint should continue into normal exit block");
1119 static int find_index(const SmallVectorImpl<Value *> &livevec, Value *val) {
1120 auto itr = std::find(livevec.begin(), livevec.end(), val);
1121 assert(livevec.end() != itr);
1122 size_t index = std::distance(livevec.begin(), itr);
1123 assert(index < livevec.size());
1127 // Create new attribute set containing only attributes which can be transfered
1128 // from original call to the safepoint.
1129 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1132 for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1133 unsigned index = AS.getSlotIndex(Slot);
1135 if (index == AttributeSet::ReturnIndex ||
1136 index == AttributeSet::FunctionIndex) {
1138 for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1140 Attribute attr = *it;
1142 // Do not allow certain attributes - just skip them
1143 // Safepoint can not be read only or read none.
1144 if (attr.hasAttribute(Attribute::ReadNone) ||
1145 attr.hasAttribute(Attribute::ReadOnly))
1148 ret = ret.addAttributes(
1149 AS.getContext(), index,
1150 AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1154 // Just skip parameter attributes for now
1160 /// Helper function to place all gc relocates necessary for the given
1163 /// liveVariables - list of variables to be relocated.
1164 /// liveStart - index of the first live variable.
1165 /// basePtrs - base pointers.
1166 /// statepointToken - statepoint instruction to which relocates should be
1168 /// Builder - Llvm IR builder to be used to construct new calls.
1169 /// Returns array with newly created relocates.
1170 static std::vector<llvm::Instruction *>
1171 CreateGCRelocates(const SmallVectorImpl<llvm::Value *> &liveVariables,
1172 const int liveStart,
1173 const SmallVectorImpl<llvm::Value *> &basePtrs,
1174 Instruction *statepointToken, IRBuilder<> Builder) {
1176 std::vector<llvm::Instruction *> newDefs;
1178 Module *M = statepointToken->getParent()->getParent()->getParent();
1180 for (unsigned i = 0; i < liveVariables.size(); i++) {
1181 // We generate a (potentially) unique declaration for every pointer type
1182 // combination. This results is some blow up the function declarations in
1183 // the IR, but removes the need for argument bitcasts which shrinks the IR
1184 // greatly and makes it much more readable.
1185 std::vector<Type *> types; // one per 'any' type
1186 types.push_back(liveVariables[i]->getType()); // result type
1187 Value *gc_relocate_decl = Intrinsic::getDeclaration(
1188 M, Intrinsic::experimental_gc_relocate, types);
1190 // Generate the gc.relocate call and save the result
1192 ConstantInt::get(Type::getInt32Ty(M->getContext()),
1193 liveStart + find_index(liveVariables, basePtrs[i]));
1194 Value *liveIdx = ConstantInt::get(
1195 Type::getInt32Ty(M->getContext()),
1196 liveStart + find_index(liveVariables, liveVariables[i]));
1198 // only specify a debug name if we can give a useful one
1199 Value *reloc = Builder.CreateCall3(
1200 gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1201 liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1203 // Trick CodeGen into thinking there are lots of free registers at this
1205 cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1207 newDefs.push_back(cast<Instruction>(reloc));
1209 assert(newDefs.size() == liveVariables.size() &&
1210 "missing or extra redefinition at safepoint");
1216 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1217 const SmallVectorImpl<llvm::Value *> &basePtrs,
1218 const SmallVectorImpl<llvm::Value *> &liveVariables,
1220 PartiallyConstructedSafepointRecord &result) {
1221 assert(basePtrs.size() == liveVariables.size());
1222 assert(isStatepoint(CS) &&
1223 "This method expects to be rewriting a statepoint");
1225 BasicBlock *BB = CS.getInstruction()->getParent();
1227 Function *F = BB->getParent();
1228 assert(F && "must be set");
1229 Module *M = F->getParent();
1231 assert(M && "must be set");
1233 // We're not changing the function signature of the statepoint since the gc
1234 // arguments go into the var args section.
1235 Function *gc_statepoint_decl = CS.getCalledFunction();
1237 // Then go ahead and use the builder do actually do the inserts. We insert
1238 // immediately before the previous instruction under the assumption that all
1239 // arguments will be available here. We can't insert afterwards since we may
1240 // be replacing a terminator.
1241 Instruction *insertBefore = CS.getInstruction();
1242 IRBuilder<> Builder(insertBefore);
1243 // Copy all of the arguments from the original statepoint - this includes the
1244 // target, call args, and deopt args
1245 std::vector<llvm::Value *> args;
1246 args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1247 // TODO: Clear the 'needs rewrite' flag
1249 // add all the pointers to be relocated (gc arguments)
1250 // Capture the start of the live variable list for use in the gc_relocates
1251 const int live_start = args.size();
1252 args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1254 // Create the statepoint given all the arguments
1255 Instruction *token = nullptr;
1256 AttributeSet return_attributes;
1258 CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1260 Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1261 call->setTailCall(toReplace->isTailCall());
1262 call->setCallingConv(toReplace->getCallingConv());
1264 // Currently we will fail on parameter attributes and on certain
1265 // function attributes.
1266 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1267 // In case if we can handle this set of sttributes - set up function attrs
1268 // directly on statepoint and return attrs later for gc_result intrinsic.
1269 call->setAttributes(new_attrs.getFnAttributes());
1270 return_attributes = new_attrs.getRetAttributes();
1274 // Put the following gc_result and gc_relocate calls immediately after the
1275 // the old call (which we're about to delete)
1276 BasicBlock::iterator next(toReplace);
1277 assert(BB->end() != next && "not a terminator, must have next");
1279 Instruction *IP = &*(next);
1280 Builder.SetInsertPoint(IP);
1281 Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1283 } else if (CS.isInvoke()) {
1284 InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1286 // Insert the new invoke into the old block. We'll remove the old one in a
1287 // moment at which point this will become the new terminator for the
1289 InvokeInst *invoke = InvokeInst::Create(
1290 gc_statepoint_decl, toReplace->getNormalDest(),
1291 toReplace->getUnwindDest(), args, "", toReplace->getParent());
1292 invoke->setCallingConv(toReplace->getCallingConv());
1294 // Currently we will fail on parameter attributes and on certain
1295 // function attributes.
1296 AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1297 // In case if we can handle this set of sttributes - set up function attrs
1298 // directly on statepoint and return attrs later for gc_result intrinsic.
1299 invoke->setAttributes(new_attrs.getFnAttributes());
1300 return_attributes = new_attrs.getRetAttributes();
1304 // Generate gc relocates in exceptional path
1305 BasicBlock *unwindBlock = normalizeBBForInvokeSafepoint(
1306 toReplace->getUnwindDest(), invoke->getParent(), P);
1308 Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1309 Builder.SetInsertPoint(IP);
1310 Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1312 // Extract second element from landingpad return value. We will attach
1313 // exceptional gc relocates to it.
1314 const unsigned idx = 1;
1315 Instruction *exceptional_token =
1316 cast<Instruction>(Builder.CreateExtractValue(
1317 unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1318 result.exceptional_relocates_token = exceptional_token;
1320 // Just throw away return value. We will use the one we got for normal
1322 (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1323 exceptional_token, Builder);
1325 // Generate gc relocates and returns for normal block
1326 BasicBlock *normalDest = normalizeBBForInvokeSafepoint(
1327 toReplace->getNormalDest(), invoke->getParent(), P);
1329 IP = &*(normalDest->getFirstInsertionPt());
1330 Builder.SetInsertPoint(IP);
1332 // gc relocates will be generated later as if it were regular call
1335 llvm_unreachable("unexpect type of CallSite");
1339 // Take the name of the original value call if it had one.
1340 token->takeName(CS.getInstruction());
1342 // The GCResult is already inserted, we just need to find it
1343 Instruction *gc_result = nullptr;
1345 Instruction *toReplace = CS.getInstruction();
1346 assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1347 "only valid use before rewrite is gc.result");
1348 if (toReplace->hasOneUse()) {
1349 Instruction *GCResult = cast<Instruction>(*toReplace->user_begin());
1350 assert(isGCResult(GCResult));
1351 gc_result = GCResult;
1355 // Update the gc.result of the original statepoint (if any) to use the newly
1356 // inserted statepoint. This is safe to do here since the token can't be
1357 // considered a live reference.
1358 CS.getInstruction()->replaceAllUsesWith(token);
1360 // Second, create a gc.relocate for every live variable
1361 std::vector<llvm::Instruction *> newDefs =
1362 CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1364 // Need to pass through the last part of the safepoint block so that we
1365 // don't accidentally update uses in a following gc.relocate which is
1366 // still conceptually part of the same safepoint. Gah.
1367 Instruction *last = nullptr;
1368 if (!newDefs.empty()) {
1369 last = newDefs.back();
1370 } else if (gc_result) {
1375 assert(last && "can't be null");
1376 const auto bounds = std::make_pair(token, last);
1378 // Sanity check our results - this is slightly non-trivial due to invokes
1379 VerifySafepointBounds(bounds);
1381 result.safepoint = bounds;
1385 struct name_ordering {
1388 bool operator()(name_ordering const &a, name_ordering const &b) {
1389 return -1 == a.derived->getName().compare(b.derived->getName());
1393 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1394 SmallVectorImpl<Value *> &livevec) {
1395 assert(basevec.size() == livevec.size());
1397 std::vector<name_ordering> temp;
1398 for (size_t i = 0; i < basevec.size(); i++) {
1400 v.base = basevec[i];
1401 v.derived = livevec[i];
1404 std::sort(temp.begin(), temp.end(), name_ordering());
1405 for (size_t i = 0; i < basevec.size(); i++) {
1406 basevec[i] = temp[i].base;
1407 livevec[i] = temp[i].derived;
1411 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1412 // which make the relocations happening at this safepoint explicit.
1414 // WARNING: Does not do any fixup to adjust users of the original live
1415 // values. That's the callers responsibility.
1417 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1418 PartiallyConstructedSafepointRecord &result) {
1419 std::set<llvm::Value *> liveset = result.liveset;
1420 std::map<llvm::Value *, llvm::Value *> base_pairs = result.base_pairs;
1422 // Convert to vector for efficient cross referencing.
1423 SmallVector<Value *, 64> basevec, livevec;
1424 livevec.reserve(liveset.size());
1425 basevec.reserve(liveset.size());
1426 for (Value *L : liveset) {
1427 livevec.push_back(L);
1429 assert(base_pairs.find(L) != base_pairs.end());
1430 Value *base = base_pairs[L];
1431 basevec.push_back(base);
1433 assert(livevec.size() == basevec.size());
1435 // To make the output IR slightly more stable (for use in diffs), ensure a
1436 // fixed order of the values in the safepoint (by sorting the value name).
1437 // The order is otherwise meaningless.
1438 stablize_order(basevec, livevec);
1440 // Do the actual rewriting and delete the old statepoint
1441 makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1442 CS.getInstruction()->eraseFromParent();
1445 // Helper function for the relocationViaAlloca.
1446 // It receives iterator to the statepoint gc relocates and emits store to the
1448 // location (via allocaMap) for the each one of them.
1449 // Add visited values into the visitedLiveValues set we will later use them
1450 // for sanity check.
1452 insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1453 DenseMap<Value *, Value *> &allocaMap,
1454 DenseSet<Value *> &visitedLiveValues) {
1456 for (User *U : gcRelocs) {
1457 if (!isa<IntrinsicInst>(U))
1460 IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1462 // We only care about relocates
1463 if (relocatedValue->getIntrinsicID() !=
1464 Intrinsic::experimental_gc_relocate) {
1468 GCRelocateOperands relocateOperands(relocatedValue);
1469 Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1470 assert(allocaMap.count(originalValue));
1471 Value *alloca = allocaMap[originalValue];
1473 // Emit store into the related alloca
1474 StoreInst *store = new StoreInst(relocatedValue, alloca);
1475 store->insertAfter(relocatedValue);
1478 visitedLiveValues.insert(originalValue);
1483 /// do all the relocation update via allocas and mem2reg
1484 static void relocationViaAlloca(
1485 Function &F, DominatorTree &DT, const std::vector<Value *> &live,
1486 const std::vector<struct PartiallyConstructedSafepointRecord> &records) {
1488 int initialAllocaNum = 0;
1490 // record initial number of allocas
1491 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1493 if (isa<AllocaInst>(*itr))
1498 // TODO-PERF: change data structures, reserve
1499 DenseMap<Value *, Value *> allocaMap;
1500 SmallVector<AllocaInst *, 200> PromotableAllocas;
1501 PromotableAllocas.reserve(live.size());
1503 // emit alloca for each live gc pointer
1504 for (unsigned i = 0; i < live.size(); i++) {
1505 Value *liveValue = live[i];
1506 AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1507 F.getEntryBlock().getFirstNonPHI());
1508 allocaMap[liveValue] = alloca;
1509 PromotableAllocas.push_back(alloca);
1512 // The next two loops are part of the same conceptual operation. We need to
1513 // insert a store to the alloca after the original def and at each
1514 // redefinition. We need to insert a load before each use. These are split
1515 // into distinct loops for performance reasons.
1517 // update gc pointer after each statepoint
1518 // either store a relocated value or null (if no relocated value found for
1519 // this gc pointer and it is not a gc_result)
1520 // this must happen before we update the statepoint with load of alloca
1521 // otherwise we lose the link between statepoint and old def
1522 for (size_t i = 0; i < records.size(); i++) {
1523 const struct PartiallyConstructedSafepointRecord &info = records[i];
1524 Value *statepoint = info.safepoint.first;
1526 // This will be used for consistency check
1527 DenseSet<Value *> visitedLiveValues;
1529 // Insert stores for normal statepoint gc relocates
1530 insertRelocationStores(statepoint->users(), allocaMap, visitedLiveValues);
1532 // In case if it was invoke statepoint
1533 // we will insert stores for exceptional path gc relocates.
1534 if (isa<InvokeInst>(statepoint)) {
1535 insertRelocationStores(info.exceptional_relocates_token->users(),
1536 allocaMap, visitedLiveValues);
1540 // For consistency check store null's into allocas for values that are not
1542 // by this statepoint.
1543 for (auto Pair : allocaMap) {
1544 Value *def = Pair.first;
1545 Value *alloca = Pair.second;
1547 // This value was relocated
1548 if (visitedLiveValues.count(def)) {
1551 // Result should not be relocated
1552 if (def == info.result) {
1557 ConstantPointerNull::get(cast<PointerType>(def->getType()));
1558 StoreInst *store = new StoreInst(CPN, alloca);
1559 store->insertBefore(info.safepoint.second);
1563 // update use with load allocas and add store for gc_relocated
1564 for (auto Pair : allocaMap) {
1565 Value *def = Pair.first;
1566 Value *alloca = Pair.second;
1568 // we pre-record the uses of allocas so that we dont have to worry about
1570 // that change the user information.
1571 SmallVector<Instruction *, 20> uses;
1572 // PERF: trade a linear scan for repeated reallocation
1573 uses.reserve(std::distance(def->user_begin(), def->user_end()));
1574 for (User *U : def->users()) {
1575 if (!isa<ConstantExpr>(U)) {
1576 // If the def has a ConstantExpr use, then the def is either a
1577 // ConstantExpr use itself or null. In either case
1578 // (recursively in the first, directly in the second), the oop
1579 // it is ultimately dependent on is null and this particular
1580 // use does not need to be fixed up.
1581 uses.push_back(cast<Instruction>(U));
1585 std::sort(uses.begin(), uses.end());
1586 auto last = std::unique(uses.begin(), uses.end());
1587 uses.erase(last, uses.end());
1589 for (Instruction *use : uses) {
1590 if (isa<PHINode>(use)) {
1591 PHINode *phi = cast<PHINode>(use);
1592 for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1593 if (def == phi->getIncomingValue(i)) {
1594 LoadInst *load = new LoadInst(
1595 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1596 phi->setIncomingValue(i, load);
1600 LoadInst *load = new LoadInst(alloca, "", use);
1601 use->replaceUsesOfWith(def, load);
1605 // emit store for the initial gc value
1606 // store must be inserted after load, otherwise store will be in alloca's
1607 // use list and an extra load will be inserted before it
1608 StoreInst *store = new StoreInst(def, alloca);
1609 if (isa<Instruction>(def)) {
1610 store->insertAfter(cast<Instruction>(def));
1612 assert((isa<Argument>(def) || isa<GlobalVariable>(def) ||
1613 (isa<Constant>(def) && cast<Constant>(def)->isNullValue())) &&
1614 "Must be argument or global");
1615 store->insertAfter(cast<Instruction>(alloca));
1619 assert(PromotableAllocas.size() == live.size() &&
1620 "we must have the same allocas with lives");
1621 if (!PromotableAllocas.empty()) {
1622 // apply mem2reg to promote alloca to SSA
1623 PromoteMemToReg(PromotableAllocas, DT);
1627 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1629 if (isa<AllocaInst>(*itr))
1632 assert(initialAllocaNum == 0 && "We must not introduce any extra allocas");
1636 /// Implement a unique function which doesn't require we sort the input
1637 /// vector. Doing so has the effect of changing the output of a couple of
1638 /// tests in ways which make them less useful in testing fused safepoints.
1639 template <typename T> static void unique_unsorted(std::vector<T> &vec) {
1642 vec.reserve(vec.size());
1643 std::swap(tmp, vec);
1644 for (auto V : tmp) {
1645 if (seen.insert(V).second) {
1651 static Function *getUseHolder(Module &M) {
1652 FunctionType *ftype =
1653 FunctionType::get(Type::getVoidTy(M.getContext()), true);
1654 Function *Func = cast<Function>(M.getOrInsertFunction("__tmp_use", ftype));
1658 /// Insert holders so that each Value is obviously live through the entire
1659 /// liftetime of the call.
1660 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1661 std::vector<CallInst *> &holders) {
1662 Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1663 Function *Func = getUseHolder(*M);
1665 // For call safepoints insert dummy calls right after safepoint
1666 BasicBlock::iterator next(CS.getInstruction());
1668 CallInst *base_holder = CallInst::Create(Func, Values, "", next);
1669 holders.push_back(base_holder);
1670 } else if (CS.isInvoke()) {
1671 // For invoke safepooints insert dummy calls both in normal and
1672 // exceptional destination blocks
1673 InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1674 CallInst *normal_holder = CallInst::Create(
1675 Func, Values, "", invoke->getNormalDest()->getFirstInsertionPt());
1676 CallInst *unwind_holder = CallInst::Create(
1677 Func, Values, "", invoke->getUnwindDest()->getFirstInsertionPt());
1678 holders.push_back(normal_holder);
1679 holders.push_back(unwind_holder);
1681 assert(false && "Unsupported");
1685 static void findLiveReferences(
1686 Function &F, DominatorTree &DT, Pass *P, std::vector<CallSite> &toUpdate,
1687 std::vector<struct PartiallyConstructedSafepointRecord> &records) {
1688 for (size_t i = 0; i < records.size(); i++) {
1689 struct PartiallyConstructedSafepointRecord &info = records[i];
1690 CallSite &CS = toUpdate[i];
1691 analyzeParsePointLiveness(DT, CS, info);
1695 static void addBasesAsLiveValues(std::set<Value *> &liveset,
1696 std::map<Value *, Value *> &base_pairs) {
1697 // Identify any base pointers which are used in this safepoint, but not
1698 // themselves relocated. We need to relocate them so that later inserted
1699 // safepoints can get the properly relocated base register.
1700 DenseSet<Value *> missing;
1701 for (Value *L : liveset) {
1702 assert(base_pairs.find(L) != base_pairs.end());
1703 Value *base = base_pairs[L];
1705 if (liveset.find(base) == liveset.end()) {
1706 assert(base_pairs.find(base) == base_pairs.end());
1707 // uniqued by set insert
1708 missing.insert(base);
1712 // Note that we want these at the end of the list, otherwise
1713 // register placement gets screwed up once we lower to STATEPOINT
1714 // instructions. This is an utter hack, but there doesn't seem to be a
1716 for (Value *base : missing) {
1718 liveset.insert(base);
1719 base_pairs[base] = base;
1721 assert(liveset.size() == base_pairs.size());
1724 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
1725 std::vector<CallSite> &toUpdate) {
1727 // sanity check the input
1728 std::set<CallSite> uniqued;
1729 uniqued.insert(toUpdate.begin(), toUpdate.end());
1730 assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1732 for (size_t i = 0; i < toUpdate.size(); i++) {
1733 CallSite &CS = toUpdate[i];
1734 assert(CS.getInstruction()->getParent()->getParent() == &F);
1735 assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1739 // A list of dummy calls added to the IR to keep various values obviously
1740 // live in the IR. We'll remove all of these when done.
1741 std::vector<CallInst *> holders;
1743 // Insert a dummy call with all of the arguments to the vm_state we'll need
1744 // for the actual safepoint insertion. This ensures reference arguments in
1745 // the deopt argument list are considered live through the safepoint (and
1746 // thus makes sure they get relocated.)
1747 for (size_t i = 0; i < toUpdate.size(); i++) {
1748 CallSite &CS = toUpdate[i];
1749 Statepoint StatepointCS(CS);
1751 SmallVector<Value *, 64> DeoptValues;
1752 for (Use &U : StatepointCS.vm_state_args()) {
1753 Value *Arg = cast<Value>(&U);
1754 if (isGCPointerType(Arg->getType()))
1755 DeoptValues.push_back(Arg);
1757 insertUseHolderAfter(CS, DeoptValues, holders);
1760 std::vector<struct PartiallyConstructedSafepointRecord> records;
1761 records.reserve(toUpdate.size());
1762 for (size_t i = 0; i < toUpdate.size(); i++) {
1763 struct PartiallyConstructedSafepointRecord info;
1764 records.push_back(info);
1766 assert(records.size() == toUpdate.size());
1768 // A) Identify all gc pointers which are staticly live at the given call
1770 findLiveReferences(F, DT, P, toUpdate, records);
1772 // B) Find the base pointers for each live pointer
1773 /* scope for caching */ {
1774 // Cache the 'defining value' relation used in the computation and
1775 // insertion of base phis and selects. This ensures that we don't insert
1776 // large numbers of duplicate base_phis.
1777 DefiningValueMapTy DVCache;
1779 for (size_t i = 0; i < records.size(); i++) {
1780 struct PartiallyConstructedSafepointRecord &info = records[i];
1781 CallSite &CS = toUpdate[i];
1782 findBasePointers(DT, DVCache, CS, info);
1784 } // end of cache scope
1786 // The base phi insertion logic (for any safepoint) may have inserted new
1787 // instructions which are now live at some safepoint. The simplest such
1790 // phi a <-- will be a new base_phi here
1791 // safepoint 1 <-- that needs to be live here
1795 std::set<llvm::Value *> allInsertedDefs;
1796 for (size_t i = 0; i < records.size(); i++) {
1797 struct PartiallyConstructedSafepointRecord &info = records[i];
1798 allInsertedDefs.insert(info.newInsertedDefs.begin(),
1799 info.newInsertedDefs.end());
1802 // We insert some dummy calls after each safepoint to definitely hold live
1803 // the base pointers which were identified for that safepoint. We'll then
1804 // ask liveness for _every_ base inserted to see what is now live. Then we
1805 // remove the dummy calls.
1806 holders.reserve(holders.size() + records.size());
1807 for (size_t i = 0; i < records.size(); i++) {
1808 struct PartiallyConstructedSafepointRecord &info = records[i];
1809 CallSite &CS = toUpdate[i];
1811 SmallVector<Value *, 128> Bases;
1812 for (auto Pair : info.base_pairs) {
1813 Bases.push_back(Pair.second);
1815 insertUseHolderAfter(CS, Bases, holders);
1818 // Add the bases explicitly to the live vector set. This may result in a few
1819 // extra relocations, but the base has to be available whenever a pointer
1820 // derived from it is used. Thus, we need it to be part of the statepoint's
1821 // gc arguments list. TODO: Introduce an explicit notion (in the following
1822 // code) of the GC argument list as seperate from the live Values at a
1823 // given statepoint.
1824 for (size_t i = 0; i < records.size(); i++) {
1825 struct PartiallyConstructedSafepointRecord &info = records[i];
1826 addBasesAsLiveValues(info.liveset, info.base_pairs);
1829 // If we inserted any new values, we need to adjust our notion of what is
1830 // live at a particular safepoint.
1831 if (!allInsertedDefs.empty()) {
1832 fixupLiveReferences(F, DT, P, allInsertedDefs, toUpdate, records);
1834 if (PrintBasePointers) {
1835 for (size_t i = 0; i < records.size(); i++) {
1836 struct PartiallyConstructedSafepointRecord &info = records[i];
1837 errs() << "Base Pairs: (w/Relocation)\n";
1838 for (auto Pair : info.base_pairs) {
1839 errs() << " derived %" << Pair.first->getName() << " base %"
1840 << Pair.second->getName() << "\n";
1844 for (size_t i = 0; i < holders.size(); i++) {
1845 holders[i]->eraseFromParent();
1846 holders[i] = nullptr;
1850 // Now run through and replace the existing statepoints with new ones with
1851 // the live variables listed. We do not yet update uses of the values being
1852 // relocated. We have references to live variables that need to
1853 // survive to the last iteration of this loop. (By construction, the
1854 // previous statepoint can not be a live variable, thus we can and remove
1855 // the old statepoint calls as we go.)
1856 for (size_t i = 0; i < records.size(); i++) {
1857 struct PartiallyConstructedSafepointRecord &info = records[i];
1858 CallSite &CS = toUpdate[i];
1859 makeStatepointExplicit(DT, CS, P, info);
1861 toUpdate.clear(); // prevent accident use of invalid CallSites
1863 // In case if we inserted relocates in a different basic block than the
1864 // original safepoint (this can happen for invokes). We need to be sure that
1865 // original values were not used in any of the phi nodes at the
1866 // beginning of basic block containing them. Because we know that all such
1867 // blocks will have single predecessor we can safely assume that all phi
1868 // nodes have single entry (because of normalizeBBForInvokeSafepoint).
1869 // Just remove them all here.
1870 for (size_t i = 0; i < records.size(); i++) {
1871 Instruction *I = records[i].safepoint.first;
1873 if (InvokeInst *invoke = dyn_cast<InvokeInst>(I)) {
1874 FoldSingleEntryPHINodes(invoke->getNormalDest());
1875 assert(!isa<PHINode>(invoke->getNormalDest()->begin()));
1877 FoldSingleEntryPHINodes(invoke->getUnwindDest());
1878 assert(!isa<PHINode>(invoke->getUnwindDest()->begin()));
1882 // Do all the fixups of the original live variables to their relocated selves
1883 std::vector<Value *> live;
1884 for (size_t i = 0; i < records.size(); i++) {
1885 struct PartiallyConstructedSafepointRecord &info = records[i];
1886 // We can't simply save the live set from the original insertion. One of
1887 // the live values might be the result of a call which needs a safepoint.
1888 // That Value* no longer exists and we need to use the new gc_result.
1889 // Thankfully, the liveset is embedded in the statepoint (and updated), so
1890 // we just grab that.
1891 Statepoint statepoint(info.safepoint.first);
1892 live.insert(live.end(), statepoint.gc_args_begin(),
1893 statepoint.gc_args_end());
1895 unique_unsorted(live);
1899 for (auto ptr : live) {
1900 assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1904 relocationViaAlloca(F, DT, live, records);
1905 return !records.empty();
1908 /// Returns true if this function should be rewritten by this pass. The main
1909 /// point of this function is as an extension point for custom logic.
1910 static bool shouldRewriteStatepointsIn(Function &F) {
1911 // TODO: This should check the GCStrategy
1912 const std::string StatepointExampleName("statepoint-example");
1913 return StatepointExampleName == F.getGC();
1916 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1917 // Nothing to do for declarations.
1918 if (F.isDeclaration() || F.empty())
1921 // Policy choice says not to rewrite - the most common reason is that we're
1922 // compiling code without a GCStrategy.
1923 if (!shouldRewriteStatepointsIn(F))
1926 // Gather all the statepoints which need rewritten.
1927 std::vector<CallSite> ParsePointNeeded;
1928 for (inst_iterator itr = inst_begin(F), end = inst_end(F); itr != end;
1930 // TODO: only the ones with the flag set!
1931 if (isStatepoint(*itr))
1932 ParsePointNeeded.push_back(CallSite(&*itr));
1935 // Return early if no work to do.
1936 if (ParsePointNeeded.empty())
1939 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1940 return insertParsePoints(F, DT, this, ParsePointNeeded);