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