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   auto *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.StatepointRelocatedValues[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 removeDuplicatesGCPtrs(SmallVectorImpl<const Value *> &Bases,
250                        SmallVectorImpl<const Value *> &Ptrs,
251                        SmallVectorImpl<const GCRelocateInst *> &Relocs,
252                        SelectionDAGBuilder &Builder) {
253 
254   // This is horribly inefficient, but I don't care right now
255   SmallSet<SDValue, 32> Seen;
256 
257   SmallVector<const Value *, 64> NewBases, NewPtrs;
258   SmallVector<const GCRelocateInst *, 64> NewRelocs;
259   for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
260     SDValue SD = Builder.getValue(Ptrs[i]);
261     // Only add non-duplicates
262     if (Seen.count(SD) == 0) {
263       NewBases.push_back(Bases[i]);
264       NewPtrs.push_back(Ptrs[i]);
265       NewRelocs.push_back(Relocs[i]);
266     }
267     Seen.insert(SD);
268   }
269   assert(Bases.size() >= NewBases.size());
270   assert(Ptrs.size() >= NewPtrs.size());
271   assert(Relocs.size() >= NewRelocs.size());
272   Bases = NewBases;
273   Ptrs = NewPtrs;
274   Relocs = NewRelocs;
275   assert(Ptrs.size() == Bases.size());
276   assert(Ptrs.size() == Relocs.size());
277 }
278 
279 /// Extract call from statepoint, lower it and return pointer to the
280 /// call node. Also update NodeMap so that getValue(statepoint) will
281 /// reference lowered call result
282 static SDNode *
283 lowerCallFromStatepoint(ImmutableStatepoint ISP, const BasicBlock *EHPadBB,
284                         SelectionDAGBuilder &Builder,
285                         SmallVectorImpl<SDValue> &PendingExports) {
286 
287   ImmutableCallSite CS(ISP.getCallSite());
288 
289   SDValue ActualCallee;
290 
291   if (ISP.getNumPatchBytes() > 0) {
292     // If we've been asked to emit a nop sequence instead of a call instruction
293     // for this statepoint then don't lower the call target, but use a constant
294     // `null` instead.  Not lowering the call target lets statepoint clients get
295     // away without providing a physical address for the symbolic call target at
296     // link time.
297 
298     const auto &TLI = Builder.DAG.getTargetLoweringInfo();
299     const auto &DL = Builder.DAG.getDataLayout();
300 
301     unsigned AS = ISP.getCalledValue()->getType()->getPointerAddressSpace();
302     ActualCallee = Builder.DAG.getConstant(0, Builder.getCurSDLoc(),
303                                            TLI.getPointerTy(DL, AS));
304   } else {
305     ActualCallee = Builder.getValue(ISP.getCalledValue());
306   }
307 
308   assert(CS.getCallingConv() != CallingConv::AnyReg &&
309          "anyregcc is not supported on statepoints!");
310 
311   Type *DefTy = ISP.getActualReturnType();
312   bool HasDef = !DefTy->isVoidTy();
313 
314   SDValue ReturnValue, CallEndVal;
315   std::tie(ReturnValue, CallEndVal) = Builder.lowerCallOperands(
316       ISP.getCallSite(), ImmutableStatepoint::CallArgsBeginPos,
317       ISP.getNumCallArgs(), ActualCallee, DefTy, EHPadBB,
318       false /* IsPatchPoint */);
319 
320   SDNode *CallEnd = CallEndVal.getNode();
321 
322   // Get a call instruction from the call sequence chain.  Tail calls are not
323   // allowed.  The following code is essentially reverse engineering X86's
324   // LowerCallTo.
325   //
326   // We are expecting DAG to have the following form:
327   //
328   // ch = eh_label (only in case of invoke statepoint)
329   //   ch, glue = callseq_start ch
330   //   ch, glue = X86::Call ch, glue
331   //   ch, glue = callseq_end ch, glue
332   //   get_return_value ch, glue
333   //
334   // get_return_value can either be a sequence of CopyFromReg instructions
335   // to grab the return value from the return register(s), or it can be a LOAD
336   // to load a value returned by reference via a stack slot.
337 
338   if (HasDef) {
339     if (CallEnd->getOpcode() == ISD::LOAD)
340       CallEnd = CallEnd->getOperand(0).getNode();
341     else
342       while (CallEnd->getOpcode() == ISD::CopyFromReg)
343         CallEnd = CallEnd->getOperand(0).getNode();
344   }
345 
346   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
347 
348   // Export the result value if needed
349   const Instruction *GCResult = ISP.getGCResult();
350   if (HasDef && GCResult) {
351     if (GCResult->getParent() != CS.getParent()) {
352       // Result value will be used in a different basic block so we need to
353       // export it now.
354       // Default exporting mechanism will not work here because statepoint call
355       // has a different type than the actual call. It means that by default
356       // llvm will create export register of the wrong type (always i32 in our
357       // case). So instead we need to create export register with correct type
358       // manually.
359       // TODO: To eliminate this problem we can remove gc.result intrinsics
360       //       completely and make statepoint call to return a tuple.
361       unsigned Reg = Builder.FuncInfo.CreateRegs(ISP.getActualReturnType());
362       RegsForValue RFV(
363           *Builder.DAG.getContext(), Builder.DAG.getTargetLoweringInfo(),
364           Builder.DAG.getDataLayout(), Reg, ISP.getActualReturnType());
365       SDValue Chain = Builder.DAG.getEntryNode();
366 
367       RFV.getCopyToRegs(ReturnValue, Builder.DAG, Builder.getCurSDLoc(), Chain,
368                         nullptr);
369       PendingExports.push_back(Chain);
370       Builder.FuncInfo.ValueMap[CS.getInstruction()] = Reg;
371     } else {
372       // Result value will be used in a same basic block. Don't export it or
373       // perform any explicit register copies.
374       // We'll replace the actuall call node shortly. gc_result will grab
375       // this value.
376       Builder.setValue(CS.getInstruction(), ReturnValue);
377     }
378   } else {
379     // The token value is never used from here on, just generate a poison value
380     Builder.setValue(CS.getInstruction(),
381                      Builder.DAG.getIntPtrConstant(-1, Builder.getCurSDLoc()));
382   }
383 
384   return CallEnd->getOperand(0).getNode();
385 }
386 
387 /// Callect all gc pointers coming into statepoint intrinsic, clean them up,
388 /// and return two arrays:
389 ///   Bases - base pointers incoming to this statepoint
390 ///   Ptrs - derived pointers incoming to this statepoint
391 ///   Relocs - the gc_relocate corresponding to each base/ptr pair
392 /// Elements of this arrays should be in one-to-one correspondence with each
393 /// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call
394 static void getIncomingStatepointGCValues(
395     SmallVectorImpl<const Value *> &Bases, SmallVectorImpl<const Value *> &Ptrs,
396     SmallVectorImpl<const GCRelocateInst *> &Relocs,
397     ImmutableStatepoint StatepointSite, SelectionDAGBuilder &Builder) {
398   for (const GCRelocateInst *Relocate : StatepointSite.getRelocates()) {
399     Relocs.push_back(Relocate);
400     Bases.push_back(Relocate->getBasePtr());
401     Ptrs.push_back(Relocate->getDerivedPtr());
402   }
403 
404   // Remove any redundant llvm::Values which map to the same SDValue as another
405   // input.  Also has the effect of removing duplicates in the original
406   // llvm::Value input list as well.  This is a useful optimization for
407   // reducing the size of the StackMap section.  It has no other impact.
408   removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder);
409 
410   assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size());
411 }
412 
413 /// Spill a value incoming to the statepoint. It might be either part of
414 /// vmstate
415 /// or gcstate. In both cases unconditionally spill it on the stack unless it
416 /// is a null constant. Return pair with first element being frame index
417 /// containing saved value and second element with outgoing chain from the
418 /// emitted store
419 static std::pair<SDValue, SDValue>
420 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
421                              SelectionDAGBuilder &Builder) {
422   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
423 
424   // Emit new store if we didn't do it for this ptr before
425   if (!Loc.getNode()) {
426     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
427                                                        Builder);
428     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
429     // We use TargetFrameIndex so that isel will not select it into LEA
430     Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
431 
432     // TODO: We can create TokenFactor node instead of
433     //       chaining stores one after another, this may allow
434     //       a bit more optimal scheduling for them
435 
436 #ifndef NDEBUG
437     // Right now we always allocate spill slots that are of the same
438     // size as the value we're about to spill (the size of spillee can
439     // vary since we spill vectors of pointers too).  At some point we
440     // can consider allowing spills of smaller values to larger slots
441     // (i.e. change the '==' in the assert below to a '>=').
442     auto *MFI = Builder.DAG.getMachineFunction().getFrameInfo();
443     assert((MFI->getObjectSize(Index) * 8) ==
444                Incoming.getValueType().getSizeInBits() &&
445            "Bad spill:  stack slot does not match!");
446 #endif
447 
448     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
449                                  MachinePointerInfo::getFixedStack(
450                                      Builder.DAG.getMachineFunction(), Index),
451                                  false, false, 0);
452 
453     Builder.StatepointLowering.setLocation(Incoming, Loc);
454   }
455 
456   assert(Loc.getNode());
457   return std::make_pair(Loc, Chain);
458 }
459 
460 /// Lower a single value incoming to a statepoint node.  This value can be
461 /// either a deopt value or a gc value, the handling is the same.  We special
462 /// case constants and allocas, then fall back to spilling if required.
463 static void lowerIncomingStatepointValue(SDValue Incoming,
464                                          SmallVectorImpl<SDValue> &Ops,
465                                          SelectionDAGBuilder &Builder) {
466   SDValue Chain = Builder.getRoot();
467 
468   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
469     // If the original value was a constant, make sure it gets recorded as
470     // such in the stackmap.  This is required so that the consumer can
471     // parse any internal format to the deopt state.  It also handles null
472     // pointers and other constant pointers in GC states.  Note the constant
473     // vectors do not appear to actually hit this path and that anything larger
474     // than an i64 value (not type!) will fail asserts here.
475     pushStackMapConstant(Ops, Builder, C->getSExtValue());
476   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
477     // This handles allocas as arguments to the statepoint (this is only
478     // really meaningful for a deopt value.  For GC, we'd be trying to
479     // relocate the address of the alloca itself?)
480     Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
481                                                   Incoming.getValueType()));
482   } else {
483     // Otherwise, locate a spill slot and explicitly spill it so it
484     // can be found by the runtime later.  We currently do not support
485     // tracking values through callee saved registers to their eventual
486     // spill location.  This would be a useful optimization, but would
487     // need to be optional since it requires a lot of complexity on the
488     // runtime side which not all would support.
489     auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
490     Ops.push_back(Res.first);
491     Chain = Res.second;
492   }
493 
494   Builder.DAG.setRoot(Chain);
495 }
496 
497 /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
498 /// lowering is described in lowerIncomingStatepointValue.  This function is
499 /// responsible for lowering everything in the right position and playing some
500 /// tricks to avoid redundant stack manipulation where possible.  On
501 /// completion, 'Ops' will contain ready to use operands for machine code
502 /// statepoint. The chain nodes will have already been created and the DAG root
503 /// will be set to the last value spilled (if any were).
504 static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
505                                     ImmutableStatepoint StatepointSite,
506                                     SelectionDAGBuilder &Builder) {
507 
508   // Lower the deopt and gc arguments for this statepoint.  Layout will
509   // be: deopt argument length, deopt arguments.., gc arguments...
510 
511   SmallVector<const Value *, 64> Bases, Ptrs;
512   SmallVector<const GCRelocateInst *, 64> Relocations;
513   getIncomingStatepointGCValues(Bases, Ptrs, Relocations, StatepointSite,
514                                 Builder);
515 
516 #ifndef NDEBUG
517   // Check that each of the gc pointer and bases we've gotten out of the
518   // safepoint is something the strategy thinks might be a pointer (or vector
519   // of pointers) into the GC heap.  This is basically just here to help catch
520   // errors during statepoint insertion. TODO: This should actually be in the
521   // Verifier, but we can't get to the GCStrategy from there (yet).
522   GCStrategy &S = Builder.GFI->getStrategy();
523   for (const Value *V : Bases) {
524     auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
525     if (Opt.hasValue()) {
526       assert(Opt.getValue() &&
527              "non gc managed base pointer found in statepoint");
528     }
529   }
530   for (const Value *V : Ptrs) {
531     auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
532     if (Opt.hasValue()) {
533       assert(Opt.getValue() &&
534              "non gc managed derived pointer found in statepoint");
535     }
536   }
537   for (const GCRelocateInst *GCR : Relocations) {
538     auto Opt = S.isGCManagedPointer(GCR->getType()->getScalarType());
539     if (Opt.hasValue()) {
540       assert(Opt.getValue() && "non gc managed pointer relocated");
541     }
542   }
543 #endif
544 
545   // Before we actually start lowering (and allocating spill slots for values),
546   // reserve any stack slots which we judge to be profitable to reuse for a
547   // particular value.  This is purely an optimization over the code below and
548   // doesn't change semantics at all.  It is important for performance that we
549   // reserve slots for both deopt and gc values before lowering either.
550   for (const Value *V : StatepointSite.vm_state_args()) {
551     reservePreviousStackSlotForValue(V, Builder);
552   }
553   for (unsigned i = 0; i < Bases.size(); ++i) {
554     reservePreviousStackSlotForValue(Bases[i], Builder);
555     reservePreviousStackSlotForValue(Ptrs[i], Builder);
556   }
557 
558   // First, prefix the list with the number of unique values to be
559   // lowered.  Note that this is the number of *Values* not the
560   // number of SDValues required to lower them.
561   const int NumVMSArgs = StatepointSite.getNumTotalVMSArgs();
562   pushStackMapConstant(Ops, Builder, NumVMSArgs);
563 
564   assert(NumVMSArgs == std::distance(StatepointSite.vm_state_begin(),
565                                      StatepointSite.vm_state_end()));
566 
567   // The vm state arguments are lowered in an opaque manner.  We do
568   // not know what type of values are contained within.  We skip the
569   // first one since that happens to be the total number we lowered
570   // explicitly just above.  We could have left it in the loop and
571   // not done it explicitly, but it's far easier to understand this
572   // way.
573   for (const Value *V : StatepointSite.vm_state_args()) {
574     SDValue Incoming = Builder.getValue(V);
575     lowerIncomingStatepointValue(Incoming, Ops, Builder);
576   }
577 
578   // Finally, go ahead and lower all the gc arguments.  There's no prefixed
579   // length for this one.  After lowering, we'll have the base and pointer
580   // arrays interwoven with each (lowered) base pointer immediately followed by
581   // it's (lowered) derived pointer.  i.e
582   // (base[0], ptr[0], base[1], ptr[1], ...)
583   for (unsigned i = 0; i < Bases.size(); ++i) {
584     const Value *Base = Bases[i];
585     lowerIncomingStatepointValue(Builder.getValue(Base), Ops, Builder);
586 
587     const Value *Ptr = Ptrs[i];
588     lowerIncomingStatepointValue(Builder.getValue(Ptr), Ops, Builder);
589   }
590 
591   // If there are any explicit spill slots passed to the statepoint, record
592   // them, but otherwise do not do anything special.  These are user provided
593   // allocas and give control over placement to the consumer.  In this case,
594   // it is the contents of the slot which may get updated, not the pointer to
595   // the alloca
596   for (Value *V : StatepointSite.gc_args()) {
597     SDValue Incoming = Builder.getValue(V);
598     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
599       // This handles allocas as arguments to the statepoint
600       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
601                                                     Incoming.getValueType()));
602     }
603   }
604 
605   // Record computed locations for all lowered values.
606   // This can not be embedded in lowering loops as we need to record *all*
607   // values, while previous loops account only values with unique SDValues.
608   const Instruction *StatepointInstr =
609     StatepointSite.getCallSite().getInstruction();
610   auto &SpillMap = Builder.FuncInfo.StatepointRelocatedValues[StatepointInstr];
611 
612   for (const GCRelocateInst *Relocate : StatepointSite.getRelocates()) {
613     const Value *V = Relocate->getDerivedPtr();
614     SDValue SDV = Builder.getValue(V);
615     SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
616 
617     if (Loc.getNode()) {
618       SpillMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
619     } else {
620       // Record value as visited, but not spilled. This is case for allocas
621       // and constants. For this values we can avoid emitting spill load while
622       // visiting corresponding gc_relocate.
623       // Actually we do not need to record them in this map at all.
624       // We do this only to check that we are not relocating any unvisited
625       // value.
626       SpillMap[V] = None;
627 
628       // Default llvm mechanisms for exporting values which are used in
629       // different basic blocks does not work for gc relocates.
630       // Note that it would be incorrect to teach llvm that all relocates are
631       // uses of the corresponding values so that it would automatically
632       // export them. Relocates of the spilled values does not use original
633       // value.
634       if (Relocate->getParent() != StatepointInstr->getParent())
635         Builder.ExportFromCurrentBlock(V);
636     }
637   }
638 }
639 
640 void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
641   // Check some preconditions for sanity
642   assert(isStatepoint(&CI) &&
643          "Function called must be the statepoint function");
644 
645   LowerStatepoint(ImmutableStatepoint(&CI));
646 }
647 
648 void SelectionDAGBuilder::LowerStatepoint(
649     ImmutableStatepoint ISP, const BasicBlock *EHPadBB /*= nullptr*/) {
650   // The basic scheme here is that information about both the original call and
651   // the safepoint is encoded in the CallInst.  We create a temporary call and
652   // lower it, then reverse engineer the calling sequence.
653 
654   NumOfStatepoints++;
655   // Clear state
656   StatepointLowering.startNewStatepoint(*this);
657 
658   ImmutableCallSite CS(ISP.getCallSite());
659 
660 #ifndef NDEBUG
661   // Consistency check. Check only relocates in the same basic block as thier
662   // statepoint.
663   for (const User *U : CS->users()) {
664     const CallInst *Call = cast<CallInst>(U);
665     if (isa<GCRelocateInst>(Call) && Call->getParent() == CS.getParent())
666       StatepointLowering.scheduleRelocCall(*Call);
667   }
668 #endif
669 
670 #ifndef NDEBUG
671   // If this is a malformed statepoint, report it early to simplify debugging.
672   // This should catch any IR level mistake that's made when constructing or
673   // transforming statepoints.
674   ISP.verify();
675 
676   // Check that the associated GCStrategy expects to encounter statepoints.
677   assert(GFI->getStrategy().useStatepoints() &&
678          "GCStrategy does not expect to encounter statepoints");
679 #endif
680 
681   // Lower statepoint vmstate and gcstate arguments
682   SmallVector<SDValue, 10> LoweredMetaArgs;
683   lowerStatepointMetaArgs(LoweredMetaArgs, ISP, *this);
684 
685   // Get call node, we will replace it later with statepoint
686   SDNode *CallNode =
687       lowerCallFromStatepoint(ISP, EHPadBB, *this, PendingExports);
688 
689   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
690   // nodes with all the appropriate arguments and return values.
691 
692   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
693   SDValue Chain = CallNode->getOperand(0);
694 
695   SDValue Glue;
696   bool CallHasIncomingGlue = CallNode->getGluedNode();
697   if (CallHasIncomingGlue) {
698     // Glue is always last operand
699     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
700   }
701 
702   // Build the GC_TRANSITION_START node if necessary.
703   //
704   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
705   // order in which they appear in the call to the statepoint intrinsic. If
706   // any of the operands is a pointer-typed, that operand is immediately
707   // followed by a SRCVALUE for the pointer that may be used during lowering
708   // (e.g. to form MachinePointerInfo values for loads/stores).
709   const bool IsGCTransition =
710       (ISP.getFlags() & (uint64_t)StatepointFlags::GCTransition) ==
711           (uint64_t)StatepointFlags::GCTransition;
712   if (IsGCTransition) {
713     SmallVector<SDValue, 8> TSOps;
714 
715     // Add chain
716     TSOps.push_back(Chain);
717 
718     // Add GC transition arguments
719     for (const Value *V : ISP.gc_transition_args()) {
720       TSOps.push_back(getValue(V));
721       if (V->getType()->isPointerTy())
722         TSOps.push_back(DAG.getSrcValue(V));
723     }
724 
725     // Add glue if necessary
726     if (CallHasIncomingGlue)
727       TSOps.push_back(Glue);
728 
729     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
730 
731     SDValue GCTransitionStart =
732         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
733 
734     Chain = GCTransitionStart.getValue(0);
735     Glue = GCTransitionStart.getValue(1);
736   }
737 
738   // TODO: Currently, all of these operands are being marked as read/write in
739   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
740   // and flags to be read-only.
741   SmallVector<SDValue, 40> Ops;
742 
743   // Add the <id> and <numBytes> constants.
744   Ops.push_back(DAG.getTargetConstant(ISP.getID(), getCurSDLoc(), MVT::i64));
745   Ops.push_back(
746       DAG.getTargetConstant(ISP.getNumPatchBytes(), getCurSDLoc(), MVT::i32));
747 
748   // Calculate and push starting position of vmstate arguments
749   // Get number of arguments incoming directly into call node
750   unsigned NumCallRegArgs =
751       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
752   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
753 
754   // Add call target
755   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
756   Ops.push_back(CallTarget);
757 
758   // Add call arguments
759   // Get position of register mask in the call
760   SDNode::op_iterator RegMaskIt;
761   if (CallHasIncomingGlue)
762     RegMaskIt = CallNode->op_end() - 2;
763   else
764     RegMaskIt = CallNode->op_end() - 1;
765   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
766 
767   // Add a constant argument for the calling convention
768   pushStackMapConstant(Ops, *this, CS.getCallingConv());
769 
770   // Add a constant argument for the flags
771   uint64_t Flags = ISP.getFlags();
772   assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
773          "Unknown flag used");
774   pushStackMapConstant(Ops, *this, Flags);
775 
776   // Insert all vmstate and gcstate arguments
777   Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
778 
779   // Add register mask from call node
780   Ops.push_back(*RegMaskIt);
781 
782   // Add chain
783   Ops.push_back(Chain);
784 
785   // Same for the glue, but we add it only if original call had it
786   if (Glue.getNode())
787     Ops.push_back(Glue);
788 
789   // Compute return values.  Provide a glue output since we consume one as
790   // input.  This allows someone else to chain off us as needed.
791   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
792 
793   SDNode *StatepointMCNode =
794       DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
795 
796   SDNode *SinkNode = StatepointMCNode;
797 
798   // Build the GC_TRANSITION_END node if necessary.
799   //
800   // See the comment above regarding GC_TRANSITION_START for the layout of
801   // the operands to the GC_TRANSITION_END node.
802   if (IsGCTransition) {
803     SmallVector<SDValue, 8> TEOps;
804 
805     // Add chain
806     TEOps.push_back(SDValue(StatepointMCNode, 0));
807 
808     // Add GC transition arguments
809     for (const Value *V : ISP.gc_transition_args()) {
810       TEOps.push_back(getValue(V));
811       if (V->getType()->isPointerTy())
812         TEOps.push_back(DAG.getSrcValue(V));
813     }
814 
815     // Add glue
816     TEOps.push_back(SDValue(StatepointMCNode, 1));
817 
818     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
819 
820     SDValue GCTransitionStart =
821         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
822 
823     SinkNode = GCTransitionStart.getNode();
824   }
825 
826   // Replace original call
827   DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
828   // Remove original call node
829   DAG.DeleteNode(CallNode);
830 
831   // DON'T set the root - under the assumption that it's already set past the
832   // inserted node we created.
833 
834   // TODO: A better future implementation would be to emit a single variable
835   // argument, variable return value STATEPOINT node here and then hookup the
836   // return value of each gc.relocate to the respective output of the
837   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
838   // to actually be possible today.
839 }
840 
841 void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
842   // The result value of the gc_result is simply the result of the actual
843   // call.  We've already emitted this, so just grab the value.
844   Instruction *I = cast<Instruction>(CI.getArgOperand(0));
845   assert(isStatepoint(I) && "first argument must be a statepoint token");
846 
847   if (I->getParent() != CI.getParent()) {
848     // Statepoint is in different basic block so we should have stored call
849     // result in a virtual register.
850     // We can not use default getValue() functionality to copy value from this
851     // register because statepoint and actuall call return types can be
852     // different, and getValue() will use CopyFromReg of the wrong type,
853     // which is always i32 in our case.
854     PointerType *CalleeType = cast<PointerType>(
855         ImmutableStatepoint(I).getCalledValue()->getType());
856     Type *RetTy =
857         cast<FunctionType>(CalleeType->getElementType())->getReturnType();
858     SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
859 
860     assert(CopyFromReg.getNode());
861     setValue(&CI, CopyFromReg);
862   } else {
863     setValue(&CI, getValue(I));
864   }
865 }
866 
867 void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
868 #ifndef NDEBUG
869   // Consistency check
870   // We skip this check for relocates not in the same basic block as thier
871   // statepoint. It would be too expensive to preserve validation info through
872   // different basic blocks.
873   if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
874     StatepointLowering.relocCallVisited(Relocate);
875 #endif
876 
877   const Value *DerivedPtr = Relocate.getDerivedPtr();
878   SDValue SD = getValue(DerivedPtr);
879 
880   FunctionLoweringInfo::StatepointSpilledValueMapTy &SpillMap =
881     FuncInfo.StatepointRelocatedValues[Relocate.getStatepoint()];
882 
883   // We should have recorded location for this pointer
884   assert(SpillMap.count(DerivedPtr) && "Relocating not lowered gc value");
885   Optional<int> DerivedPtrLocation = SpillMap[DerivedPtr];
886 
887   // We didn't need to spill these special cases (constants and allocas).
888   // See the handling in spillIncomingValueForStatepoint for detail.
889   if (!DerivedPtrLocation) {
890     setValue(&Relocate, SD);
891     return;
892   }
893 
894   SDValue SpillSlot = DAG.getTargetFrameIndex(*DerivedPtrLocation,
895                                               SD.getValueType());
896 
897   // Be conservative: flush all pending loads
898   // TODO: Probably we can be less restrictive on this,
899   // it may allow more scheduling opportunities.
900   SDValue Chain = getRoot();
901 
902   SDValue SpillLoad =
903       DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
904                   MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
905                                                     *DerivedPtrLocation),
906                   false, false, false, 0);
907 
908   // Again, be conservative, don't emit pending loads
909   DAG.setRoot(SpillLoad.getValue(1));
910 
911   assert(SpillLoad.getNode());
912   setValue(&Relocate, SpillLoad);
913 }
914