1 //===-- StatepointLowering.cpp - SDAGBuilder's statepoint code -----------===//
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 // This file includes support code use by SelectionDAGBuilder when lowering a
11 // statepoint sequence in SelectionDAG IR.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "StatepointLowering.h"
16 #include "SelectionDAGBuilder.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/FunctionLoweringInfo.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/GCMetadata.h"
22 #include "llvm/CodeGen/GCStrategy.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/StackMaps.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/Statepoint.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include <algorithm>
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "statepoint-lowering"
35 
36 STATISTIC(NumSlotsAllocatedForStatepoints,
37           "Number of stack slots allocated for statepoints");
38 STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
39 STATISTIC(StatepointMaxSlotsRequired,
40           "Maximum number of stack slots required for a singe statepoint");
41 
42 static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
43                                  SelectionDAGBuilder &Builder, uint64_t Value) {
44   SDLoc L = Builder.getCurSDLoc();
45   Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
46                                               MVT::i64));
47   Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
48 }
49 
50 void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
51   // Consistency check
52   assert(PendingGCRelocateCalls.empty() &&
53          "Trying to visit statepoint before finished processing previous one");
54   Locations.clear();
55   NextSlotToAllocate = 0;
56   // Need to resize this on each safepoint - we need the two to stay in sync and
57   // the clear patterns of a SelectionDAGBuilder have no relation to
58   // FunctionLoweringInfo.  SmallBitVector::reset initializes all bits to false.
59   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
60 }
61 
62 void StatepointLoweringState::clear() {
63   Locations.clear();
64   AllocatedStackSlots.clear();
65   assert(PendingGCRelocateCalls.empty() &&
66          "cleared before statepoint sequence completed");
67 }
68 
69 SDValue
70 StatepointLoweringState::allocateStackSlot(EVT ValueType,
71                                            SelectionDAGBuilder &Builder) {
72   NumSlotsAllocatedForStatepoints++;
73   MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
74 
75   unsigned SpillSize = ValueType.getSizeInBits() / 8;
76   assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?");
77 
78   // First look for a previously created stack slot which is not in
79   // use (accounting for the fact arbitrary slots may already be
80   // reserved), or to create a new stack slot and use it.
81 
82   const size_t NumSlots = AllocatedStackSlots.size();
83   assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
84 
85   // The stack slots in StatepointStackSlots beyond the first NumSlots were
86   // added in this instance of StatepointLoweringState, and cannot be re-used.
87   assert(NumSlots <= Builder.FuncInfo.StatepointStackSlots.size() &&
88          "Broken invariant");
89 
90   for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
91     if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
92       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
93       if (MFI.getObjectSize(FI) == SpillSize) {
94         AllocatedStackSlots.set(NextSlotToAllocate);
95         return Builder.DAG.getFrameIndex(FI, ValueType);
96       }
97     }
98   }
99 
100   // Couldn't find a free slot, so create a new one:
101 
102   SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
103   const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
104   MFI.markAsStatepointSpillSlotObjectIndex(FI);
105 
106   Builder.FuncInfo.StatepointStackSlots.push_back(FI);
107 
108   StatepointMaxSlotsRequired = std::max<unsigned long>(
109       StatepointMaxSlotsRequired, Builder.FuncInfo.StatepointStackSlots.size());
110 
111   return SpillSlot;
112 }
113 
114 /// Utility function for reservePreviousStackSlotForValue. Tries to find
115 /// stack slot index to which we have spilled value for previous statepoints.
116 /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
117 static Optional<int> findPreviousSpillSlot(const Value *Val,
118                                            SelectionDAGBuilder &Builder,
119                                            int LookUpDepth) {
120   // Can not look any further - give up now
121   if (LookUpDepth <= 0)
122     return None;
123 
124   // Spill location is known for gc relocates
125   if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
126     const auto &SpillMap =
127         Builder.FuncInfo.StatepointSpillMaps[Relocate->getStatepoint()];
128 
129     auto It = SpillMap.find(Relocate->getDerivedPtr());
130     if (It == SpillMap.end())
131       return None;
132 
133     return It->second;
134   }
135 
136   // Look through bitcast instructions.
137   if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
138     return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
139 
140   // Look through phi nodes
141   // All incoming values should have same known stack slot, otherwise result
142   // is unknown.
143   if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
144     Optional<int> MergedResult = None;
145 
146     for (auto &IncomingValue : Phi->incoming_values()) {
147       Optional<int> SpillSlot =
148           findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
149       if (!SpillSlot.hasValue())
150         return None;
151 
152       if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
153         return None;
154 
155       MergedResult = SpillSlot;
156     }
157     return MergedResult;
158   }
159 
160   // TODO: We can do better for PHI nodes. In cases like this:
161   //   ptr = phi(relocated_pointer, not_relocated_pointer)
162   //   statepoint(ptr)
163   // We will return that stack slot for ptr is unknown. And later we might
164   // assign different stack slots for ptr and relocated_pointer. This limits
165   // llvm's ability to remove redundant stores.
166   // Unfortunately it's hard to accomplish in current infrastructure.
167   // We use this function to eliminate spill store completely, while
168   // in example we still need to emit store, but instead of any location
169   // we need to use special "preferred" location.
170 
171   // TODO: handle simple updates.  If a value is modified and the original
172   // value is no longer live, it would be nice to put the modified value in the
173   // same slot.  This allows folding of the memory accesses for some
174   // instructions types (like an increment).
175   //   statepoint (i)
176   //   i1 = i+1
177   //   statepoint (i1)
178   // However we need to be careful for cases like this:
179   //   statepoint(i)
180   //   i1 = i+1
181   //   statepoint(i, i1)
182   // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
183   // put handling of simple modifications in this function like it's done
184   // for bitcasts we might end up reserving i's slot for 'i+1' because order in
185   // which we visit values is unspecified.
186 
187   // Don't know any information about this instruction
188   return None;
189 }
190 
191 /// Try to find existing copies of the incoming values in stack slots used for
192 /// statepoint spilling.  If we can find a spill slot for the incoming value,
193 /// mark that slot as allocated, and reuse the same slot for this safepoint.
194 /// This helps to avoid series of loads and stores that only serve to reshuffle
195 /// values on the stack between calls.
196 static void reservePreviousStackSlotForValue(const Value *IncomingValue,
197                                              SelectionDAGBuilder &Builder) {
198 
199   SDValue Incoming = Builder.getValue(IncomingValue);
200 
201   if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
202     // We won't need to spill this, so no need to check for previously
203     // allocated stack slots
204     return;
205   }
206 
207   SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
208   if (OldLocation.getNode())
209     // Duplicates in input
210     return;
211 
212   const int LookUpDepth = 6;
213   Optional<int> Index =
214       findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
215   if (!Index.hasValue())
216     return;
217 
218   const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
219 
220   auto SlotIt = find(StatepointSlots, *Index);
221   assert(SlotIt != StatepointSlots.end() &&
222          "Value spilled to the unknown stack slot");
223 
224   // This is one of our dedicated lowering slots
225   const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
226   if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
227     // stack slot already assigned to someone else, can't use it!
228     // TODO: currently we reserve space for gc arguments after doing
229     // normal allocation for deopt arguments.  We should reserve for
230     // _all_ deopt and gc arguments, then start allocating.  This
231     // will prevent some moves being inserted when vm state changes,
232     // but gc state doesn't between two calls.
233     return;
234   }
235   // Reserve this stack slot
236   Builder.StatepointLowering.reserveStackSlot(Offset);
237 
238   // Cache this slot so we find it when going through the normal
239   // assignment loop.
240   SDValue Loc = Builder.DAG.getTargetFrameIndex(*Index, Incoming.getValueType());
241   Builder.StatepointLowering.setLocation(Incoming, Loc);
242 }
243 
244 /// Remove any duplicate (as SDValues) from the derived pointer pairs.  This
245 /// is not required for correctness.  It's purpose is to reduce the size of
246 /// StackMap section.  It has no effect on the number of spill slots required
247 /// or the actual lowering.
248 static void
249 removeDuplicateGCPtrs(SmallVectorImpl<const Value *> &Bases,
250                       SmallVectorImpl<const Value *> &Ptrs,
251                       SmallVectorImpl<const GCRelocateInst *> &Relocs,
252                       SelectionDAGBuilder &Builder,
253                       FunctionLoweringInfo::StatepointSpillMap &SSM) {
254   DenseMap<SDValue, const Value *> Seen;
255 
256   SmallVector<const Value *, 64> NewBases, NewPtrs;
257   SmallVector<const GCRelocateInst *, 64> NewRelocs;
258   for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
259     SDValue SD = Builder.getValue(Ptrs[i]);
260     auto SeenIt = Seen.find(SD);
261 
262     if (SeenIt == Seen.end()) {
263       // Only add non-duplicates
264       NewBases.push_back(Bases[i]);
265       NewPtrs.push_back(Ptrs[i]);
266       NewRelocs.push_back(Relocs[i]);
267       Seen[SD] = Ptrs[i];
268     } else {
269       // Duplicate pointer found, note in SSM and move on:
270       SSM.DuplicateMap[Ptrs[i]] = SeenIt->second;
271     }
272   }
273   assert(Bases.size() >= NewBases.size());
274   assert(Ptrs.size() >= NewPtrs.size());
275   assert(Relocs.size() >= NewRelocs.size());
276   Bases = NewBases;
277   Ptrs = NewPtrs;
278   Relocs = NewRelocs;
279   assert(Ptrs.size() == Bases.size());
280   assert(Ptrs.size() == Relocs.size());
281 }
282 
283 /// Extract call from statepoint, lower it and return pointer to the
284 /// call node. Also update NodeMap so that getValue(statepoint) will
285 /// reference lowered call result
286 static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
287     SelectionDAGBuilder::StatepointLoweringInfo &SI,
288     SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
289 
290   SDValue ReturnValue, CallEndVal;
291   std::tie(ReturnValue, CallEndVal) =
292       Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
293   SDNode *CallEnd = CallEndVal.getNode();
294 
295   // Get a call instruction from the call sequence chain.  Tail calls are not
296   // allowed.  The following code is essentially reverse engineering X86's
297   // LowerCallTo.
298   //
299   // We are expecting DAG to have the following form:
300   //
301   // ch = eh_label (only in case of invoke statepoint)
302   //   ch, glue = callseq_start ch
303   //   ch, glue = X86::Call ch, glue
304   //   ch, glue = callseq_end ch, glue
305   //   get_return_value ch, glue
306   //
307   // get_return_value can either be a sequence of CopyFromReg instructions
308   // to grab the return value from the return register(s), or it can be a LOAD
309   // to load a value returned by reference via a stack slot.
310 
311   bool HasDef = !SI.CLI.RetTy->isVoidTy();
312   if (HasDef) {
313     if (CallEnd->getOpcode() == ISD::LOAD)
314       CallEnd = CallEnd->getOperand(0).getNode();
315     else
316       while (CallEnd->getOpcode() == ISD::CopyFromReg)
317         CallEnd = CallEnd->getOperand(0).getNode();
318   }
319 
320   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
321   return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
322 }
323 
324 /// Spill a value incoming to the statepoint. It might be either part of
325 /// vmstate
326 /// or gcstate. In both cases unconditionally spill it on the stack unless it
327 /// is a null constant. Return pair with first element being frame index
328 /// containing saved value and second element with outgoing chain from the
329 /// emitted store
330 static std::pair<SDValue, SDValue>
331 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
332                              SelectionDAGBuilder &Builder) {
333   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
334 
335   // Emit new store if we didn't do it for this ptr before
336   if (!Loc.getNode()) {
337     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
338                                                        Builder);
339     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
340     // We use TargetFrameIndex so that isel will not select it into LEA
341     Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
342 
343     // TODO: We can create TokenFactor node instead of
344     //       chaining stores one after another, this may allow
345     //       a bit more optimal scheduling for them
346 
347 #ifndef NDEBUG
348     // Right now we always allocate spill slots that are of the same
349     // size as the value we're about to spill (the size of spillee can
350     // vary since we spill vectors of pointers too).  At some point we
351     // can consider allowing spills of smaller values to larger slots
352     // (i.e. change the '==' in the assert below to a '>=').
353     MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
354     assert((MFI.getObjectSize(Index) * 8) == Incoming.getValueSizeInBits() &&
355            "Bad spill:  stack slot does not match!");
356 #endif
357 
358     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
359                                  MachinePointerInfo::getFixedStack(
360                                      Builder.DAG.getMachineFunction(), Index));
361 
362     Builder.StatepointLowering.setLocation(Incoming, Loc);
363   }
364 
365   assert(Loc.getNode());
366   return std::make_pair(Loc, Chain);
367 }
368 
369 /// Lower a single value incoming to a statepoint node.  This value can be
370 /// either a deopt value or a gc value, the handling is the same.  We special
371 /// case constants and allocas, then fall back to spilling if required.
372 static void lowerIncomingStatepointValue(SDValue Incoming, bool LiveInOnly,
373                                          SmallVectorImpl<SDValue> &Ops,
374                                          SelectionDAGBuilder &Builder) {
375   SDValue Chain = Builder.getRoot();
376 
377   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
378     // If the original value was a constant, make sure it gets recorded as
379     // such in the stackmap.  This is required so that the consumer can
380     // parse any internal format to the deopt state.  It also handles null
381     // pointers and other constant pointers in GC states.  Note the constant
382     // vectors do not appear to actually hit this path and that anything larger
383     // than an i64 value (not type!) will fail asserts here.
384     pushStackMapConstant(Ops, Builder, C->getSExtValue());
385   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
386     // This handles allocas as arguments to the statepoint (this is only
387     // really meaningful for a deopt value.  For GC, we'd be trying to
388     // relocate the address of the alloca itself?)
389     Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
390                                                   Incoming.getValueType()));
391   } else if (LiveInOnly) {
392     // If this value is live in (not live-on-return, or live-through), we can
393     // treat it the same way patchpoint treats it's "live in" values.  We'll
394     // end up folding some of these into stack references, but they'll be
395     // handled by the register allocator.  Note that we do not have the notion
396     // of a late use so these values might be placed in registers which are
397     // clobbered by the call.  This is fine for live-in.
398     Ops.push_back(Incoming);
399   } else {
400     // Otherwise, locate a spill slot and explicitly spill it so it
401     // can be found by the runtime later.  We currently do not support
402     // tracking values through callee saved registers to their eventual
403     // spill location.  This would be a useful optimization, but would
404     // need to be optional since it requires a lot of complexity on the
405     // runtime side which not all would support.
406     auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
407     Ops.push_back(Res.first);
408     Chain = Res.second;
409   }
410 
411   Builder.DAG.setRoot(Chain);
412 }
413 
414 /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
415 /// lowering is described in lowerIncomingStatepointValue.  This function is
416 /// responsible for lowering everything in the right position and playing some
417 /// tricks to avoid redundant stack manipulation where possible.  On
418 /// completion, 'Ops' will contain ready to use operands for machine code
419 /// statepoint. The chain nodes will have already been created and the DAG root
420 /// will be set to the last value spilled (if any were).
421 static void
422 lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
423                         SelectionDAGBuilder::StatepointLoweringInfo &SI,
424                         SelectionDAGBuilder &Builder) {
425   // Lower the deopt and gc arguments for this statepoint.  Layout will be:
426   // deopt argument length, deopt arguments.., gc arguments...
427 #ifndef NDEBUG
428   if (auto *GFI = Builder.GFI) {
429     // Check that each of the gc pointer and bases we've gotten out of the
430     // safepoint is something the strategy thinks might be a pointer (or vector
431     // of pointers) into the GC heap.  This is basically just here to help catch
432     // errors during statepoint insertion. TODO: This should actually be in the
433     // Verifier, but we can't get to the GCStrategy from there (yet).
434     GCStrategy &S = GFI->getStrategy();
435     for (const Value *V : SI.Bases) {
436       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
437       if (Opt.hasValue()) {
438         assert(Opt.getValue() &&
439                "non gc managed base pointer found in statepoint");
440       }
441     }
442     for (const Value *V : SI.Ptrs) {
443       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
444       if (Opt.hasValue()) {
445         assert(Opt.getValue() &&
446                "non gc managed derived pointer found in statepoint");
447       }
448     }
449     assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");
450   } else {
451     assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
452     assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
453   }
454 #endif
455 
456   // Figure out what lowering strategy we're going to use for each part
457   // Note: Is is conservatively correct to lower both "live-in" and "live-out"
458   // as "live-through". A "live-through" variable is one which is "live-in",
459   // "live-out", and live throughout the lifetime of the call (i.e. we can find
460   // it from any PC within the transitive callee of the statepoint).  In
461   // particular, if the callee spills callee preserved registers we may not
462   // be able to find a value placed in that register during the call.  This is
463   // fine for live-out, but not for live-through.  If we were willing to make
464   // assumptions about the code generator producing the callee, we could
465   // potentially allow live-through values in callee saved registers.
466   const bool LiveInDeopt =
467     SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
468 
469   auto isGCValue =[&](const Value *V) {
470     return is_contained(SI.Ptrs, V) || is_contained(SI.Bases, V);
471   };
472 
473   // Before we actually start lowering (and allocating spill slots for values),
474   // reserve any stack slots which we judge to be profitable to reuse for a
475   // particular value.  This is purely an optimization over the code below and
476   // doesn't change semantics at all.  It is important for performance that we
477   // reserve slots for both deopt and gc values before lowering either.
478   for (const Value *V : SI.DeoptState) {
479     if (!LiveInDeopt || isGCValue(V))
480       reservePreviousStackSlotForValue(V, Builder);
481   }
482   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
483     reservePreviousStackSlotForValue(SI.Bases[i], Builder);
484     reservePreviousStackSlotForValue(SI.Ptrs[i], Builder);
485   }
486 
487   // First, prefix the list with the number of unique values to be
488   // lowered.  Note that this is the number of *Values* not the
489   // number of SDValues required to lower them.
490   const int NumVMSArgs = SI.DeoptState.size();
491   pushStackMapConstant(Ops, Builder, NumVMSArgs);
492 
493   // The vm state arguments are lowered in an opaque manner.  We do not know
494   // what type of values are contained within.
495   for (const Value *V : SI.DeoptState) {
496     SDValue Incoming = Builder.getValue(V);
497     const bool LiveInValue = LiveInDeopt && !isGCValue(V);
498     lowerIncomingStatepointValue(Incoming, LiveInValue, Ops, Builder);
499   }
500 
501   // Finally, go ahead and lower all the gc arguments.  There's no prefixed
502   // length for this one.  After lowering, we'll have the base and pointer
503   // arrays interwoven with each (lowered) base pointer immediately followed by
504   // it's (lowered) derived pointer.  i.e
505   // (base[0], ptr[0], base[1], ptr[1], ...)
506   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
507     const Value *Base = SI.Bases[i];
508     lowerIncomingStatepointValue(Builder.getValue(Base), /*LiveInOnly*/ false,
509                                  Ops, Builder);
510 
511     const Value *Ptr = SI.Ptrs[i];
512     lowerIncomingStatepointValue(Builder.getValue(Ptr), /*LiveInOnly*/ false,
513                                  Ops, Builder);
514   }
515 
516   // If there are any explicit spill slots passed to the statepoint, record
517   // them, but otherwise do not do anything special.  These are user provided
518   // allocas and give control over placement to the consumer.  In this case,
519   // it is the contents of the slot which may get updated, not the pointer to
520   // the alloca
521   for (Value *V : SI.GCArgs) {
522     SDValue Incoming = Builder.getValue(V);
523     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
524       // This handles allocas as arguments to the statepoint
525       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
526                                                     Incoming.getValueType()));
527     }
528   }
529 
530   // Record computed locations for all lowered values.
531   // This can not be embedded in lowering loops as we need to record *all*
532   // values, while previous loops account only values with unique SDValues.
533   const Instruction *StatepointInstr = SI.StatepointInstr;
534   auto &SpillMap = Builder.FuncInfo.StatepointSpillMaps[StatepointInstr];
535 
536   for (const GCRelocateInst *Relocate : SI.GCRelocates) {
537     const Value *V = Relocate->getDerivedPtr();
538     SDValue SDV = Builder.getValue(V);
539     SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
540 
541     if (Loc.getNode()) {
542       SpillMap.SlotMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
543     } else {
544       // Record value as visited, but not spilled. This is case for allocas
545       // and constants. For this values we can avoid emitting spill load while
546       // visiting corresponding gc_relocate.
547       // Actually we do not need to record them in this map at all.
548       // We do this only to check that we are not relocating any unvisited
549       // value.
550       SpillMap.SlotMap[V] = None;
551 
552       // Default llvm mechanisms for exporting values which are used in
553       // different basic blocks does not work for gc relocates.
554       // Note that it would be incorrect to teach llvm that all relocates are
555       // uses of the corresponding values so that it would automatically
556       // export them. Relocates of the spilled values does not use original
557       // value.
558       if (Relocate->getParent() != StatepointInstr->getParent())
559         Builder.ExportFromCurrentBlock(V);
560     }
561   }
562 }
563 
564 SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
565     SelectionDAGBuilder::StatepointLoweringInfo &SI) {
566   // The basic scheme here is that information about both the original call and
567   // the safepoint is encoded in the CallInst.  We create a temporary call and
568   // lower it, then reverse engineer the calling sequence.
569 
570   NumOfStatepoints++;
571   // Clear state
572   StatepointLowering.startNewStatepoint(*this);
573 
574 #ifndef NDEBUG
575   // We schedule gc relocates before removeDuplicateGCPtrs since we _will_
576   // encounter the duplicate gc relocates we elide in removeDuplicateGCPtrs.
577   for (auto *Reloc : SI.GCRelocates)
578     if (Reloc->getParent() == SI.StatepointInstr->getParent())
579       StatepointLowering.scheduleRelocCall(*Reloc);
580 #endif
581 
582   // Remove any redundant llvm::Values which map to the same SDValue as another
583   // input.  Also has the effect of removing duplicates in the original
584   // llvm::Value input list as well.  This is a useful optimization for
585   // reducing the size of the StackMap section.  It has no other impact.
586   removeDuplicateGCPtrs(SI.Bases, SI.Ptrs, SI.GCRelocates, *this,
587                         FuncInfo.StatepointSpillMaps[SI.StatepointInstr]);
588   assert(SI.Bases.size() == SI.Ptrs.size() &&
589          SI.Ptrs.size() == SI.GCRelocates.size());
590 
591   // Lower statepoint vmstate and gcstate arguments
592   SmallVector<SDValue, 10> LoweredMetaArgs;
593   lowerStatepointMetaArgs(LoweredMetaArgs, SI, *this);
594 
595   // Now that we've emitted the spills, we need to update the root so that the
596   // call sequence is ordered correctly.
597   SI.CLI.setChain(getRoot());
598 
599   // Get call node, we will replace it later with statepoint
600   SDValue ReturnVal;
601   SDNode *CallNode;
602   std::tie(ReturnVal, CallNode) =
603       lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
604 
605   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
606   // nodes with all the appropriate arguments and return values.
607 
608   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
609   SDValue Chain = CallNode->getOperand(0);
610 
611   SDValue Glue;
612   bool CallHasIncomingGlue = CallNode->getGluedNode();
613   if (CallHasIncomingGlue) {
614     // Glue is always last operand
615     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
616   }
617 
618   // Build the GC_TRANSITION_START node if necessary.
619   //
620   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
621   // order in which they appear in the call to the statepoint intrinsic. If
622   // any of the operands is a pointer-typed, that operand is immediately
623   // followed by a SRCVALUE for the pointer that may be used during lowering
624   // (e.g. to form MachinePointerInfo values for loads/stores).
625   const bool IsGCTransition =
626       (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
627       (uint64_t)StatepointFlags::GCTransition;
628   if (IsGCTransition) {
629     SmallVector<SDValue, 8> TSOps;
630 
631     // Add chain
632     TSOps.push_back(Chain);
633 
634     // Add GC transition arguments
635     for (const Value *V : SI.GCTransitionArgs) {
636       TSOps.push_back(getValue(V));
637       if (V->getType()->isPointerTy())
638         TSOps.push_back(DAG.getSrcValue(V));
639     }
640 
641     // Add glue if necessary
642     if (CallHasIncomingGlue)
643       TSOps.push_back(Glue);
644 
645     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
646 
647     SDValue GCTransitionStart =
648         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
649 
650     Chain = GCTransitionStart.getValue(0);
651     Glue = GCTransitionStart.getValue(1);
652   }
653 
654   // TODO: Currently, all of these operands are being marked as read/write in
655   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
656   // and flags to be read-only.
657   SmallVector<SDValue, 40> Ops;
658 
659   // Add the <id> and <numBytes> constants.
660   Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
661   Ops.push_back(
662       DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
663 
664   // Calculate and push starting position of vmstate arguments
665   // Get number of arguments incoming directly into call node
666   unsigned NumCallRegArgs =
667       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
668   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
669 
670   // Add call target
671   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
672   Ops.push_back(CallTarget);
673 
674   // Add call arguments
675   // Get position of register mask in the call
676   SDNode::op_iterator RegMaskIt;
677   if (CallHasIncomingGlue)
678     RegMaskIt = CallNode->op_end() - 2;
679   else
680     RegMaskIt = CallNode->op_end() - 1;
681   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
682 
683   // Add a constant argument for the calling convention
684   pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
685 
686   // Add a constant argument for the flags
687   uint64_t Flags = SI.StatepointFlags;
688   assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
689          "Unknown flag used");
690   pushStackMapConstant(Ops, *this, Flags);
691 
692   // Insert all vmstate and gcstate arguments
693   Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
694 
695   // Add register mask from call node
696   Ops.push_back(*RegMaskIt);
697 
698   // Add chain
699   Ops.push_back(Chain);
700 
701   // Same for the glue, but we add it only if original call had it
702   if (Glue.getNode())
703     Ops.push_back(Glue);
704 
705   // Compute return values.  Provide a glue output since we consume one as
706   // input.  This allows someone else to chain off us as needed.
707   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
708 
709   SDNode *StatepointMCNode =
710       DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
711 
712   SDNode *SinkNode = StatepointMCNode;
713 
714   // Build the GC_TRANSITION_END node if necessary.
715   //
716   // See the comment above regarding GC_TRANSITION_START for the layout of
717   // the operands to the GC_TRANSITION_END node.
718   if (IsGCTransition) {
719     SmallVector<SDValue, 8> TEOps;
720 
721     // Add chain
722     TEOps.push_back(SDValue(StatepointMCNode, 0));
723 
724     // Add GC transition arguments
725     for (const Value *V : SI.GCTransitionArgs) {
726       TEOps.push_back(getValue(V));
727       if (V->getType()->isPointerTy())
728         TEOps.push_back(DAG.getSrcValue(V));
729     }
730 
731     // Add glue
732     TEOps.push_back(SDValue(StatepointMCNode, 1));
733 
734     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
735 
736     SDValue GCTransitionStart =
737         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
738 
739     SinkNode = GCTransitionStart.getNode();
740   }
741 
742   // Replace original call
743   DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
744   // Remove original call node
745   DAG.DeleteNode(CallNode);
746 
747   // DON'T set the root - under the assumption that it's already set past the
748   // inserted node we created.
749 
750   // TODO: A better future implementation would be to emit a single variable
751   // argument, variable return value STATEPOINT node here and then hookup the
752   // return value of each gc.relocate to the respective output of the
753   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
754   // to actually be possible today.
755 
756   return ReturnVal;
757 }
758 
759 void
760 SelectionDAGBuilder::LowerStatepoint(ImmutableStatepoint ISP,
761                                      const BasicBlock *EHPadBB /*= nullptr*/) {
762   assert(ISP.getCallSite().getCallingConv() != CallingConv::AnyReg &&
763          "anyregcc is not supported on statepoints!");
764 
765 #ifndef NDEBUG
766   // If this is a malformed statepoint, report it early to simplify debugging.
767   // This should catch any IR level mistake that's made when constructing or
768   // transforming statepoints.
769   ISP.verify();
770 
771   // Check that the associated GCStrategy expects to encounter statepoints.
772   assert(GFI->getStrategy().useStatepoints() &&
773          "GCStrategy does not expect to encounter statepoints");
774 #endif
775 
776   SDValue ActualCallee;
777 
778   if (ISP.getNumPatchBytes() > 0) {
779     // If we've been asked to emit a nop sequence instead of a call instruction
780     // for this statepoint then don't lower the call target, but use a constant
781     // `null` instead.  Not lowering the call target lets statepoint clients get
782     // away without providing a physical address for the symbolic call target at
783     // link time.
784 
785     const auto &TLI = DAG.getTargetLoweringInfo();
786     const auto &DL = DAG.getDataLayout();
787 
788     unsigned AS = ISP.getCalledValue()->getType()->getPointerAddressSpace();
789     ActualCallee = DAG.getConstant(0, getCurSDLoc(), TLI.getPointerTy(DL, AS));
790   } else {
791     ActualCallee = getValue(ISP.getCalledValue());
792   }
793 
794   StatepointLoweringInfo SI(DAG);
795   populateCallLoweringInfo(SI.CLI, ISP.getCallSite(),
796                            ImmutableStatepoint::CallArgsBeginPos,
797                            ISP.getNumCallArgs(), ActualCallee,
798                            ISP.getActualReturnType(), false /* IsPatchPoint */);
799 
800   for (const GCRelocateInst *Relocate : ISP.getRelocates()) {
801     SI.GCRelocates.push_back(Relocate);
802     SI.Bases.push_back(Relocate->getBasePtr());
803     SI.Ptrs.push_back(Relocate->getDerivedPtr());
804   }
805 
806   SI.GCArgs = ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
807   SI.StatepointInstr = ISP.getInstruction();
808   SI.GCTransitionArgs =
809       ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
810   SI.ID = ISP.getID();
811   SI.DeoptState = ArrayRef<const Use>(ISP.vm_state_begin(), ISP.vm_state_end());
812   SI.StatepointFlags = ISP.getFlags();
813   SI.NumPatchBytes = ISP.getNumPatchBytes();
814   SI.EHPadBB = EHPadBB;
815 
816   SDValue ReturnValue = LowerAsSTATEPOINT(SI);
817 
818   // Export the result value if needed
819   const GCResultInst *GCResult = ISP.getGCResult();
820   Type *RetTy = ISP.getActualReturnType();
821   if (!RetTy->isVoidTy() && GCResult) {
822     if (GCResult->getParent() != ISP.getCallSite().getParent()) {
823       // Result value will be used in a different basic block so we need to
824       // export it now.  Default exporting mechanism will not work here because
825       // statepoint call has a different type than the actual call. It means
826       // that by default llvm will create export register of the wrong type
827       // (always i32 in our case). So instead we need to create export register
828       // with correct type manually.
829       // TODO: To eliminate this problem we can remove gc.result intrinsics
830       //       completely and make statepoint call to return a tuple.
831       unsigned Reg = FuncInfo.CreateRegs(RetTy);
832       RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
833                        DAG.getDataLayout(), Reg, RetTy);
834       SDValue Chain = DAG.getEntryNode();
835 
836       RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
837       PendingExports.push_back(Chain);
838       FuncInfo.ValueMap[ISP.getInstruction()] = Reg;
839     } else {
840       // Result value will be used in a same basic block. Don't export it or
841       // perform any explicit register copies.
842       // We'll replace the actuall call node shortly. gc_result will grab
843       // this value.
844       setValue(ISP.getInstruction(), ReturnValue);
845     }
846   } else {
847     // The token value is never used from here on, just generate a poison value
848     setValue(ISP.getInstruction(), DAG.getIntPtrConstant(-1, getCurSDLoc()));
849   }
850 }
851 
852 void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
853     ImmutableCallSite CS, SDValue Callee, const BasicBlock *EHPadBB,
854     bool VarArgDisallowed, bool ForceVoidReturnTy) {
855   StatepointLoweringInfo SI(DAG);
856   unsigned ArgBeginIndex = CS.arg_begin() - CS.getInstruction()->op_begin();
857   populateCallLoweringInfo(
858       SI.CLI, CS, ArgBeginIndex, CS.getNumArgOperands(), Callee,
859       ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : CS.getType(),
860       false);
861   if (!VarArgDisallowed)
862     SI.CLI.IsVarArg = CS.getFunctionType()->isVarArg();
863 
864   auto DeoptBundle = *CS.getOperandBundle(LLVMContext::OB_deopt);
865 
866   unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
867 
868   auto SD = parseStatepointDirectivesFromAttrs(CS.getAttributes());
869   SI.ID = SD.StatepointID.getValueOr(DefaultID);
870   SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
871 
872   SI.DeoptState =
873       ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
874   SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
875   SI.EHPadBB = EHPadBB;
876 
877   // NB! The GC arguments are deliberately left empty.
878 
879   if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
880     const Instruction *Inst = CS.getInstruction();
881     ReturnVal = lowerRangeToAssertZExt(DAG, *Inst, ReturnVal);
882     setValue(Inst, ReturnVal);
883   }
884 }
885 
886 void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
887     ImmutableCallSite CS, SDValue Callee, const BasicBlock *EHPadBB) {
888   LowerCallSiteWithDeoptBundleImpl(CS, Callee, EHPadBB,
889                                    /* VarArgDisallowed = */ false,
890                                    /* ForceVoidReturnTy  = */ false);
891 }
892 
893 void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
894   // The result value of the gc_result is simply the result of the actual
895   // call.  We've already emitted this, so just grab the value.
896   const Instruction *I = CI.getStatepoint();
897 
898   if (I->getParent() != CI.getParent()) {
899     // Statepoint is in different basic block so we should have stored call
900     // result in a virtual register.
901     // We can not use default getValue() functionality to copy value from this
902     // register because statepoint and actual call return types can be
903     // different, and getValue() will use CopyFromReg of the wrong type,
904     // which is always i32 in our case.
905     PointerType *CalleeType = cast<PointerType>(
906         ImmutableStatepoint(I).getCalledValue()->getType());
907     Type *RetTy =
908         cast<FunctionType>(CalleeType->getElementType())->getReturnType();
909     SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
910 
911     assert(CopyFromReg.getNode());
912     setValue(&CI, CopyFromReg);
913   } else {
914     setValue(&CI, getValue(I));
915   }
916 }
917 
918 void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
919 #ifndef NDEBUG
920   // Consistency check
921   // We skip this check for relocates not in the same basic block as thier
922   // statepoint. It would be too expensive to preserve validation info through
923   // different basic blocks.
924   if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
925     StatepointLowering.relocCallVisited(Relocate);
926 
927   auto *Ty = Relocate.getType()->getScalarType();
928   if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
929     assert(*IsManaged && "Non gc managed pointer relocated!");
930 #endif
931 
932   const Value *DerivedPtr = Relocate.getDerivedPtr();
933   SDValue SD = getValue(DerivedPtr);
934 
935   auto &SpillMap = FuncInfo.StatepointSpillMaps[Relocate.getStatepoint()];
936   auto SlotIt = SpillMap.find(DerivedPtr);
937   assert(SlotIt != SpillMap.end() && "Relocating not lowered gc value");
938   Optional<int> DerivedPtrLocation = SlotIt->second;
939 
940   // We didn't need to spill these special cases (constants and allocas).
941   // See the handling in spillIncomingValueForStatepoint for detail.
942   if (!DerivedPtrLocation) {
943     setValue(&Relocate, SD);
944     return;
945   }
946 
947   SDValue SpillSlot = DAG.getTargetFrameIndex(*DerivedPtrLocation,
948                                               SD.getValueType());
949 
950   // Be conservative: flush all pending loads
951   // TODO: Probably we can be less restrictive on this,
952   // it may allow more scheduling opportunities.
953   SDValue Chain = getRoot();
954 
955   SDValue SpillLoad =
956       DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
957                   MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
958                                                     *DerivedPtrLocation));
959 
960   // Again, be conservative, don't emit pending loads
961   DAG.setRoot(SpillLoad.getValue(1));
962 
963   assert(SpillLoad.getNode());
964   setValue(&Relocate, SpillLoad);
965 }
966 
967 void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
968   const auto &TLI = DAG.getTargetLoweringInfo();
969   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
970                                          TLI.getPointerTy(DAG.getDataLayout()));
971 
972   // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
973   // call.  We also do not lower the return value to any virtual register, and
974   // change the immediately following return to a trap instruction.
975   LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
976                                    /* VarArgDisallowed = */ true,
977                                    /* ForceVoidReturnTy = */ true);
978 }
979 
980 void SelectionDAGBuilder::LowerDeoptimizingReturn() {
981   // We do not lower the return value from llvm.deoptimize to any virtual
982   // register, and change the immediately following return to a trap
983   // instruction.
984   if (DAG.getTarget().Options.TrapUnreachable)
985     DAG.setRoot(
986         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
987 }
988