[RewriteStatepointsForGC] Exclude constant values from being considered live at a...
[oota-llvm.git] / lib / Transforms / Scalar / RewriteStatepointsForGC.cpp
1 //===- RewriteStatepointsForGC.cpp - Make GC relocations explicit ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Rewrite an existing set of gc.statepoints such that they make potential
11 // relocations performed by the garbage collector explicit in the IR.
12 //
13 //===----------------------------------------------------------------------===//
14
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/ADT/SetVector.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/InstIterator.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Statepoint.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/IR/Verifier.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Cloning.h"
39 #include "llvm/Transforms/Utils/Local.h"
40 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
41
42 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
43
44 using namespace llvm;
45
46 // Print tracing output
47 static cl::opt<bool> TraceLSP("trace-rewrite-statepoints", cl::Hidden,
48                               cl::init(false));
49
50 // Print the liveset found at the insert location
51 static cl::opt<bool> PrintLiveSet("spp-print-liveset", cl::Hidden,
52                                   cl::init(false));
53 static cl::opt<bool> PrintLiveSetSize("spp-print-liveset-size", cl::Hidden,
54                                       cl::init(false));
55 // Print out the base pointers for debugging
56 static cl::opt<bool> PrintBasePointers("spp-print-base-pointers", cl::Hidden,
57                                        cl::init(false));
58
59 #ifdef XDEBUG
60 static bool ClobberNonLive = true;
61 #else
62 static bool ClobberNonLive = false;
63 #endif
64 static cl::opt<bool, true> ClobberNonLiveOverride("rs4gc-clobber-non-live",
65                                                   cl::location(ClobberNonLive),
66                                                   cl::Hidden);
67
68 namespace {
69 struct RewriteStatepointsForGC : public FunctionPass {
70   static char ID; // Pass identification, replacement for typeid
71
72   RewriteStatepointsForGC() : FunctionPass(ID) {
73     initializeRewriteStatepointsForGCPass(*PassRegistry::getPassRegistry());
74   }
75   bool runOnFunction(Function &F) override;
76
77   void getAnalysisUsage(AnalysisUsage &AU) const override {
78     // We add and rewrite a bunch of instructions, but don't really do much
79     // else.  We could in theory preserve a lot more analyses here.
80     AU.addRequired<DominatorTreeWrapperPass>();
81   }
82 };
83 } // namespace
84
85 char RewriteStatepointsForGC::ID = 0;
86
87 FunctionPass *llvm::createRewriteStatepointsForGCPass() {
88   return new RewriteStatepointsForGC();
89 }
90
91 INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
92                       "Make relocations explicit at statepoints", false, false)
93 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
94 INITIALIZE_PASS_END(RewriteStatepointsForGC, "rewrite-statepoints-for-gc",
95                     "Make relocations explicit at statepoints", false, false)
96
97 namespace {
98 struct GCPtrLivenessData {
99   /// Values defined in this block.
100   DenseMap<BasicBlock *, DenseSet<Value *>> KillSet;
101   /// Values used in this block (and thus live); does not included values
102   /// killed within this block.
103   DenseMap<BasicBlock *, DenseSet<Value *>> LiveSet;
104
105   /// Values live into this basic block (i.e. used by any
106   /// instruction in this basic block or ones reachable from here)
107   DenseMap<BasicBlock *, DenseSet<Value *>> LiveIn;
108
109   /// Values live out of this basic block (i.e. live into
110   /// any successor block)
111   DenseMap<BasicBlock *, DenseSet<Value *>> LiveOut;
112 };
113
114 // The type of the internal cache used inside the findBasePointers family
115 // of functions.  From the callers perspective, this is an opaque type and
116 // should not be inspected.
117 //
118 // In the actual implementation this caches two relations:
119 // - The base relation itself (i.e. this pointer is based on that one)
120 // - The base defining value relation (i.e. before base_phi insertion)
121 // Generally, after the execution of a full findBasePointer call, only the
122 // base relation will remain.  Internally, we add a mixture of the two
123 // types, then update all the second type to the first type
124 typedef DenseMap<Value *, Value *> DefiningValueMapTy;
125 typedef DenseSet<llvm::Value *> StatepointLiveSetTy;
126
127 struct PartiallyConstructedSafepointRecord {
128   /// The set of values known to be live accross this safepoint
129   StatepointLiveSetTy liveset;
130
131   /// Mapping from live pointers to a base-defining-value
132   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
133
134   /// The *new* gc.statepoint instruction itself.  This produces the token
135   /// that normal path gc.relocates and the gc.result are tied to.
136   Instruction *StatepointToken;
137
138   /// Instruction to which exceptional gc relocates are attached
139   /// Makes it easier to iterate through them during relocationViaAlloca.
140   Instruction *UnwindToken;
141 };
142 }
143
144 /// Compute the live-in set for every basic block in the function
145 static void computeLiveInValues(DominatorTree &DT, Function &F,
146                                 GCPtrLivenessData &Data);
147
148 /// Given results from the dataflow liveness computation, find the set of live
149 /// Values at a particular instruction.
150 static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data,
151                               StatepointLiveSetTy &out);
152
153 // TODO: Once we can get to the GCStrategy, this becomes
154 // Optional<bool> isGCManagedPointer(const Value *V) const override {
155
156 static bool isGCPointerType(const Type *T) {
157   if (const PointerType *PT = dyn_cast<PointerType>(T))
158     // For the sake of this example GC, we arbitrarily pick addrspace(1) as our
159     // GC managed heap.  We know that a pointer into this heap needs to be
160     // updated and that no other pointer does.
161     return (1 == PT->getAddressSpace());
162   return false;
163 }
164
165 // Return true if this type is one which a) is a gc pointer or contains a GC
166 // pointer and b) is of a type this code expects to encounter as a live value.
167 // (The insertion code will assert that a type which matches (a) and not (b)
168 // is not encountered.)
169 static bool isHandledGCPointerType(Type *T) {
170   // We fully support gc pointers
171   if (isGCPointerType(T))
172     return true;
173   // We partially support vectors of gc pointers. The code will assert if it
174   // can't handle something.
175   if (auto VT = dyn_cast<VectorType>(T))
176     if (isGCPointerType(VT->getElementType()))
177       return true;
178   return false;
179 }
180
181 #ifndef NDEBUG
182 /// Returns true if this type contains a gc pointer whether we know how to
183 /// handle that type or not.
184 static bool containsGCPtrType(Type *Ty) {
185   if (isGCPointerType(Ty))
186     return true;
187   if (VectorType *VT = dyn_cast<VectorType>(Ty))
188     return isGCPointerType(VT->getScalarType());
189   if (ArrayType *AT = dyn_cast<ArrayType>(Ty))
190     return containsGCPtrType(AT->getElementType());
191   if (StructType *ST = dyn_cast<StructType>(Ty))
192     return std::any_of(
193         ST->subtypes().begin(), ST->subtypes().end(),
194         [](Type *SubType) { return containsGCPtrType(SubType); });
195   return false;
196 }
197
198 // Returns true if this is a type which a) is a gc pointer or contains a GC
199 // pointer and b) is of a type which the code doesn't expect (i.e. first class
200 // aggregates).  Used to trip assertions.
201 static bool isUnhandledGCPointerType(Type *Ty) {
202   return containsGCPtrType(Ty) && !isHandledGCPointerType(Ty);
203 }
204 #endif
205
206 static bool order_by_name(llvm::Value *a, llvm::Value *b) {
207   if (a->hasName() && b->hasName()) {
208     return -1 == a->getName().compare(b->getName());
209   } else if (a->hasName() && !b->hasName()) {
210     return true;
211   } else if (!a->hasName() && b->hasName()) {
212     return false;
213   } else {
214     // Better than nothing, but not stable
215     return a < b;
216   }
217 }
218
219 // Conservatively identifies any definitions which might be live at the
220 // given instruction. The  analysis is performed immediately before the
221 // given instruction. Values defined by that instruction are not considered
222 // live.  Values used by that instruction are considered live.
223 static void analyzeParsePointLiveness(
224     DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData,
225     const CallSite &CS, PartiallyConstructedSafepointRecord &result) {
226   Instruction *inst = CS.getInstruction();
227
228   StatepointLiveSetTy liveset;
229   findLiveSetAtInst(inst, OriginalLivenessData, liveset);
230
231   if (PrintLiveSet) {
232     // Note: This output is used by several of the test cases
233     // The order of elemtns in a set is not stable, put them in a vec and sort
234     // by name
235     SmallVector<Value *, 64> temp;
236     temp.insert(temp.end(), liveset.begin(), liveset.end());
237     std::sort(temp.begin(), temp.end(), order_by_name);
238     errs() << "Live Variables:\n";
239     for (Value *V : temp) {
240       errs() << " " << V->getName(); // no newline
241       V->dump();
242     }
243   }
244   if (PrintLiveSetSize) {
245     errs() << "Safepoint For: " << CS.getCalledValue()->getName() << "\n";
246     errs() << "Number live values: " << liveset.size() << "\n";
247   }
248   result.liveset = liveset;
249 }
250
251 /// If we can trivially determine that this vector contains only base pointers,
252 /// return the base instruction.
253 static Value *findBaseOfVector(Value *I) {
254   assert(I->getType()->isVectorTy() &&
255          cast<VectorType>(I->getType())->getElementType()->isPointerTy() &&
256          "Illegal to ask for the base pointer of a non-pointer type");
257
258   // Each case parallels findBaseDefiningValue below, see that code for
259   // detailed motivation.
260
261   if (isa<Argument>(I))
262     // An incoming argument to the function is a base pointer
263     return I;
264
265   // We shouldn't see the address of a global as a vector value?
266   assert(!isa<GlobalVariable>(I) &&
267          "unexpected global variable found in base of vector");
268
269   // inlining could possibly introduce phi node that contains
270   // undef if callee has multiple returns
271   if (isa<UndefValue>(I))
272     // utterly meaningless, but useful for dealing with partially optimized
273     // code.
274     return I;
275
276   // Due to inheritance, this must be _after_ the global variable and undef
277   // checks
278   if (Constant *Con = dyn_cast<Constant>(I)) {
279     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
280            "order of checks wrong!");
281     assert(Con->isNullValue() && "null is the only case which makes sense");
282     return Con;
283   }
284
285   if (isa<LoadInst>(I))
286     return I;
287
288   // Note: This code is currently rather incomplete.  We are essentially only
289   // handling cases where the vector element is trivially a base pointer.  We
290   // need to update the entire base pointer construction algorithm to know how
291   // to track vector elements and potentially scalarize, but the case which
292   // would motivate the work hasn't shown up in real workloads yet.
293   llvm_unreachable("no base found for vector element");
294 }
295
296 /// Helper function for findBasePointer - Will return a value which either a)
297 /// defines the base pointer for the input or b) blocks the simple search
298 /// (i.e. a PHI or Select of two derived pointers)
299 static Value *findBaseDefiningValue(Value *I) {
300   assert(I->getType()->isPointerTy() &&
301          "Illegal to ask for the base pointer of a non-pointer type");
302
303   // This case is a bit of a hack - it only handles extracts from vectors which
304   // trivially contain only base pointers.  See note inside the function for
305   // how to improve this.
306   if (auto *EEI = dyn_cast<ExtractElementInst>(I)) {
307     Value *VectorOperand = EEI->getVectorOperand();
308     Value *VectorBase = findBaseOfVector(VectorOperand);
309     (void)VectorBase;
310     assert(VectorBase && "extract element not known to be a trivial base");
311     return EEI;
312   }
313
314   if (isa<Argument>(I))
315     // An incoming argument to the function is a base pointer
316     // We should have never reached here if this argument isn't an gc value
317     return I;
318
319   if (isa<GlobalVariable>(I))
320     // base case
321     return I;
322
323   // inlining could possibly introduce phi node that contains
324   // undef if callee has multiple returns
325   if (isa<UndefValue>(I))
326     // utterly meaningless, but useful for dealing with
327     // partially optimized code.
328     return I;
329
330   // Due to inheritance, this must be _after_ the global variable and undef
331   // checks
332   if (Constant *Con = dyn_cast<Constant>(I)) {
333     assert(!isa<GlobalVariable>(I) && !isa<UndefValue>(I) &&
334            "order of checks wrong!");
335     // Note: Finding a constant base for something marked for relocation
336     // doesn't really make sense.  The most likely case is either a) some
337     // screwed up the address space usage or b) your validating against
338     // compiled C++ code w/o the proper separation.  The only real exception
339     // is a null pointer.  You could have generic code written to index of
340     // off a potentially null value and have proven it null.  We also use
341     // null pointers in dead paths of relocation phis (which we might later
342     // want to find a base pointer for).
343     assert(isa<ConstantPointerNull>(Con) &&
344            "null is the only case which makes sense");
345     return Con;
346   }
347
348   if (CastInst *CI = dyn_cast<CastInst>(I)) {
349     Value *Def = CI->stripPointerCasts();
350     // If we find a cast instruction here, it means we've found a cast which is
351     // not simply a pointer cast (i.e. an inttoptr).  We don't know how to
352     // handle int->ptr conversion.
353     assert(!isa<CastInst>(Def) && "shouldn't find another cast here");
354     return findBaseDefiningValue(Def);
355   }
356
357   if (isa<LoadInst>(I))
358     return I; // The value loaded is an gc base itself
359
360   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I))
361     // The base of this GEP is the base
362     return findBaseDefiningValue(GEP->getPointerOperand());
363
364   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
365     switch (II->getIntrinsicID()) {
366     case Intrinsic::experimental_gc_result_ptr:
367     default:
368       // fall through to general call handling
369       break;
370     case Intrinsic::experimental_gc_statepoint:
371     case Intrinsic::experimental_gc_result_float:
372     case Intrinsic::experimental_gc_result_int:
373       llvm_unreachable("these don't produce pointers");
374     case Intrinsic::experimental_gc_relocate: {
375       // Rerunning safepoint insertion after safepoints are already
376       // inserted is not supported.  It could probably be made to work,
377       // but why are you doing this?  There's no good reason.
378       llvm_unreachable("repeat safepoint insertion is not supported");
379     }
380     case Intrinsic::gcroot:
381       // Currently, this mechanism hasn't been extended to work with gcroot.
382       // There's no reason it couldn't be, but I haven't thought about the
383       // implications much.
384       llvm_unreachable(
385           "interaction with the gcroot mechanism is not supported");
386     }
387   }
388   // We assume that functions in the source language only return base
389   // pointers.  This should probably be generalized via attributes to support
390   // both source language and internal functions.
391   if (isa<CallInst>(I) || isa<InvokeInst>(I))
392     return I;
393
394   // I have absolutely no idea how to implement this part yet.  It's not
395   // neccessarily hard, I just haven't really looked at it yet.
396   assert(!isa<LandingPadInst>(I) && "Landing Pad is unimplemented");
397
398   if (isa<AtomicCmpXchgInst>(I))
399     // A CAS is effectively a atomic store and load combined under a
400     // predicate.  From the perspective of base pointers, we just treat it
401     // like a load.
402     return I;
403
404   assert(!isa<AtomicRMWInst>(I) && "Xchg handled above, all others are "
405                                    "binary ops which don't apply to pointers");
406
407   // The aggregate ops.  Aggregates can either be in the heap or on the
408   // stack, but in either case, this is simply a field load.  As a result,
409   // this is a defining definition of the base just like a load is.
410   if (isa<ExtractValueInst>(I))
411     return I;
412
413   // We should never see an insert vector since that would require we be
414   // tracing back a struct value not a pointer value.
415   assert(!isa<InsertValueInst>(I) &&
416          "Base pointer for a struct is meaningless");
417
418   // The last two cases here don't return a base pointer.  Instead, they
419   // return a value which dynamically selects from amoung several base
420   // derived pointers (each with it's own base potentially).  It's the job of
421   // the caller to resolve these.
422   assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
423          "missing instruction case in findBaseDefiningValing");
424   return I;
425 }
426
427 /// Returns the base defining value for this value.
428 static Value *findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache) {
429   Value *&Cached = Cache[I];
430   if (!Cached) {
431     Cached = findBaseDefiningValue(I);
432   }
433   assert(Cache[I] != nullptr);
434
435   if (TraceLSP) {
436     dbgs() << "fBDV-cached: " << I->getName() << " -> " << Cached->getName()
437            << "\n";
438   }
439   return Cached;
440 }
441
442 /// Return a base pointer for this value if known.  Otherwise, return it's
443 /// base defining value.
444 static Value *findBaseOrBDV(Value *I, DefiningValueMapTy &Cache) {
445   Value *Def = findBaseDefiningValueCached(I, Cache);
446   auto Found = Cache.find(Def);
447   if (Found != Cache.end()) {
448     // Either a base-of relation, or a self reference.  Caller must check.
449     return Found->second;
450   }
451   // Only a BDV available
452   return Def;
453 }
454
455 /// Given the result of a call to findBaseDefiningValue, or findBaseOrBDV,
456 /// is it known to be a base pointer?  Or do we need to continue searching.
457 static bool isKnownBaseResult(Value *V) {
458   if (!isa<PHINode>(V) && !isa<SelectInst>(V)) {
459     // no recursion possible
460     return true;
461   }
462   if (isa<Instruction>(V) &&
463       cast<Instruction>(V)->getMetadata("is_base_value")) {
464     // This is a previously inserted base phi or select.  We know
465     // that this is a base value.
466     return true;
467   }
468
469   // We need to keep searching
470   return false;
471 }
472
473 // TODO: find a better name for this
474 namespace {
475 class PhiState {
476 public:
477   enum Status { Unknown, Base, Conflict };
478
479   PhiState(Status s, Value *b = nullptr) : status(s), base(b) {
480     assert(status != Base || b);
481   }
482   PhiState(Value *b) : status(Base), base(b) {}
483   PhiState() : status(Unknown), base(nullptr) {}
484
485   Status getStatus() const { return status; }
486   Value *getBase() const { return base; }
487
488   bool isBase() const { return getStatus() == Base; }
489   bool isUnknown() const { return getStatus() == Unknown; }
490   bool isConflict() const { return getStatus() == Conflict; }
491
492   bool operator==(const PhiState &other) const {
493     return base == other.base && status == other.status;
494   }
495
496   bool operator!=(const PhiState &other) const { return !(*this == other); }
497
498   void dump() {
499     errs() << status << " (" << base << " - "
500            << (base ? base->getName() : "nullptr") << "): ";
501   }
502
503 private:
504   Status status;
505   Value *base; // non null only if status == base
506 };
507
508 typedef DenseMap<Value *, PhiState> ConflictStateMapTy;
509 // Values of type PhiState form a lattice, and this is a helper
510 // class that implementes the meet operation.  The meat of the meet
511 // operation is implemented in MeetPhiStates::pureMeet
512 class MeetPhiStates {
513 public:
514   // phiStates is a mapping from PHINodes and SelectInst's to PhiStates.
515   explicit MeetPhiStates(const ConflictStateMapTy &phiStates)
516       : phiStates(phiStates) {}
517
518   // Destructively meet the current result with the base V.  V can
519   // either be a merge instruction (SelectInst / PHINode), in which
520   // case its status is looked up in the phiStates map; or a regular
521   // SSA value, in which case it is assumed to be a base.
522   void meetWith(Value *V) {
523     PhiState otherState = getStateForBDV(V);
524     assert((MeetPhiStates::pureMeet(otherState, currentResult) ==
525             MeetPhiStates::pureMeet(currentResult, otherState)) &&
526            "math is wrong: meet does not commute!");
527     currentResult = MeetPhiStates::pureMeet(otherState, currentResult);
528   }
529
530   PhiState getResult() const { return currentResult; }
531
532 private:
533   const ConflictStateMapTy &phiStates;
534   PhiState currentResult;
535
536   /// Return a phi state for a base defining value.  We'll generate a new
537   /// base state for known bases and expect to find a cached state otherwise
538   PhiState getStateForBDV(Value *baseValue) {
539     if (isKnownBaseResult(baseValue)) {
540       return PhiState(baseValue);
541     } else {
542       return lookupFromMap(baseValue);
543     }
544   }
545
546   PhiState lookupFromMap(Value *V) {
547     auto I = phiStates.find(V);
548     assert(I != phiStates.end() && "lookup failed!");
549     return I->second;
550   }
551
552   static PhiState pureMeet(const PhiState &stateA, const PhiState &stateB) {
553     switch (stateA.getStatus()) {
554     case PhiState::Unknown:
555       return stateB;
556
557     case PhiState::Base:
558       assert(stateA.getBase() && "can't be null");
559       if (stateB.isUnknown())
560         return stateA;
561
562       if (stateB.isBase()) {
563         if (stateA.getBase() == stateB.getBase()) {
564           assert(stateA == stateB && "equality broken!");
565           return stateA;
566         }
567         return PhiState(PhiState::Conflict);
568       }
569       assert(stateB.isConflict() && "only three states!");
570       return PhiState(PhiState::Conflict);
571
572     case PhiState::Conflict:
573       return stateA;
574     }
575     llvm_unreachable("only three states!");
576   }
577 };
578 }
579 /// For a given value or instruction, figure out what base ptr it's derived
580 /// from.  For gc objects, this is simply itself.  On success, returns a value
581 /// which is the base pointer.  (This is reliable and can be used for
582 /// relocation.)  On failure, returns nullptr.
583 static Value *findBasePointer(Value *I, DefiningValueMapTy &cache) {
584   Value *def = findBaseOrBDV(I, cache);
585
586   if (isKnownBaseResult(def)) {
587     return def;
588   }
589
590   // Here's the rough algorithm:
591   // - For every SSA value, construct a mapping to either an actual base
592   //   pointer or a PHI which obscures the base pointer.
593   // - Construct a mapping from PHI to unknown TOP state.  Use an
594   //   optimistic algorithm to propagate base pointer information.  Lattice
595   //   looks like:
596   //   UNKNOWN
597   //   b1 b2 b3 b4
598   //   CONFLICT
599   //   When algorithm terminates, all PHIs will either have a single concrete
600   //   base or be in a conflict state.
601   // - For every conflict, insert a dummy PHI node without arguments.  Add
602   //   these to the base[Instruction] = BasePtr mapping.  For every
603   //   non-conflict, add the actual base.
604   //  - For every conflict, add arguments for the base[a] of each input
605   //   arguments.
606   //
607   // Note: A simpler form of this would be to add the conflict form of all
608   // PHIs without running the optimistic algorithm.  This would be
609   // analougous to pessimistic data flow and would likely lead to an
610   // overall worse solution.
611
612   ConflictStateMapTy states;
613   states[def] = PhiState();
614   // Recursively fill in all phis & selects reachable from the initial one
615   // for which we don't already know a definite base value for
616   // TODO: This should be rewritten with a worklist
617   bool done = false;
618   while (!done) {
619     done = true;
620     // Since we're adding elements to 'states' as we run, we can't keep
621     // iterators into the set.
622     SmallVector<Value *, 16> Keys;
623     Keys.reserve(states.size());
624     for (auto Pair : states) {
625       Value *V = Pair.first;
626       Keys.push_back(V);
627     }
628     for (Value *v : Keys) {
629       assert(!isKnownBaseResult(v) && "why did it get added?");
630       if (PHINode *phi = dyn_cast<PHINode>(v)) {
631         assert(phi->getNumIncomingValues() > 0 &&
632                "zero input phis are illegal");
633         for (Value *InVal : phi->incoming_values()) {
634           Value *local = findBaseOrBDV(InVal, cache);
635           if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
636             states[local] = PhiState();
637             done = false;
638           }
639         }
640       } else if (SelectInst *sel = dyn_cast<SelectInst>(v)) {
641         Value *local = findBaseOrBDV(sel->getTrueValue(), cache);
642         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
643           states[local] = PhiState();
644           done = false;
645         }
646         local = findBaseOrBDV(sel->getFalseValue(), cache);
647         if (!isKnownBaseResult(local) && states.find(local) == states.end()) {
648           states[local] = PhiState();
649           done = false;
650         }
651       }
652     }
653   }
654
655   if (TraceLSP) {
656     errs() << "States after initialization:\n";
657     for (auto Pair : states) {
658       Instruction *v = cast<Instruction>(Pair.first);
659       PhiState state = Pair.second;
660       state.dump();
661       v->dump();
662     }
663   }
664
665   // TODO: come back and revisit the state transitions around inputs which
666   // have reached conflict state.  The current version seems too conservative.
667
668   bool progress = true;
669   while (progress) {
670 #ifndef NDEBUG
671     size_t oldSize = states.size();
672 #endif
673     progress = false;
674     // We're only changing keys in this loop, thus safe to keep iterators
675     for (auto Pair : states) {
676       MeetPhiStates calculateMeet(states);
677       Value *v = Pair.first;
678       assert(!isKnownBaseResult(v) && "why did it get added?");
679       if (SelectInst *select = dyn_cast<SelectInst>(v)) {
680         calculateMeet.meetWith(findBaseOrBDV(select->getTrueValue(), cache));
681         calculateMeet.meetWith(findBaseOrBDV(select->getFalseValue(), cache));
682       } else
683         for (Value *Val : cast<PHINode>(v)->incoming_values())
684           calculateMeet.meetWith(findBaseOrBDV(Val, cache));
685
686       PhiState oldState = states[v];
687       PhiState newState = calculateMeet.getResult();
688       if (oldState != newState) {
689         progress = true;
690         states[v] = newState;
691       }
692     }
693
694     assert(oldSize <= states.size());
695     assert(oldSize == states.size() || progress);
696   }
697
698   if (TraceLSP) {
699     errs() << "States after meet iteration:\n";
700     for (auto Pair : states) {
701       Instruction *v = cast<Instruction>(Pair.first);
702       PhiState state = Pair.second;
703       state.dump();
704       v->dump();
705     }
706   }
707
708   // Insert Phis for all conflicts
709   // We want to keep naming deterministic in the loop that follows, so
710   // sort the keys before iteration.  This is useful in allowing us to
711   // write stable tests. Note that there is no invalidation issue here.
712   SmallVector<Value *, 16> Keys;
713   Keys.reserve(states.size());
714   for (auto Pair : states) {
715     Value *V = Pair.first;
716     Keys.push_back(V);
717   }
718   std::sort(Keys.begin(), Keys.end(), order_by_name);
719   // TODO: adjust naming patterns to avoid this order of iteration dependency
720   for (Value *V : Keys) {
721     Instruction *v = cast<Instruction>(V);
722     PhiState state = states[V];
723     assert(!isKnownBaseResult(v) && "why did it get added?");
724     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
725     if (!state.isConflict())
726       continue;
727
728     if (isa<PHINode>(v)) {
729       int num_preds =
730           std::distance(pred_begin(v->getParent()), pred_end(v->getParent()));
731       assert(num_preds > 0 && "how did we reach here");
732       PHINode *phi = PHINode::Create(v->getType(), num_preds, "base_phi", v);
733       // Add metadata marking this as a base value
734       auto *const_1 = ConstantInt::get(
735           Type::getInt32Ty(
736               v->getParent()->getParent()->getParent()->getContext()),
737           1);
738       auto MDConst = ConstantAsMetadata::get(const_1);
739       MDNode *md = MDNode::get(
740           v->getParent()->getParent()->getParent()->getContext(), MDConst);
741       phi->setMetadata("is_base_value", md);
742       states[v] = PhiState(PhiState::Conflict, phi);
743     } else {
744       SelectInst *sel = cast<SelectInst>(v);
745       // The undef will be replaced later
746       UndefValue *undef = UndefValue::get(sel->getType());
747       SelectInst *basesel = SelectInst::Create(sel->getCondition(), undef,
748                                                undef, "base_select", sel);
749       // Add metadata marking this as a base value
750       auto *const_1 = ConstantInt::get(
751           Type::getInt32Ty(
752               v->getParent()->getParent()->getParent()->getContext()),
753           1);
754       auto MDConst = ConstantAsMetadata::get(const_1);
755       MDNode *md = MDNode::get(
756           v->getParent()->getParent()->getParent()->getContext(), MDConst);
757       basesel->setMetadata("is_base_value", md);
758       states[v] = PhiState(PhiState::Conflict, basesel);
759     }
760   }
761
762   // Fixup all the inputs of the new PHIs
763   for (auto Pair : states) {
764     Instruction *v = cast<Instruction>(Pair.first);
765     PhiState state = Pair.second;
766
767     assert(!isKnownBaseResult(v) && "why did it get added?");
768     assert(!state.isUnknown() && "Optimistic algorithm didn't complete!");
769     if (!state.isConflict())
770       continue;
771
772     if (PHINode *basephi = dyn_cast<PHINode>(state.getBase())) {
773       PHINode *phi = cast<PHINode>(v);
774       unsigned NumPHIValues = phi->getNumIncomingValues();
775       for (unsigned i = 0; i < NumPHIValues; i++) {
776         Value *InVal = phi->getIncomingValue(i);
777         BasicBlock *InBB = phi->getIncomingBlock(i);
778
779         // If we've already seen InBB, add the same incoming value
780         // we added for it earlier.  The IR verifier requires phi
781         // nodes with multiple entries from the same basic block
782         // to have the same incoming value for each of those
783         // entries.  If we don't do this check here and basephi
784         // has a different type than base, we'll end up adding two
785         // bitcasts (and hence two distinct values) as incoming
786         // values for the same basic block.
787
788         int blockIndex = basephi->getBasicBlockIndex(InBB);
789         if (blockIndex != -1) {
790           Value *oldBase = basephi->getIncomingValue(blockIndex);
791           basephi->addIncoming(oldBase, InBB);
792 #ifndef NDEBUG
793           Value *base = findBaseOrBDV(InVal, cache);
794           if (!isKnownBaseResult(base)) {
795             // Either conflict or base.
796             assert(states.count(base));
797             base = states[base].getBase();
798             assert(base != nullptr && "unknown PhiState!");
799           }
800
801           // In essense this assert states: the only way two
802           // values incoming from the same basic block may be
803           // different is by being different bitcasts of the same
804           // value.  A cleanup that remains TODO is changing
805           // findBaseOrBDV to return an llvm::Value of the correct
806           // type (and still remain pure).  This will remove the
807           // need to add bitcasts.
808           assert(base->stripPointerCasts() == oldBase->stripPointerCasts() &&
809                  "sanity -- findBaseOrBDV should be pure!");
810 #endif
811           continue;
812         }
813
814         // Find either the defining value for the PHI or the normal base for
815         // a non-phi node
816         Value *base = findBaseOrBDV(InVal, cache);
817         if (!isKnownBaseResult(base)) {
818           // Either conflict or base.
819           assert(states.count(base));
820           base = states[base].getBase();
821           assert(base != nullptr && "unknown PhiState!");
822         }
823         assert(base && "can't be null");
824         // Must use original input BB since base may not be Instruction
825         // The cast is needed since base traversal may strip away bitcasts
826         if (base->getType() != basephi->getType()) {
827           base = new BitCastInst(base, basephi->getType(), "cast",
828                                  InBB->getTerminator());
829         }
830         basephi->addIncoming(base, InBB);
831       }
832       assert(basephi->getNumIncomingValues() == NumPHIValues);
833     } else {
834       SelectInst *basesel = cast<SelectInst>(state.getBase());
835       SelectInst *sel = cast<SelectInst>(v);
836       // Operand 1 & 2 are true, false path respectively. TODO: refactor to
837       // something more safe and less hacky.
838       for (int i = 1; i <= 2; i++) {
839         Value *InVal = sel->getOperand(i);
840         // Find either the defining value for the PHI or the normal base for
841         // a non-phi node
842         Value *base = findBaseOrBDV(InVal, cache);
843         if (!isKnownBaseResult(base)) {
844           // Either conflict or base.
845           assert(states.count(base));
846           base = states[base].getBase();
847           assert(base != nullptr && "unknown PhiState!");
848         }
849         assert(base && "can't be null");
850         // Must use original input BB since base may not be Instruction
851         // The cast is needed since base traversal may strip away bitcasts
852         if (base->getType() != basesel->getType()) {
853           base = new BitCastInst(base, basesel->getType(), "cast", basesel);
854         }
855         basesel->setOperand(i, base);
856       }
857     }
858   }
859
860   // Cache all of our results so we can cheaply reuse them
861   // NOTE: This is actually two caches: one of the base defining value
862   // relation and one of the base pointer relation!  FIXME
863   for (auto item : states) {
864     Value *v = item.first;
865     Value *base = item.second.getBase();
866     assert(v && base);
867     assert(!isKnownBaseResult(v) && "why did it get added?");
868
869     if (TraceLSP) {
870       std::string fromstr =
871           cache.count(v) ? (cache[v]->hasName() ? cache[v]->getName() : "")
872                          : "none";
873       errs() << "Updating base value cache"
874              << " for: " << (v->hasName() ? v->getName() : "")
875              << " from: " << fromstr
876              << " to: " << (base->hasName() ? base->getName() : "") << "\n";
877     }
878
879     assert(isKnownBaseResult(base) &&
880            "must be something we 'know' is a base pointer");
881     if (cache.count(v)) {
882       // Once we transition from the BDV relation being store in the cache to
883       // the base relation being stored, it must be stable
884       assert((!isKnownBaseResult(cache[v]) || cache[v] == base) &&
885              "base relation should be stable");
886     }
887     cache[v] = base;
888   }
889   assert(cache.find(def) != cache.end());
890   return cache[def];
891 }
892
893 // For a set of live pointers (base and/or derived), identify the base
894 // pointer of the object which they are derived from.  This routine will
895 // mutate the IR graph as needed to make the 'base' pointer live at the
896 // definition site of 'derived'.  This ensures that any use of 'derived' can
897 // also use 'base'.  This may involve the insertion of a number of
898 // additional PHI nodes.
899 //
900 // preconditions: live is a set of pointer type Values
901 //
902 // side effects: may insert PHI nodes into the existing CFG, will preserve
903 // CFG, will not remove or mutate any existing nodes
904 //
905 // post condition: PointerToBase contains one (derived, base) pair for every
906 // pointer in live.  Note that derived can be equal to base if the original
907 // pointer was a base pointer.
908 static void
909 findBasePointers(const StatepointLiveSetTy &live,
910                  DenseMap<llvm::Value *, llvm::Value *> &PointerToBase,
911                  DominatorTree *DT, DefiningValueMapTy &DVCache) {
912   // For the naming of values inserted to be deterministic - which makes for
913   // much cleaner and more stable tests - we need to assign an order to the
914   // live values.  DenseSets do not provide a deterministic order across runs.
915   SmallVector<Value *, 64> Temp;
916   Temp.insert(Temp.end(), live.begin(), live.end());
917   std::sort(Temp.begin(), Temp.end(), order_by_name);
918   for (Value *ptr : Temp) {
919     Value *base = findBasePointer(ptr, DVCache);
920     assert(base && "failed to find base pointer");
921     PointerToBase[ptr] = base;
922     assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
923             DT->dominates(cast<Instruction>(base)->getParent(),
924                           cast<Instruction>(ptr)->getParent())) &&
925            "The base we found better dominate the derived pointer");
926
927     // If you see this trip and like to live really dangerously, the code should
928     // be correct, just with idioms the verifier can't handle.  You can try
929     // disabling the verifier at your own substaintial risk.
930     assert(!isa<ConstantPointerNull>(base) &&
931            "the relocation code needs adjustment to handle the relocation of "
932            "a null pointer constant without causing false positives in the "
933            "safepoint ir verifier.");
934   }
935 }
936
937 /// Find the required based pointers (and adjust the live set) for the given
938 /// parse point.
939 static void findBasePointers(DominatorTree &DT, DefiningValueMapTy &DVCache,
940                              const CallSite &CS,
941                              PartiallyConstructedSafepointRecord &result) {
942   DenseMap<llvm::Value *, llvm::Value *> PointerToBase;
943   findBasePointers(result.liveset, PointerToBase, &DT, DVCache);
944
945   if (PrintBasePointers) {
946     // Note: Need to print these in a stable order since this is checked in
947     // some tests.
948     errs() << "Base Pairs (w/o Relocation):\n";
949     SmallVector<Value *, 64> Temp;
950     Temp.reserve(PointerToBase.size());
951     for (auto Pair : PointerToBase) {
952       Temp.push_back(Pair.first);
953     }
954     std::sort(Temp.begin(), Temp.end(), order_by_name);
955     for (Value *Ptr : Temp) {
956       Value *Base = PointerToBase[Ptr];
957       errs() << " derived %" << Ptr->getName() << " base %" << Base->getName()
958              << "\n";
959     }
960   }
961
962   result.PointerToBase = PointerToBase;
963 }
964
965 /// Given an updated version of the dataflow liveness results, update the
966 /// liveset and base pointer maps for the call site CS.
967 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
968                                   const CallSite &CS,
969                                   PartiallyConstructedSafepointRecord &result);
970
971 static void recomputeLiveInValues(
972     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
973     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
974   // TODO-PERF: reuse the original liveness, then simply run the dataflow
975   // again.  The old values are still live and will help it stablize quickly.
976   GCPtrLivenessData RevisedLivenessData;
977   computeLiveInValues(DT, F, RevisedLivenessData);
978   for (size_t i = 0; i < records.size(); i++) {
979     struct PartiallyConstructedSafepointRecord &info = records[i];
980     const CallSite &CS = toUpdate[i];
981     recomputeLiveInValues(RevisedLivenessData, CS, info);
982   }
983 }
984
985 // When inserting gc.relocate calls, we need to ensure there are no uses
986 // of the original value between the gc.statepoint and the gc.relocate call.
987 // One case which can arise is a phi node starting one of the successor blocks.
988 // We also need to be able to insert the gc.relocates only on the path which
989 // goes through the statepoint.  We might need to split an edge to make this
990 // possible.
991 static BasicBlock *
992 normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent, Pass *P) {
993   DominatorTree *DT = nullptr;
994   if (auto *DTP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
995     DT = &DTP->getDomTree();
996
997   BasicBlock *Ret = BB;
998   if (!BB->getUniquePredecessor()) {
999     Ret = SplitBlockPredecessors(BB, InvokeParent, "", nullptr, DT);
1000   }
1001
1002   // Now that 'ret' has unique predecessor we can safely remove all phi nodes
1003   // from it
1004   FoldSingleEntryPHINodes(Ret);
1005   assert(!isa<PHINode>(Ret->begin()));
1006
1007   // At this point, we can safely insert a gc.relocate as the first instruction
1008   // in Ret if needed.
1009   return Ret;
1010 }
1011
1012 static int find_index(ArrayRef<Value *> livevec, Value *val) {
1013   auto itr = std::find(livevec.begin(), livevec.end(), val);
1014   assert(livevec.end() != itr);
1015   size_t index = std::distance(livevec.begin(), itr);
1016   assert(index < livevec.size());
1017   return index;
1018 }
1019
1020 // Create new attribute set containing only attributes which can be transfered
1021 // from original call to the safepoint.
1022 static AttributeSet legalizeCallAttributes(AttributeSet AS) {
1023   AttributeSet ret;
1024
1025   for (unsigned Slot = 0; Slot < AS.getNumSlots(); Slot++) {
1026     unsigned index = AS.getSlotIndex(Slot);
1027
1028     if (index == AttributeSet::ReturnIndex ||
1029         index == AttributeSet::FunctionIndex) {
1030
1031       for (auto it = AS.begin(Slot), it_end = AS.end(Slot); it != it_end;
1032            ++it) {
1033         Attribute attr = *it;
1034
1035         // Do not allow certain attributes - just skip them
1036         // Safepoint can not be read only or read none.
1037         if (attr.hasAttribute(Attribute::ReadNone) ||
1038             attr.hasAttribute(Attribute::ReadOnly))
1039           continue;
1040
1041         ret = ret.addAttributes(
1042             AS.getContext(), index,
1043             AttributeSet::get(AS.getContext(), index, AttrBuilder(attr)));
1044       }
1045     }
1046
1047     // Just skip parameter attributes for now
1048   }
1049
1050   return ret;
1051 }
1052
1053 /// Helper function to place all gc relocates necessary for the given
1054 /// statepoint.
1055 /// Inputs:
1056 ///   liveVariables - list of variables to be relocated.
1057 ///   liveStart - index of the first live variable.
1058 ///   basePtrs - base pointers.
1059 ///   statepointToken - statepoint instruction to which relocates should be
1060 ///   bound.
1061 ///   Builder - Llvm IR builder to be used to construct new calls.
1062 static void CreateGCRelocates(ArrayRef<llvm::Value *> liveVariables,
1063                               const int liveStart,
1064                               ArrayRef<llvm::Value *> basePtrs,
1065                               Instruction *statepointToken,
1066                               IRBuilder<> Builder) {
1067   SmallVector<Instruction *, 64> NewDefs;
1068   NewDefs.reserve(liveVariables.size());
1069
1070   Module *M = statepointToken->getParent()->getParent()->getParent();
1071
1072   for (unsigned i = 0; i < liveVariables.size(); i++) {
1073     // We generate a (potentially) unique declaration for every pointer type
1074     // combination.  This results is some blow up the function declarations in
1075     // the IR, but removes the need for argument bitcasts which shrinks the IR
1076     // greatly and makes it much more readable.
1077     SmallVector<Type *, 1> types;                 // one per 'any' type
1078     types.push_back(liveVariables[i]->getType()); // result type
1079     Value *gc_relocate_decl = Intrinsic::getDeclaration(
1080         M, Intrinsic::experimental_gc_relocate, types);
1081
1082     // Generate the gc.relocate call and save the result
1083     Value *baseIdx =
1084         ConstantInt::get(Type::getInt32Ty(M->getContext()),
1085                          liveStart + find_index(liveVariables, basePtrs[i]));
1086     Value *liveIdx = ConstantInt::get(
1087         Type::getInt32Ty(M->getContext()),
1088         liveStart + find_index(liveVariables, liveVariables[i]));
1089
1090     // only specify a debug name if we can give a useful one
1091     Value *reloc = Builder.CreateCall3(
1092         gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1093         liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1094                                     : "");
1095     // Trick CodeGen into thinking there are lots of free registers at this
1096     // fake call.
1097     cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1098
1099     NewDefs.push_back(cast<Instruction>(reloc));
1100   }
1101   assert(NewDefs.size() == liveVariables.size() &&
1102          "missing or extra redefinition at safepoint");
1103 }
1104
1105 static void
1106 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1107                            const SmallVectorImpl<llvm::Value *> &basePtrs,
1108                            const SmallVectorImpl<llvm::Value *> &liveVariables,
1109                            Pass *P,
1110                            PartiallyConstructedSafepointRecord &result) {
1111   assert(basePtrs.size() == liveVariables.size());
1112   assert(isStatepoint(CS) &&
1113          "This method expects to be rewriting a statepoint");
1114
1115   BasicBlock *BB = CS.getInstruction()->getParent();
1116   assert(BB);
1117   Function *F = BB->getParent();
1118   assert(F && "must be set");
1119   Module *M = F->getParent();
1120   (void)M;
1121   assert(M && "must be set");
1122
1123   // We're not changing the function signature of the statepoint since the gc
1124   // arguments go into the var args section.
1125   Function *gc_statepoint_decl = CS.getCalledFunction();
1126
1127   // Then go ahead and use the builder do actually do the inserts.  We insert
1128   // immediately before the previous instruction under the assumption that all
1129   // arguments will be available here.  We can't insert afterwards since we may
1130   // be replacing a terminator.
1131   Instruction *insertBefore = CS.getInstruction();
1132   IRBuilder<> Builder(insertBefore);
1133   // Copy all of the arguments from the original statepoint - this includes the
1134   // target, call args, and deopt args
1135   SmallVector<llvm::Value *, 64> args;
1136   args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1137   // TODO: Clear the 'needs rewrite' flag
1138
1139   // add all the pointers to be relocated (gc arguments)
1140   // Capture the start of the live variable list for use in the gc_relocates
1141   const int live_start = args.size();
1142   args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1143
1144   // Create the statepoint given all the arguments
1145   Instruction *token = nullptr;
1146   AttributeSet return_attributes;
1147   if (CS.isCall()) {
1148     CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1149     CallInst *call =
1150         Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1151     call->setTailCall(toReplace->isTailCall());
1152     call->setCallingConv(toReplace->getCallingConv());
1153
1154     // Currently we will fail on parameter attributes and on certain
1155     // function attributes.
1156     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1157     // In case if we can handle this set of sttributes - set up function attrs
1158     // directly on statepoint and return attrs later for gc_result intrinsic.
1159     call->setAttributes(new_attrs.getFnAttributes());
1160     return_attributes = new_attrs.getRetAttributes();
1161
1162     token = call;
1163
1164     // Put the following gc_result and gc_relocate calls immediately after the
1165     // the old call (which we're about to delete)
1166     BasicBlock::iterator next(toReplace);
1167     assert(BB->end() != next && "not a terminator, must have next");
1168     next++;
1169     Instruction *IP = &*(next);
1170     Builder.SetInsertPoint(IP);
1171     Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1172
1173   } else {
1174     InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1175
1176     // Insert the new invoke into the old block.  We'll remove the old one in a
1177     // moment at which point this will become the new terminator for the
1178     // original block.
1179     InvokeInst *invoke = InvokeInst::Create(
1180         gc_statepoint_decl, toReplace->getNormalDest(),
1181         toReplace->getUnwindDest(), args, "", toReplace->getParent());
1182     invoke->setCallingConv(toReplace->getCallingConv());
1183
1184     // Currently we will fail on parameter attributes and on certain
1185     // function attributes.
1186     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1187     // In case if we can handle this set of sttributes - set up function attrs
1188     // directly on statepoint and return attrs later for gc_result intrinsic.
1189     invoke->setAttributes(new_attrs.getFnAttributes());
1190     return_attributes = new_attrs.getRetAttributes();
1191
1192     token = invoke;
1193
1194     // Generate gc relocates in exceptional path
1195     BasicBlock *unwindBlock = toReplace->getUnwindDest();
1196     assert(!isa<PHINode>(unwindBlock->begin()) &&
1197            unwindBlock->getUniquePredecessor() &&
1198            "can't safely insert in this block!");
1199
1200     Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1201     Builder.SetInsertPoint(IP);
1202     Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1203
1204     // Extract second element from landingpad return value. We will attach
1205     // exceptional gc relocates to it.
1206     const unsigned idx = 1;
1207     Instruction *exceptional_token =
1208         cast<Instruction>(Builder.CreateExtractValue(
1209             unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1210     result.UnwindToken = exceptional_token;
1211
1212     // Just throw away return value. We will use the one we got for normal
1213     // block.
1214     (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1215                             exceptional_token, Builder);
1216
1217     // Generate gc relocates and returns for normal block
1218     BasicBlock *normalDest = toReplace->getNormalDest();
1219     assert(!isa<PHINode>(normalDest->begin()) &&
1220            normalDest->getUniquePredecessor() &&
1221            "can't safely insert in this block!");
1222
1223     IP = &*(normalDest->getFirstInsertionPt());
1224     Builder.SetInsertPoint(IP);
1225
1226     // gc relocates will be generated later as if it were regular call
1227     // statepoint
1228   }
1229   assert(token);
1230
1231   // Take the name of the original value call if it had one.
1232   token->takeName(CS.getInstruction());
1233
1234 // The GCResult is already inserted, we just need to find it
1235 #ifndef NDEBUG
1236   Instruction *toReplace = CS.getInstruction();
1237   assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1238          "only valid use before rewrite is gc.result");
1239   assert(!toReplace->hasOneUse() ||
1240          isGCResult(cast<Instruction>(*toReplace->user_begin())));
1241 #endif
1242
1243   // Update the gc.result of the original statepoint (if any) to use the newly
1244   // inserted statepoint.  This is safe to do here since the token can't be
1245   // considered a live reference.
1246   CS.getInstruction()->replaceAllUsesWith(token);
1247
1248   result.StatepointToken = token;
1249
1250   // Second, create a gc.relocate for every live variable
1251   CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1252 }
1253
1254 namespace {
1255 struct name_ordering {
1256   Value *base;
1257   Value *derived;
1258   bool operator()(name_ordering const &a, name_ordering const &b) {
1259     return -1 == a.derived->getName().compare(b.derived->getName());
1260   }
1261 };
1262 }
1263 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1264                            SmallVectorImpl<Value *> &livevec) {
1265   assert(basevec.size() == livevec.size());
1266
1267   SmallVector<name_ordering, 64> temp;
1268   for (size_t i = 0; i < basevec.size(); i++) {
1269     name_ordering v;
1270     v.base = basevec[i];
1271     v.derived = livevec[i];
1272     temp.push_back(v);
1273   }
1274   std::sort(temp.begin(), temp.end(), name_ordering());
1275   for (size_t i = 0; i < basevec.size(); i++) {
1276     basevec[i] = temp[i].base;
1277     livevec[i] = temp[i].derived;
1278   }
1279 }
1280
1281 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1282 // which make the relocations happening at this safepoint explicit.
1283 //
1284 // WARNING: Does not do any fixup to adjust users of the original live
1285 // values.  That's the callers responsibility.
1286 static void
1287 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1288                        PartiallyConstructedSafepointRecord &result) {
1289   auto liveset = result.liveset;
1290   auto PointerToBase = result.PointerToBase;
1291
1292   // Convert to vector for efficient cross referencing.
1293   SmallVector<Value *, 64> basevec, livevec;
1294   livevec.reserve(liveset.size());
1295   basevec.reserve(liveset.size());
1296   for (Value *L : liveset) {
1297     livevec.push_back(L);
1298
1299     assert(PointerToBase.find(L) != PointerToBase.end());
1300     Value *base = PointerToBase[L];
1301     basevec.push_back(base);
1302   }
1303   assert(livevec.size() == basevec.size());
1304
1305   // To make the output IR slightly more stable (for use in diffs), ensure a
1306   // fixed order of the values in the safepoint (by sorting the value name).
1307   // The order is otherwise meaningless.
1308   stablize_order(basevec, livevec);
1309
1310   // Do the actual rewriting and delete the old statepoint
1311   makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1312   CS.getInstruction()->eraseFromParent();
1313 }
1314
1315 // Helper function for the relocationViaAlloca.
1316 // It receives iterator to the statepoint gc relocates and emits store to the
1317 // assigned
1318 // location (via allocaMap) for the each one of them.
1319 // Add visited values into the visitedLiveValues set we will later use them
1320 // for sanity check.
1321 static void
1322 insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1323                        DenseMap<Value *, Value *> &allocaMap,
1324                        DenseSet<Value *> &visitedLiveValues) {
1325
1326   for (User *U : gcRelocs) {
1327     if (!isa<IntrinsicInst>(U))
1328       continue;
1329
1330     IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1331
1332     // We only care about relocates
1333     if (relocatedValue->getIntrinsicID() !=
1334         Intrinsic::experimental_gc_relocate) {
1335       continue;
1336     }
1337
1338     GCRelocateOperands relocateOperands(relocatedValue);
1339     Value *originalValue = const_cast<Value *>(relocateOperands.derivedPtr());
1340     assert(allocaMap.count(originalValue));
1341     Value *alloca = allocaMap[originalValue];
1342
1343     // Emit store into the related alloca
1344     StoreInst *store = new StoreInst(relocatedValue, alloca);
1345     store->insertAfter(relocatedValue);
1346
1347 #ifndef NDEBUG
1348     visitedLiveValues.insert(originalValue);
1349 #endif
1350   }
1351 }
1352
1353 /// do all the relocation update via allocas and mem2reg
1354 static void relocationViaAlloca(
1355     Function &F, DominatorTree &DT, ArrayRef<Value *> live,
1356     ArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1357 #ifndef NDEBUG
1358   // record initial number of (static) allocas; we'll check we have the same
1359   // number when we get done.
1360   int InitialAllocaNum = 0;
1361   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1362        I++)
1363     if (isa<AllocaInst>(*I))
1364       InitialAllocaNum++;
1365 #endif
1366
1367   // TODO-PERF: change data structures, reserve
1368   DenseMap<Value *, Value *> allocaMap;
1369   SmallVector<AllocaInst *, 200> PromotableAllocas;
1370   PromotableAllocas.reserve(live.size());
1371
1372   // emit alloca for each live gc pointer
1373   for (unsigned i = 0; i < live.size(); i++) {
1374     Value *liveValue = live[i];
1375     AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1376                                         F.getEntryBlock().getFirstNonPHI());
1377     allocaMap[liveValue] = alloca;
1378     PromotableAllocas.push_back(alloca);
1379   }
1380
1381   // The next two loops are part of the same conceptual operation.  We need to
1382   // insert a store to the alloca after the original def and at each
1383   // redefinition.  We need to insert a load before each use.  These are split
1384   // into distinct loops for performance reasons.
1385
1386   // update gc pointer after each statepoint
1387   // either store a relocated value or null (if no relocated value found for
1388   // this gc pointer and it is not a gc_result)
1389   // this must happen before we update the statepoint with load of alloca
1390   // otherwise we lose the link between statepoint and old def
1391   for (size_t i = 0; i < records.size(); i++) {
1392     const struct PartiallyConstructedSafepointRecord &info = records[i];
1393     Value *Statepoint = info.StatepointToken;
1394
1395     // This will be used for consistency check
1396     DenseSet<Value *> visitedLiveValues;
1397
1398     // Insert stores for normal statepoint gc relocates
1399     insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues);
1400
1401     // In case if it was invoke statepoint
1402     // we will insert stores for exceptional path gc relocates.
1403     if (isa<InvokeInst>(Statepoint)) {
1404       insertRelocationStores(info.UnwindToken->users(), allocaMap,
1405                              visitedLiveValues);
1406     }
1407
1408     if (ClobberNonLive) {
1409       // As a debuging aid, pretend that an unrelocated pointer becomes null at
1410       // the gc.statepoint.  This will turn some subtle GC problems into
1411       // slightly easier to debug SEGVs.  Note that on large IR files with
1412       // lots of gc.statepoints this is extremely costly both memory and time
1413       // wise.
1414       SmallVector<AllocaInst *, 64> ToClobber;
1415       for (auto Pair : allocaMap) {
1416         Value *Def = Pair.first;
1417         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1418
1419         // This value was relocated
1420         if (visitedLiveValues.count(Def)) {
1421           continue;
1422         }
1423         ToClobber.push_back(Alloca);
1424       }
1425
1426       auto InsertClobbersAt = [&](Instruction *IP) {
1427         for (auto *AI : ToClobber) {
1428           auto AIType = cast<PointerType>(AI->getType());
1429           auto PT = cast<PointerType>(AIType->getElementType());
1430           Constant *CPN = ConstantPointerNull::get(PT);
1431           StoreInst *store = new StoreInst(CPN, AI);
1432           store->insertBefore(IP);
1433         }
1434       };
1435
1436       // Insert the clobbering stores.  These may get intermixed with the
1437       // gc.results and gc.relocates, but that's fine.
1438       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1439         InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1440         InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1441       } else {
1442         BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1443         Next++;
1444         InsertClobbersAt(Next);
1445       }
1446     }
1447   }
1448   // update use with load allocas and add store for gc_relocated
1449   for (auto Pair : allocaMap) {
1450     Value *def = Pair.first;
1451     Value *alloca = Pair.second;
1452
1453     // we pre-record the uses of allocas so that we dont have to worry about
1454     // later update
1455     // that change the user information.
1456     SmallVector<Instruction *, 20> uses;
1457     // PERF: trade a linear scan for repeated reallocation
1458     uses.reserve(std::distance(def->user_begin(), def->user_end()));
1459     for (User *U : def->users()) {
1460       if (!isa<ConstantExpr>(U)) {
1461         // If the def has a ConstantExpr use, then the def is either a
1462         // ConstantExpr use itself or null.  In either case
1463         // (recursively in the first, directly in the second), the oop
1464         // it is ultimately dependent on is null and this particular
1465         // use does not need to be fixed up.
1466         uses.push_back(cast<Instruction>(U));
1467       }
1468     }
1469
1470     std::sort(uses.begin(), uses.end());
1471     auto last = std::unique(uses.begin(), uses.end());
1472     uses.erase(last, uses.end());
1473
1474     for (Instruction *use : uses) {
1475       if (isa<PHINode>(use)) {
1476         PHINode *phi = cast<PHINode>(use);
1477         for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1478           if (def == phi->getIncomingValue(i)) {
1479             LoadInst *load = new LoadInst(
1480                 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1481             phi->setIncomingValue(i, load);
1482           }
1483         }
1484       } else {
1485         LoadInst *load = new LoadInst(alloca, "", use);
1486         use->replaceUsesOfWith(def, load);
1487       }
1488     }
1489
1490     // emit store for the initial gc value
1491     // store must be inserted after load, otherwise store will be in alloca's
1492     // use list and an extra load will be inserted before it
1493     StoreInst *store = new StoreInst(def, alloca);
1494     if (Instruction *inst = dyn_cast<Instruction>(def)) {
1495       if (InvokeInst *invoke = dyn_cast<InvokeInst>(inst)) {
1496         // InvokeInst is a TerminatorInst so the store need to be inserted
1497         // into its normal destination block.
1498         BasicBlock *normalDest = invoke->getNormalDest();
1499         store->insertBefore(normalDest->getFirstNonPHI());
1500       } else {
1501         assert(!inst->isTerminator() &&
1502                "The only TerminatorInst that can produce a value is "
1503                "InvokeInst which is handled above.");
1504         store->insertAfter(inst);
1505       }
1506     } else {
1507       assert(isa<Argument>(def));
1508       store->insertAfter(cast<Instruction>(alloca));
1509     }
1510   }
1511
1512   assert(PromotableAllocas.size() == live.size() &&
1513          "we must have the same allocas with lives");
1514   if (!PromotableAllocas.empty()) {
1515     // apply mem2reg to promote alloca to SSA
1516     PromoteMemToReg(PromotableAllocas, DT);
1517   }
1518
1519 #ifndef NDEBUG
1520   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1521        I++)
1522     if (isa<AllocaInst>(*I))
1523       InitialAllocaNum--;
1524   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1525 #endif
1526 }
1527
1528 /// Implement a unique function which doesn't require we sort the input
1529 /// vector.  Doing so has the effect of changing the output of a couple of
1530 /// tests in ways which make them less useful in testing fused safepoints.
1531 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1532   DenseSet<T> Seen;
1533   SmallVector<T, 128> TempVec;
1534   TempVec.reserve(Vec.size());
1535   for (auto Element : Vec)
1536     TempVec.push_back(Element);
1537   Vec.clear();
1538   for (auto V : TempVec) {
1539     if (Seen.insert(V).second) {
1540       Vec.push_back(V);
1541     }
1542   }
1543 }
1544
1545 /// Insert holders so that each Value is obviously live through the entire
1546 /// lifetime of the call.
1547 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1548                                  SmallVectorImpl<CallInst *> &Holders) {
1549   if (Values.empty())
1550     // No values to hold live, might as well not insert the empty holder
1551     return;
1552
1553   Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1554   // Use a dummy vararg function to actually hold the values live
1555   Function *Func = cast<Function>(M->getOrInsertFunction(
1556       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1557   if (CS.isCall()) {
1558     // For call safepoints insert dummy calls right after safepoint
1559     BasicBlock::iterator Next(CS.getInstruction());
1560     Next++;
1561     Holders.push_back(CallInst::Create(Func, Values, "", Next));
1562     return;
1563   }
1564   // For invoke safepooints insert dummy calls both in normal and
1565   // exceptional destination blocks
1566   auto *II = cast<InvokeInst>(CS.getInstruction());
1567   Holders.push_back(CallInst::Create(
1568       Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1569   Holders.push_back(CallInst::Create(
1570       Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
1571 }
1572
1573 static void findLiveReferences(
1574     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1575     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1576   GCPtrLivenessData OriginalLivenessData;
1577   computeLiveInValues(DT, F, OriginalLivenessData);
1578   for (size_t i = 0; i < records.size(); i++) {
1579     struct PartiallyConstructedSafepointRecord &info = records[i];
1580     const CallSite &CS = toUpdate[i];
1581     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1582   }
1583 }
1584
1585 /// Remove any vector of pointers from the liveset by scalarizing them over the
1586 /// statepoint instruction.  Adds the scalarized pieces to the liveset.  It
1587 /// would be preferrable to include the vector in the statepoint itself, but
1588 /// the lowering code currently does not handle that.  Extending it would be
1589 /// slightly non-trivial since it requires a format change.  Given how rare
1590 /// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1591 static void splitVectorValues(Instruction *StatepointInst,
1592                               StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
1593   SmallVector<Value *, 16> ToSplit;
1594   for (Value *V : LiveSet)
1595     if (isa<VectorType>(V->getType()))
1596       ToSplit.push_back(V);
1597
1598   if (ToSplit.empty())
1599     return;
1600
1601   Function &F = *(StatepointInst->getParent()->getParent());
1602
1603   DenseMap<Value *, AllocaInst *> AllocaMap;
1604   // First is normal return, second is exceptional return (invoke only)
1605   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1606   for (Value *V : ToSplit) {
1607     LiveSet.erase(V);
1608
1609     AllocaInst *Alloca =
1610         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1611     AllocaMap[V] = Alloca;
1612
1613     VectorType *VT = cast<VectorType>(V->getType());
1614     IRBuilder<> Builder(StatepointInst);
1615     SmallVector<Value *, 16> Elements;
1616     for (unsigned i = 0; i < VT->getNumElements(); i++)
1617       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1618     LiveSet.insert(Elements.begin(), Elements.end());
1619
1620     auto InsertVectorReform = [&](Instruction *IP) {
1621       Builder.SetInsertPoint(IP);
1622       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1623       Value *ResultVec = UndefValue::get(VT);
1624       for (unsigned i = 0; i < VT->getNumElements(); i++)
1625         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1626                                                 Builder.getInt32(i));
1627       return ResultVec;
1628     };
1629
1630     if (isa<CallInst>(StatepointInst)) {
1631       BasicBlock::iterator Next(StatepointInst);
1632       Next++;
1633       Instruction *IP = &*(Next);
1634       Replacements[V].first = InsertVectorReform(IP);
1635       Replacements[V].second = nullptr;
1636     } else {
1637       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1638       // We've already normalized - check that we don't have shared destination
1639       // blocks
1640       BasicBlock *NormalDest = Invoke->getNormalDest();
1641       assert(!isa<PHINode>(NormalDest->begin()));
1642       BasicBlock *UnwindDest = Invoke->getUnwindDest();
1643       assert(!isa<PHINode>(UnwindDest->begin()));
1644       // Insert insert element sequences in both successors
1645       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1646       Replacements[V].first = InsertVectorReform(IP);
1647       IP = &*(UnwindDest->getFirstInsertionPt());
1648       Replacements[V].second = InsertVectorReform(IP);
1649     }
1650   }
1651   for (Value *V : ToSplit) {
1652     AllocaInst *Alloca = AllocaMap[V];
1653
1654     // Capture all users before we start mutating use lists
1655     SmallVector<Instruction *, 16> Users;
1656     for (User *U : V->users())
1657       Users.push_back(cast<Instruction>(U));
1658
1659     for (Instruction *I : Users) {
1660       if (auto Phi = dyn_cast<PHINode>(I)) {
1661         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1662           if (V == Phi->getIncomingValue(i)) {
1663             LoadInst *Load = new LoadInst(
1664                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1665             Phi->setIncomingValue(i, Load);
1666           }
1667       } else {
1668         LoadInst *Load = new LoadInst(Alloca, "", I);
1669         I->replaceUsesOfWith(V, Load);
1670       }
1671     }
1672
1673     // Store the original value and the replacement value into the alloca
1674     StoreInst *Store = new StoreInst(V, Alloca);
1675     if (auto I = dyn_cast<Instruction>(V))
1676       Store->insertAfter(I);
1677     else
1678       Store->insertAfter(Alloca);
1679
1680     // Normal return for invoke, or call return
1681     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1682     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1683     // Unwind return for invoke only
1684     Replacement = cast_or_null<Instruction>(Replacements[V].second);
1685     if (Replacement)
1686       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1687   }
1688
1689   // apply mem2reg to promote alloca to SSA
1690   SmallVector<AllocaInst *, 16> Allocas;
1691   for (Value *V : ToSplit)
1692     Allocas.push_back(AllocaMap[V]);
1693   PromoteMemToReg(Allocas, DT);
1694 }
1695
1696 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
1697                               SmallVectorImpl<CallSite> &toUpdate) {
1698 #ifndef NDEBUG
1699   // sanity check the input
1700   std::set<CallSite> uniqued;
1701   uniqued.insert(toUpdate.begin(), toUpdate.end());
1702   assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1703
1704   for (size_t i = 0; i < toUpdate.size(); i++) {
1705     CallSite &CS = toUpdate[i];
1706     assert(CS.getInstruction()->getParent()->getParent() == &F);
1707     assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1708   }
1709 #endif
1710
1711   // When inserting gc.relocates for invokes, we need to be able to insert at
1712   // the top of the successor blocks.  See the comment on
1713   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
1714   // may restructure the CFG.
1715   for (CallSite CS : toUpdate) {
1716     if (!CS.isInvoke())
1717       continue;
1718     InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1719     normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
1720                                 P);
1721     normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
1722                                 P);
1723   }
1724
1725   // A list of dummy calls added to the IR to keep various values obviously
1726   // live in the IR.  We'll remove all of these when done.
1727   SmallVector<CallInst *, 64> holders;
1728
1729   // Insert a dummy call with all of the arguments to the vm_state we'll need
1730   // for the actual safepoint insertion.  This ensures reference arguments in
1731   // the deopt argument list are considered live through the safepoint (and
1732   // thus makes sure they get relocated.)
1733   for (size_t i = 0; i < toUpdate.size(); i++) {
1734     CallSite &CS = toUpdate[i];
1735     Statepoint StatepointCS(CS);
1736
1737     SmallVector<Value *, 64> DeoptValues;
1738     for (Use &U : StatepointCS.vm_state_args()) {
1739       Value *Arg = cast<Value>(&U);
1740       assert(!isUnhandledGCPointerType(Arg->getType()) &&
1741              "support for FCA unimplemented");
1742       if (isHandledGCPointerType(Arg->getType()))
1743         DeoptValues.push_back(Arg);
1744     }
1745     insertUseHolderAfter(CS, DeoptValues, holders);
1746   }
1747
1748   SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
1749   records.reserve(toUpdate.size());
1750   for (size_t i = 0; i < toUpdate.size(); i++) {
1751     struct PartiallyConstructedSafepointRecord info;
1752     records.push_back(info);
1753   }
1754   assert(records.size() == toUpdate.size());
1755
1756   // A) Identify all gc pointers which are staticly live at the given call
1757   // site.
1758   findLiveReferences(F, DT, P, toUpdate, records);
1759
1760   // Do a limited scalarization of any live at safepoint vector values which
1761   // contain pointers.  This enables this pass to run after vectorization at
1762   // the cost of some possible performance loss.  TODO: it would be nice to
1763   // natively support vectors all the way through the backend so we don't need
1764   // to scalarize here.
1765   for (size_t i = 0; i < records.size(); i++) {
1766     struct PartiallyConstructedSafepointRecord &info = records[i];
1767     Instruction *statepoint = toUpdate[i].getInstruction();
1768     splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
1769   }
1770
1771   // B) Find the base pointers for each live pointer
1772   /* scope for caching */ {
1773     // Cache the 'defining value' relation used in the computation and
1774     // insertion of base phis and selects.  This ensures that we don't insert
1775     // large numbers of duplicate base_phis.
1776     DefiningValueMapTy DVCache;
1777
1778     for (size_t i = 0; i < records.size(); i++) {
1779       struct PartiallyConstructedSafepointRecord &info = records[i];
1780       CallSite &CS = toUpdate[i];
1781       findBasePointers(DT, DVCache, CS, info);
1782     }
1783   } // end of cache scope
1784
1785   // The base phi insertion logic (for any safepoint) may have inserted new
1786   // instructions which are now live at some safepoint.  The simplest such
1787   // example is:
1788   // loop:
1789   //   phi a  <-- will be a new base_phi here
1790   //   safepoint 1 <-- that needs to be live here
1791   //   gep a + 1
1792   //   safepoint 2
1793   //   br loop
1794   // We insert some dummy calls after each safepoint to definitely hold live
1795   // the base pointers which were identified for that safepoint.  We'll then
1796   // ask liveness for _every_ base inserted to see what is now live.  Then we
1797   // remove the dummy calls.
1798   holders.reserve(holders.size() + records.size());
1799   for (size_t i = 0; i < records.size(); i++) {
1800     struct PartiallyConstructedSafepointRecord &info = records[i];
1801     CallSite &CS = toUpdate[i];
1802
1803     SmallVector<Value *, 128> Bases;
1804     for (auto Pair : info.PointerToBase) {
1805       Bases.push_back(Pair.second);
1806     }
1807     insertUseHolderAfter(CS, Bases, holders);
1808   }
1809
1810   // By selecting base pointers, we've effectively inserted new uses. Thus, we
1811   // need to rerun liveness.  We may *also* have inserted new defs, but that's
1812   // not the key issue.
1813   recomputeLiveInValues(F, DT, P, toUpdate, records);
1814
1815   if (PrintBasePointers) {
1816     for (size_t i = 0; i < records.size(); i++) {
1817       struct PartiallyConstructedSafepointRecord &info = records[i];
1818       errs() << "Base Pairs: (w/Relocation)\n";
1819       for (auto Pair : info.PointerToBase) {
1820         errs() << " derived %" << Pair.first->getName() << " base %"
1821                << Pair.second->getName() << "\n";
1822       }
1823     }
1824   }
1825   for (size_t i = 0; i < holders.size(); i++) {
1826     holders[i]->eraseFromParent();
1827     holders[i] = nullptr;
1828   }
1829   holders.clear();
1830
1831   // Now run through and replace the existing statepoints with new ones with
1832   // the live variables listed.  We do not yet update uses of the values being
1833   // relocated. We have references to live variables that need to
1834   // survive to the last iteration of this loop.  (By construction, the
1835   // previous statepoint can not be a live variable, thus we can and remove
1836   // the old statepoint calls as we go.)
1837   for (size_t i = 0; i < records.size(); i++) {
1838     struct PartiallyConstructedSafepointRecord &info = records[i];
1839     CallSite &CS = toUpdate[i];
1840     makeStatepointExplicit(DT, CS, P, info);
1841   }
1842   toUpdate.clear(); // prevent accident use of invalid CallSites
1843
1844   // Do all the fixups of the original live variables to their relocated selves
1845   SmallVector<Value *, 128> live;
1846   for (size_t i = 0; i < records.size(); i++) {
1847     struct PartiallyConstructedSafepointRecord &info = records[i];
1848     // We can't simply save the live set from the original insertion.  One of
1849     // the live values might be the result of a call which needs a safepoint.
1850     // That Value* no longer exists and we need to use the new gc_result.
1851     // Thankfully, the liveset is embedded in the statepoint (and updated), so
1852     // we just grab that.
1853     Statepoint statepoint(info.StatepointToken);
1854     live.insert(live.end(), statepoint.gc_args_begin(),
1855                 statepoint.gc_args_end());
1856 #ifndef NDEBUG
1857     // Do some basic sanity checks on our liveness results before performing
1858     // relocation.  Relocation can and will turn mistakes in liveness results
1859     // into non-sensical code which is must harder to debug.
1860     // TODO: It would be nice to test consistency as well
1861     assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
1862            "statepoint must be reachable or liveness is meaningless");
1863     for (Value *V : statepoint.gc_args()) {
1864       if (!isa<Instruction>(V))
1865         // Non-instruction values trivial dominate all possible uses
1866         continue;
1867       auto LiveInst = cast<Instruction>(V);
1868       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
1869              "unreachable values should never be live");
1870       assert(DT.dominates(LiveInst, info.StatepointToken) &&
1871              "basic SSA liveness expectation violated by liveness analysis");
1872     }
1873 #endif
1874   }
1875   unique_unsorted(live);
1876
1877 #ifndef NDEBUG
1878   // sanity check
1879   for (auto ptr : live) {
1880     assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1881   }
1882 #endif
1883
1884   relocationViaAlloca(F, DT, live, records);
1885   return !records.empty();
1886 }
1887
1888 /// Returns true if this function should be rewritten by this pass.  The main
1889 /// point of this function is as an extension point for custom logic.
1890 static bool shouldRewriteStatepointsIn(Function &F) {
1891   // TODO: This should check the GCStrategy
1892   if (F.hasGC()) {
1893     const std::string StatepointExampleName("statepoint-example");
1894     return StatepointExampleName == F.getGC();
1895   } else
1896     return false;
1897 }
1898
1899 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1900   // Nothing to do for declarations.
1901   if (F.isDeclaration() || F.empty())
1902     return false;
1903
1904   // Policy choice says not to rewrite - the most common reason is that we're
1905   // compiling code without a GCStrategy.
1906   if (!shouldRewriteStatepointsIn(F))
1907     return false;
1908
1909   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1910
1911   // Gather all the statepoints which need rewritten.  Be careful to only
1912   // consider those in reachable code since we need to ask dominance queries
1913   // when rewriting.  We'll delete the unreachable ones in a moment.
1914   SmallVector<CallSite, 64> ParsePointNeeded;
1915   bool HasUnreachableStatepoint = false;
1916   for (Instruction &I : inst_range(F)) {
1917     // TODO: only the ones with the flag set!
1918     if (isStatepoint(I)) {
1919       if (DT.isReachableFromEntry(I.getParent()))
1920         ParsePointNeeded.push_back(CallSite(&I));
1921       else
1922         HasUnreachableStatepoint = true;
1923     }
1924   }
1925
1926   bool MadeChange = false;
1927
1928   // Delete any unreachable statepoints so that we don't have unrewritten
1929   // statepoints surviving this pass.  This makes testing easier and the
1930   // resulting IR less confusing to human readers.  Rather than be fancy, we
1931   // just reuse a utility function which removes the unreachable blocks.
1932   if (HasUnreachableStatepoint)
1933     MadeChange |= removeUnreachableBlocks(F);
1934
1935   // Return early if no work to do.
1936   if (ParsePointNeeded.empty())
1937     return MadeChange;
1938
1939   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
1940   // These are created by LCSSA.  They have the effect of increasing the size
1941   // of liveness sets for no good reason.  It may be harder to do this post
1942   // insertion since relocations and base phis can confuse things.
1943   for (BasicBlock &BB : F)
1944     if (BB.getUniquePredecessor()) {
1945       MadeChange = true;
1946       FoldSingleEntryPHINodes(&BB);
1947     }
1948
1949   MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
1950   return MadeChange;
1951 }
1952
1953 // liveness computation via standard dataflow
1954 // -------------------------------------------------------------------
1955
1956 // TODO: Consider using bitvectors for liveness, the set of potentially
1957 // interesting values should be small and easy to pre-compute.
1958
1959 /// Compute the live-in set for the location rbegin starting from
1960 /// the live-out set of the basic block
1961 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
1962                                 BasicBlock::reverse_iterator rend,
1963                                 DenseSet<Value *> &LiveTmp) {
1964
1965   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
1966     Instruction *I = &*ritr;
1967
1968     // KILL/Def - Remove this definition from LiveIn
1969     LiveTmp.erase(I);
1970
1971     // Don't consider *uses* in PHI nodes, we handle their contribution to
1972     // predecessor blocks when we seed the LiveOut sets
1973     if (isa<PHINode>(I))
1974       continue;
1975
1976     // USE - Add to the LiveIn set for this instruction
1977     for (Value *V : I->operands()) {
1978       assert(!isUnhandledGCPointerType(V->getType()) &&
1979              "support for FCA unimplemented");
1980       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
1981         // The choice to exclude all things constant here is slightly subtle.
1982         // There are two idependent reasons:
1983         // - We assume that things which are constant (from LLVM's definition)
1984         // do not move at runtime.  For example, the address of a global
1985         // variable is fixed, even though it's contents may not be.
1986         // - Second, we can't disallow arbitrary inttoptr constants even
1987         // if the language frontend does.  Optimization passes are free to
1988         // locally exploit facts without respect to global reachability.  This
1989         // can create sections of code which are dynamically unreachable and
1990         // contain just about anything.  (see constants.ll in tests)
1991         LiveTmp.insert(V);
1992       }
1993     }
1994   }
1995 }
1996
1997 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
1998
1999   for (BasicBlock *Succ : successors(BB)) {
2000     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2001     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2002       PHINode *Phi = cast<PHINode>(&*I);
2003       Value *V = Phi->getIncomingValueForBlock(BB);
2004       assert(!isUnhandledGCPointerType(V->getType()) &&
2005              "support for FCA unimplemented");
2006       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2007         LiveTmp.insert(V);
2008       }
2009     }
2010   }
2011 }
2012
2013 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2014   DenseSet<Value *> KillSet;
2015   for (Instruction &I : *BB)
2016     if (isHandledGCPointerType(I.getType()))
2017       KillSet.insert(&I);
2018   return KillSet;
2019 }
2020
2021 #ifndef NDEBUG
2022 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2023 /// sanity check for the liveness computation.
2024 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2025                           TerminatorInst *TI, bool TermOkay = false) {
2026   for (Value *V : Live) {
2027     if (auto *I = dyn_cast<Instruction>(V)) {
2028       // The terminator can be a member of the LiveOut set.  LLVM's definition
2029       // of instruction dominance states that V does not dominate itself.  As
2030       // such, we need to special case this to allow it.
2031       if (TermOkay && TI == I)
2032         continue;
2033       assert(DT.dominates(I, TI) &&
2034              "basic SSA liveness expectation violated by liveness analysis");
2035     }
2036   }
2037 }
2038
2039 /// Check that all the liveness sets used during the computation of liveness
2040 /// obey basic SSA properties.  This is useful for finding cases where we miss
2041 /// a def.
2042 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2043                           BasicBlock &BB) {
2044   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2045   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2046   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2047 }
2048 #endif
2049
2050 static void computeLiveInValues(DominatorTree &DT, Function &F,
2051                                 GCPtrLivenessData &Data) {
2052
2053   SmallSetVector<BasicBlock *, 200> Worklist;
2054   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2055     // We use a SetVector so that we don't have duplicates in the worklist.
2056     Worklist.insert(pred_begin(BB), pred_end(BB));
2057   };
2058   auto NextItem = [&]() {
2059     BasicBlock *BB = Worklist.back();
2060     Worklist.pop_back();
2061     return BB;
2062   };
2063
2064   // Seed the liveness for each individual block
2065   for (BasicBlock &BB : F) {
2066     Data.KillSet[&BB] = computeKillSet(&BB);
2067     Data.LiveSet[&BB].clear();
2068     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2069
2070 #ifndef NDEBUG
2071     for (Value *Kill : Data.KillSet[&BB])
2072       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2073 #endif
2074
2075     Data.LiveOut[&BB] = DenseSet<Value *>();
2076     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2077     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2078     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2079     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2080     if (!Data.LiveIn[&BB].empty())
2081       AddPredsToWorklist(&BB);
2082   }
2083
2084   // Propagate that liveness until stable
2085   while (!Worklist.empty()) {
2086     BasicBlock *BB = NextItem();
2087
2088     // Compute our new liveout set, then exit early if it hasn't changed
2089     // despite the contribution of our successor.
2090     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2091     const auto OldLiveOutSize = LiveOut.size();
2092     for (BasicBlock *Succ : successors(BB)) {
2093       assert(Data.LiveIn.count(Succ));
2094       set_union(LiveOut, Data.LiveIn[Succ]);
2095     }
2096     // assert OutLiveOut is a subset of LiveOut
2097     if (OldLiveOutSize == LiveOut.size()) {
2098       // If the sets are the same size, then we didn't actually add anything
2099       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2100       // hasn't changed.
2101       continue;
2102     }
2103     Data.LiveOut[BB] = LiveOut;
2104
2105     // Apply the effects of this basic block
2106     DenseSet<Value *> LiveTmp = LiveOut;
2107     set_union(LiveTmp, Data.LiveSet[BB]);
2108     set_subtract(LiveTmp, Data.KillSet[BB]);
2109
2110     assert(Data.LiveIn.count(BB));
2111     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2112     // assert: OldLiveIn is a subset of LiveTmp
2113     if (OldLiveIn.size() != LiveTmp.size()) {
2114       Data.LiveIn[BB] = LiveTmp;
2115       AddPredsToWorklist(BB);
2116     }
2117   } // while( !worklist.empty() )
2118
2119 #ifndef NDEBUG
2120   // Sanity check our ouput against SSA properties.  This helps catch any
2121   // missing kills during the above iteration.
2122   for (BasicBlock &BB : F) {
2123     checkBasicSSA(DT, Data, BB);
2124   }
2125 #endif
2126 }
2127
2128 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2129                               StatepointLiveSetTy &Out) {
2130
2131   BasicBlock *BB = Inst->getParent();
2132
2133   // Note: The copy is intentional and required
2134   assert(Data.LiveOut.count(BB));
2135   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2136
2137   // We want to handle the statepoint itself oddly.  It's
2138   // call result is not live (normal), nor are it's arguments
2139   // (unless they're used again later).  This adjustment is
2140   // specifically what we need to relocate
2141   BasicBlock::reverse_iterator rend(Inst);
2142   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2143   LiveOut.erase(Inst);
2144   Out.insert(LiveOut.begin(), LiveOut.end());
2145 }
2146
2147 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2148                                   const CallSite &CS,
2149                                   PartiallyConstructedSafepointRecord &Info) {
2150   Instruction *Inst = CS.getInstruction();
2151   StatepointLiveSetTy Updated;
2152   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2153
2154 #ifndef NDEBUG
2155   DenseSet<Value *> Bases;
2156   for (auto KVPair : Info.PointerToBase) {
2157     Bases.insert(KVPair.second);
2158   }
2159 #endif
2160   // We may have base pointers which are now live that weren't before.  We need
2161   // to update the PointerToBase structure to reflect this.
2162   for (auto V : Updated)
2163     if (!Info.PointerToBase.count(V)) {
2164       assert(Bases.count(V) && "can't find base for unexpected live value");
2165       Info.PointerToBase[V] = V;
2166       continue;
2167     }
2168
2169 #ifndef NDEBUG
2170   for (auto V : Updated) {
2171     assert(Info.PointerToBase.count(V) &&
2172            "must be able to find base for live value");
2173   }
2174 #endif
2175
2176   // Remove any stale base mappings - this can happen since our liveness is
2177   // more precise then the one inherent in the base pointer analysis
2178   DenseSet<Value *> ToErase;
2179   for (auto KVPair : Info.PointerToBase)
2180     if (!Updated.count(KVPair.first))
2181       ToErase.insert(KVPair.first);
2182   for (auto V : ToErase)
2183     Info.PointerToBase.erase(V);
2184
2185 #ifndef NDEBUG
2186   for (auto KVPair : Info.PointerToBase)
2187     assert(Updated.count(KVPair.first) && "record for non-live value");
2188 #endif
2189
2190   Info.liveset = Updated;
2191 }