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