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