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