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