1 //===- StatepointLowering.cpp - SDAGBuilder's statepoint code -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file includes support code use by SelectionDAGBuilder when lowering a
10 // statepoint sequence in SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "StatepointLowering.h"
15 #include "SelectionDAGBuilder.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/FunctionLoweringInfo.h"
23 #include "llvm/CodeGen/GCMetadata.h"
24 #include "llvm/CodeGen/GCStrategy.h"
25 #include "llvm/CodeGen/ISDOpcodes.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/RuntimeLibcalls.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/StackMaps.h"
32 #include "llvm/CodeGen/TargetLowering.h"
33 #include "llvm/CodeGen/TargetOpcodes.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/Statepoint.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/MachineValueType.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include <cassert>
47 #include <cstddef>
48 #include <cstdint>
49 #include <iterator>
50 #include <tuple>
51 #include <utility>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "statepoint-lowering"
56 
57 STATISTIC(NumSlotsAllocatedForStatepoints,
58           "Number of stack slots allocated for statepoints");
59 STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
60 STATISTIC(StatepointMaxSlotsRequired,
61           "Maximum number of stack slots required for a singe statepoint");
62 
63 cl::opt<bool> UseRegistersForDeoptValues(
64     "use-registers-for-deopt-values", cl::Hidden, cl::init(false),
65     cl::desc("Allow using registers for non pointer deopt args"));
66 
67 cl::opt<bool> UseRegistersForGCPointersInLandingPad(
68     "use-registers-for-gc-values-in-landing-pad", cl::Hidden, cl::init(false),
69     cl::desc("Allow using registers for gc pointer in landing pad"));
70 
71 cl::opt<unsigned> MaxRegistersForGCPointers(
72     "max-registers-for-gc-values", cl::Hidden, cl::init(0),
73     cl::desc("Max number of VRegs allowed to pass GC pointer meta args in"));
74 
75 cl::opt<bool> AlwaysSpillBase("statepoint-always-spill-base", cl::Hidden,
76                               cl::init(true),
77                               cl::desc("Force spilling of base GC pointers"));
78 
79 typedef FunctionLoweringInfo::StatepointRelocationRecord RecordType;
80 
81 static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
82                                  SelectionDAGBuilder &Builder, uint64_t Value) {
83   SDLoc L = Builder.getCurSDLoc();
84   Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
85                                               MVT::i64));
86   Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
87 }
88 
89 void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
90   // Consistency check
91   assert(PendingGCRelocateCalls.empty() &&
92          "Trying to visit statepoint before finished processing previous one");
93   Locations.clear();
94   NextSlotToAllocate = 0;
95   // Need to resize this on each safepoint - we need the two to stay in sync and
96   // the clear patterns of a SelectionDAGBuilder have no relation to
97   // FunctionLoweringInfo.  Also need to ensure used bits get cleared.
98   AllocatedStackSlots.clear();
99   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
100 }
101 
102 void StatepointLoweringState::clear() {
103   Locations.clear();
104   AllocatedStackSlots.clear();
105   assert(PendingGCRelocateCalls.empty() &&
106          "cleared before statepoint sequence completed");
107 }
108 
109 SDValue
110 StatepointLoweringState::allocateStackSlot(EVT ValueType,
111                                            SelectionDAGBuilder &Builder) {
112   NumSlotsAllocatedForStatepoints++;
113   MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
114 
115   unsigned SpillSize = ValueType.getStoreSize();
116   assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?");
117 
118   // First look for a previously created stack slot which is not in
119   // use (accounting for the fact arbitrary slots may already be
120   // reserved), or to create a new stack slot and use it.
121 
122   const size_t NumSlots = AllocatedStackSlots.size();
123   assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
124 
125   assert(AllocatedStackSlots.size() ==
126          Builder.FuncInfo.StatepointStackSlots.size() &&
127          "Broken invariant");
128 
129   for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
130     if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
131       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
132       if (MFI.getObjectSize(FI) == SpillSize) {
133         AllocatedStackSlots.set(NextSlotToAllocate);
134         // TODO: Is ValueType the right thing to use here?
135         return Builder.DAG.getFrameIndex(FI, ValueType);
136       }
137     }
138   }
139 
140   // Couldn't find a free slot, so create a new one:
141 
142   SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
143   const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
144   MFI.markAsStatepointSpillSlotObjectIndex(FI);
145 
146   Builder.FuncInfo.StatepointStackSlots.push_back(FI);
147   AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
148   assert(AllocatedStackSlots.size() ==
149          Builder.FuncInfo.StatepointStackSlots.size() &&
150          "Broken invariant");
151 
152   StatepointMaxSlotsRequired.updateMax(
153       Builder.FuncInfo.StatepointStackSlots.size());
154 
155   return SpillSlot;
156 }
157 
158 /// Utility function for reservePreviousStackSlotForValue. Tries to find
159 /// stack slot index to which we have spilled value for previous statepoints.
160 /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
161 static Optional<int> findPreviousSpillSlot(const Value *Val,
162                                            SelectionDAGBuilder &Builder,
163                                            int LookUpDepth) {
164   // Can not look any further - give up now
165   if (LookUpDepth <= 0)
166     return None;
167 
168   // Spill location is known for gc relocates
169   if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
170     const auto &RelocationMap =
171         Builder.FuncInfo.StatepointRelocationMaps[Relocate->getStatepoint()];
172 
173     auto It = RelocationMap.find(Relocate->getDerivedPtr());
174     if (It == RelocationMap.end())
175       return None;
176 
177     auto &Record = It->second;
178     if (Record.type != RecordType::Spill)
179       return None;
180 
181     return Record.payload.FI;
182   }
183 
184   // Look through bitcast instructions.
185   if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
186     return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
187 
188   // Look through phi nodes
189   // All incoming values should have same known stack slot, otherwise result
190   // is unknown.
191   if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
192     Optional<int> MergedResult = None;
193 
194     for (auto &IncomingValue : Phi->incoming_values()) {
195       Optional<int> SpillSlot =
196           findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
197       if (!SpillSlot.hasValue())
198         return None;
199 
200       if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
201         return None;
202 
203       MergedResult = SpillSlot;
204     }
205     return MergedResult;
206   }
207 
208   // TODO: We can do better for PHI nodes. In cases like this:
209   //   ptr = phi(relocated_pointer, not_relocated_pointer)
210   //   statepoint(ptr)
211   // We will return that stack slot for ptr is unknown. And later we might
212   // assign different stack slots for ptr and relocated_pointer. This limits
213   // llvm's ability to remove redundant stores.
214   // Unfortunately it's hard to accomplish in current infrastructure.
215   // We use this function to eliminate spill store completely, while
216   // in example we still need to emit store, but instead of any location
217   // we need to use special "preferred" location.
218 
219   // TODO: handle simple updates.  If a value is modified and the original
220   // value is no longer live, it would be nice to put the modified value in the
221   // same slot.  This allows folding of the memory accesses for some
222   // instructions types (like an increment).
223   //   statepoint (i)
224   //   i1 = i+1
225   //   statepoint (i1)
226   // However we need to be careful for cases like this:
227   //   statepoint(i)
228   //   i1 = i+1
229   //   statepoint(i, i1)
230   // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
231   // put handling of simple modifications in this function like it's done
232   // for bitcasts we might end up reserving i's slot for 'i+1' because order in
233   // which we visit values is unspecified.
234 
235   // Don't know any information about this instruction
236   return None;
237 }
238 
239 /// Return true if-and-only-if the given SDValue can be lowered as either a
240 /// constant argument or a stack reference.  The key point is that the value
241 /// doesn't need to be spilled or tracked as a vreg use.
242 static bool willLowerDirectly(SDValue Incoming) {
243   // We are making an unchecked assumption that the frame size <= 2^16 as that
244   // is the largest offset which can be encoded in the stackmap format.
245   if (isa<FrameIndexSDNode>(Incoming))
246     return true;
247 
248   // The largest constant describeable in the StackMap format is 64 bits.
249   // Potential Optimization:  Constants values are sign extended by consumer,
250   // and thus there are many constants of static type > 64 bits whose value
251   // happens to be sext(Con64) and could thus be lowered directly.
252   if (Incoming.getValueType().getSizeInBits() > 64)
253     return false;
254 
255   return (isa<ConstantSDNode>(Incoming) || isa<ConstantFPSDNode>(Incoming) ||
256           Incoming.isUndef());
257 }
258 
259 /// Try to find existing copies of the incoming values in stack slots used for
260 /// statepoint spilling.  If we can find a spill slot for the incoming value,
261 /// mark that slot as allocated, and reuse the same slot for this safepoint.
262 /// This helps to avoid series of loads and stores that only serve to reshuffle
263 /// values on the stack between calls.
264 static void reservePreviousStackSlotForValue(const Value *IncomingValue,
265                                              SelectionDAGBuilder &Builder) {
266   SDValue Incoming = Builder.getValue(IncomingValue);
267 
268   // If we won't spill this, we don't need to check for previously allocated
269   // stack slots.
270   if (willLowerDirectly(Incoming))
271     return;
272 
273   SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
274   if (OldLocation.getNode())
275     // Duplicates in input
276     return;
277 
278   const int LookUpDepth = 6;
279   Optional<int> Index =
280       findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
281   if (!Index.hasValue())
282     return;
283 
284   const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
285 
286   auto SlotIt = find(StatepointSlots, *Index);
287   assert(SlotIt != StatepointSlots.end() &&
288          "Value spilled to the unknown stack slot");
289 
290   // This is one of our dedicated lowering slots
291   const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
292   if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
293     // stack slot already assigned to someone else, can't use it!
294     // TODO: currently we reserve space for gc arguments after doing
295     // normal allocation for deopt arguments.  We should reserve for
296     // _all_ deopt and gc arguments, then start allocating.  This
297     // will prevent some moves being inserted when vm state changes,
298     // but gc state doesn't between two calls.
299     return;
300   }
301   // Reserve this stack slot
302   Builder.StatepointLowering.reserveStackSlot(Offset);
303 
304   // Cache this slot so we find it when going through the normal
305   // assignment loop.
306   SDValue Loc =
307       Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
308   Builder.StatepointLowering.setLocation(Incoming, Loc);
309 }
310 
311 /// Extract call from statepoint, lower it and return pointer to the
312 /// call node. Also update NodeMap so that getValue(statepoint) will
313 /// reference lowered call result
314 static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
315     SelectionDAGBuilder::StatepointLoweringInfo &SI,
316     SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
317   SDValue ReturnValue, CallEndVal;
318   std::tie(ReturnValue, CallEndVal) =
319       Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
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   bool HasDef = !SI.CLI.RetTy->isVoidTy();
339   if (HasDef) {
340     if (CallEnd->getOpcode() == ISD::LOAD)
341       CallEnd = CallEnd->getOperand(0).getNode();
342     else
343       while (CallEnd->getOpcode() == ISD::CopyFromReg)
344         CallEnd = CallEnd->getOperand(0).getNode();
345   }
346 
347   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
348   return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
349 }
350 
351 static MachineMemOperand* getMachineMemOperand(MachineFunction &MF,
352                                                FrameIndexSDNode &FI) {
353   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
354   auto MMOFlags = MachineMemOperand::MOStore |
355     MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
356   auto &MFI = MF.getFrameInfo();
357   return MF.getMachineMemOperand(PtrInfo, MMOFlags,
358                                  MFI.getObjectSize(FI.getIndex()),
359                                  MFI.getObjectAlign(FI.getIndex()));
360 }
361 
362 /// Spill a value incoming to the statepoint. It might be either part of
363 /// vmstate
364 /// or gcstate. In both cases unconditionally spill it on the stack unless it
365 /// is a null constant. Return pair with first element being frame index
366 /// containing saved value and second element with outgoing chain from the
367 /// emitted store
368 static std::tuple<SDValue, SDValue, MachineMemOperand*>
369 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
370                              SelectionDAGBuilder &Builder) {
371   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
372   MachineMemOperand* MMO = nullptr;
373 
374   // Emit new store if we didn't do it for this ptr before
375   if (!Loc.getNode()) {
376     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
377                                                        Builder);
378     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
379     // We use TargetFrameIndex so that isel will not select it into LEA
380     Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
381 
382     // Right now we always allocate spill slots that are of the same
383     // size as the value we're about to spill (the size of spillee can
384     // vary since we spill vectors of pointers too).  At some point we
385     // can consider allowing spills of smaller values to larger slots
386     // (i.e. change the '==' in the assert below to a '>=').
387     MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
388     assert((MFI.getObjectSize(Index) * 8) ==
389            (int64_t)Incoming.getValueSizeInBits() &&
390            "Bad spill:  stack slot does not match!");
391 
392     // Note: Using the alignment of the spill slot (rather than the abi or
393     // preferred alignment) is required for correctness when dealing with spill
394     // slots with preferred alignments larger than frame alignment..
395     auto &MF = Builder.DAG.getMachineFunction();
396     auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
397     auto *StoreMMO = MF.getMachineMemOperand(
398         PtrInfo, MachineMemOperand::MOStore, MFI.getObjectSize(Index),
399         MFI.getObjectAlign(Index));
400     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
401                                  StoreMMO);
402 
403     MMO = getMachineMemOperand(MF, *cast<FrameIndexSDNode>(Loc));
404 
405     Builder.StatepointLowering.setLocation(Incoming, Loc);
406   }
407 
408   assert(Loc.getNode());
409   return std::make_tuple(Loc, Chain, MMO);
410 }
411 
412 /// Lower a single value incoming to a statepoint node.  This value can be
413 /// either a deopt value or a gc value, the handling is the same.  We special
414 /// case constants and allocas, then fall back to spilling if required.
415 static void
416 lowerIncomingStatepointValue(SDValue Incoming, bool RequireSpillSlot,
417                              SmallVectorImpl<SDValue> &Ops,
418                              SmallVectorImpl<MachineMemOperand *> &MemRefs,
419                              SelectionDAGBuilder &Builder) {
420 
421   if (willLowerDirectly(Incoming)) {
422     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
423       // This handles allocas as arguments to the statepoint (this is only
424       // really meaningful for a deopt value.  For GC, we'd be trying to
425       // relocate the address of the alloca itself?)
426       assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
427              "Incoming value is a frame index!");
428       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
429                                                     Builder.getFrameIndexTy()));
430 
431       auto &MF = Builder.DAG.getMachineFunction();
432       auto *MMO = getMachineMemOperand(MF, *FI);
433       MemRefs.push_back(MMO);
434       return;
435     }
436 
437     assert(Incoming.getValueType().getSizeInBits() <= 64);
438 
439     if (Incoming.isUndef()) {
440       // Put an easily recognized constant that's unlikely to be a valid
441       // value so that uses of undef by the consumer of the stackmap is
442       // easily recognized. This is legal since the compiler is always
443       // allowed to chose an arbitrary value for undef.
444       pushStackMapConstant(Ops, Builder, 0xFEFEFEFE);
445       return;
446     }
447 
448     // If the original value was a constant, make sure it gets recorded as
449     // such in the stackmap.  This is required so that the consumer can
450     // parse any internal format to the deopt state.  It also handles null
451     // pointers and other constant pointers in GC states.
452     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
453       pushStackMapConstant(Ops, Builder, C->getSExtValue());
454       return;
455     } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Incoming)) {
456       pushStackMapConstant(Ops, Builder,
457                            C->getValueAPF().bitcastToAPInt().getZExtValue());
458       return;
459     }
460 
461     llvm_unreachable("unhandled direct lowering case");
462   }
463 
464 
465 
466   if (!RequireSpillSlot) {
467     // If this value is live in (not live-on-return, or live-through), we can
468     // treat it the same way patchpoint treats it's "live in" values.  We'll
469     // end up folding some of these into stack references, but they'll be
470     // handled by the register allocator.  Note that we do not have the notion
471     // of a late use so these values might be placed in registers which are
472     // clobbered by the call.  This is fine for live-in. For live-through
473     // fix-up pass should be executed to force spilling of such registers.
474     Ops.push_back(Incoming);
475   } else {
476     // Otherwise, locate a spill slot and explicitly spill it so it can be
477     // found by the runtime later.  Note: We know all of these spills are
478     // independent, but don't bother to exploit that chain wise.  DAGCombine
479     // will happily do so as needed, so doing it here would be a small compile
480     // time win at most.
481     SDValue Chain = Builder.getRoot();
482     auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
483     Ops.push_back(std::get<0>(Res));
484     if (auto *MMO = std::get<2>(Res))
485       MemRefs.push_back(MMO);
486     Chain = std::get<1>(Res);;
487     Builder.DAG.setRoot(Chain);
488   }
489 
490 }
491 
492 /// Return true if value V represents the GC value. The behavior is conservative
493 /// in case it is not sure that value is not GC the function returns true.
494 static bool isGCValue(const Value *V, SelectionDAGBuilder &Builder) {
495   auto *Ty = V->getType();
496   if (!Ty->isPtrOrPtrVectorTy())
497     return false;
498   if (auto *GFI = Builder.GFI)
499     if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
500       return *IsManaged;
501   return true; // conservative
502 }
503 
504 /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
505 /// lowering is described in lowerIncomingStatepointValue.  This function is
506 /// responsible for lowering everything in the right position and playing some
507 /// tricks to avoid redundant stack manipulation where possible.  On
508 /// completion, 'Ops' will contain ready to use operands for machine code
509 /// statepoint. The chain nodes will have already been created and the DAG root
510 /// will be set to the last value spilled (if any were).
511 static void
512 lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
513                         SmallVectorImpl<MachineMemOperand *> &MemRefs,
514                         SmallVectorImpl<SDValue> &GCPtrs,
515                         DenseMap<SDValue, int> &LowerAsVReg,
516                         SelectionDAGBuilder::StatepointLoweringInfo &SI,
517                         SelectionDAGBuilder &Builder) {
518   // Lower the deopt and gc arguments for this statepoint.  Layout will be:
519   // deopt argument length, deopt arguments.., gc arguments...
520 #ifndef NDEBUG
521   if (auto *GFI = Builder.GFI) {
522     // Check that each of the gc pointer and bases we've gotten out of the
523     // safepoint is something the strategy thinks might be a pointer (or vector
524     // of pointers) into the GC heap.  This is basically just here to help catch
525     // errors during statepoint insertion. TODO: This should actually be in the
526     // Verifier, but we can't get to the GCStrategy from there (yet).
527     GCStrategy &S = GFI->getStrategy();
528     for (const Value *V : SI.Bases) {
529       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
530       if (Opt.hasValue()) {
531         assert(Opt.getValue() &&
532                "non gc managed base pointer found in statepoint");
533       }
534     }
535     for (const Value *V : SI.Ptrs) {
536       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
537       if (Opt.hasValue()) {
538         assert(Opt.getValue() &&
539                "non gc managed derived pointer found in statepoint");
540       }
541     }
542     assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");
543   } else {
544     assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
545     assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
546   }
547 #endif
548 
549   // Figure out what lowering strategy we're going to use for each part
550   // Note: Is is conservatively correct to lower both "live-in" and "live-out"
551   // as "live-through". A "live-through" variable is one which is "live-in",
552   // "live-out", and live throughout the lifetime of the call (i.e. we can find
553   // it from any PC within the transitive callee of the statepoint).  In
554   // particular, if the callee spills callee preserved registers we may not
555   // be able to find a value placed in that register during the call.  This is
556   // fine for live-out, but not for live-through.  If we were willing to make
557   // assumptions about the code generator producing the callee, we could
558   // potentially allow live-through values in callee saved registers.
559   const bool LiveInDeopt =
560     SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
561 
562   // Decide which deriver pointers will go on VRegs
563   unsigned MaxVRegPtrs = MaxRegistersForGCPointers.getValue();
564 
565   // Pointers used on exceptional path of invoke statepoint.
566   // We cannot assing them to VRegs.
567   SmallSet<SDValue, 8> LPadPointers;
568   if (!UseRegistersForGCPointersInLandingPad)
569     if (auto *StInvoke = dyn_cast_or_null<InvokeInst>(SI.StatepointInstr)) {
570       LandingPadInst *LPI = StInvoke->getLandingPadInst();
571       for (auto *Relocate : SI.GCRelocates)
572         if (Relocate->getOperand(0) == LPI) {
573           LPadPointers.insert(Builder.getValue(Relocate->getBasePtr()));
574           LPadPointers.insert(Builder.getValue(Relocate->getDerivedPtr()));
575         }
576     }
577 
578   LLVM_DEBUG(dbgs() << "Deciding how to lower GC Pointers:\n");
579 
580   // List of unique lowered GC Pointer values.
581   SmallSetVector<SDValue, 16> LoweredGCPtrs;
582   // Map lowered GC Pointer value to the index in above vector
583   DenseMap<SDValue, unsigned> GCPtrIndexMap;
584 
585   unsigned CurNumVRegs = 0;
586 
587   auto canPassGCPtrOnVReg = [&](SDValue SD) {
588     if (SD.getValueType().isVector())
589       return false;
590     if (LPadPointers.count(SD))
591       return false;
592     return !willLowerDirectly(SD);
593   };
594 
595   auto processGCPtr = [&](const Value *V) {
596     SDValue PtrSD = Builder.getValue(V);
597     if (!LoweredGCPtrs.insert(PtrSD))
598       return; // skip duplicates
599     GCPtrIndexMap[PtrSD] = LoweredGCPtrs.size() - 1;
600 
601     assert(!LowerAsVReg.count(PtrSD) && "must not have been seen");
602     if (LowerAsVReg.size() == MaxVRegPtrs)
603       return;
604     assert(V->getType()->isVectorTy() == PtrSD.getValueType().isVector() &&
605            "IR and SD types disagree");
606     if (!canPassGCPtrOnVReg(PtrSD)) {
607       LLVM_DEBUG(dbgs() << "direct/spill "; PtrSD.dump(&Builder.DAG));
608       return;
609     }
610     LLVM_DEBUG(dbgs() << "vreg "; PtrSD.dump(&Builder.DAG));
611     LowerAsVReg[PtrSD] = CurNumVRegs++;
612   };
613 
614   // Process derived pointers first to give them more chance to go on VReg.
615   for (const Value *V : SI.Ptrs)
616     processGCPtr(V);
617   for (const Value *V : SI.Bases)
618     processGCPtr(V);
619 
620   LLVM_DEBUG(dbgs() << LowerAsVReg.size() << " pointers will go in vregs\n");
621 
622   auto requireSpillSlot = [&](const Value *V) {
623     if (!Builder.DAG.getTargetLoweringInfo().isTypeLegal(
624              Builder.getValue(V).getValueType()))
625       return true;
626     if (isGCValue(V, Builder))
627       return !LowerAsVReg.count(Builder.getValue(V));
628     return !(LiveInDeopt || UseRegistersForDeoptValues);
629   };
630 
631   // Before we actually start lowering (and allocating spill slots for values),
632   // reserve any stack slots which we judge to be profitable to reuse for a
633   // particular value.  This is purely an optimization over the code below and
634   // doesn't change semantics at all.  It is important for performance that we
635   // reserve slots for both deopt and gc values before lowering either.
636   for (const Value *V : SI.DeoptState) {
637     if (requireSpillSlot(V))
638       reservePreviousStackSlotForValue(V, Builder);
639   }
640 
641   for (const Value *V : SI.Ptrs) {
642     SDValue SDV = Builder.getValue(V);
643     if (!LowerAsVReg.count(SDV))
644       reservePreviousStackSlotForValue(V, Builder);
645   }
646 
647   for (const Value *V : SI.Bases) {
648     SDValue SDV = Builder.getValue(V);
649     if (!LowerAsVReg.count(SDV))
650       reservePreviousStackSlotForValue(V, Builder);
651   }
652 
653   // First, prefix the list with the number of unique values to be
654   // lowered.  Note that this is the number of *Values* not the
655   // number of SDValues required to lower them.
656   const int NumVMSArgs = SI.DeoptState.size();
657   pushStackMapConstant(Ops, Builder, NumVMSArgs);
658 
659   // The vm state arguments are lowered in an opaque manner.  We do not know
660   // what type of values are contained within.
661   LLVM_DEBUG(dbgs() << "Lowering deopt state\n");
662   for (const Value *V : SI.DeoptState) {
663     SDValue Incoming;
664     // If this is a function argument at a static frame index, generate it as
665     // the frame index.
666     if (const Argument *Arg = dyn_cast<Argument>(V)) {
667       int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
668       if (FI != INT_MAX)
669         Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy());
670     }
671     if (!Incoming.getNode())
672       Incoming = Builder.getValue(V);
673     LLVM_DEBUG(dbgs() << "Value " << *V
674                       << " requireSpillSlot = " << requireSpillSlot(V) << "\n");
675     lowerIncomingStatepointValue(Incoming, requireSpillSlot(V), Ops, MemRefs,
676                                  Builder);
677   }
678 
679   // Finally, go ahead and lower all the gc arguments.
680   pushStackMapConstant(Ops, Builder, LoweredGCPtrs.size());
681   for (SDValue SDV : LoweredGCPtrs)
682     lowerIncomingStatepointValue(SDV, !LowerAsVReg.count(SDV), Ops, MemRefs,
683                                  Builder);
684 
685   // Copy to out vector. LoweredGCPtrs will be empty after this point.
686   GCPtrs = LoweredGCPtrs.takeVector();
687 
688   // If there are any explicit spill slots passed to the statepoint, record
689   // them, but otherwise do not do anything special.  These are user provided
690   // allocas and give control over placement to the consumer.  In this case,
691   // it is the contents of the slot which may get updated, not the pointer to
692   // the alloca
693   SmallVector<SDValue, 4> Allocas;
694   for (Value *V : SI.GCArgs) {
695     SDValue Incoming = Builder.getValue(V);
696     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
697       // This handles allocas as arguments to the statepoint
698       assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
699              "Incoming value is a frame index!");
700       Allocas.push_back(Builder.DAG.getTargetFrameIndex(
701           FI->getIndex(), Builder.getFrameIndexTy()));
702 
703       auto &MF = Builder.DAG.getMachineFunction();
704       auto *MMO = getMachineMemOperand(MF, *FI);
705       MemRefs.push_back(MMO);
706     }
707   }
708   pushStackMapConstant(Ops, Builder, Allocas.size());
709   Ops.append(Allocas.begin(), Allocas.end());
710 
711   // Now construct GC base/derived map;
712   pushStackMapConstant(Ops, Builder, SI.Ptrs.size());
713   SDLoc L = Builder.getCurSDLoc();
714   for (unsigned i = 0; i < SI.Ptrs.size(); ++i) {
715     SDValue Base = Builder.getValue(SI.Bases[i]);
716     assert(GCPtrIndexMap.count(Base) && "base not found in index map");
717     Ops.push_back(
718         Builder.DAG.getTargetConstant(GCPtrIndexMap[Base], L, MVT::i64));
719     SDValue Derived = Builder.getValue(SI.Ptrs[i]);
720     assert(GCPtrIndexMap.count(Derived) && "derived not found in index map");
721     Ops.push_back(
722         Builder.DAG.getTargetConstant(GCPtrIndexMap[Derived], L, MVT::i64));
723   }
724 }
725 
726 SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
727     SelectionDAGBuilder::StatepointLoweringInfo &SI) {
728   // The basic scheme here is that information about both the original call and
729   // the safepoint is encoded in the CallInst.  We create a temporary call and
730   // lower it, then reverse engineer the calling sequence.
731 
732   NumOfStatepoints++;
733   // Clear state
734   StatepointLowering.startNewStatepoint(*this);
735   assert(SI.Bases.size() == SI.Ptrs.size());
736 
737   LLVM_DEBUG(dbgs() << "Lowering statepoint " << *SI.StatepointInstr << "\n");
738 #ifndef NDEBUG
739   for (auto *Reloc : SI.GCRelocates)
740     if (Reloc->getParent() == SI.StatepointInstr->getParent())
741       StatepointLowering.scheduleRelocCall(*Reloc);
742 #endif
743 
744   // Lower statepoint vmstate and gcstate arguments
745 
746   // All lowered meta args.
747   SmallVector<SDValue, 10> LoweredMetaArgs;
748   // Lowered GC pointers (subset of above).
749   SmallVector<SDValue, 16> LoweredGCArgs;
750   SmallVector<MachineMemOperand*, 16> MemRefs;
751   // Maps derived pointer SDValue to statepoint result of relocated pointer.
752   DenseMap<SDValue, int> LowerAsVReg;
753   lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, LoweredGCArgs, LowerAsVReg,
754                           SI, *this);
755 
756   // Now that we've emitted the spills, we need to update the root so that the
757   // call sequence is ordered correctly.
758   SI.CLI.setChain(getRoot());
759 
760   // Get call node, we will replace it later with statepoint
761   SDValue ReturnVal;
762   SDNode *CallNode;
763   std::tie(ReturnVal, CallNode) =
764       lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
765 
766   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
767   // nodes with all the appropriate arguments and return values.
768 
769   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
770   SDValue Chain = CallNode->getOperand(0);
771 
772   SDValue Glue;
773   bool CallHasIncomingGlue = CallNode->getGluedNode();
774   if (CallHasIncomingGlue) {
775     // Glue is always last operand
776     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
777   }
778 
779   // Build the GC_TRANSITION_START node if necessary.
780   //
781   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
782   // order in which they appear in the call to the statepoint intrinsic. If
783   // any of the operands is a pointer-typed, that operand is immediately
784   // followed by a SRCVALUE for the pointer that may be used during lowering
785   // (e.g. to form MachinePointerInfo values for loads/stores).
786   const bool IsGCTransition =
787       (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
788       (uint64_t)StatepointFlags::GCTransition;
789   if (IsGCTransition) {
790     SmallVector<SDValue, 8> TSOps;
791 
792     // Add chain
793     TSOps.push_back(Chain);
794 
795     // Add GC transition arguments
796     for (const Value *V : SI.GCTransitionArgs) {
797       TSOps.push_back(getValue(V));
798       if (V->getType()->isPointerTy())
799         TSOps.push_back(DAG.getSrcValue(V));
800     }
801 
802     // Add glue if necessary
803     if (CallHasIncomingGlue)
804       TSOps.push_back(Glue);
805 
806     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
807 
808     SDValue GCTransitionStart =
809         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
810 
811     Chain = GCTransitionStart.getValue(0);
812     Glue = GCTransitionStart.getValue(1);
813   }
814 
815   // TODO: Currently, all of these operands are being marked as read/write in
816   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
817   // and flags to be read-only.
818   SmallVector<SDValue, 40> Ops;
819 
820   // Add the <id> and <numBytes> constants.
821   Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
822   Ops.push_back(
823       DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
824 
825   // Calculate and push starting position of vmstate arguments
826   // Get number of arguments incoming directly into call node
827   unsigned NumCallRegArgs =
828       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
829   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
830 
831   // Add call target
832   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
833   Ops.push_back(CallTarget);
834 
835   // Add call arguments
836   // Get position of register mask in the call
837   SDNode::op_iterator RegMaskIt;
838   if (CallHasIncomingGlue)
839     RegMaskIt = CallNode->op_end() - 2;
840   else
841     RegMaskIt = CallNode->op_end() - 1;
842   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
843 
844   // Add a constant argument for the calling convention
845   pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
846 
847   // Add a constant argument for the flags
848   uint64_t Flags = SI.StatepointFlags;
849   assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
850          "Unknown flag used");
851   pushStackMapConstant(Ops, *this, Flags);
852 
853   // Insert all vmstate and gcstate arguments
854   llvm::append_range(Ops, LoweredMetaArgs);
855 
856   // Add register mask from call node
857   Ops.push_back(*RegMaskIt);
858 
859   // Add chain
860   Ops.push_back(Chain);
861 
862   // Same for the glue, but we add it only if original call had it
863   if (Glue.getNode())
864     Ops.push_back(Glue);
865 
866   // Compute return values.  Provide a glue output since we consume one as
867   // input.  This allows someone else to chain off us as needed.
868   SmallVector<EVT, 8> NodeTys;
869   for (auto SD : LoweredGCArgs) {
870     if (!LowerAsVReg.count(SD))
871       continue;
872     NodeTys.push_back(SD.getValueType());
873   }
874   LLVM_DEBUG(dbgs() << "Statepoint has " << NodeTys.size() << " results\n");
875   assert(NodeTys.size() == LowerAsVReg.size() && "Inconsistent GC Ptr lowering");
876   NodeTys.push_back(MVT::Other);
877   NodeTys.push_back(MVT::Glue);
878 
879   unsigned NumResults = NodeTys.size();
880   MachineSDNode *StatepointMCNode =
881     DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
882   DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
883 
884   // For values lowered to tied-defs, create the virtual registers.  Note that
885   // for simplicity, we *always* create a vreg even within a single block.
886   DenseMap<SDValue, Register> VirtRegs;
887   for (const auto *Relocate : SI.GCRelocates) {
888     Value *Derived = Relocate->getDerivedPtr();
889     SDValue SD = getValue(Derived);
890     if (!LowerAsVReg.count(SD))
891       continue;
892 
893     // Handle multiple gc.relocates of the same input efficiently.
894     if (VirtRegs.count(SD))
895       continue;
896 
897     SDValue Relocated = SDValue(StatepointMCNode, LowerAsVReg[SD]);
898 
899     auto *RetTy = Relocate->getType();
900     Register Reg = FuncInfo.CreateRegs(RetTy);
901     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
902                      DAG.getDataLayout(), Reg, RetTy, None);
903     SDValue Chain = DAG.getRoot();
904     RFV.getCopyToRegs(Relocated, DAG, getCurSDLoc(), Chain, nullptr);
905     PendingExports.push_back(Chain);
906 
907     VirtRegs[SD] = Reg;
908   }
909 
910   // Record for later use how each relocation was lowered.  This is needed to
911   // allow later gc.relocates to mirror the lowering chosen.
912   const Instruction *StatepointInstr = SI.StatepointInstr;
913   auto &RelocationMap = FuncInfo.StatepointRelocationMaps[StatepointInstr];
914   for (const GCRelocateInst *Relocate : SI.GCRelocates) {
915     const Value *V = Relocate->getDerivedPtr();
916     SDValue SDV = getValue(V);
917     SDValue Loc = StatepointLowering.getLocation(SDV);
918 
919     RecordType Record;
920     if (LowerAsVReg.count(SDV)) {
921       Record.type = RecordType::VReg;
922       assert(VirtRegs.count(SDV));
923       Record.payload.Reg = VirtRegs[SDV];
924     } else if (Loc.getNode()) {
925       Record.type = RecordType::Spill;
926       Record.payload.FI = cast<FrameIndexSDNode>(Loc)->getIndex();
927     } else {
928       Record.type = RecordType::NoRelocate;
929       // If we didn't relocate a value, we'll essentialy end up inserting an
930       // additional use of the original value when lowering the gc.relocate.
931       // We need to make sure the value is available at the new use, which
932       // might be in another block.
933       if (Relocate->getParent() != StatepointInstr->getParent())
934         ExportFromCurrentBlock(V);
935     }
936     RelocationMap[V] = Record;
937   }
938 
939 
940 
941   SDNode *SinkNode = StatepointMCNode;
942 
943   // Build the GC_TRANSITION_END node if necessary.
944   //
945   // See the comment above regarding GC_TRANSITION_START for the layout of
946   // the operands to the GC_TRANSITION_END node.
947   if (IsGCTransition) {
948     SmallVector<SDValue, 8> TEOps;
949 
950     // Add chain
951     TEOps.push_back(SDValue(StatepointMCNode, NumResults - 2));
952 
953     // Add GC transition arguments
954     for (const Value *V : SI.GCTransitionArgs) {
955       TEOps.push_back(getValue(V));
956       if (V->getType()->isPointerTy())
957         TEOps.push_back(DAG.getSrcValue(V));
958     }
959 
960     // Add glue
961     TEOps.push_back(SDValue(StatepointMCNode, NumResults - 1));
962 
963     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
964 
965     SDValue GCTransitionStart =
966         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
967 
968     SinkNode = GCTransitionStart.getNode();
969   }
970 
971   // Replace original call
972   // Call: ch,glue = CALL ...
973   // Statepoint: [gc relocates],ch,glue = STATEPOINT ...
974   unsigned NumSinkValues = SinkNode->getNumValues();
975   SDValue StatepointValues[2] = {SDValue(SinkNode, NumSinkValues - 2),
976                                  SDValue(SinkNode, NumSinkValues - 1)};
977   DAG.ReplaceAllUsesWith(CallNode, StatepointValues);
978   // Remove original call node
979   DAG.DeleteNode(CallNode);
980 
981   // Since we always emit CopyToRegs (even for local relocates), we must
982   // update root, so that they are emitted before any local uses.
983   (void)getControlRoot();
984 
985   // TODO: A better future implementation would be to emit a single variable
986   // argument, variable return value STATEPOINT node here and then hookup the
987   // return value of each gc.relocate to the respective output of the
988   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
989   // to actually be possible today.
990 
991   return ReturnVal;
992 }
993 
994 void
995 SelectionDAGBuilder::LowerStatepoint(const GCStatepointInst &I,
996                                      const BasicBlock *EHPadBB /*= nullptr*/) {
997   assert(I.getCallingConv() != CallingConv::AnyReg &&
998          "anyregcc is not supported on statepoints!");
999 
1000 #ifndef NDEBUG
1001   // Check that the associated GCStrategy expects to encounter statepoints.
1002   assert(GFI->getStrategy().useStatepoints() &&
1003          "GCStrategy does not expect to encounter statepoints");
1004 #endif
1005 
1006   SDValue ActualCallee;
1007   SDValue Callee = getValue(I.getActualCalledOperand());
1008 
1009   if (I.getNumPatchBytes() > 0) {
1010     // If we've been asked to emit a nop sequence instead of a call instruction
1011     // for this statepoint then don't lower the call target, but use a constant
1012     // `undef` instead.  Not lowering the call target lets statepoint clients
1013     // get away without providing a physical address for the symbolic call
1014     // target at link time.
1015     ActualCallee = DAG.getUNDEF(Callee.getValueType());
1016   } else {
1017     ActualCallee = Callee;
1018   }
1019 
1020   StatepointLoweringInfo SI(DAG);
1021   populateCallLoweringInfo(SI.CLI, &I, GCStatepointInst::CallArgsBeginPos,
1022                            I.getNumCallArgs(), ActualCallee,
1023                            I.getActualReturnType(), false /* IsPatchPoint */);
1024 
1025   // There may be duplication in the gc.relocate list; such as two copies of
1026   // each relocation on normal and exceptional path for an invoke.  We only
1027   // need to spill once and record one copy in the stackmap, but we need to
1028   // reload once per gc.relocate.  (Dedupping gc.relocates is trickier and best
1029   // handled as a CSE problem elsewhere.)
1030   // TODO: There a couple of major stackmap size optimizations we could do
1031   // here if we wished.
1032   // 1) If we've encountered a derived pair {B, D}, we don't need to actually
1033   // record {B,B} if it's seen later.
1034   // 2) Due to rematerialization, actual derived pointers are somewhat rare;
1035   // given that, we could change the format to record base pointer relocations
1036   // separately with half the space. This would require a format rev and a
1037   // fairly major rework of the STATEPOINT node though.
1038   SmallSet<SDValue, 8> Seen;
1039   for (const GCRelocateInst *Relocate : I.getGCRelocates()) {
1040     SI.GCRelocates.push_back(Relocate);
1041 
1042     SDValue DerivedSD = getValue(Relocate->getDerivedPtr());
1043     if (Seen.insert(DerivedSD).second) {
1044       SI.Bases.push_back(Relocate->getBasePtr());
1045       SI.Ptrs.push_back(Relocate->getDerivedPtr());
1046     }
1047   }
1048 
1049   // If we find a deopt value which isn't explicitly added, we need to
1050   // ensure it gets lowered such that gc cycles occurring before the
1051   // deoptimization event during the lifetime of the call don't invalidate
1052   // the pointer we're deopting with.  Note that we assume that all
1053   // pointers passed to deopt are base pointers; relaxing that assumption
1054   // would require relatively large changes to how we represent relocations.
1055   for (Value *V : I.deopt_operands()) {
1056     if (!isGCValue(V, *this))
1057       continue;
1058     if (Seen.insert(getValue(V)).second) {
1059       SI.Bases.push_back(V);
1060       SI.Ptrs.push_back(V);
1061     }
1062   }
1063 
1064   SI.GCArgs = ArrayRef<const Use>(I.gc_args_begin(), I.gc_args_end());
1065   SI.StatepointInstr = &I;
1066   SI.ID = I.getID();
1067 
1068   SI.DeoptState = ArrayRef<const Use>(I.deopt_begin(), I.deopt_end());
1069   SI.GCTransitionArgs = ArrayRef<const Use>(I.gc_transition_args_begin(),
1070                                             I.gc_transition_args_end());
1071 
1072   SI.StatepointFlags = I.getFlags();
1073   SI.NumPatchBytes = I.getNumPatchBytes();
1074   SI.EHPadBB = EHPadBB;
1075 
1076   SDValue ReturnValue = LowerAsSTATEPOINT(SI);
1077 
1078   // Export the result value if needed
1079   const GCResultInst *GCResult = I.getGCResult();
1080   Type *RetTy = I.getActualReturnType();
1081 
1082   if (RetTy->isVoidTy() || !GCResult) {
1083     // The return value is not needed, just generate a poison value.
1084     setValue(&I, DAG.getIntPtrConstant(-1, getCurSDLoc()));
1085     return;
1086   }
1087 
1088   if (GCResult->getParent() == I.getParent()) {
1089     // Result value will be used in a same basic block. Don't export it or
1090     // perform any explicit register copies. The gc_result will simply grab
1091     // this value.
1092     setValue(&I, ReturnValue);
1093     return;
1094   }
1095 
1096   // Result value will be used in a different basic block so we need to export
1097   // it now.  Default exporting mechanism will not work here because statepoint
1098   // call has a different type than the actual call. It means that by default
1099   // llvm will create export register of the wrong type (always i32 in our
1100   // case). So instead we need to create export register with correct type
1101   // manually.
1102   // TODO: To eliminate this problem we can remove gc.result intrinsics
1103   //       completely and make statepoint call to return a tuple.
1104   unsigned Reg = FuncInfo.CreateRegs(RetTy);
1105   RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1106                    DAG.getDataLayout(), Reg, RetTy,
1107                    I.getCallingConv());
1108   SDValue Chain = DAG.getEntryNode();
1109 
1110   RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
1111   PendingExports.push_back(Chain);
1112   FuncInfo.ValueMap[&I] = Reg;
1113 }
1114 
1115 void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
1116     const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
1117     bool VarArgDisallowed, bool ForceVoidReturnTy) {
1118   StatepointLoweringInfo SI(DAG);
1119   unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
1120   populateCallLoweringInfo(
1121       SI.CLI, Call, ArgBeginIndex, Call->getNumArgOperands(), Callee,
1122       ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
1123       false);
1124   if (!VarArgDisallowed)
1125     SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
1126 
1127   auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
1128 
1129   unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
1130 
1131   auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
1132   SI.ID = SD.StatepointID.getValueOr(DefaultID);
1133   SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
1134 
1135   SI.DeoptState =
1136       ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
1137   SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
1138   SI.EHPadBB = EHPadBB;
1139 
1140   // NB! The GC arguments are deliberately left empty.
1141 
1142   if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
1143     ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
1144     setValue(Call, ReturnVal);
1145   }
1146 }
1147 
1148 void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
1149     const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
1150   LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
1151                                    /* VarArgDisallowed = */ false,
1152                                    /* ForceVoidReturnTy  = */ false);
1153 }
1154 
1155 void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
1156   // The result value of the gc_result is simply the result of the actual
1157   // call.  We've already emitted this, so just grab the value.
1158   const GCStatepointInst *SI = CI.getStatepoint();
1159 
1160   if (SI->getParent() == CI.getParent()) {
1161     setValue(&CI, getValue(SI));
1162     return;
1163   }
1164   // Statepoint is in different basic block so we should have stored call
1165   // result in a virtual register.
1166   // We can not use default getValue() functionality to copy value from this
1167   // register because statepoint and actual call return types can be
1168   // different, and getValue() will use CopyFromReg of the wrong type,
1169   // which is always i32 in our case.
1170   Type *RetTy = SI->getActualReturnType();
1171   SDValue CopyFromReg = getCopyFromRegs(SI, RetTy);
1172 
1173   assert(CopyFromReg.getNode());
1174   setValue(&CI, CopyFromReg);
1175 }
1176 
1177 void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
1178 #ifndef NDEBUG
1179   // Consistency check
1180   // We skip this check for relocates not in the same basic block as their
1181   // statepoint. It would be too expensive to preserve validation info through
1182   // different basic blocks.
1183   if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
1184     StatepointLowering.relocCallVisited(Relocate);
1185 
1186   auto *Ty = Relocate.getType()->getScalarType();
1187   if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
1188     assert(*IsManaged && "Non gc managed pointer relocated!");
1189 #endif
1190 
1191   const Value *DerivedPtr = Relocate.getDerivedPtr();
1192   auto &RelocationMap =
1193     FuncInfo.StatepointRelocationMaps[Relocate.getStatepoint()];
1194   auto SlotIt = RelocationMap.find(DerivedPtr);
1195   assert(SlotIt != RelocationMap.end() && "Relocating not lowered gc value");
1196   const RecordType &Record = SlotIt->second;
1197 
1198   // If relocation was done via virtual register..
1199   if (Record.type == RecordType::VReg) {
1200     Register InReg = Record.payload.Reg;
1201     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1202                      DAG.getDataLayout(), InReg, Relocate.getType(),
1203                      None); // This is not an ABI copy.
1204     // We generate copy to/from regs even for local uses, hence we must
1205     // chain with current root to ensure proper ordering of copies w.r.t.
1206     // statepoint.
1207     SDValue Chain = DAG.getRoot();
1208     SDValue Relocation = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
1209                                              Chain, nullptr, nullptr);
1210     setValue(&Relocate, Relocation);
1211     return;
1212   }
1213 
1214   SDValue SD = getValue(DerivedPtr);
1215 
1216   if (SD.isUndef() && SD.getValueType().getSizeInBits() <= 64) {
1217     // Lowering relocate(undef) as arbitrary constant. Current constant value
1218     // is chosen such that it's unlikely to be a valid pointer.
1219     setValue(&Relocate, DAG.getTargetConstant(0xFEFEFEFE, SDLoc(SD), MVT::i64));
1220     return;
1221   }
1222 
1223 
1224   // We didn't need to spill these special cases (constants and allocas).
1225   // See the handling in spillIncomingValueForStatepoint for detail.
1226   if (Record.type == RecordType::NoRelocate) {
1227     setValue(&Relocate, SD);
1228     return;
1229   }
1230 
1231   assert(Record.type == RecordType::Spill);
1232 
1233   unsigned Index = Record.payload.FI;;
1234   SDValue SpillSlot = DAG.getTargetFrameIndex(Index, getFrameIndexTy());
1235 
1236   // All the reloads are independent and are reading memory only modified by
1237   // statepoints (i.e. no other aliasing stores); informing SelectionDAG of
1238   // this this let's CSE kick in for free and allows reordering of instructions
1239   // if possible.  The lowering for statepoint sets the root, so this is
1240   // ordering all reloads with the either a) the statepoint node itself, or b)
1241   // the entry of the current block for an invoke statepoint.
1242   const SDValue Chain = DAG.getRoot(); // != Builder.getRoot()
1243 
1244   auto &MF = DAG.getMachineFunction();
1245   auto &MFI = MF.getFrameInfo();
1246   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
1247   auto *LoadMMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
1248                                           MFI.getObjectSize(Index),
1249                                           MFI.getObjectAlign(Index));
1250 
1251   auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
1252                                                          Relocate.getType());
1253 
1254   SDValue SpillLoad = DAG.getLoad(LoadVT, getCurSDLoc(), Chain,
1255                                   SpillSlot, LoadMMO);
1256   PendingLoads.push_back(SpillLoad.getValue(1));
1257 
1258   assert(SpillLoad.getNode());
1259   setValue(&Relocate, SpillLoad);
1260 }
1261 
1262 void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
1263   const auto &TLI = DAG.getTargetLoweringInfo();
1264   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
1265                                          TLI.getPointerTy(DAG.getDataLayout()));
1266 
1267   // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
1268   // call.  We also do not lower the return value to any virtual register, and
1269   // change the immediately following return to a trap instruction.
1270   LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
1271                                    /* VarArgDisallowed = */ true,
1272                                    /* ForceVoidReturnTy = */ true);
1273 }
1274 
1275 void SelectionDAGBuilder::LowerDeoptimizingReturn() {
1276   // We do not lower the return value from llvm.deoptimize to any virtual
1277   // register, and change the immediately following return to a trap
1278   // instruction.
1279   if (DAG.getTarget().Options.TrapUnreachable)
1280     DAG.setRoot(
1281         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
1282 }
1283