[RewriteStatepointsForGC] Fix a bug on creating gc_relocate for pointer to vector...
[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     // All gc_relocate are set to i8 addrspace(1)* type. This could help avoid
1079     // cases where the actual value's type mangling is not supported by llvm. A
1080     // bitcast is added later to convert gc_relocate to the actual value's type.
1081     types.push_back(Type::getInt8PtrTy(M->getContext(), 1));
1082     Value *gc_relocate_decl = Intrinsic::getDeclaration(
1083         M, Intrinsic::experimental_gc_relocate, types);
1084
1085     // Generate the gc.relocate call and save the result
1086     Value *baseIdx =
1087         ConstantInt::get(Type::getInt32Ty(M->getContext()),
1088                          liveStart + find_index(liveVariables, basePtrs[i]));
1089     Value *liveIdx = ConstantInt::get(
1090         Type::getInt32Ty(M->getContext()),
1091         liveStart + find_index(liveVariables, liveVariables[i]));
1092
1093     // only specify a debug name if we can give a useful one
1094     Value *reloc = Builder.CreateCall3(
1095         gc_relocate_decl, statepointToken, baseIdx, liveIdx,
1096         liveVariables[i]->hasName() ? liveVariables[i]->getName() + ".relocated"
1097                                     : "");
1098     // Trick CodeGen into thinking there are lots of free registers at this
1099     // fake call.
1100     cast<CallInst>(reloc)->setCallingConv(CallingConv::Cold);
1101
1102     NewDefs.push_back(cast<Instruction>(reloc));
1103   }
1104   assert(NewDefs.size() == liveVariables.size() &&
1105          "missing or extra redefinition at safepoint");
1106 }
1107
1108 static void
1109 makeStatepointExplicitImpl(const CallSite &CS, /* to replace */
1110                            const SmallVectorImpl<llvm::Value *> &basePtrs,
1111                            const SmallVectorImpl<llvm::Value *> &liveVariables,
1112                            Pass *P,
1113                            PartiallyConstructedSafepointRecord &result) {
1114   assert(basePtrs.size() == liveVariables.size());
1115   assert(isStatepoint(CS) &&
1116          "This method expects to be rewriting a statepoint");
1117
1118   BasicBlock *BB = CS.getInstruction()->getParent();
1119   assert(BB);
1120   Function *F = BB->getParent();
1121   assert(F && "must be set");
1122   Module *M = F->getParent();
1123   (void)M;
1124   assert(M && "must be set");
1125
1126   // We're not changing the function signature of the statepoint since the gc
1127   // arguments go into the var args section.
1128   Function *gc_statepoint_decl = CS.getCalledFunction();
1129
1130   // Then go ahead and use the builder do actually do the inserts.  We insert
1131   // immediately before the previous instruction under the assumption that all
1132   // arguments will be available here.  We can't insert afterwards since we may
1133   // be replacing a terminator.
1134   Instruction *insertBefore = CS.getInstruction();
1135   IRBuilder<> Builder(insertBefore);
1136   // Copy all of the arguments from the original statepoint - this includes the
1137   // target, call args, and deopt args
1138   SmallVector<llvm::Value *, 64> args;
1139   args.insert(args.end(), CS.arg_begin(), CS.arg_end());
1140   // TODO: Clear the 'needs rewrite' flag
1141
1142   // add all the pointers to be relocated (gc arguments)
1143   // Capture the start of the live variable list for use in the gc_relocates
1144   const int live_start = args.size();
1145   args.insert(args.end(), liveVariables.begin(), liveVariables.end());
1146
1147   // Create the statepoint given all the arguments
1148   Instruction *token = nullptr;
1149   AttributeSet return_attributes;
1150   if (CS.isCall()) {
1151     CallInst *toReplace = cast<CallInst>(CS.getInstruction());
1152     CallInst *call =
1153         Builder.CreateCall(gc_statepoint_decl, args, "safepoint_token");
1154     call->setTailCall(toReplace->isTailCall());
1155     call->setCallingConv(toReplace->getCallingConv());
1156
1157     // Currently we will fail on parameter attributes and on certain
1158     // function attributes.
1159     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1160     // In case if we can handle this set of sttributes - set up function attrs
1161     // directly on statepoint and return attrs later for gc_result intrinsic.
1162     call->setAttributes(new_attrs.getFnAttributes());
1163     return_attributes = new_attrs.getRetAttributes();
1164
1165     token = call;
1166
1167     // Put the following gc_result and gc_relocate calls immediately after the
1168     // the old call (which we're about to delete)
1169     BasicBlock::iterator next(toReplace);
1170     assert(BB->end() != next && "not a terminator, must have next");
1171     next++;
1172     Instruction *IP = &*(next);
1173     Builder.SetInsertPoint(IP);
1174     Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1175
1176   } else {
1177     InvokeInst *toReplace = cast<InvokeInst>(CS.getInstruction());
1178
1179     // Insert the new invoke into the old block.  We'll remove the old one in a
1180     // moment at which point this will become the new terminator for the
1181     // original block.
1182     InvokeInst *invoke = InvokeInst::Create(
1183         gc_statepoint_decl, toReplace->getNormalDest(),
1184         toReplace->getUnwindDest(), args, "", toReplace->getParent());
1185     invoke->setCallingConv(toReplace->getCallingConv());
1186
1187     // Currently we will fail on parameter attributes and on certain
1188     // function attributes.
1189     AttributeSet new_attrs = legalizeCallAttributes(toReplace->getAttributes());
1190     // In case if we can handle this set of sttributes - set up function attrs
1191     // directly on statepoint and return attrs later for gc_result intrinsic.
1192     invoke->setAttributes(new_attrs.getFnAttributes());
1193     return_attributes = new_attrs.getRetAttributes();
1194
1195     token = invoke;
1196
1197     // Generate gc relocates in exceptional path
1198     BasicBlock *unwindBlock = toReplace->getUnwindDest();
1199     assert(!isa<PHINode>(unwindBlock->begin()) &&
1200            unwindBlock->getUniquePredecessor() &&
1201            "can't safely insert in this block!");
1202
1203     Instruction *IP = &*(unwindBlock->getFirstInsertionPt());
1204     Builder.SetInsertPoint(IP);
1205     Builder.SetCurrentDebugLocation(toReplace->getDebugLoc());
1206
1207     // Extract second element from landingpad return value. We will attach
1208     // exceptional gc relocates to it.
1209     const unsigned idx = 1;
1210     Instruction *exceptional_token =
1211         cast<Instruction>(Builder.CreateExtractValue(
1212             unwindBlock->getLandingPadInst(), idx, "relocate_token"));
1213     result.UnwindToken = exceptional_token;
1214
1215     // Just throw away return value. We will use the one we got for normal
1216     // block.
1217     (void)CreateGCRelocates(liveVariables, live_start, basePtrs,
1218                             exceptional_token, Builder);
1219
1220     // Generate gc relocates and returns for normal block
1221     BasicBlock *normalDest = toReplace->getNormalDest();
1222     assert(!isa<PHINode>(normalDest->begin()) &&
1223            normalDest->getUniquePredecessor() &&
1224            "can't safely insert in this block!");
1225
1226     IP = &*(normalDest->getFirstInsertionPt());
1227     Builder.SetInsertPoint(IP);
1228
1229     // gc relocates will be generated later as if it were regular call
1230     // statepoint
1231   }
1232   assert(token);
1233
1234   // Take the name of the original value call if it had one.
1235   token->takeName(CS.getInstruction());
1236
1237 // The GCResult is already inserted, we just need to find it
1238 #ifndef NDEBUG
1239   Instruction *toReplace = CS.getInstruction();
1240   assert((toReplace->hasNUses(0) || toReplace->hasNUses(1)) &&
1241          "only valid use before rewrite is gc.result");
1242   assert(!toReplace->hasOneUse() ||
1243          isGCResult(cast<Instruction>(*toReplace->user_begin())));
1244 #endif
1245
1246   // Update the gc.result of the original statepoint (if any) to use the newly
1247   // inserted statepoint.  This is safe to do here since the token can't be
1248   // considered a live reference.
1249   CS.getInstruction()->replaceAllUsesWith(token);
1250
1251   result.StatepointToken = token;
1252
1253   // Second, create a gc.relocate for every live variable
1254   CreateGCRelocates(liveVariables, live_start, basePtrs, token, Builder);
1255 }
1256
1257 namespace {
1258 struct name_ordering {
1259   Value *base;
1260   Value *derived;
1261   bool operator()(name_ordering const &a, name_ordering const &b) {
1262     return -1 == a.derived->getName().compare(b.derived->getName());
1263   }
1264 };
1265 }
1266 static void stablize_order(SmallVectorImpl<Value *> &basevec,
1267                            SmallVectorImpl<Value *> &livevec) {
1268   assert(basevec.size() == livevec.size());
1269
1270   SmallVector<name_ordering, 64> temp;
1271   for (size_t i = 0; i < basevec.size(); i++) {
1272     name_ordering v;
1273     v.base = basevec[i];
1274     v.derived = livevec[i];
1275     temp.push_back(v);
1276   }
1277   std::sort(temp.begin(), temp.end(), name_ordering());
1278   for (size_t i = 0; i < basevec.size(); i++) {
1279     basevec[i] = temp[i].base;
1280     livevec[i] = temp[i].derived;
1281   }
1282 }
1283
1284 // Replace an existing gc.statepoint with a new one and a set of gc.relocates
1285 // which make the relocations happening at this safepoint explicit.
1286 //
1287 // WARNING: Does not do any fixup to adjust users of the original live
1288 // values.  That's the callers responsibility.
1289 static void
1290 makeStatepointExplicit(DominatorTree &DT, const CallSite &CS, Pass *P,
1291                        PartiallyConstructedSafepointRecord &result) {
1292   auto liveset = result.liveset;
1293   auto PointerToBase = result.PointerToBase;
1294
1295   // Convert to vector for efficient cross referencing.
1296   SmallVector<Value *, 64> basevec, livevec;
1297   livevec.reserve(liveset.size());
1298   basevec.reserve(liveset.size());
1299   for (Value *L : liveset) {
1300     livevec.push_back(L);
1301
1302     assert(PointerToBase.find(L) != PointerToBase.end());
1303     Value *base = PointerToBase[L];
1304     basevec.push_back(base);
1305   }
1306   assert(livevec.size() == basevec.size());
1307
1308   // To make the output IR slightly more stable (for use in diffs), ensure a
1309   // fixed order of the values in the safepoint (by sorting the value name).
1310   // The order is otherwise meaningless.
1311   stablize_order(basevec, livevec);
1312
1313   // Do the actual rewriting and delete the old statepoint
1314   makeStatepointExplicitImpl(CS, basevec, livevec, P, result);
1315   CS.getInstruction()->eraseFromParent();
1316 }
1317
1318 // Helper function for the relocationViaAlloca.
1319 // It receives iterator to the statepoint gc relocates and emits store to the
1320 // assigned
1321 // location (via allocaMap) for the each one of them.
1322 // Add visited values into the visitedLiveValues set we will later use them
1323 // for sanity check.
1324 static void
1325 insertRelocationStores(iterator_range<Value::user_iterator> gcRelocs,
1326                        DenseMap<Value *, Value *> &allocaMap,
1327                        DenseSet<Value *> &visitedLiveValues) {
1328
1329   for (User *U : gcRelocs) {
1330     if (!isa<IntrinsicInst>(U))
1331       continue;
1332
1333     IntrinsicInst *relocatedValue = cast<IntrinsicInst>(U);
1334
1335     // We only care about relocates
1336     if (relocatedValue->getIntrinsicID() !=
1337         Intrinsic::experimental_gc_relocate) {
1338       continue;
1339     }
1340
1341     GCRelocateOperands relocateOperands(relocatedValue);
1342     Value *originalValue =
1343         const_cast<Value *>(relocateOperands.getDerivedPtr());
1344     assert(allocaMap.count(originalValue));
1345     Value *alloca = allocaMap[originalValue];
1346
1347     // Emit store into the related alloca
1348     // All gc_relocate are i8 addrspace(1)* typed, and it must be bitcasted to
1349     // the correct type according to alloca.
1350     assert(relocatedValue->getNextNode() && "Should always have one since it's not a terminator");
1351     IRBuilder<> Builder(relocatedValue->getNextNode());
1352     Value *CastedRelocatedValue =
1353         Builder.CreateBitCast(relocatedValue, cast<AllocaInst>(alloca)->getAllocatedType(),
1354         relocatedValue->hasName() ? relocatedValue->getName() + ".casted" : "");
1355
1356     StoreInst *store = new StoreInst(CastedRelocatedValue, alloca);
1357     store->insertAfter(cast<Instruction>(CastedRelocatedValue));
1358
1359 #ifndef NDEBUG
1360     visitedLiveValues.insert(originalValue);
1361 #endif
1362   }
1363 }
1364
1365 /// do all the relocation update via allocas and mem2reg
1366 static void relocationViaAlloca(
1367     Function &F, DominatorTree &DT, ArrayRef<Value *> live,
1368     ArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1369 #ifndef NDEBUG
1370   // record initial number of (static) allocas; we'll check we have the same
1371   // number when we get done.
1372   int InitialAllocaNum = 0;
1373   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1374        I++)
1375     if (isa<AllocaInst>(*I))
1376       InitialAllocaNum++;
1377 #endif
1378
1379   // TODO-PERF: change data structures, reserve
1380   DenseMap<Value *, Value *> allocaMap;
1381   SmallVector<AllocaInst *, 200> PromotableAllocas;
1382   PromotableAllocas.reserve(live.size());
1383
1384   // emit alloca for each live gc pointer
1385   for (unsigned i = 0; i < live.size(); i++) {
1386     Value *liveValue = live[i];
1387     AllocaInst *alloca = new AllocaInst(liveValue->getType(), "",
1388                                         F.getEntryBlock().getFirstNonPHI());
1389     allocaMap[liveValue] = alloca;
1390     PromotableAllocas.push_back(alloca);
1391   }
1392
1393   // The next two loops are part of the same conceptual operation.  We need to
1394   // insert a store to the alloca after the original def and at each
1395   // redefinition.  We need to insert a load before each use.  These are split
1396   // into distinct loops for performance reasons.
1397
1398   // update gc pointer after each statepoint
1399   // either store a relocated value or null (if no relocated value found for
1400   // this gc pointer and it is not a gc_result)
1401   // this must happen before we update the statepoint with load of alloca
1402   // otherwise we lose the link between statepoint and old def
1403   for (size_t i = 0; i < records.size(); i++) {
1404     const struct PartiallyConstructedSafepointRecord &info = records[i];
1405     Value *Statepoint = info.StatepointToken;
1406
1407     // This will be used for consistency check
1408     DenseSet<Value *> visitedLiveValues;
1409
1410     // Insert stores for normal statepoint gc relocates
1411     insertRelocationStores(Statepoint->users(), allocaMap, visitedLiveValues);
1412
1413     // In case if it was invoke statepoint
1414     // we will insert stores for exceptional path gc relocates.
1415     if (isa<InvokeInst>(Statepoint)) {
1416       insertRelocationStores(info.UnwindToken->users(), allocaMap,
1417                              visitedLiveValues);
1418     }
1419
1420     if (ClobberNonLive) {
1421       // As a debuging aid, pretend that an unrelocated pointer becomes null at
1422       // the gc.statepoint.  This will turn some subtle GC problems into
1423       // slightly easier to debug SEGVs.  Note that on large IR files with
1424       // lots of gc.statepoints this is extremely costly both memory and time
1425       // wise.
1426       SmallVector<AllocaInst *, 64> ToClobber;
1427       for (auto Pair : allocaMap) {
1428         Value *Def = Pair.first;
1429         AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1430
1431         // This value was relocated
1432         if (visitedLiveValues.count(Def)) {
1433           continue;
1434         }
1435         ToClobber.push_back(Alloca);
1436       }
1437
1438       auto InsertClobbersAt = [&](Instruction *IP) {
1439         for (auto *AI : ToClobber) {
1440           auto AIType = cast<PointerType>(AI->getType());
1441           auto PT = cast<PointerType>(AIType->getElementType());
1442           Constant *CPN = ConstantPointerNull::get(PT);
1443           StoreInst *store = new StoreInst(CPN, AI);
1444           store->insertBefore(IP);
1445         }
1446       };
1447
1448       // Insert the clobbering stores.  These may get intermixed with the
1449       // gc.results and gc.relocates, but that's fine.
1450       if (auto II = dyn_cast<InvokeInst>(Statepoint)) {
1451         InsertClobbersAt(II->getNormalDest()->getFirstInsertionPt());
1452         InsertClobbersAt(II->getUnwindDest()->getFirstInsertionPt());
1453       } else {
1454         BasicBlock::iterator Next(cast<CallInst>(Statepoint));
1455         Next++;
1456         InsertClobbersAt(Next);
1457       }
1458     }
1459   }
1460   // update use with load allocas and add store for gc_relocated
1461   for (auto Pair : allocaMap) {
1462     Value *def = Pair.first;
1463     Value *alloca = Pair.second;
1464
1465     // we pre-record the uses of allocas so that we dont have to worry about
1466     // later update
1467     // that change the user information.
1468     SmallVector<Instruction *, 20> uses;
1469     // PERF: trade a linear scan for repeated reallocation
1470     uses.reserve(std::distance(def->user_begin(), def->user_end()));
1471     for (User *U : def->users()) {
1472       if (!isa<ConstantExpr>(U)) {
1473         // If the def has a ConstantExpr use, then the def is either a
1474         // ConstantExpr use itself or null.  In either case
1475         // (recursively in the first, directly in the second), the oop
1476         // it is ultimately dependent on is null and this particular
1477         // use does not need to be fixed up.
1478         uses.push_back(cast<Instruction>(U));
1479       }
1480     }
1481
1482     std::sort(uses.begin(), uses.end());
1483     auto last = std::unique(uses.begin(), uses.end());
1484     uses.erase(last, uses.end());
1485
1486     for (Instruction *use : uses) {
1487       if (isa<PHINode>(use)) {
1488         PHINode *phi = cast<PHINode>(use);
1489         for (unsigned i = 0; i < phi->getNumIncomingValues(); i++) {
1490           if (def == phi->getIncomingValue(i)) {
1491             LoadInst *load = new LoadInst(
1492                 alloca, "", phi->getIncomingBlock(i)->getTerminator());
1493             phi->setIncomingValue(i, load);
1494           }
1495         }
1496       } else {
1497         LoadInst *load = new LoadInst(alloca, "", use);
1498         use->replaceUsesOfWith(def, load);
1499       }
1500     }
1501
1502     // emit store for the initial gc value
1503     // store must be inserted after load, otherwise store will be in alloca's
1504     // use list and an extra load will be inserted before it
1505     StoreInst *store = new StoreInst(def, alloca);
1506     if (Instruction *inst = dyn_cast<Instruction>(def)) {
1507       if (InvokeInst *invoke = dyn_cast<InvokeInst>(inst)) {
1508         // InvokeInst is a TerminatorInst so the store need to be inserted
1509         // into its normal destination block.
1510         BasicBlock *normalDest = invoke->getNormalDest();
1511         store->insertBefore(normalDest->getFirstNonPHI());
1512       } else {
1513         assert(!inst->isTerminator() &&
1514                "The only TerminatorInst that can produce a value is "
1515                "InvokeInst which is handled above.");
1516         store->insertAfter(inst);
1517       }
1518     } else {
1519       assert(isa<Argument>(def));
1520       store->insertAfter(cast<Instruction>(alloca));
1521     }
1522   }
1523
1524   assert(PromotableAllocas.size() == live.size() &&
1525          "we must have the same allocas with lives");
1526   if (!PromotableAllocas.empty()) {
1527     // apply mem2reg to promote alloca to SSA
1528     PromoteMemToReg(PromotableAllocas, DT);
1529   }
1530
1531 #ifndef NDEBUG
1532   for (auto I = F.getEntryBlock().begin(), E = F.getEntryBlock().end(); I != E;
1533        I++)
1534     if (isa<AllocaInst>(*I))
1535       InitialAllocaNum--;
1536   assert(InitialAllocaNum == 0 && "We must not introduce any extra allocas");
1537 #endif
1538 }
1539
1540 /// Implement a unique function which doesn't require we sort the input
1541 /// vector.  Doing so has the effect of changing the output of a couple of
1542 /// tests in ways which make them less useful in testing fused safepoints.
1543 template <typename T> static void unique_unsorted(SmallVectorImpl<T> &Vec) {
1544   DenseSet<T> Seen;
1545   SmallVector<T, 128> TempVec;
1546   TempVec.reserve(Vec.size());
1547   for (auto Element : Vec)
1548     TempVec.push_back(Element);
1549   Vec.clear();
1550   for (auto V : TempVec) {
1551     if (Seen.insert(V).second) {
1552       Vec.push_back(V);
1553     }
1554   }
1555 }
1556
1557 /// Insert holders so that each Value is obviously live through the entire
1558 /// lifetime of the call.
1559 static void insertUseHolderAfter(CallSite &CS, const ArrayRef<Value *> Values,
1560                                  SmallVectorImpl<CallInst *> &Holders) {
1561   if (Values.empty())
1562     // No values to hold live, might as well not insert the empty holder
1563     return;
1564
1565   Module *M = CS.getInstruction()->getParent()->getParent()->getParent();
1566   // Use a dummy vararg function to actually hold the values live
1567   Function *Func = cast<Function>(M->getOrInsertFunction(
1568       "__tmp_use", FunctionType::get(Type::getVoidTy(M->getContext()), true)));
1569   if (CS.isCall()) {
1570     // For call safepoints insert dummy calls right after safepoint
1571     BasicBlock::iterator Next(CS.getInstruction());
1572     Next++;
1573     Holders.push_back(CallInst::Create(Func, Values, "", Next));
1574     return;
1575   }
1576   // For invoke safepooints insert dummy calls both in normal and
1577   // exceptional destination blocks
1578   auto *II = cast<InvokeInst>(CS.getInstruction());
1579   Holders.push_back(CallInst::Create(
1580       Func, Values, "", II->getNormalDest()->getFirstInsertionPt()));
1581   Holders.push_back(CallInst::Create(
1582       Func, Values, "", II->getUnwindDest()->getFirstInsertionPt()));
1583 }
1584
1585 static void findLiveReferences(
1586     Function &F, DominatorTree &DT, Pass *P, ArrayRef<CallSite> toUpdate,
1587     MutableArrayRef<struct PartiallyConstructedSafepointRecord> records) {
1588   GCPtrLivenessData OriginalLivenessData;
1589   computeLiveInValues(DT, F, OriginalLivenessData);
1590   for (size_t i = 0; i < records.size(); i++) {
1591     struct PartiallyConstructedSafepointRecord &info = records[i];
1592     const CallSite &CS = toUpdate[i];
1593     analyzeParsePointLiveness(DT, OriginalLivenessData, CS, info);
1594   }
1595 }
1596
1597 /// Remove any vector of pointers from the liveset by scalarizing them over the
1598 /// statepoint instruction.  Adds the scalarized pieces to the liveset.  It
1599 /// would be preferrable to include the vector in the statepoint itself, but
1600 /// the lowering code currently does not handle that.  Extending it would be
1601 /// slightly non-trivial since it requires a format change.  Given how rare
1602 /// such cases are (for the moment?) scalarizing is an acceptable comprimise.
1603 static void splitVectorValues(Instruction *StatepointInst,
1604                               StatepointLiveSetTy &LiveSet, DominatorTree &DT) {
1605   SmallVector<Value *, 16> ToSplit;
1606   for (Value *V : LiveSet)
1607     if (isa<VectorType>(V->getType()))
1608       ToSplit.push_back(V);
1609
1610   if (ToSplit.empty())
1611     return;
1612
1613   Function &F = *(StatepointInst->getParent()->getParent());
1614
1615   DenseMap<Value *, AllocaInst *> AllocaMap;
1616   // First is normal return, second is exceptional return (invoke only)
1617   DenseMap<Value *, std::pair<Value *, Value *>> Replacements;
1618   for (Value *V : ToSplit) {
1619     LiveSet.erase(V);
1620
1621     AllocaInst *Alloca =
1622         new AllocaInst(V->getType(), "", F.getEntryBlock().getFirstNonPHI());
1623     AllocaMap[V] = Alloca;
1624
1625     VectorType *VT = cast<VectorType>(V->getType());
1626     IRBuilder<> Builder(StatepointInst);
1627     SmallVector<Value *, 16> Elements;
1628     for (unsigned i = 0; i < VT->getNumElements(); i++)
1629       Elements.push_back(Builder.CreateExtractElement(V, Builder.getInt32(i)));
1630     LiveSet.insert(Elements.begin(), Elements.end());
1631
1632     auto InsertVectorReform = [&](Instruction *IP) {
1633       Builder.SetInsertPoint(IP);
1634       Builder.SetCurrentDebugLocation(IP->getDebugLoc());
1635       Value *ResultVec = UndefValue::get(VT);
1636       for (unsigned i = 0; i < VT->getNumElements(); i++)
1637         ResultVec = Builder.CreateInsertElement(ResultVec, Elements[i],
1638                                                 Builder.getInt32(i));
1639       return ResultVec;
1640     };
1641
1642     if (isa<CallInst>(StatepointInst)) {
1643       BasicBlock::iterator Next(StatepointInst);
1644       Next++;
1645       Instruction *IP = &*(Next);
1646       Replacements[V].first = InsertVectorReform(IP);
1647       Replacements[V].second = nullptr;
1648     } else {
1649       InvokeInst *Invoke = cast<InvokeInst>(StatepointInst);
1650       // We've already normalized - check that we don't have shared destination
1651       // blocks
1652       BasicBlock *NormalDest = Invoke->getNormalDest();
1653       assert(!isa<PHINode>(NormalDest->begin()));
1654       BasicBlock *UnwindDest = Invoke->getUnwindDest();
1655       assert(!isa<PHINode>(UnwindDest->begin()));
1656       // Insert insert element sequences in both successors
1657       Instruction *IP = &*(NormalDest->getFirstInsertionPt());
1658       Replacements[V].first = InsertVectorReform(IP);
1659       IP = &*(UnwindDest->getFirstInsertionPt());
1660       Replacements[V].second = InsertVectorReform(IP);
1661     }
1662   }
1663   for (Value *V : ToSplit) {
1664     AllocaInst *Alloca = AllocaMap[V];
1665
1666     // Capture all users before we start mutating use lists
1667     SmallVector<Instruction *, 16> Users;
1668     for (User *U : V->users())
1669       Users.push_back(cast<Instruction>(U));
1670
1671     for (Instruction *I : Users) {
1672       if (auto Phi = dyn_cast<PHINode>(I)) {
1673         for (unsigned i = 0; i < Phi->getNumIncomingValues(); i++)
1674           if (V == Phi->getIncomingValue(i)) {
1675             LoadInst *Load = new LoadInst(
1676                 Alloca, "", Phi->getIncomingBlock(i)->getTerminator());
1677             Phi->setIncomingValue(i, Load);
1678           }
1679       } else {
1680         LoadInst *Load = new LoadInst(Alloca, "", I);
1681         I->replaceUsesOfWith(V, Load);
1682       }
1683     }
1684
1685     // Store the original value and the replacement value into the alloca
1686     StoreInst *Store = new StoreInst(V, Alloca);
1687     if (auto I = dyn_cast<Instruction>(V))
1688       Store->insertAfter(I);
1689     else
1690       Store->insertAfter(Alloca);
1691
1692     // Normal return for invoke, or call return
1693     Instruction *Replacement = cast<Instruction>(Replacements[V].first);
1694     (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1695     // Unwind return for invoke only
1696     Replacement = cast_or_null<Instruction>(Replacements[V].second);
1697     if (Replacement)
1698       (new StoreInst(Replacement, Alloca))->insertAfter(Replacement);
1699   }
1700
1701   // apply mem2reg to promote alloca to SSA
1702   SmallVector<AllocaInst *, 16> Allocas;
1703   for (Value *V : ToSplit)
1704     Allocas.push_back(AllocaMap[V]);
1705   PromoteMemToReg(Allocas, DT);
1706 }
1707
1708 static bool insertParsePoints(Function &F, DominatorTree &DT, Pass *P,
1709                               SmallVectorImpl<CallSite> &toUpdate) {
1710 #ifndef NDEBUG
1711   // sanity check the input
1712   std::set<CallSite> uniqued;
1713   uniqued.insert(toUpdate.begin(), toUpdate.end());
1714   assert(uniqued.size() == toUpdate.size() && "no duplicates please!");
1715
1716   for (size_t i = 0; i < toUpdate.size(); i++) {
1717     CallSite &CS = toUpdate[i];
1718     assert(CS.getInstruction()->getParent()->getParent() == &F);
1719     assert(isStatepoint(CS) && "expected to already be a deopt statepoint");
1720   }
1721 #endif
1722
1723   // When inserting gc.relocates for invokes, we need to be able to insert at
1724   // the top of the successor blocks.  See the comment on
1725   // normalForInvokeSafepoint on exactly what is needed.  Note that this step
1726   // may restructure the CFG.
1727   for (CallSite CS : toUpdate) {
1728     if (!CS.isInvoke())
1729       continue;
1730     InvokeInst *invoke = cast<InvokeInst>(CS.getInstruction());
1731     normalizeForInvokeSafepoint(invoke->getNormalDest(), invoke->getParent(),
1732                                 P);
1733     normalizeForInvokeSafepoint(invoke->getUnwindDest(), invoke->getParent(),
1734                                 P);
1735   }
1736
1737   // A list of dummy calls added to the IR to keep various values obviously
1738   // live in the IR.  We'll remove all of these when done.
1739   SmallVector<CallInst *, 64> holders;
1740
1741   // Insert a dummy call with all of the arguments to the vm_state we'll need
1742   // for the actual safepoint insertion.  This ensures reference arguments in
1743   // the deopt argument list are considered live through the safepoint (and
1744   // thus makes sure they get relocated.)
1745   for (size_t i = 0; i < toUpdate.size(); i++) {
1746     CallSite &CS = toUpdate[i];
1747     Statepoint StatepointCS(CS);
1748
1749     SmallVector<Value *, 64> DeoptValues;
1750     for (Use &U : StatepointCS.vm_state_args()) {
1751       Value *Arg = cast<Value>(&U);
1752       assert(!isUnhandledGCPointerType(Arg->getType()) &&
1753              "support for FCA unimplemented");
1754       if (isHandledGCPointerType(Arg->getType()))
1755         DeoptValues.push_back(Arg);
1756     }
1757     insertUseHolderAfter(CS, DeoptValues, holders);
1758   }
1759
1760   SmallVector<struct PartiallyConstructedSafepointRecord, 64> records;
1761   records.reserve(toUpdate.size());
1762   for (size_t i = 0; i < toUpdate.size(); i++) {
1763     struct PartiallyConstructedSafepointRecord info;
1764     records.push_back(info);
1765   }
1766   assert(records.size() == toUpdate.size());
1767
1768   // A) Identify all gc pointers which are staticly live at the given call
1769   // site.
1770   findLiveReferences(F, DT, P, toUpdate, records);
1771
1772   // Do a limited scalarization of any live at safepoint vector values which
1773   // contain pointers.  This enables this pass to run after vectorization at
1774   // the cost of some possible performance loss.  TODO: it would be nice to
1775   // natively support vectors all the way through the backend so we don't need
1776   // to scalarize here.
1777   for (size_t i = 0; i < records.size(); i++) {
1778     struct PartiallyConstructedSafepointRecord &info = records[i];
1779     Instruction *statepoint = toUpdate[i].getInstruction();
1780     splitVectorValues(cast<Instruction>(statepoint), info.liveset, DT);
1781   }
1782
1783   // B) Find the base pointers for each live pointer
1784   /* scope for caching */ {
1785     // Cache the 'defining value' relation used in the computation and
1786     // insertion of base phis and selects.  This ensures that we don't insert
1787     // large numbers of duplicate base_phis.
1788     DefiningValueMapTy DVCache;
1789
1790     for (size_t i = 0; i < records.size(); i++) {
1791       struct PartiallyConstructedSafepointRecord &info = records[i];
1792       CallSite &CS = toUpdate[i];
1793       findBasePointers(DT, DVCache, CS, info);
1794     }
1795   } // end of cache scope
1796
1797   // The base phi insertion logic (for any safepoint) may have inserted new
1798   // instructions which are now live at some safepoint.  The simplest such
1799   // example is:
1800   // loop:
1801   //   phi a  <-- will be a new base_phi here
1802   //   safepoint 1 <-- that needs to be live here
1803   //   gep a + 1
1804   //   safepoint 2
1805   //   br loop
1806   // We insert some dummy calls after each safepoint to definitely hold live
1807   // the base pointers which were identified for that safepoint.  We'll then
1808   // ask liveness for _every_ base inserted to see what is now live.  Then we
1809   // remove the dummy calls.
1810   holders.reserve(holders.size() + records.size());
1811   for (size_t i = 0; i < records.size(); i++) {
1812     struct PartiallyConstructedSafepointRecord &info = records[i];
1813     CallSite &CS = toUpdate[i];
1814
1815     SmallVector<Value *, 128> Bases;
1816     for (auto Pair : info.PointerToBase) {
1817       Bases.push_back(Pair.second);
1818     }
1819     insertUseHolderAfter(CS, Bases, holders);
1820   }
1821
1822   // By selecting base pointers, we've effectively inserted new uses. Thus, we
1823   // need to rerun liveness.  We may *also* have inserted new defs, but that's
1824   // not the key issue.
1825   recomputeLiveInValues(F, DT, P, toUpdate, records);
1826
1827   if (PrintBasePointers) {
1828     for (size_t i = 0; i < records.size(); i++) {
1829       struct PartiallyConstructedSafepointRecord &info = records[i];
1830       errs() << "Base Pairs: (w/Relocation)\n";
1831       for (auto Pair : info.PointerToBase) {
1832         errs() << " derived %" << Pair.first->getName() << " base %"
1833                << Pair.second->getName() << "\n";
1834       }
1835     }
1836   }
1837   for (size_t i = 0; i < holders.size(); i++) {
1838     holders[i]->eraseFromParent();
1839     holders[i] = nullptr;
1840   }
1841   holders.clear();
1842
1843   // Now run through and replace the existing statepoints with new ones with
1844   // the live variables listed.  We do not yet update uses of the values being
1845   // relocated. We have references to live variables that need to
1846   // survive to the last iteration of this loop.  (By construction, the
1847   // previous statepoint can not be a live variable, thus we can and remove
1848   // the old statepoint calls as we go.)
1849   for (size_t i = 0; i < records.size(); i++) {
1850     struct PartiallyConstructedSafepointRecord &info = records[i];
1851     CallSite &CS = toUpdate[i];
1852     makeStatepointExplicit(DT, CS, P, info);
1853   }
1854   toUpdate.clear(); // prevent accident use of invalid CallSites
1855
1856   // Do all the fixups of the original live variables to their relocated selves
1857   SmallVector<Value *, 128> live;
1858   for (size_t i = 0; i < records.size(); i++) {
1859     struct PartiallyConstructedSafepointRecord &info = records[i];
1860     // We can't simply save the live set from the original insertion.  One of
1861     // the live values might be the result of a call which needs a safepoint.
1862     // That Value* no longer exists and we need to use the new gc_result.
1863     // Thankfully, the liveset is embedded in the statepoint (and updated), so
1864     // we just grab that.
1865     Statepoint statepoint(info.StatepointToken);
1866     live.insert(live.end(), statepoint.gc_args_begin(),
1867                 statepoint.gc_args_end());
1868 #ifndef NDEBUG
1869     // Do some basic sanity checks on our liveness results before performing
1870     // relocation.  Relocation can and will turn mistakes in liveness results
1871     // into non-sensical code which is must harder to debug.
1872     // TODO: It would be nice to test consistency as well
1873     assert(DT.isReachableFromEntry(info.StatepointToken->getParent()) &&
1874            "statepoint must be reachable or liveness is meaningless");
1875     for (Value *V : statepoint.gc_args()) {
1876       if (!isa<Instruction>(V))
1877         // Non-instruction values trivial dominate all possible uses
1878         continue;
1879       auto LiveInst = cast<Instruction>(V);
1880       assert(DT.isReachableFromEntry(LiveInst->getParent()) &&
1881              "unreachable values should never be live");
1882       assert(DT.dominates(LiveInst, info.StatepointToken) &&
1883              "basic SSA liveness expectation violated by liveness analysis");
1884     }
1885 #endif
1886   }
1887   unique_unsorted(live);
1888
1889 #ifndef NDEBUG
1890   // sanity check
1891   for (auto ptr : live) {
1892     assert(isGCPointerType(ptr->getType()) && "must be a gc pointer type");
1893   }
1894 #endif
1895
1896   relocationViaAlloca(F, DT, live, records);
1897   return !records.empty();
1898 }
1899
1900 /// Returns true if this function should be rewritten by this pass.  The main
1901 /// point of this function is as an extension point for custom logic.
1902 static bool shouldRewriteStatepointsIn(Function &F) {
1903   // TODO: This should check the GCStrategy
1904   if (F.hasGC()) {
1905     const std::string StatepointExampleName("statepoint-example");
1906     return StatepointExampleName == F.getGC();
1907   } else
1908     return false;
1909 }
1910
1911 bool RewriteStatepointsForGC::runOnFunction(Function &F) {
1912   // Nothing to do for declarations.
1913   if (F.isDeclaration() || F.empty())
1914     return false;
1915
1916   // Policy choice says not to rewrite - the most common reason is that we're
1917   // compiling code without a GCStrategy.
1918   if (!shouldRewriteStatepointsIn(F))
1919     return false;
1920
1921   DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1922
1923   // Gather all the statepoints which need rewritten.  Be careful to only
1924   // consider those in reachable code since we need to ask dominance queries
1925   // when rewriting.  We'll delete the unreachable ones in a moment.
1926   SmallVector<CallSite, 64> ParsePointNeeded;
1927   bool HasUnreachableStatepoint = false;
1928   for (Instruction &I : inst_range(F)) {
1929     // TODO: only the ones with the flag set!
1930     if (isStatepoint(I)) {
1931       if (DT.isReachableFromEntry(I.getParent()))
1932         ParsePointNeeded.push_back(CallSite(&I));
1933       else
1934         HasUnreachableStatepoint = true;
1935     }
1936   }
1937
1938   bool MadeChange = false;
1939
1940   // Delete any unreachable statepoints so that we don't have unrewritten
1941   // statepoints surviving this pass.  This makes testing easier and the
1942   // resulting IR less confusing to human readers.  Rather than be fancy, we
1943   // just reuse a utility function which removes the unreachable blocks.
1944   if (HasUnreachableStatepoint)
1945     MadeChange |= removeUnreachableBlocks(F);
1946
1947   // Return early if no work to do.
1948   if (ParsePointNeeded.empty())
1949     return MadeChange;
1950
1951   // As a prepass, go ahead and aggressively destroy single entry phi nodes.
1952   // These are created by LCSSA.  They have the effect of increasing the size
1953   // of liveness sets for no good reason.  It may be harder to do this post
1954   // insertion since relocations and base phis can confuse things.
1955   for (BasicBlock &BB : F)
1956     if (BB.getUniquePredecessor()) {
1957       MadeChange = true;
1958       FoldSingleEntryPHINodes(&BB);
1959     }
1960
1961   MadeChange |= insertParsePoints(F, DT, this, ParsePointNeeded);
1962   return MadeChange;
1963 }
1964
1965 // liveness computation via standard dataflow
1966 // -------------------------------------------------------------------
1967
1968 // TODO: Consider using bitvectors for liveness, the set of potentially
1969 // interesting values should be small and easy to pre-compute.
1970
1971 /// Compute the live-in set for the location rbegin starting from
1972 /// the live-out set of the basic block
1973 static void computeLiveInValues(BasicBlock::reverse_iterator rbegin,
1974                                 BasicBlock::reverse_iterator rend,
1975                                 DenseSet<Value *> &LiveTmp) {
1976
1977   for (BasicBlock::reverse_iterator ritr = rbegin; ritr != rend; ritr++) {
1978     Instruction *I = &*ritr;
1979
1980     // KILL/Def - Remove this definition from LiveIn
1981     LiveTmp.erase(I);
1982
1983     // Don't consider *uses* in PHI nodes, we handle their contribution to
1984     // predecessor blocks when we seed the LiveOut sets
1985     if (isa<PHINode>(I))
1986       continue;
1987
1988     // USE - Add to the LiveIn set for this instruction
1989     for (Value *V : I->operands()) {
1990       assert(!isUnhandledGCPointerType(V->getType()) &&
1991              "support for FCA unimplemented");
1992       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
1993         // The choice to exclude all things constant here is slightly subtle.
1994         // There are two idependent reasons:
1995         // - We assume that things which are constant (from LLVM's definition)
1996         // do not move at runtime.  For example, the address of a global
1997         // variable is fixed, even though it's contents may not be.
1998         // - Second, we can't disallow arbitrary inttoptr constants even
1999         // if the language frontend does.  Optimization passes are free to
2000         // locally exploit facts without respect to global reachability.  This
2001         // can create sections of code which are dynamically unreachable and
2002         // contain just about anything.  (see constants.ll in tests)
2003         LiveTmp.insert(V);
2004       }
2005     }
2006   }
2007 }
2008
2009 static void computeLiveOutSeed(BasicBlock *BB, DenseSet<Value *> &LiveTmp) {
2010
2011   for (BasicBlock *Succ : successors(BB)) {
2012     const BasicBlock::iterator E(Succ->getFirstNonPHI());
2013     for (BasicBlock::iterator I = Succ->begin(); I != E; I++) {
2014       PHINode *Phi = cast<PHINode>(&*I);
2015       Value *V = Phi->getIncomingValueForBlock(BB);
2016       assert(!isUnhandledGCPointerType(V->getType()) &&
2017              "support for FCA unimplemented");
2018       if (isHandledGCPointerType(V->getType()) && !isa<Constant>(V)) {
2019         LiveTmp.insert(V);
2020       }
2021     }
2022   }
2023 }
2024
2025 static DenseSet<Value *> computeKillSet(BasicBlock *BB) {
2026   DenseSet<Value *> KillSet;
2027   for (Instruction &I : *BB)
2028     if (isHandledGCPointerType(I.getType()))
2029       KillSet.insert(&I);
2030   return KillSet;
2031 }
2032
2033 #ifndef NDEBUG
2034 /// Check that the items in 'Live' dominate 'TI'.  This is used as a basic
2035 /// sanity check for the liveness computation.
2036 static void checkBasicSSA(DominatorTree &DT, DenseSet<Value *> &Live,
2037                           TerminatorInst *TI, bool TermOkay = false) {
2038   for (Value *V : Live) {
2039     if (auto *I = dyn_cast<Instruction>(V)) {
2040       // The terminator can be a member of the LiveOut set.  LLVM's definition
2041       // of instruction dominance states that V does not dominate itself.  As
2042       // such, we need to special case this to allow it.
2043       if (TermOkay && TI == I)
2044         continue;
2045       assert(DT.dominates(I, TI) &&
2046              "basic SSA liveness expectation violated by liveness analysis");
2047     }
2048   }
2049 }
2050
2051 /// Check that all the liveness sets used during the computation of liveness
2052 /// obey basic SSA properties.  This is useful for finding cases where we miss
2053 /// a def.
2054 static void checkBasicSSA(DominatorTree &DT, GCPtrLivenessData &Data,
2055                           BasicBlock &BB) {
2056   checkBasicSSA(DT, Data.LiveSet[&BB], BB.getTerminator());
2057   checkBasicSSA(DT, Data.LiveOut[&BB], BB.getTerminator(), true);
2058   checkBasicSSA(DT, Data.LiveIn[&BB], BB.getTerminator());
2059 }
2060 #endif
2061
2062 static void computeLiveInValues(DominatorTree &DT, Function &F,
2063                                 GCPtrLivenessData &Data) {
2064
2065   SmallSetVector<BasicBlock *, 200> Worklist;
2066   auto AddPredsToWorklist = [&](BasicBlock *BB) {
2067     // We use a SetVector so that we don't have duplicates in the worklist.
2068     Worklist.insert(pred_begin(BB), pred_end(BB));
2069   };
2070   auto NextItem = [&]() {
2071     BasicBlock *BB = Worklist.back();
2072     Worklist.pop_back();
2073     return BB;
2074   };
2075
2076   // Seed the liveness for each individual block
2077   for (BasicBlock &BB : F) {
2078     Data.KillSet[&BB] = computeKillSet(&BB);
2079     Data.LiveSet[&BB].clear();
2080     computeLiveInValues(BB.rbegin(), BB.rend(), Data.LiveSet[&BB]);
2081
2082 #ifndef NDEBUG
2083     for (Value *Kill : Data.KillSet[&BB])
2084       assert(!Data.LiveSet[&BB].count(Kill) && "live set contains kill");
2085 #endif
2086
2087     Data.LiveOut[&BB] = DenseSet<Value *>();
2088     computeLiveOutSeed(&BB, Data.LiveOut[&BB]);
2089     Data.LiveIn[&BB] = Data.LiveSet[&BB];
2090     set_union(Data.LiveIn[&BB], Data.LiveOut[&BB]);
2091     set_subtract(Data.LiveIn[&BB], Data.KillSet[&BB]);
2092     if (!Data.LiveIn[&BB].empty())
2093       AddPredsToWorklist(&BB);
2094   }
2095
2096   // Propagate that liveness until stable
2097   while (!Worklist.empty()) {
2098     BasicBlock *BB = NextItem();
2099
2100     // Compute our new liveout set, then exit early if it hasn't changed
2101     // despite the contribution of our successor.
2102     DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2103     const auto OldLiveOutSize = LiveOut.size();
2104     for (BasicBlock *Succ : successors(BB)) {
2105       assert(Data.LiveIn.count(Succ));
2106       set_union(LiveOut, Data.LiveIn[Succ]);
2107     }
2108     // assert OutLiveOut is a subset of LiveOut
2109     if (OldLiveOutSize == LiveOut.size()) {
2110       // If the sets are the same size, then we didn't actually add anything
2111       // when unioning our successors LiveIn  Thus, the LiveIn of this block
2112       // hasn't changed.
2113       continue;
2114     }
2115     Data.LiveOut[BB] = LiveOut;
2116
2117     // Apply the effects of this basic block
2118     DenseSet<Value *> LiveTmp = LiveOut;
2119     set_union(LiveTmp, Data.LiveSet[BB]);
2120     set_subtract(LiveTmp, Data.KillSet[BB]);
2121
2122     assert(Data.LiveIn.count(BB));
2123     const DenseSet<Value *> &OldLiveIn = Data.LiveIn[BB];
2124     // assert: OldLiveIn is a subset of LiveTmp
2125     if (OldLiveIn.size() != LiveTmp.size()) {
2126       Data.LiveIn[BB] = LiveTmp;
2127       AddPredsToWorklist(BB);
2128     }
2129   } // while( !worklist.empty() )
2130
2131 #ifndef NDEBUG
2132   // Sanity check our ouput against SSA properties.  This helps catch any
2133   // missing kills during the above iteration.
2134   for (BasicBlock &BB : F) {
2135     checkBasicSSA(DT, Data, BB);
2136   }
2137 #endif
2138 }
2139
2140 static void findLiveSetAtInst(Instruction *Inst, GCPtrLivenessData &Data,
2141                               StatepointLiveSetTy &Out) {
2142
2143   BasicBlock *BB = Inst->getParent();
2144
2145   // Note: The copy is intentional and required
2146   assert(Data.LiveOut.count(BB));
2147   DenseSet<Value *> LiveOut = Data.LiveOut[BB];
2148
2149   // We want to handle the statepoint itself oddly.  It's
2150   // call result is not live (normal), nor are it's arguments
2151   // (unless they're used again later).  This adjustment is
2152   // specifically what we need to relocate
2153   BasicBlock::reverse_iterator rend(Inst);
2154   computeLiveInValues(BB->rbegin(), rend, LiveOut);
2155   LiveOut.erase(Inst);
2156   Out.insert(LiveOut.begin(), LiveOut.end());
2157 }
2158
2159 static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData,
2160                                   const CallSite &CS,
2161                                   PartiallyConstructedSafepointRecord &Info) {
2162   Instruction *Inst = CS.getInstruction();
2163   StatepointLiveSetTy Updated;
2164   findLiveSetAtInst(Inst, RevisedLivenessData, Updated);
2165
2166 #ifndef NDEBUG
2167   DenseSet<Value *> Bases;
2168   for (auto KVPair : Info.PointerToBase) {
2169     Bases.insert(KVPair.second);
2170   }
2171 #endif
2172   // We may have base pointers which are now live that weren't before.  We need
2173   // to update the PointerToBase structure to reflect this.
2174   for (auto V : Updated)
2175     if (!Info.PointerToBase.count(V)) {
2176       assert(Bases.count(V) && "can't find base for unexpected live value");
2177       Info.PointerToBase[V] = V;
2178       continue;
2179     }
2180
2181 #ifndef NDEBUG
2182   for (auto V : Updated) {
2183     assert(Info.PointerToBase.count(V) &&
2184            "must be able to find base for live value");
2185   }
2186 #endif
2187
2188   // Remove any stale base mappings - this can happen since our liveness is
2189   // more precise then the one inherent in the base pointer analysis
2190   DenseSet<Value *> ToErase;
2191   for (auto KVPair : Info.PointerToBase)
2192     if (!Updated.count(KVPair.first))
2193       ToErase.insert(KVPair.first);
2194   for (auto V : ToErase)
2195     Info.PointerToBase.erase(V);
2196
2197 #ifndef NDEBUG
2198   for (auto KVPair : Info.PointerToBase)
2199     assert(Updated.count(KVPair.first) && "record for non-live value");
2200 #endif
2201
2202   Info.liveset = Updated;
2203 }