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