LLVM 24.0.0git
StatepointLowering.cpp
Go to the documentation of this file.
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"
21#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/Statistic.h"
36#include "llvm/IR/CallingConv.h"
38#include "llvm/IR/GCStrategy.h"
39#include "llvm/IR/Instruction.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Statepoint.h"
43#include "llvm/IR/Type.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
70
73 SDLoc L = Builder.getCurSDLoc();
74 Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
75 MVT::i64));
76 Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
77}
78
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(Builder.FuncInfo.StatepointStackSlots.size());
90}
91
93 Locations.clear();
94 AllocatedStackSlots.clear();
95 assert(PendingGCRelocateCalls.empty() &&
96 "cleared before statepoint sequence completed");
97}
98
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(NextSlotToAllocate)) {
123 const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
124 if (MFI.getObjectSize(FI) == SpillSize) {
125 AllocatedStackSlots.set(NextSlotToAllocate);
126 // TODO: Is ValueType the right thing to use here?
127 return Builder.DAG.getFrameIndex(FI, ValueType);
128 }
129 }
130 }
131
132 // Couldn't find a free slot, so create a new one:
133
134 SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
135 const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
137
138 Builder.FuncInfo.StatepointStackSlots.push_back(FI);
139 AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
140 assert(AllocatedStackSlots.size() ==
141 Builder.FuncInfo.StatepointStackSlots.size() &&
142 "Broken invariant");
143
144 StatepointMaxSlotsRequired.updateMax(
145 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>(Statepoint))
166 return std::nullopt;
167
168 const auto &RelocationMap = Builder.FuncInfo.StatepointRelocationMaps
169 [cast<GCStatepointInst>(Statepoint)];
170
171 auto It = RelocationMap.find(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(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 std::optional<int> MergedResult;
191
192 for (const auto &IncomingValue : Phi->incoming_values()) {
193 std::optional<int> SpillSlot =
194 findPreviousSpillSlot(IncomingValue, Builder, 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>(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(Incoming) || Incoming.isUndef();
254}
255
257 assert(willLowerDirectly(V) && "not a directly-lowered leaf");
258 if (V.isUndef()) {
259 Kind = Undef;
260 } else if (auto *FI = dyn_cast<FrameIndexSDNode>(V)) {
262 FrameIndexValue = FI->getIndex();
263 } else {
264 Kind = Constant;
265 IntValue = cast<ConstantSDNode>(V)->getAPIntValue();
266 }
267}
268
270 SelectionDAG &DAG, const SDLoc &DL, EVT VT) const {
271 switch (Kind) {
272 case FrameIndex:
273 return DAG.getFrameIndex(FrameIndexValue, VT);
274 case Constant:
275 return DAG.getConstant(IntValue, DL, VT);
276 case Undef:
277 return DAG.getConstant(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(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(Incoming);
297 if (OldLocation.getNode())
298 // Duplicates in input
299 return;
300
301 const int LookUpDepth = 6;
302 std::optional<int> Index =
303 findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
304 if (!Index)
305 return;
306
307 const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
308
309 auto SlotIt = find(StatepointSlots, *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(StatepointSlots.begin(), 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(*Index, Builder.getFrameIndexTy());
331 Builder.StatepointLowering.setLocation(Incoming, 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(
339 SelectionDAGBuilder &Builder) {
340 SDValue ReturnValue, CallEndVal;
341 std::tie(ReturnValue, CallEndVal) =
342 Builder.lowerInvokable(SI.CLI, 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(0).getNode();
363
364 bool HasDef = !SI.CLI.RetTy->isVoidTy();
365 if (HasDef) {
366 if (CallEnd->getOpcode() == ISD::LOAD)
367 CallEnd = CallEnd->getOperand(0).getNode();
368 else
369 while (CallEnd->getOpcode() == ISD::CopyFromReg)
370 CallEnd = CallEnd->getOperand(0).getNode();
371 }
372
373 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
374 return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
375}
376
378 FrameIndexSDNode &FI) {
379 auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
380 auto MMOFlags = MachineMemOperand::MOStore |
382 auto &MFI = MF.getFrameInfo();
383 return MF.getMachineMemOperand(PtrInfo, MMOFlags,
384 MFI.getObjectSize(FI.getIndex()),
385 MFI.getObjectAlign(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*>
396 SelectionDAGBuilder &Builder) {
397 SDValue Loc = Builder.StatepointLowering.getLocation(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(Incoming.getValueType(),
403 Builder);
404 int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
405 // We use TargetFrameIndex so that isel will not select it into LEA
406 Loc = Builder.DAG.getTargetFrameIndex(Index, 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, Index);
424 auto *StoreMMO = MF.getMachineMemOperand(
425 PtrInfo, MachineMemOperand::MOStore, MFI.getObjectSize(Index),
426 MFI.getObjectAlign(Index));
427 Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
428 StoreMMO);
429
431
432 Builder.StatepointLowering.setLocation(Incoming, Loc);
433 }
434
435 assert(Loc.getNode());
436 return std::make_tuple(Loc, Chain, 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,
446 SelectionDAGBuilder &Builder) {
447
448 if (willLowerDirectly(Incoming)) {
449 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(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(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
456 Builder.getFrameIndexTy()));
457
458 auto &MF = Builder.DAG.getMachineFunction();
459 auto *MMO = getMachineMemOperand(MF, *FI);
460 MemRefs.push_back(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, 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>(Incoming)) {
480 pushStackMapConstant(Ops, Builder, C->getSExtValue());
481 return;
482 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Incoming)) {
483 pushStackMapConstant(Ops, Builder,
484 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(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(std::get<0>(Res));
511 if (auto *MMO = std::get<2>(Res))
512 MemRefs.push_back(MMO);
513 Chain = std::get<1>(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
542 DenseMap<SDValue, int> &LowerAsVReg,
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>(SI.StatepointInstr)) {
572 LandingPadInst *LPI = StInvoke->getLandingPadInst();
573 for (const auto *Relocate : SI.GCRelocates)
574 if (Relocate->getOperand(0) == LPI) {
575 LPadPointers.insert(Builder.getValue(Relocate->getBasePtr()));
576 LPadPointers.insert(Builder.getValue(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(SD))
594 return false;
595 return !willLowerDirectly(SD);
596 };
597
598 auto processGCPtr = [&](const Value *V) {
599 SDValue PtrSD = Builder.getValue(V);
600 if (!LoweredGCPtrs.insert(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 Builder.getValue(V).getValueType()))
628 return true;
629 if (isGCValue(V, Builder))
630 return !LowerAsVReg.count(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))
644 }
645
646 for (const Value *V : SI.Ptrs) {
647 SDValue SDV = Builder.getValue(V);
648 if (!LowerAsVReg.count(SDV))
650 }
651
652 for (const Value *V : SI.Bases) {
653 SDValue SDV = Builder.getValue(V);
654 if (!LowerAsVReg.count(SDV))
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, 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>(V)) {
672 int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
673 if (FI != INT_MAX)
674 Incoming = Builder.DAG.getFrameIndex(FI, 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(V), Ops, MemRefs,
681 Builder);
682 }
683
684 // Finally, go ahead and lower all the gc arguments.
685 pushStackMapConstant(Ops, Builder, LoweredGCPtrs.size());
686 for (SDValue SDV : LoweredGCPtrs)
687 lowerIncomingStatepointValue(SDV, !LowerAsVReg.count(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
699 for (Value *V : SI.GCLives) {
700 SDValue Incoming = Builder.getValue(V);
701 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(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(Builder.DAG.getTargetFrameIndex(
706 FI->getIndex(), Builder.getFrameIndexTy()));
707
708 auto &MF = Builder.DAG.getMachineFunction();
709 auto *MMO = getMachineMemOperand(MF, *FI);
710 MemRefs.push_back(MMO);
711 }
712 }
713 pushStackMapConstant(Ops, Builder, Allocas.size());
714 Ops.append(Allocas.begin(), Allocas.end());
715
716 // Now construct GC base/derived map;
717 pushStackMapConstant(Ops, Builder, SI.Ptrs.size());
718 SDLoc L = Builder.getCurSDLoc();
719 for (unsigned i = 0; i < SI.Ptrs.size(); ++i) {
720 SDValue Base = Builder.getValue(SI.Bases[i]);
721 assert(GCPtrIndexMap.count(Base) && "base not found in index map");
722 Ops.push_back(
723 Builder.DAG.getTargetConstant(GCPtrIndexMap[Base], L, MVT::i64));
724 SDValue Derived = Builder.getValue(SI.Ptrs[i]);
725 assert(GCPtrIndexMap.count(Derived) && "derived not found in index map");
726 Ops.push_back(
727 Builder.DAG.getTargetConstant(GCPtrIndexMap[Derived], L, MVT::i64));
728 }
729}
730
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(*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;
759 // Maps derived pointer SDValue to statepoint result of relocated pointer.
760 DenseMap<SDValue, int> LowerAsVReg;
761 lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, LoweredGCArgs, LowerAsVReg,
762 SI, *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(ReturnVal, CallNode) = lowerCallFromStatepointLoweringInfo(SI, *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(0);
778
779 SDValue Glue;
780 bool CallHasIncomingGlue = CallNode->getGluedNode();
781 if (CallHasIncomingGlue) {
782 // Glue is always last operand
783 Glue = CallNode->getOperand(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) ==
796 if (IsGCTransition) {
798
799 // Add chain
800 TSOps.push_back(Chain);
801
802 // Add GC transition arguments
803 for (const Value *V : SI.GCTransitionArgs) {
804 TSOps.push_back(getValue(V));
805 if (V->getType()->isPointerTy())
806 TSOps.push_back(DAG.getSrcValue(V));
807 }
808
809 // Add glue if necessary
810 if (CallHasIncomingGlue)
811 TSOps.push_back(Glue);
812
813 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
814
815 SDValue GCTransitionStart =
816 DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
817
818 Chain = GCTransitionStart.getValue(0);
819 Glue = GCTransitionStart.getValue(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.
826
827 // Add the <id> and <numBytes> constants.
828 Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
829 Ops.push_back(
830 DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), 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(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
837
838 // Add call target
839 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
840 Ops.push_back(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(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
850
851 // Add a constant argument for the calling convention
852 pushStackMapConstant(Ops, *this, 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, *this, Flags);
859
860 // Insert all vmstate and gcstate arguments
861 llvm::append_range(Ops, LoweredMetaArgs);
862
863 // Add register mask from call node
864 Ops.push_back(*RegMaskIt);
865
866 // Add chain
867 Ops.push_back(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(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(SD))
878 continue;
879 NodeTys.push_back(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(MVT::Other);
884 NodeTys.push_back(MVT::Glue);
885
886 unsigned NumResults = NodeTys.size();
887 MachineSDNode *StatepointMCNode =
888 DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
889 DAG.setNodeMemRefs(StatepointMCNode, 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.
895 for (const auto *Relocate : SI.GCRelocates) {
896 Value *Derived = Relocate->getDerivedPtr();
897 SDValue SD = getValue(Derived);
898 auto It = LowerAsVReg.find(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(SD);
908 if (Res)
909 assert(Res == Relocated);
910 else
911 StatepointLowering.setLocation(SD, Relocated);
912 continue;
913 }
914
915 // Handle multiple gc.relocates of the same input efficiently.
916 auto [VRegIt, Inserted] = VirtRegs.try_emplace(SD);
917 if (!Inserted)
918 continue;
919
920 auto *RetTy = Relocate->getType();
921 Register Reg = FuncInfo.CreateRegs(RetTy);
922 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
923 DAG.getDataLayout(), Reg, RetTy, std::nullopt);
924 SDValue Chain = DAG.getRoot();
925 RFV.getCopyToRegs(Relocated, DAG, getCurSDLoc(), Chain, nullptr);
926 PendingExports.push_back(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(SDV);
939
940 bool IsLocal = (Relocate->getParent() == StatepointInstr->getParent());
941
943 if (LowerAsVReg.count(SDV)) {
944 if (IsLocal) {
945 // Result is already stored in StatepointLowering
947 } else {
949 auto It = VirtRegs.find(SDV);
950 assert(It != VirtRegs.end());
951 Record.payload.Reg = It->second;
952 }
953 } else if (Loc.getNode()) {
955 Record.payload.FI = cast<FrameIndexSDNode>(Loc)->getIndex();
956 } else {
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(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) {
978
979 // Add chain
980 TEOps.push_back(SDValue(StatepointMCNode, NumResults - 2));
981
982 // Add GC transition arguments
983 for (const Value *V : SI.GCTransitionArgs) {
984 TEOps.push_back(getValue(V));
985 if (V->getType()->isPointerTy())
986 TEOps.push_back(DAG.getSrcValue(V));
987 }
988
989 // Add glue
990 TEOps.push_back(SDValue(StatepointMCNode, NumResults - 1));
991
992 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
993
994 SDValue GCTransitionStart =
995 DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, 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(CallNode, StatepointValues);
1007 // Remove original call node
1008 DAG.DeleteNode(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*>
1028 std::pair<const GCResultInst *, const GCResultInst*> Res(nullptr, nullptr);
1029 for (const auto *U : S.users()) {
1030 auto *GRI = dyn_cast<GCResultInst>(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
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(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(Callee.getValueType());
1063 } else {
1064 ActualCallee = Callee;
1065 }
1066
1067 const auto GCResultLocality = getGCResultLocality(I);
1068 AttributeSet retAttrs;
1069 if (GCResultLocality.first)
1070 retAttrs = GCResultLocality.first->getAttributes().getRetAttrs();
1071
1074 I.getNumCallArgs(), ActualCallee,
1075 I.getActualReturnType(), 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.
1092 for (const GCRelocateInst *Relocate : I.getGCRelocates()) {
1093 SI.GCRelocates.push_back(Relocate);
1094
1095 SDValue DerivedSD = getValue(Relocate->getDerivedPtr());
1096 if (Seen.insert(DerivedSD).second) {
1097 SI.Bases.push_back(Relocate->getBasePtr());
1098 SI.Ptrs.push_back(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, *this))
1110 continue;
1111 if (Seen.insert(getValue(V)).second) {
1112 SI.Bases.push_back(V);
1113 SI.Ptrs.push_back(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(&I, DAG.getIntPtrConstant(-1, 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(&I, 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(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(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
1164 PendingExports.push_back(Chain);
1165 FuncInfo.ValueMap[&I] = Reg;
1166}
1167
1169 const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
1170 bool VarArgDisallowed, bool ForceVoidReturnTy) {
1172 SI.CLI.CB = Call;
1173
1174 unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
1176 SI.CLI, Call, ArgBeginIndex, Call->arg_size(), Callee,
1177 ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
1178 Call->getAttributes().getRetAttrs(), /*IsPatchPoint=*/false);
1179 if (!VarArgDisallowed)
1180 SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
1181
1182 auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
1183
1185
1186 auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
1187 SI.ID = SD.StatepointID.value_or(DefaultID);
1188 SI.NumPatchBytes = SD.NumPatchBytes.value_or(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, *Call, ReturnVal);
1200 setValue(Call, ReturnVal);
1201 }
1202}
1203
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();
1216 "GetStatepoint must return one of two types");
1217 if (isa<UndefValue>(SI))
1218 return;
1219
1220 if (cast<GCStatepointInst>(SI)->getParent() == CI.getParent()) {
1221 setValue(&CI, getValue(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(SI, RetTy);
1232
1233 assert(CopyFromReg.getNode());
1234 setValue(&CI, 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>(Statepoint)];
1256 auto SlotIt = RelocationMap.find(&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(getValue(DerivedPtr));
1266 assert(SDV.getNode() && "empty SDValue");
1267 setValue(&Relocate, 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, getCurSDLoc(),
1280 Chain, nullptr, nullptr);
1281 setValue(&Relocate, Relocation);
1282 return;
1283 }
1284
1285 if (Record.type == RecordType::Spill) {
1286 unsigned Index = Record.payload.FI;
1287 SDValue SpillSlot = DAG.getFrameIndex(Index, 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, Index);
1301 auto *LoadMMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
1302 MFI.getObjectSize(Index),
1303 MFI.getObjectAlign(Index));
1304
1305 auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
1306 Relocate.getType());
1307
1308 SDValue SpillLoad =
1309 DAG.getLoad(LoadVT, getCurSDLoc(), Chain, SpillSlot, LoadMMO);
1310 PendingLoads.push_back(SpillLoad.getValue(1));
1311
1312 assert(SpillLoad.getNode());
1313 setValue(&Relocate, SpillLoad);
1314 return;
1315 }
1316
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(DAG.getDataLayout(),
1323 Relocate.getType());
1324 setValue(&Relocate,
1325 Record.RematLeaf->rematerialize(DAG, getCurSDLoc(), VT));
1326 return;
1327 }
1328
1329 SDValue SD = getValue(DerivedPtr);
1330
1331 if (SD.isUndef() && SD.getValueType().getSizeInBits() <= 64) {
1332 setValue(&Relocate,
1333 DAG.getConstant(UndefStackMapValue, SDLoc(SD), 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(&Relocate, SD);
1340}
1341
1343 const auto &TLI = DAG.getTargetLoweringInfo();
1344
1345 RTLIB::LibcallImpl DeoptImpl =
1346 DAG.getLibcalls().getLibcallImpl(RTLIB::DEOPTIMIZE);
1347 if (DeoptImpl == RTLIB::Unsupported) {
1348 DAG.getContext()->emitError("no deoptimize libcall available");
1349 return;
1350 }
1351
1352 SDValue Callee =
1353 DAG.getExternalSymbol(DeoptImpl, TLI.getPointerTy(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(CI, Callee, /* EHPadBB = */ nullptr,
1360 /* VarArgDisallowed = */ true,
1361 /* ForceVoidReturnTy = */ true);
1362}
1363
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(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
1371}
return SDValue()
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static DeltaTreeNode * getRoot(void *Root)
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:57
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file implements the SmallBitVector class.
This file defines the SmallSet class.
This file defines the SmallVector class.
static void lowerIncomingStatepointValue(SDValue Incoming, bool RequireSpillSlot, SmallVectorImpl< SDValue > &Ops, SmallVectorImpl< MachineMemOperand * > &MemRefs, SelectionDAGBuilder &Builder)
Lower a single value incoming to a statepoint node.
static constexpr uint32_t UndefStackMapValue
static std::optional< int > findPreviousSpillSlot(const Value *Val, SelectionDAGBuilder &Builder, int LookUpDepth)
Utility function for reservePreviousStackSlotForValue.
static void pushStackMapConstant(SmallVectorImpl< SDValue > &Ops, SelectionDAGBuilder &Builder, uint64_t Value)
static bool isGCValue(const Value *V, SelectionDAGBuilder &Builder)
Return true if value V represents the GC value.
static bool willLowerDirectly(SDValue Incoming)
Return true if-and-only-if the given SDValue can be lowered as either a constant argument or a stack ...
static void lowerStatepointMetaArgs(SmallVectorImpl< SDValue > &Ops, SmallVectorImpl< MachineMemOperand * > &MemRefs, SmallVectorImpl< SDValue > &GCPtrs, DenseMap< SDValue, int > &LowerAsVReg, SelectionDAGBuilder::StatepointLoweringInfo &SI, SelectionDAGBuilder &Builder)
Lower deopt state and gc pointer arguments of the statepoint.
static std::pair< const GCResultInst *, const GCResultInst * > getGCResultLocality(const GCStatepointInst &S)
Return two gc.results if present.
static void reservePreviousStackSlotForValue(const Value *IncomingValue, SelectionDAGBuilder &Builder)
Try to find existing copies of the incoming values in stack slots used for statepoint spilling.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
static MachineMemOperand * getMachineMemOperand(MachineFunction &MF, FrameIndexSDNode &FI)
static std::pair< SDValue, SDNode * > lowerCallFromStatepointLoweringInfo(SelectionDAGBuilder::StatepointLoweringInfo &SI, SelectionDAGBuilder &Builder)
Extract call from statepoint, lower it and return pointer to the call node.
static std::tuple< SDValue, SDValue, MachineMemOperand * > spillIncomingStatepointValue(SDValue Incoming, SDValue Chain, SelectionDAGBuilder &Builder)
Spill a value incoming to the statepoint.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:406
LLVM Basic Block Representation.
Definition BasicBlock.h:62
This class represents a no-op cast from one type to another.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a function call, abstracting a target machine's calling convention.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
LLVM_ABI const Value * getStatepoint() const
The statepoint with which this gc.relocate is associated.
Represents calls to the gc.relocate intrinsic.
LLVM_ABI Value * getDerivedPtr() const
Represents calls to the gc.result intrinsic.
Represents a gc.statepoint intrinsic call.
Definition Statepoint.h:61
iterator_range< user_iterator > users()
The landingpad instruction holds all of the information necessary to generate correct exception handl...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void markAsStatepointSpillSlotObjectIndex(int ObjectIdx)
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
A description of a memory reference used in the backend.
@ MOVolatile
The memory access is volatile.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
An SDNode that represents everything that will be needed to construct a MachineInstr.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
SDNode * getGluedNode() const
If this node has a glue operand, return the node to which the glue operand points.
op_iterator op_end() const
op_iterator op_begin() const
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
SDValue getValue(const Value *V)
getValue - Return an SDValue for the given Value.
void LowerStatepoint(const GCStatepointInst &I, const BasicBlock *EHPadBB=nullptr)
SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I, SDValue Op)
void LowerDeoptimizeCall(const CallInst *CI)
void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB)
void LowerCallSiteWithDeoptBundleImpl(const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB, bool VarArgDisallowed, bool ForceVoidReturnTy)
StatepointLoweringState StatepointLowering
State used while lowering a statepoint sequence (gc_statepoint, gc_relocate, and gc_result).
void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, AttributeSet RetAttrs, bool IsPatchPoint)
Populate a CallLowerinInfo (into CLI) based on the properties of the call being lowered.
GCFunctionInfo * GFI
Garbage collection metadata for the function.
FunctionLoweringInfo & FuncInfo
Information about the function as a whole.
void setValue(const Value *V, SDValue NewN)
SDValue getControlRoot()
Similar to getRoot, but instead of flushing all the PendingLoad items, flush all the PendingExports (...
SDValue LowerAsSTATEPOINT(StatepointLoweringInfo &SI)
Lower SLI into a STATEPOINT instruction.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
Vector takeVector()
Clear the SetVector and return the underlying vector.
Definition SetVector.h:94
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void clear()
Clear the memory usage of this object.
SDValue allocateStackSlot(EVT ValueType, SelectionDAGBuilder &Builder)
Get a stack slot we can use to store an value of type ValueType.
void startNewStatepoint(SelectionDAGBuilder &Builder)
Reset all state tracking for a newly encountered safepoint.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ GC_TRANSITION_START
GC_TRANSITION_START/GC_TRANSITION_END - These operators mark the beginning and end of GC transition s...
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ TRAP
TRAP - Trapping instruction.
@ GC_TRANSITION_END
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI StatepointDirectives parseStatepointDirectivesFromAttrs(AttributeList AS)
Parse out statepoint directives from the function attributes present in AS.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
ArrayRef(const T &OneElt) -> ArrayRef< T >
@ MaskAll
A bitmask that includes all valid flags.
Definition Statepoint.h:51
@ DeoptLiveIn
Mark the deopt arguments associated with the statepoint as only being "live-in".
Definition Statepoint.h:49
@ GCTransition
Indicates that this statepoint is a transition from GC-aware code to code that is not GC-aware.
Definition Statepoint.h:41
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
LLVM_ABI SDValue rematerialize(SelectionDAG &DAG, const SDLoc &DL, EVT VT) const
Rebuild the captured leaf as a fresh SDValue of type VT.
LLVM_ABI StatepointDirectLeaf(SDValue V)
Capture the leaf V, which must be a directly-lowered value.
Helper object to track which of three possible relocation mechanisms are used for a particular value ...
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct represents the registers (physical or virtual) that a particular set of values is assigne...
void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl, SDValue &Chain, SDValue *Glue, const Value *V=nullptr, ISD::NodeType PreferredExtendType=ISD::ANY_EXTEND) const
Emit a series of CopyToReg nodes that copies the specified value into the registers specified by this...
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
Describes a gc.statepoint or a gc.statepoint like thing for the purposes of lowering into a STATEPOIN...
static const uint64_t DeoptBundleStatepointID
Definition Statepoint.h:240