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