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