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   const unsigned MaxTiedRegs = 15; // Max  number of tied regs MI can have.
548   unsigned MaxVRegPtrs =
549       std::min(MaxTiedRegs, MaxRegistersForGCPointers.getValue());
550 
551   LLVM_DEBUG(dbgs() << "Deciding how to lower GC Pointers:\n");
552 
553   // List of unique lowered GC Pointer values.
554   SmallSetVector<SDValue, 16> LoweredGCPtrs;
555   // Map lowered GC Pointer value to the index in above vector
556   DenseMap<SDValue, unsigned> GCPtrIndexMap;
557 
558   unsigned CurNumVRegs = 0;
559 
560   auto processGCPtr = [&](const Value *V) {
561     SDValue PtrSD = Builder.getValue(V);
562     if (!LoweredGCPtrs.insert(PtrSD))
563       return; // skip duplicates
564     GCPtrIndexMap[PtrSD] = LoweredGCPtrs.size() - 1;
565 
566     assert(!LowerAsVReg.count(PtrSD) && "must not have been seen");
567     if (LowerAsVReg.size() == MaxVRegPtrs)
568       return;
569     if (willLowerDirectly(PtrSD) || V->getType()->isVectorTy()) {
570       LLVM_DEBUG(dbgs() << "direct/spill "; PtrSD.dump(&Builder.DAG));
571       return;
572     }
573     LLVM_DEBUG(dbgs() << "vreg "; PtrSD.dump(&Builder.DAG));
574     LowerAsVReg[PtrSD] = CurNumVRegs++;
575   };
576 
577   // Process derived pointers first to give them more chance to go on VReg.
578   for (const Value *V : SI.Ptrs)
579     processGCPtr(V);
580   for (const Value *V : SI.Bases)
581     processGCPtr(V);
582 
583   LLVM_DEBUG(dbgs() << LowerAsVReg.size() << " pointers will go in vregs\n");
584 
585   auto isGCValue = [&](const Value *V) {
586     auto *Ty = V->getType();
587     if (!Ty->isPtrOrPtrVectorTy())
588       return false;
589     if (auto *GFI = Builder.GFI)
590       if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
591         return *IsManaged;
592     return true; // conservative
593   };
594 
595   auto requireSpillSlot = [&](const Value *V) {
596     if (isGCValue(V))
597       return !LowerAsVReg.count(Builder.getValue(V));
598     return !(LiveInDeopt || UseRegistersForDeoptValues);
599   };
600 
601   // Before we actually start lowering (and allocating spill slots for values),
602   // reserve any stack slots which we judge to be profitable to reuse for a
603   // particular value.  This is purely an optimization over the code below and
604   // doesn't change semantics at all.  It is important for performance that we
605   // reserve slots for both deopt and gc values before lowering either.
606   for (const Value *V : SI.DeoptState) {
607     if (requireSpillSlot(V))
608       reservePreviousStackSlotForValue(V, Builder);
609   }
610 
611   for (const Value *V : SI.Ptrs) {
612     SDValue SDV = Builder.getValue(V);
613     if (!LowerAsVReg.count(SDV))
614       reservePreviousStackSlotForValue(V, Builder);
615   }
616 
617   for (const Value *V : SI.Bases) {
618     SDValue SDV = Builder.getValue(V);
619     if (!LowerAsVReg.count(SDV))
620       reservePreviousStackSlotForValue(V, Builder);
621   }
622 
623   // First, prefix the list with the number of unique values to be
624   // lowered.  Note that this is the number of *Values* not the
625   // number of SDValues required to lower them.
626   const int NumVMSArgs = SI.DeoptState.size();
627   pushStackMapConstant(Ops, Builder, NumVMSArgs);
628 
629   // The vm state arguments are lowered in an opaque manner.  We do not know
630   // what type of values are contained within.
631   LLVM_DEBUG(dbgs() << "Lowering deopt state\n");
632   for (const Value *V : SI.DeoptState) {
633     SDValue Incoming;
634     // If this is a function argument at a static frame index, generate it as
635     // the frame index.
636     if (const Argument *Arg = dyn_cast<Argument>(V)) {
637       int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
638       if (FI != INT_MAX)
639         Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy());
640     }
641     if (!Incoming.getNode())
642       Incoming = Builder.getValue(V);
643     LLVM_DEBUG(dbgs() << "Value " << *V
644                       << " requireSpillSlot = " << requireSpillSlot(V) << "\n");
645     lowerIncomingStatepointValue(Incoming, requireSpillSlot(V), Ops, MemRefs,
646                                  Builder);
647   }
648 
649   // Finally, go ahead and lower all the gc arguments.
650   pushStackMapConstant(Ops, Builder, LoweredGCPtrs.size());
651   for (SDValue SDV : LoweredGCPtrs)
652     lowerIncomingStatepointValue(SDV, !LowerAsVReg.count(SDV), Ops, MemRefs,
653                                  Builder);
654 
655   // Copy to out vector. LoweredGCPtrs will be empty after this point.
656   GCPtrs = LoweredGCPtrs.takeVector();
657 
658   // If there are any explicit spill slots passed to the statepoint, record
659   // them, but otherwise do not do anything special.  These are user provided
660   // allocas and give control over placement to the consumer.  In this case,
661   // it is the contents of the slot which may get updated, not the pointer to
662   // the alloca
663   SmallVector<SDValue, 4> Allocas;
664   for (Value *V : SI.GCArgs) {
665     SDValue Incoming = Builder.getValue(V);
666     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
667       // This handles allocas as arguments to the statepoint
668       assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
669              "Incoming value is a frame index!");
670       Allocas.push_back(Builder.DAG.getTargetFrameIndex(
671           FI->getIndex(), Builder.getFrameIndexTy()));
672 
673       auto &MF = Builder.DAG.getMachineFunction();
674       auto *MMO = getMachineMemOperand(MF, *FI);
675       MemRefs.push_back(MMO);
676     }
677   }
678   pushStackMapConstant(Ops, Builder, Allocas.size());
679   Ops.append(Allocas.begin(), Allocas.end());
680 
681   // Now construct GC base/derived map;
682   pushStackMapConstant(Ops, Builder, SI.Ptrs.size());
683   SDLoc L = Builder.getCurSDLoc();
684   for (unsigned i = 0; i < SI.Ptrs.size(); ++i) {
685     SDValue Base = Builder.getValue(SI.Bases[i]);
686     assert(GCPtrIndexMap.count(Base) && "base not found in index map");
687     Ops.push_back(
688         Builder.DAG.getTargetConstant(GCPtrIndexMap[Base], L, MVT::i64));
689     SDValue Derived = Builder.getValue(SI.Ptrs[i]);
690     assert(GCPtrIndexMap.count(Derived) && "derived not found in index map");
691     Ops.push_back(
692         Builder.DAG.getTargetConstant(GCPtrIndexMap[Derived], L, MVT::i64));
693   }
694 }
695 
696 SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
697     SelectionDAGBuilder::StatepointLoweringInfo &SI) {
698   // The basic scheme here is that information about both the original call and
699   // the safepoint is encoded in the CallInst.  We create a temporary call and
700   // lower it, then reverse engineer the calling sequence.
701 
702   NumOfStatepoints++;
703   // Clear state
704   StatepointLowering.startNewStatepoint(*this);
705   assert(SI.Bases.size() == SI.Ptrs.size() &&
706          SI.Ptrs.size() <= SI.GCRelocates.size());
707 
708   LLVM_DEBUG(dbgs() << "Lowering statepoint " << *SI.StatepointInstr << "\n");
709 #ifndef NDEBUG
710   for (auto *Reloc : SI.GCRelocates)
711     if (Reloc->getParent() == SI.StatepointInstr->getParent())
712       StatepointLowering.scheduleRelocCall(*Reloc);
713 #endif
714 
715   // Lower statepoint vmstate and gcstate arguments
716 
717   // All lowered meta args.
718   SmallVector<SDValue, 10> LoweredMetaArgs;
719   // Lowered GC pointers (subset of above).
720   SmallVector<SDValue, 16> LoweredGCArgs;
721   SmallVector<MachineMemOperand*, 16> MemRefs;
722   // Maps derived pointer SDValue to statepoint result of relocated pointer.
723   DenseMap<SDValue, int> LowerAsVReg;
724   lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, LoweredGCArgs, LowerAsVReg,
725                           SI, *this);
726 
727   // Now that we've emitted the spills, we need to update the root so that the
728   // call sequence is ordered correctly.
729   SI.CLI.setChain(getRoot());
730 
731   // Get call node, we will replace it later with statepoint
732   SDValue ReturnVal;
733   SDNode *CallNode;
734   std::tie(ReturnVal, CallNode) =
735       lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
736 
737   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
738   // nodes with all the appropriate arguments and return values.
739 
740   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
741   SDValue Chain = CallNode->getOperand(0);
742 
743   SDValue Glue;
744   bool CallHasIncomingGlue = CallNode->getGluedNode();
745   if (CallHasIncomingGlue) {
746     // Glue is always last operand
747     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
748   }
749 
750   // Build the GC_TRANSITION_START node if necessary.
751   //
752   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
753   // order in which they appear in the call to the statepoint intrinsic. If
754   // any of the operands is a pointer-typed, that operand is immediately
755   // followed by a SRCVALUE for the pointer that may be used during lowering
756   // (e.g. to form MachinePointerInfo values for loads/stores).
757   const bool IsGCTransition =
758       (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
759       (uint64_t)StatepointFlags::GCTransition;
760   if (IsGCTransition) {
761     SmallVector<SDValue, 8> TSOps;
762 
763     // Add chain
764     TSOps.push_back(Chain);
765 
766     // Add GC transition arguments
767     for (const Value *V : SI.GCTransitionArgs) {
768       TSOps.push_back(getValue(V));
769       if (V->getType()->isPointerTy())
770         TSOps.push_back(DAG.getSrcValue(V));
771     }
772 
773     // Add glue if necessary
774     if (CallHasIncomingGlue)
775       TSOps.push_back(Glue);
776 
777     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
778 
779     SDValue GCTransitionStart =
780         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
781 
782     Chain = GCTransitionStart.getValue(0);
783     Glue = GCTransitionStart.getValue(1);
784   }
785 
786   // TODO: Currently, all of these operands are being marked as read/write in
787   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
788   // and flags to be read-only.
789   SmallVector<SDValue, 40> Ops;
790 
791   // Add the <id> and <numBytes> constants.
792   Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
793   Ops.push_back(
794       DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
795 
796   // Calculate and push starting position of vmstate arguments
797   // Get number of arguments incoming directly into call node
798   unsigned NumCallRegArgs =
799       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
800   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
801 
802   // Add call target
803   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
804   Ops.push_back(CallTarget);
805 
806   // Add call arguments
807   // Get position of register mask in the call
808   SDNode::op_iterator RegMaskIt;
809   if (CallHasIncomingGlue)
810     RegMaskIt = CallNode->op_end() - 2;
811   else
812     RegMaskIt = CallNode->op_end() - 1;
813   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
814 
815   // Add a constant argument for the calling convention
816   pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
817 
818   // Add a constant argument for the flags
819   uint64_t Flags = SI.StatepointFlags;
820   assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
821          "Unknown flag used");
822   pushStackMapConstant(Ops, *this, Flags);
823 
824   // Insert all vmstate and gcstate arguments
825   Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
826 
827   // Add register mask from call node
828   Ops.push_back(*RegMaskIt);
829 
830   // Add chain
831   Ops.push_back(Chain);
832 
833   // Same for the glue, but we add it only if original call had it
834   if (Glue.getNode())
835     Ops.push_back(Glue);
836 
837   // Compute return values.  Provide a glue output since we consume one as
838   // input.  This allows someone else to chain off us as needed.
839   SmallVector<EVT, 8> NodeTys;
840   for (auto SD : LoweredGCArgs) {
841     if (!LowerAsVReg.count(SD))
842       continue;
843     NodeTys.push_back(SD.getValueType());
844   }
845   LLVM_DEBUG(dbgs() << "Statepoint has " << NodeTys.size() << " results\n");
846   assert(NodeTys.size() == LowerAsVReg.size() && "Inconsistent GC Ptr lowering");
847   NodeTys.push_back(MVT::Other);
848   NodeTys.push_back(MVT::Glue);
849 
850   unsigned NumResults = NodeTys.size();
851   MachineSDNode *StatepointMCNode =
852     DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
853   DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
854 
855   // For values lowered to tied-defs, create the virtual registers.  Note that
856   // for simplicity, we *always* create a vreg even within a single block.
857   DenseMap<SDValue, Register> VirtRegs;
858   for (const auto *Relocate : SI.GCRelocates) {
859     Value *Derived = Relocate->getDerivedPtr();
860     SDValue SD = getValue(Derived);
861     if (!LowerAsVReg.count(SD))
862       continue;
863 
864     // Handle multiple gc.relocates of the same input efficiently.
865     if (VirtRegs.count(SD))
866       continue;
867 
868     SDValue Relocated = SDValue(StatepointMCNode, LowerAsVReg[SD]);
869 
870     auto *RetTy = Relocate->getType();
871     Register Reg = FuncInfo.CreateRegs(RetTy);
872     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
873                      DAG.getDataLayout(), Reg, RetTy, None);
874     SDValue Chain = DAG.getRoot();
875     RFV.getCopyToRegs(Relocated, DAG, getCurSDLoc(), Chain, nullptr);
876     PendingExports.push_back(Chain);
877 
878     VirtRegs[SD] = Reg;
879   }
880 
881   // Record for later use how each relocation was lowered.  This is needed to
882   // allow later gc.relocates to mirror the lowering chosen.
883   const Instruction *StatepointInstr = SI.StatepointInstr;
884   auto &RelocationMap = FuncInfo.StatepointRelocationMaps[StatepointInstr];
885   for (const GCRelocateInst *Relocate : SI.GCRelocates) {
886     const Value *V = Relocate->getDerivedPtr();
887     SDValue SDV = getValue(V);
888     SDValue Loc = StatepointLowering.getLocation(SDV);
889 
890     RecordType Record;
891     if (LowerAsVReg.count(SDV)) {
892       Record.type = RecordType::VReg;
893       assert(VirtRegs.count(SDV));
894       Record.payload.Reg = VirtRegs[SDV];
895     } else if (Loc.getNode()) {
896       Record.type = RecordType::Spill;
897       Record.payload.FI = cast<FrameIndexSDNode>(Loc)->getIndex();
898     } else {
899       Record.type = RecordType::NoRelocate;
900       // If we didn't relocate a value, we'll essentialy end up inserting an
901       // additional use of the original value when lowering the gc.relocate.
902       // We need to make sure the value is available at the new use, which
903       // might be in another block.
904       if (Relocate->getParent() != StatepointInstr->getParent())
905         ExportFromCurrentBlock(V);
906     }
907     RelocationMap[V] = Record;
908   }
909 
910 
911 
912   SDNode *SinkNode = StatepointMCNode;
913 
914   // Build the GC_TRANSITION_END node if necessary.
915   //
916   // See the comment above regarding GC_TRANSITION_START for the layout of
917   // the operands to the GC_TRANSITION_END node.
918   if (IsGCTransition) {
919     SmallVector<SDValue, 8> TEOps;
920 
921     // Add chain
922     TEOps.push_back(SDValue(StatepointMCNode, NumResults - 2));
923 
924     // Add GC transition arguments
925     for (const Value *V : SI.GCTransitionArgs) {
926       TEOps.push_back(getValue(V));
927       if (V->getType()->isPointerTy())
928         TEOps.push_back(DAG.getSrcValue(V));
929     }
930 
931     // Add glue
932     TEOps.push_back(SDValue(StatepointMCNode, NumResults - 1));
933 
934     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
935 
936     SDValue GCTransitionStart =
937         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
938 
939     SinkNode = GCTransitionStart.getNode();
940   }
941 
942   // Replace original call
943   // Call: ch,glue = CALL ...
944   // Statepoint: [gc relocates],ch,glue = STATEPOINT ...
945   unsigned NumSinkValues = SinkNode->getNumValues();
946   SDValue StatepointValues[2] = {SDValue(SinkNode, NumSinkValues - 2),
947                                  SDValue(SinkNode, NumSinkValues - 1)};
948   DAG.ReplaceAllUsesWith(CallNode, StatepointValues);
949   // Remove original call node
950   DAG.DeleteNode(CallNode);
951 
952   // Since we always emit CopyToRegs (even for local relocates), we must
953   // update root, so that they are emitted before any local uses.
954   (void)getControlRoot();
955 
956   // TODO: A better future implementation would be to emit a single variable
957   // argument, variable return value STATEPOINT node here and then hookup the
958   // return value of each gc.relocate to the respective output of the
959   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
960   // to actually be possible today.
961 
962   return ReturnVal;
963 }
964 
965 void
966 SelectionDAGBuilder::LowerStatepoint(const GCStatepointInst &I,
967                                      const BasicBlock *EHPadBB /*= nullptr*/) {
968   assert(I.getCallingConv() != CallingConv::AnyReg &&
969          "anyregcc is not supported on statepoints!");
970 
971 #ifndef NDEBUG
972   // Check that the associated GCStrategy expects to encounter statepoints.
973   assert(GFI->getStrategy().useStatepoints() &&
974          "GCStrategy does not expect to encounter statepoints");
975 #endif
976 
977   SDValue ActualCallee;
978   SDValue Callee = getValue(I.getActualCalledOperand());
979 
980   if (I.getNumPatchBytes() > 0) {
981     // If we've been asked to emit a nop sequence instead of a call instruction
982     // for this statepoint then don't lower the call target, but use a constant
983     // `undef` instead.  Not lowering the call target lets statepoint clients
984     // get away without providing a physical address for the symbolic call
985     // target at link time.
986     ActualCallee = DAG.getUNDEF(Callee.getValueType());
987   } else {
988     ActualCallee = Callee;
989   }
990 
991   StatepointLoweringInfo SI(DAG);
992   populateCallLoweringInfo(SI.CLI, &I, GCStatepointInst::CallArgsBeginPos,
993                            I.getNumCallArgs(), ActualCallee,
994                            I.getActualReturnType(), false /* IsPatchPoint */);
995 
996   // There may be duplication in the gc.relocate list; such as two copies of
997   // each relocation on normal and exceptional path for an invoke.  We only
998   // need to spill once and record one copy in the stackmap, but we need to
999   // reload once per gc.relocate.  (Dedupping gc.relocates is trickier and best
1000   // handled as a CSE problem elsewhere.)
1001   // TODO: There a couple of major stackmap size optimizations we could do
1002   // here if we wished.
1003   // 1) If we've encountered a derived pair {B, D}, we don't need to actually
1004   // record {B,B} if it's seen later.
1005   // 2) Due to rematerialization, actual derived pointers are somewhat rare;
1006   // given that, we could change the format to record base pointer relocations
1007   // separately with half the space. This would require a format rev and a
1008   // fairly major rework of the STATEPOINT node though.
1009   SmallSet<SDValue, 8> Seen;
1010   for (const GCRelocateInst *Relocate : I.getGCRelocates()) {
1011     SI.GCRelocates.push_back(Relocate);
1012 
1013     SDValue DerivedSD = getValue(Relocate->getDerivedPtr());
1014     if (Seen.insert(DerivedSD).second) {
1015       SI.Bases.push_back(Relocate->getBasePtr());
1016       SI.Ptrs.push_back(Relocate->getDerivedPtr());
1017     }
1018   }
1019 
1020   SI.GCArgs = ArrayRef<const Use>(I.gc_args_begin(), I.gc_args_end());
1021   SI.StatepointInstr = &I;
1022   SI.ID = I.getID();
1023 
1024   SI.DeoptState = ArrayRef<const Use>(I.deopt_begin(), I.deopt_end());
1025   SI.GCTransitionArgs = ArrayRef<const Use>(I.gc_transition_args_begin(),
1026                                             I.gc_transition_args_end());
1027 
1028   SI.StatepointFlags = I.getFlags();
1029   SI.NumPatchBytes = I.getNumPatchBytes();
1030   SI.EHPadBB = EHPadBB;
1031 
1032   SDValue ReturnValue = LowerAsSTATEPOINT(SI);
1033 
1034   // Export the result value if needed
1035   const GCResultInst *GCResult = I.getGCResult();
1036   Type *RetTy = I.getActualReturnType();
1037 
1038   if (RetTy->isVoidTy() || !GCResult) {
1039     // The return value is not needed, just generate a poison value.
1040     setValue(&I, DAG.getIntPtrConstant(-1, getCurSDLoc()));
1041     return;
1042   }
1043 
1044   if (GCResult->getParent() == I.getParent()) {
1045     // Result value will be used in a same basic block. Don't export it or
1046     // perform any explicit register copies. The gc_result will simply grab
1047     // this value.
1048     setValue(&I, ReturnValue);
1049     return;
1050   }
1051 
1052   // Result value will be used in a different basic block so we need to export
1053   // it now.  Default exporting mechanism will not work here because statepoint
1054   // call has a different type than the actual call. It means that by default
1055   // llvm will create export register of the wrong type (always i32 in our
1056   // case). So instead we need to create export register with correct type
1057   // manually.
1058   // TODO: To eliminate this problem we can remove gc.result intrinsics
1059   //       completely and make statepoint call to return a tuple.
1060   unsigned Reg = FuncInfo.CreateRegs(RetTy);
1061   RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1062                    DAG.getDataLayout(), Reg, RetTy,
1063                    I.getCallingConv());
1064   SDValue Chain = DAG.getEntryNode();
1065 
1066   RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
1067   PendingExports.push_back(Chain);
1068   FuncInfo.ValueMap[&I] = Reg;
1069 }
1070 
1071 void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
1072     const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
1073     bool VarArgDisallowed, bool ForceVoidReturnTy) {
1074   StatepointLoweringInfo SI(DAG);
1075   unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
1076   populateCallLoweringInfo(
1077       SI.CLI, Call, ArgBeginIndex, Call->getNumArgOperands(), Callee,
1078       ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
1079       false);
1080   if (!VarArgDisallowed)
1081     SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
1082 
1083   auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
1084 
1085   unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
1086 
1087   auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
1088   SI.ID = SD.StatepointID.getValueOr(DefaultID);
1089   SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
1090 
1091   SI.DeoptState =
1092       ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
1093   SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
1094   SI.EHPadBB = EHPadBB;
1095 
1096   // NB! The GC arguments are deliberately left empty.
1097 
1098   if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
1099     ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
1100     setValue(Call, ReturnVal);
1101   }
1102 }
1103 
1104 void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
1105     const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
1106   LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
1107                                    /* VarArgDisallowed = */ false,
1108                                    /* ForceVoidReturnTy  = */ false);
1109 }
1110 
1111 void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
1112   // The result value of the gc_result is simply the result of the actual
1113   // call.  We've already emitted this, so just grab the value.
1114   const GCStatepointInst *SI = CI.getStatepoint();
1115 
1116   if (SI->getParent() == CI.getParent()) {
1117     setValue(&CI, getValue(SI));
1118     return;
1119   }
1120   // Statepoint is in different basic block so we should have stored call
1121   // result in a virtual register.
1122   // We can not use default getValue() functionality to copy value from this
1123   // register because statepoint and actual call return types can be
1124   // different, and getValue() will use CopyFromReg of the wrong type,
1125   // which is always i32 in our case.
1126   Type *RetTy = SI->getActualReturnType();
1127   SDValue CopyFromReg = getCopyFromRegs(SI, RetTy);
1128 
1129   assert(CopyFromReg.getNode());
1130   setValue(&CI, CopyFromReg);
1131 }
1132 
1133 void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
1134 #ifndef NDEBUG
1135   // Consistency check
1136   // We skip this check for relocates not in the same basic block as their
1137   // statepoint. It would be too expensive to preserve validation info through
1138   // different basic blocks.
1139   if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
1140     StatepointLowering.relocCallVisited(Relocate);
1141 
1142   auto *Ty = Relocate.getType()->getScalarType();
1143   if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
1144     assert(*IsManaged && "Non gc managed pointer relocated!");
1145 #endif
1146 
1147   const Value *DerivedPtr = Relocate.getDerivedPtr();
1148   auto &RelocationMap =
1149     FuncInfo.StatepointRelocationMaps[Relocate.getStatepoint()];
1150   auto SlotIt = RelocationMap.find(DerivedPtr);
1151   assert(SlotIt != RelocationMap.end() && "Relocating not lowered gc value");
1152   const RecordType &Record = SlotIt->second;
1153 
1154   // If relocation was done via virtual register..
1155   if (Record.type == RecordType::VReg) {
1156     Register InReg = Record.payload.Reg;
1157     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1158                      DAG.getDataLayout(), InReg, Relocate.getType(),
1159                      None); // This is not an ABI copy.
1160     // We generate copy to/from regs even for local uses, hence we must
1161     // chain with current root to ensure proper ordering of copies w.r.t.
1162     // statepoint.
1163     SDValue Chain = DAG.getRoot();
1164     SDValue Relocation = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
1165                                              Chain, nullptr, nullptr);
1166     setValue(&Relocate, Relocation);
1167     return;
1168   }
1169 
1170   SDValue SD = getValue(DerivedPtr);
1171 
1172   if (SD.isUndef() && SD.getValueType().getSizeInBits() <= 64) {
1173     // Lowering relocate(undef) as arbitrary constant. Current constant value
1174     // is chosen such that it's unlikely to be a valid pointer.
1175     setValue(&Relocate, DAG.getTargetConstant(0xFEFEFEFE, SDLoc(SD), MVT::i64));
1176     return;
1177   }
1178 
1179 
1180   // We didn't need to spill these special cases (constants and allocas).
1181   // See the handling in spillIncomingValueForStatepoint for detail.
1182   if (Record.type == RecordType::NoRelocate) {
1183     setValue(&Relocate, SD);
1184     return;
1185   }
1186 
1187   assert(Record.type == RecordType::Spill);
1188 
1189   unsigned Index = Record.payload.FI;;
1190   SDValue SpillSlot = DAG.getTargetFrameIndex(Index, getFrameIndexTy());
1191 
1192   // All the reloads are independent and are reading memory only modified by
1193   // statepoints (i.e. no other aliasing stores); informing SelectionDAG of
1194   // this this let's CSE kick in for free and allows reordering of instructions
1195   // if possible.  The lowering for statepoint sets the root, so this is
1196   // ordering all reloads with the either a) the statepoint node itself, or b)
1197   // the entry of the current block for an invoke statepoint.
1198   const SDValue Chain = DAG.getRoot(); // != Builder.getRoot()
1199 
1200   auto &MF = DAG.getMachineFunction();
1201   auto &MFI = MF.getFrameInfo();
1202   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
1203   auto *LoadMMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
1204                                           MFI.getObjectSize(Index),
1205                                           MFI.getObjectAlign(Index));
1206 
1207   auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
1208                                                          Relocate.getType());
1209 
1210   SDValue SpillLoad = DAG.getLoad(LoadVT, getCurSDLoc(), Chain,
1211                                   SpillSlot, LoadMMO);
1212   PendingLoads.push_back(SpillLoad.getValue(1));
1213 
1214   assert(SpillLoad.getNode());
1215   setValue(&Relocate, SpillLoad);
1216 }
1217 
1218 void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
1219   const auto &TLI = DAG.getTargetLoweringInfo();
1220   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
1221                                          TLI.getPointerTy(DAG.getDataLayout()));
1222 
1223   // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
1224   // call.  We also do not lower the return value to any virtual register, and
1225   // change the immediately following return to a trap instruction.
1226   LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
1227                                    /* VarArgDisallowed = */ true,
1228                                    /* ForceVoidReturnTy = */ true);
1229 }
1230 
1231 void SelectionDAGBuilder::LowerDeoptimizingReturn() {
1232   // We do not lower the return value from llvm.deoptimize to any virtual
1233   // register, and change the immediately following return to a trap
1234   // instruction.
1235   if (DAG.getTarget().Options.TrapUnreachable)
1236     DAG.setRoot(
1237         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
1238 }
1239