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