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