17330f729Sjoerg //===- StatepointLowering.cpp - SDAGBuilder's statepoint code -------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file includes support code use by SelectionDAGBuilder when lowering a
107330f729Sjoerg // statepoint sequence in SelectionDAG IR.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg
147330f729Sjoerg #include "StatepointLowering.h"
157330f729Sjoerg #include "SelectionDAGBuilder.h"
167330f729Sjoerg #include "llvm/ADT/ArrayRef.h"
177330f729Sjoerg #include "llvm/ADT/None.h"
187330f729Sjoerg #include "llvm/ADT/Optional.h"
197330f729Sjoerg #include "llvm/ADT/STLExtras.h"
20*82d56013Sjoerg #include "llvm/ADT/SmallSet.h"
217330f729Sjoerg #include "llvm/ADT/Statistic.h"
227330f729Sjoerg #include "llvm/CodeGen/FunctionLoweringInfo.h"
237330f729Sjoerg #include "llvm/CodeGen/GCMetadata.h"
247330f729Sjoerg #include "llvm/CodeGen/ISDOpcodes.h"
257330f729Sjoerg #include "llvm/CodeGen/MachineFrameInfo.h"
267330f729Sjoerg #include "llvm/CodeGen/MachineFunction.h"
277330f729Sjoerg #include "llvm/CodeGen/MachineMemOperand.h"
287330f729Sjoerg #include "llvm/CodeGen/RuntimeLibcalls.h"
297330f729Sjoerg #include "llvm/CodeGen/SelectionDAG.h"
307330f729Sjoerg #include "llvm/CodeGen/StackMaps.h"
317330f729Sjoerg #include "llvm/CodeGen/TargetLowering.h"
327330f729Sjoerg #include "llvm/CodeGen/TargetOpcodes.h"
337330f729Sjoerg #include "llvm/IR/CallingConv.h"
347330f729Sjoerg #include "llvm/IR/DerivedTypes.h"
35*82d56013Sjoerg #include "llvm/IR/GCStrategy.h"
367330f729Sjoerg #include "llvm/IR/Instruction.h"
377330f729Sjoerg #include "llvm/IR/Instructions.h"
387330f729Sjoerg #include "llvm/IR/LLVMContext.h"
397330f729Sjoerg #include "llvm/IR/Statepoint.h"
407330f729Sjoerg #include "llvm/IR/Type.h"
417330f729Sjoerg #include "llvm/Support/Casting.h"
42*82d56013Sjoerg #include "llvm/Support/CommandLine.h"
437330f729Sjoerg #include "llvm/Support/MachineValueType.h"
447330f729Sjoerg #include "llvm/Target/TargetMachine.h"
457330f729Sjoerg #include "llvm/Target/TargetOptions.h"
467330f729Sjoerg #include <cassert>
477330f729Sjoerg #include <cstddef>
487330f729Sjoerg #include <cstdint>
497330f729Sjoerg #include <iterator>
507330f729Sjoerg #include <tuple>
517330f729Sjoerg #include <utility>
527330f729Sjoerg
537330f729Sjoerg using namespace llvm;
547330f729Sjoerg
557330f729Sjoerg #define DEBUG_TYPE "statepoint-lowering"
567330f729Sjoerg
577330f729Sjoerg STATISTIC(NumSlotsAllocatedForStatepoints,
587330f729Sjoerg "Number of stack slots allocated for statepoints");
597330f729Sjoerg STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
607330f729Sjoerg STATISTIC(StatepointMaxSlotsRequired,
617330f729Sjoerg "Maximum number of stack slots required for a singe statepoint");
627330f729Sjoerg
63*82d56013Sjoerg cl::opt<bool> UseRegistersForDeoptValues(
64*82d56013Sjoerg "use-registers-for-deopt-values", cl::Hidden, cl::init(false),
65*82d56013Sjoerg cl::desc("Allow using registers for non pointer deopt args"));
66*82d56013Sjoerg
67*82d56013Sjoerg cl::opt<bool> UseRegistersForGCPointersInLandingPad(
68*82d56013Sjoerg "use-registers-for-gc-values-in-landing-pad", cl::Hidden, cl::init(false),
69*82d56013Sjoerg cl::desc("Allow using registers for gc pointer in landing pad"));
70*82d56013Sjoerg
71*82d56013Sjoerg cl::opt<unsigned> MaxRegistersForGCPointers(
72*82d56013Sjoerg "max-registers-for-gc-values", cl::Hidden, cl::init(0),
73*82d56013Sjoerg cl::desc("Max number of VRegs allowed to pass GC pointer meta args in"));
74*82d56013Sjoerg
75*82d56013Sjoerg typedef FunctionLoweringInfo::StatepointRelocationRecord RecordType;
76*82d56013Sjoerg
pushStackMapConstant(SmallVectorImpl<SDValue> & Ops,SelectionDAGBuilder & Builder,uint64_t Value)777330f729Sjoerg static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
787330f729Sjoerg SelectionDAGBuilder &Builder, uint64_t Value) {
797330f729Sjoerg SDLoc L = Builder.getCurSDLoc();
807330f729Sjoerg Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
817330f729Sjoerg MVT::i64));
827330f729Sjoerg Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
837330f729Sjoerg }
847330f729Sjoerg
startNewStatepoint(SelectionDAGBuilder & Builder)857330f729Sjoerg void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
867330f729Sjoerg // Consistency check
877330f729Sjoerg assert(PendingGCRelocateCalls.empty() &&
887330f729Sjoerg "Trying to visit statepoint before finished processing previous one");
897330f729Sjoerg Locations.clear();
907330f729Sjoerg NextSlotToAllocate = 0;
917330f729Sjoerg // Need to resize this on each safepoint - we need the two to stay in sync and
927330f729Sjoerg // the clear patterns of a SelectionDAGBuilder have no relation to
937330f729Sjoerg // FunctionLoweringInfo. Also need to ensure used bits get cleared.
947330f729Sjoerg AllocatedStackSlots.clear();
957330f729Sjoerg AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
967330f729Sjoerg }
977330f729Sjoerg
clear()987330f729Sjoerg void StatepointLoweringState::clear() {
997330f729Sjoerg Locations.clear();
1007330f729Sjoerg AllocatedStackSlots.clear();
1017330f729Sjoerg assert(PendingGCRelocateCalls.empty() &&
1027330f729Sjoerg "cleared before statepoint sequence completed");
1037330f729Sjoerg }
1047330f729Sjoerg
1057330f729Sjoerg SDValue
allocateStackSlot(EVT ValueType,SelectionDAGBuilder & Builder)1067330f729Sjoerg StatepointLoweringState::allocateStackSlot(EVT ValueType,
1077330f729Sjoerg SelectionDAGBuilder &Builder) {
1087330f729Sjoerg NumSlotsAllocatedForStatepoints++;
1097330f729Sjoerg MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
1107330f729Sjoerg
1117330f729Sjoerg unsigned SpillSize = ValueType.getStoreSize();
112*82d56013Sjoerg assert((SpillSize * 8) ==
113*82d56013Sjoerg (-8u & (7 + ValueType.getSizeInBits())) && // Round up modulo 8.
114*82d56013Sjoerg "Size not in bytes?");
1157330f729Sjoerg
1167330f729Sjoerg // First look for a previously created stack slot which is not in
1177330f729Sjoerg // use (accounting for the fact arbitrary slots may already be
1187330f729Sjoerg // reserved), or to create a new stack slot and use it.
1197330f729Sjoerg
1207330f729Sjoerg const size_t NumSlots = AllocatedStackSlots.size();
1217330f729Sjoerg assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
1227330f729Sjoerg
1237330f729Sjoerg assert(AllocatedStackSlots.size() ==
1247330f729Sjoerg Builder.FuncInfo.StatepointStackSlots.size() &&
1257330f729Sjoerg "Broken invariant");
1267330f729Sjoerg
1277330f729Sjoerg for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
1287330f729Sjoerg if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
1297330f729Sjoerg const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
1307330f729Sjoerg if (MFI.getObjectSize(FI) == SpillSize) {
1317330f729Sjoerg AllocatedStackSlots.set(NextSlotToAllocate);
1327330f729Sjoerg // TODO: Is ValueType the right thing to use here?
1337330f729Sjoerg return Builder.DAG.getFrameIndex(FI, ValueType);
1347330f729Sjoerg }
1357330f729Sjoerg }
1367330f729Sjoerg }
1377330f729Sjoerg
1387330f729Sjoerg // Couldn't find a free slot, so create a new one:
1397330f729Sjoerg
1407330f729Sjoerg SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
1417330f729Sjoerg const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1427330f729Sjoerg MFI.markAsStatepointSpillSlotObjectIndex(FI);
1437330f729Sjoerg
1447330f729Sjoerg Builder.FuncInfo.StatepointStackSlots.push_back(FI);
1457330f729Sjoerg AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
1467330f729Sjoerg assert(AllocatedStackSlots.size() ==
1477330f729Sjoerg Builder.FuncInfo.StatepointStackSlots.size() &&
1487330f729Sjoerg "Broken invariant");
1497330f729Sjoerg
1507330f729Sjoerg StatepointMaxSlotsRequired.updateMax(
1517330f729Sjoerg Builder.FuncInfo.StatepointStackSlots.size());
1527330f729Sjoerg
1537330f729Sjoerg return SpillSlot;
1547330f729Sjoerg }
1557330f729Sjoerg
1567330f729Sjoerg /// Utility function for reservePreviousStackSlotForValue. Tries to find
1577330f729Sjoerg /// stack slot index to which we have spilled value for previous statepoints.
1587330f729Sjoerg /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
findPreviousSpillSlot(const Value * Val,SelectionDAGBuilder & Builder,int LookUpDepth)1597330f729Sjoerg static Optional<int> findPreviousSpillSlot(const Value *Val,
1607330f729Sjoerg SelectionDAGBuilder &Builder,
1617330f729Sjoerg int LookUpDepth) {
1627330f729Sjoerg // Can not look any further - give up now
1637330f729Sjoerg if (LookUpDepth <= 0)
1647330f729Sjoerg return None;
1657330f729Sjoerg
1667330f729Sjoerg // Spill location is known for gc relocates
1677330f729Sjoerg if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
168*82d56013Sjoerg const auto &RelocationMap =
169*82d56013Sjoerg Builder.FuncInfo.StatepointRelocationMaps[Relocate->getStatepoint()];
1707330f729Sjoerg
171*82d56013Sjoerg auto It = RelocationMap.find(Relocate->getDerivedPtr());
172*82d56013Sjoerg if (It == RelocationMap.end())
1737330f729Sjoerg return None;
1747330f729Sjoerg
175*82d56013Sjoerg auto &Record = It->second;
176*82d56013Sjoerg if (Record.type != RecordType::Spill)
177*82d56013Sjoerg return None;
178*82d56013Sjoerg
179*82d56013Sjoerg return Record.payload.FI;
1807330f729Sjoerg }
1817330f729Sjoerg
1827330f729Sjoerg // Look through bitcast instructions.
1837330f729Sjoerg if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
1847330f729Sjoerg return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
1857330f729Sjoerg
1867330f729Sjoerg // Look through phi nodes
1877330f729Sjoerg // All incoming values should have same known stack slot, otherwise result
1887330f729Sjoerg // is unknown.
1897330f729Sjoerg if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
1907330f729Sjoerg Optional<int> MergedResult = None;
1917330f729Sjoerg
1927330f729Sjoerg for (auto &IncomingValue : Phi->incoming_values()) {
1937330f729Sjoerg Optional<int> SpillSlot =
1947330f729Sjoerg findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
1957330f729Sjoerg if (!SpillSlot.hasValue())
1967330f729Sjoerg return None;
1977330f729Sjoerg
1987330f729Sjoerg if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
1997330f729Sjoerg return None;
2007330f729Sjoerg
2017330f729Sjoerg MergedResult = SpillSlot;
2027330f729Sjoerg }
2037330f729Sjoerg return MergedResult;
2047330f729Sjoerg }
2057330f729Sjoerg
2067330f729Sjoerg // TODO: We can do better for PHI nodes. In cases like this:
2077330f729Sjoerg // ptr = phi(relocated_pointer, not_relocated_pointer)
2087330f729Sjoerg // statepoint(ptr)
2097330f729Sjoerg // We will return that stack slot for ptr is unknown. And later we might
2107330f729Sjoerg // assign different stack slots for ptr and relocated_pointer. This limits
2117330f729Sjoerg // llvm's ability to remove redundant stores.
2127330f729Sjoerg // Unfortunately it's hard to accomplish in current infrastructure.
2137330f729Sjoerg // We use this function to eliminate spill store completely, while
2147330f729Sjoerg // in example we still need to emit store, but instead of any location
2157330f729Sjoerg // we need to use special "preferred" location.
2167330f729Sjoerg
2177330f729Sjoerg // TODO: handle simple updates. If a value is modified and the original
2187330f729Sjoerg // value is no longer live, it would be nice to put the modified value in the
2197330f729Sjoerg // same slot. This allows folding of the memory accesses for some
2207330f729Sjoerg // instructions types (like an increment).
2217330f729Sjoerg // statepoint (i)
2227330f729Sjoerg // i1 = i+1
2237330f729Sjoerg // statepoint (i1)
2247330f729Sjoerg // However we need to be careful for cases like this:
2257330f729Sjoerg // statepoint(i)
2267330f729Sjoerg // i1 = i+1
2277330f729Sjoerg // statepoint(i, i1)
2287330f729Sjoerg // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
2297330f729Sjoerg // put handling of simple modifications in this function like it's done
2307330f729Sjoerg // for bitcasts we might end up reserving i's slot for 'i+1' because order in
2317330f729Sjoerg // which we visit values is unspecified.
2327330f729Sjoerg
2337330f729Sjoerg // Don't know any information about this instruction
2347330f729Sjoerg return None;
2357330f729Sjoerg }
2367330f729Sjoerg
237*82d56013Sjoerg /// Return true if-and-only-if the given SDValue can be lowered as either a
238*82d56013Sjoerg /// constant argument or a stack reference. The key point is that the value
239*82d56013Sjoerg /// doesn't need to be spilled or tracked as a vreg use.
willLowerDirectly(SDValue Incoming)240*82d56013Sjoerg static bool willLowerDirectly(SDValue Incoming) {
241*82d56013Sjoerg // We are making an unchecked assumption that the frame size <= 2^16 as that
242*82d56013Sjoerg // is the largest offset which can be encoded in the stackmap format.
243*82d56013Sjoerg if (isa<FrameIndexSDNode>(Incoming))
244*82d56013Sjoerg return true;
245*82d56013Sjoerg
246*82d56013Sjoerg // The largest constant describeable in the StackMap format is 64 bits.
247*82d56013Sjoerg // Potential Optimization: Constants values are sign extended by consumer,
248*82d56013Sjoerg // and thus there are many constants of static type > 64 bits whose value
249*82d56013Sjoerg // happens to be sext(Con64) and could thus be lowered directly.
250*82d56013Sjoerg if (Incoming.getValueType().getSizeInBits() > 64)
251*82d56013Sjoerg return false;
252*82d56013Sjoerg
253*82d56013Sjoerg return (isa<ConstantSDNode>(Incoming) || isa<ConstantFPSDNode>(Incoming) ||
254*82d56013Sjoerg Incoming.isUndef());
255*82d56013Sjoerg }
256*82d56013Sjoerg
2577330f729Sjoerg /// Try to find existing copies of the incoming values in stack slots used for
2587330f729Sjoerg /// statepoint spilling. If we can find a spill slot for the incoming value,
2597330f729Sjoerg /// mark that slot as allocated, and reuse the same slot for this safepoint.
2607330f729Sjoerg /// This helps to avoid series of loads and stores that only serve to reshuffle
2617330f729Sjoerg /// values on the stack between calls.
reservePreviousStackSlotForValue(const Value * IncomingValue,SelectionDAGBuilder & Builder)2627330f729Sjoerg static void reservePreviousStackSlotForValue(const Value *IncomingValue,
2637330f729Sjoerg SelectionDAGBuilder &Builder) {
2647330f729Sjoerg SDValue Incoming = Builder.getValue(IncomingValue);
2657330f729Sjoerg
266*82d56013Sjoerg // If we won't spill this, we don't need to check for previously allocated
267*82d56013Sjoerg // stack slots.
268*82d56013Sjoerg if (willLowerDirectly(Incoming))
2697330f729Sjoerg return;
2707330f729Sjoerg
2717330f729Sjoerg SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
2727330f729Sjoerg if (OldLocation.getNode())
2737330f729Sjoerg // Duplicates in input
2747330f729Sjoerg return;
2757330f729Sjoerg
2767330f729Sjoerg const int LookUpDepth = 6;
2777330f729Sjoerg Optional<int> Index =
2787330f729Sjoerg findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
2797330f729Sjoerg if (!Index.hasValue())
2807330f729Sjoerg return;
2817330f729Sjoerg
2827330f729Sjoerg const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
2837330f729Sjoerg
2847330f729Sjoerg auto SlotIt = find(StatepointSlots, *Index);
2857330f729Sjoerg assert(SlotIt != StatepointSlots.end() &&
2867330f729Sjoerg "Value spilled to the unknown stack slot");
2877330f729Sjoerg
2887330f729Sjoerg // This is one of our dedicated lowering slots
2897330f729Sjoerg const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
2907330f729Sjoerg if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
2917330f729Sjoerg // stack slot already assigned to someone else, can't use it!
2927330f729Sjoerg // TODO: currently we reserve space for gc arguments after doing
2937330f729Sjoerg // normal allocation for deopt arguments. We should reserve for
2947330f729Sjoerg // _all_ deopt and gc arguments, then start allocating. This
2957330f729Sjoerg // will prevent some moves being inserted when vm state changes,
2967330f729Sjoerg // but gc state doesn't between two calls.
2977330f729Sjoerg return;
2987330f729Sjoerg }
2997330f729Sjoerg // Reserve this stack slot
3007330f729Sjoerg Builder.StatepointLowering.reserveStackSlot(Offset);
3017330f729Sjoerg
3027330f729Sjoerg // Cache this slot so we find it when going through the normal
3037330f729Sjoerg // assignment loop.
3047330f729Sjoerg SDValue Loc =
3057330f729Sjoerg Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
3067330f729Sjoerg Builder.StatepointLowering.setLocation(Incoming, Loc);
3077330f729Sjoerg }
3087330f729Sjoerg
3097330f729Sjoerg /// Extract call from statepoint, lower it and return pointer to the
3107330f729Sjoerg /// call node. Also update NodeMap so that getValue(statepoint) will
3117330f729Sjoerg /// reference lowered call result
lowerCallFromStatepointLoweringInfo(SelectionDAGBuilder::StatepointLoweringInfo & SI,SelectionDAGBuilder & Builder,SmallVectorImpl<SDValue> & PendingExports)3127330f729Sjoerg static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
3137330f729Sjoerg SelectionDAGBuilder::StatepointLoweringInfo &SI,
3147330f729Sjoerg SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
3157330f729Sjoerg SDValue ReturnValue, CallEndVal;
3167330f729Sjoerg std::tie(ReturnValue, CallEndVal) =
3177330f729Sjoerg Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
3187330f729Sjoerg SDNode *CallEnd = CallEndVal.getNode();
3197330f729Sjoerg
3207330f729Sjoerg // Get a call instruction from the call sequence chain. Tail calls are not
3217330f729Sjoerg // allowed. The following code is essentially reverse engineering X86's
3227330f729Sjoerg // LowerCallTo.
3237330f729Sjoerg //
3247330f729Sjoerg // We are expecting DAG to have the following form:
3257330f729Sjoerg //
3267330f729Sjoerg // ch = eh_label (only in case of invoke statepoint)
3277330f729Sjoerg // ch, glue = callseq_start ch
3287330f729Sjoerg // ch, glue = X86::Call ch, glue
3297330f729Sjoerg // ch, glue = callseq_end ch, glue
3307330f729Sjoerg // get_return_value ch, glue
3317330f729Sjoerg //
3327330f729Sjoerg // get_return_value can either be a sequence of CopyFromReg instructions
3337330f729Sjoerg // to grab the return value from the return register(s), or it can be a LOAD
3347330f729Sjoerg // to load a value returned by reference via a stack slot.
3357330f729Sjoerg
3367330f729Sjoerg bool HasDef = !SI.CLI.RetTy->isVoidTy();
3377330f729Sjoerg if (HasDef) {
3387330f729Sjoerg if (CallEnd->getOpcode() == ISD::LOAD)
3397330f729Sjoerg CallEnd = CallEnd->getOperand(0).getNode();
3407330f729Sjoerg else
3417330f729Sjoerg while (CallEnd->getOpcode() == ISD::CopyFromReg)
3427330f729Sjoerg CallEnd = CallEnd->getOperand(0).getNode();
3437330f729Sjoerg }
3447330f729Sjoerg
3457330f729Sjoerg assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
3467330f729Sjoerg return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
3477330f729Sjoerg }
3487330f729Sjoerg
getMachineMemOperand(MachineFunction & MF,FrameIndexSDNode & FI)3497330f729Sjoerg static MachineMemOperand* getMachineMemOperand(MachineFunction &MF,
3507330f729Sjoerg FrameIndexSDNode &FI) {
3517330f729Sjoerg auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
3527330f729Sjoerg auto MMOFlags = MachineMemOperand::MOStore |
3537330f729Sjoerg MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
3547330f729Sjoerg auto &MFI = MF.getFrameInfo();
3557330f729Sjoerg return MF.getMachineMemOperand(PtrInfo, MMOFlags,
3567330f729Sjoerg MFI.getObjectSize(FI.getIndex()),
357*82d56013Sjoerg MFI.getObjectAlign(FI.getIndex()));
3587330f729Sjoerg }
3597330f729Sjoerg
3607330f729Sjoerg /// Spill a value incoming to the statepoint. It might be either part of
3617330f729Sjoerg /// vmstate
3627330f729Sjoerg /// or gcstate. In both cases unconditionally spill it on the stack unless it
3637330f729Sjoerg /// is a null constant. Return pair with first element being frame index
3647330f729Sjoerg /// containing saved value and second element with outgoing chain from the
3657330f729Sjoerg /// emitted store
3667330f729Sjoerg static std::tuple<SDValue, SDValue, MachineMemOperand*>
spillIncomingStatepointValue(SDValue Incoming,SDValue Chain,SelectionDAGBuilder & Builder)3677330f729Sjoerg spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
3687330f729Sjoerg SelectionDAGBuilder &Builder) {
3697330f729Sjoerg SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
3707330f729Sjoerg MachineMemOperand* MMO = nullptr;
3717330f729Sjoerg
3727330f729Sjoerg // Emit new store if we didn't do it for this ptr before
3737330f729Sjoerg if (!Loc.getNode()) {
3747330f729Sjoerg Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
3757330f729Sjoerg Builder);
3767330f729Sjoerg int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
3777330f729Sjoerg // We use TargetFrameIndex so that isel will not select it into LEA
3787330f729Sjoerg Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
3797330f729Sjoerg
3807330f729Sjoerg // Right now we always allocate spill slots that are of the same
3817330f729Sjoerg // size as the value we're about to spill (the size of spillee can
3827330f729Sjoerg // vary since we spill vectors of pointers too). At some point we
3837330f729Sjoerg // can consider allowing spills of smaller values to larger slots
3847330f729Sjoerg // (i.e. change the '==' in the assert below to a '>=').
3857330f729Sjoerg MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
386*82d56013Sjoerg assert((MFI.getObjectSize(Index) * 8) ==
387*82d56013Sjoerg (-8 & (7 + // Round up modulo 8.
388*82d56013Sjoerg (int64_t)Incoming.getValueSizeInBits())) &&
3897330f729Sjoerg "Bad spill: stack slot does not match!");
3907330f729Sjoerg
3917330f729Sjoerg // Note: Using the alignment of the spill slot (rather than the abi or
3927330f729Sjoerg // preferred alignment) is required for correctness when dealing with spill
3937330f729Sjoerg // slots with preferred alignments larger than frame alignment..
3947330f729Sjoerg auto &MF = Builder.DAG.getMachineFunction();
3957330f729Sjoerg auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
396*82d56013Sjoerg auto *StoreMMO = MF.getMachineMemOperand(
397*82d56013Sjoerg PtrInfo, MachineMemOperand::MOStore, MFI.getObjectSize(Index),
398*82d56013Sjoerg MFI.getObjectAlign(Index));
3997330f729Sjoerg Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
4007330f729Sjoerg StoreMMO);
4017330f729Sjoerg
4027330f729Sjoerg MMO = getMachineMemOperand(MF, *cast<FrameIndexSDNode>(Loc));
4037330f729Sjoerg
4047330f729Sjoerg Builder.StatepointLowering.setLocation(Incoming, Loc);
4057330f729Sjoerg }
4067330f729Sjoerg
4077330f729Sjoerg assert(Loc.getNode());
4087330f729Sjoerg return std::make_tuple(Loc, Chain, MMO);
4097330f729Sjoerg }
4107330f729Sjoerg
4117330f729Sjoerg /// Lower a single value incoming to a statepoint node. This value can be
4127330f729Sjoerg /// either a deopt value or a gc value, the handling is the same. We special
4137330f729Sjoerg /// case constants and allocas, then fall back to spilling if required.
414*82d56013Sjoerg static void
lowerIncomingStatepointValue(SDValue Incoming,bool RequireSpillSlot,SmallVectorImpl<SDValue> & Ops,SmallVectorImpl<MachineMemOperand * > & MemRefs,SelectionDAGBuilder & Builder)415*82d56013Sjoerg lowerIncomingStatepointValue(SDValue Incoming, bool RequireSpillSlot,
4167330f729Sjoerg SmallVectorImpl<SDValue> &Ops,
4177330f729Sjoerg SmallVectorImpl<MachineMemOperand *> &MemRefs,
4187330f729Sjoerg SelectionDAGBuilder &Builder) {
4197330f729Sjoerg
420*82d56013Sjoerg if (willLowerDirectly(Incoming)) {
421*82d56013Sjoerg if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
4227330f729Sjoerg // This handles allocas as arguments to the statepoint (this is only
4237330f729Sjoerg // really meaningful for a deopt value. For GC, we'd be trying to
4247330f729Sjoerg // relocate the address of the alloca itself?)
4257330f729Sjoerg assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
4267330f729Sjoerg "Incoming value is a frame index!");
4277330f729Sjoerg Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
4287330f729Sjoerg Builder.getFrameIndexTy()));
4297330f729Sjoerg
4307330f729Sjoerg auto &MF = Builder.DAG.getMachineFunction();
4317330f729Sjoerg auto *MMO = getMachineMemOperand(MF, *FI);
4327330f729Sjoerg MemRefs.push_back(MMO);
433*82d56013Sjoerg return;
434*82d56013Sjoerg }
4357330f729Sjoerg
436*82d56013Sjoerg assert(Incoming.getValueType().getSizeInBits() <= 64);
437*82d56013Sjoerg
438*82d56013Sjoerg if (Incoming.isUndef()) {
439*82d56013Sjoerg // Put an easily recognized constant that's unlikely to be a valid
440*82d56013Sjoerg // value so that uses of undef by the consumer of the stackmap is
441*82d56013Sjoerg // easily recognized. This is legal since the compiler is always
442*82d56013Sjoerg // allowed to chose an arbitrary value for undef.
443*82d56013Sjoerg pushStackMapConstant(Ops, Builder, 0xFEFEFEFE);
444*82d56013Sjoerg return;
445*82d56013Sjoerg }
446*82d56013Sjoerg
447*82d56013Sjoerg // If the original value was a constant, make sure it gets recorded as
448*82d56013Sjoerg // such in the stackmap. This is required so that the consumer can
449*82d56013Sjoerg // parse any internal format to the deopt state. It also handles null
450*82d56013Sjoerg // pointers and other constant pointers in GC states.
451*82d56013Sjoerg if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
452*82d56013Sjoerg pushStackMapConstant(Ops, Builder, C->getSExtValue());
453*82d56013Sjoerg return;
454*82d56013Sjoerg } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Incoming)) {
455*82d56013Sjoerg pushStackMapConstant(Ops, Builder,
456*82d56013Sjoerg C->getValueAPF().bitcastToAPInt().getZExtValue());
457*82d56013Sjoerg return;
458*82d56013Sjoerg }
459*82d56013Sjoerg
460*82d56013Sjoerg llvm_unreachable("unhandled direct lowering case");
461*82d56013Sjoerg }
462*82d56013Sjoerg
463*82d56013Sjoerg
464*82d56013Sjoerg
465*82d56013Sjoerg if (!RequireSpillSlot) {
4667330f729Sjoerg // If this value is live in (not live-on-return, or live-through), we can
4677330f729Sjoerg // treat it the same way patchpoint treats it's "live in" values. We'll
4687330f729Sjoerg // end up folding some of these into stack references, but they'll be
4697330f729Sjoerg // handled by the register allocator. Note that we do not have the notion
4707330f729Sjoerg // of a late use so these values might be placed in registers which are
471*82d56013Sjoerg // clobbered by the call. This is fine for live-in. For live-through
472*82d56013Sjoerg // fix-up pass should be executed to force spilling of such registers.
4737330f729Sjoerg Ops.push_back(Incoming);
4747330f729Sjoerg } else {
475*82d56013Sjoerg // Otherwise, locate a spill slot and explicitly spill it so it can be
476*82d56013Sjoerg // found by the runtime later. Note: We know all of these spills are
477*82d56013Sjoerg // independent, but don't bother to exploit that chain wise. DAGCombine
478*82d56013Sjoerg // will happily do so as needed, so doing it here would be a small compile
479*82d56013Sjoerg // time win at most.
480*82d56013Sjoerg SDValue Chain = Builder.getRoot();
4817330f729Sjoerg auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
4827330f729Sjoerg Ops.push_back(std::get<0>(Res));
4837330f729Sjoerg if (auto *MMO = std::get<2>(Res))
4847330f729Sjoerg MemRefs.push_back(MMO);
4857330f729Sjoerg Chain = std::get<1>(Res);;
486*82d56013Sjoerg Builder.DAG.setRoot(Chain);
4877330f729Sjoerg }
4887330f729Sjoerg
489*82d56013Sjoerg }
490*82d56013Sjoerg
491*82d56013Sjoerg /// Return true if value V represents the GC value. The behavior is conservative
492*82d56013Sjoerg /// in case it is not sure that value is not GC the function returns true.
isGCValue(const Value * V,SelectionDAGBuilder & Builder)493*82d56013Sjoerg static bool isGCValue(const Value *V, SelectionDAGBuilder &Builder) {
494*82d56013Sjoerg auto *Ty = V->getType();
495*82d56013Sjoerg if (!Ty->isPtrOrPtrVectorTy())
496*82d56013Sjoerg return false;
497*82d56013Sjoerg if (auto *GFI = Builder.GFI)
498*82d56013Sjoerg if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
499*82d56013Sjoerg return *IsManaged;
500*82d56013Sjoerg return true; // conservative
5017330f729Sjoerg }
5027330f729Sjoerg
5037330f729Sjoerg /// Lower deopt state and gc pointer arguments of the statepoint. The actual
5047330f729Sjoerg /// lowering is described in lowerIncomingStatepointValue. This function is
5057330f729Sjoerg /// responsible for lowering everything in the right position and playing some
5067330f729Sjoerg /// tricks to avoid redundant stack manipulation where possible. On
5077330f729Sjoerg /// completion, 'Ops' will contain ready to use operands for machine code
5087330f729Sjoerg /// statepoint. The chain nodes will have already been created and the DAG root
5097330f729Sjoerg /// will be set to the last value spilled (if any were).
5107330f729Sjoerg static void
lowerStatepointMetaArgs(SmallVectorImpl<SDValue> & Ops,SmallVectorImpl<MachineMemOperand * > & MemRefs,SmallVectorImpl<SDValue> & GCPtrs,DenseMap<SDValue,int> & LowerAsVReg,SelectionDAGBuilder::StatepointLoweringInfo & SI,SelectionDAGBuilder & Builder)5117330f729Sjoerg lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
512*82d56013Sjoerg SmallVectorImpl<MachineMemOperand *> &MemRefs,
513*82d56013Sjoerg SmallVectorImpl<SDValue> &GCPtrs,
514*82d56013Sjoerg DenseMap<SDValue, int> &LowerAsVReg,
515*82d56013Sjoerg SelectionDAGBuilder::StatepointLoweringInfo &SI,
5167330f729Sjoerg SelectionDAGBuilder &Builder) {
5177330f729Sjoerg // Lower the deopt and gc arguments for this statepoint. Layout will be:
5187330f729Sjoerg // deopt argument length, deopt arguments.., gc arguments...
5197330f729Sjoerg #ifndef NDEBUG
5207330f729Sjoerg if (auto *GFI = Builder.GFI) {
5217330f729Sjoerg // Check that each of the gc pointer and bases we've gotten out of the
5227330f729Sjoerg // safepoint is something the strategy thinks might be a pointer (or vector
5237330f729Sjoerg // of pointers) into the GC heap. This is basically just here to help catch
5247330f729Sjoerg // errors during statepoint insertion. TODO: This should actually be in the
5257330f729Sjoerg // Verifier, but we can't get to the GCStrategy from there (yet).
5267330f729Sjoerg GCStrategy &S = GFI->getStrategy();
5277330f729Sjoerg for (const Value *V : SI.Bases) {
5287330f729Sjoerg auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
5297330f729Sjoerg if (Opt.hasValue()) {
5307330f729Sjoerg assert(Opt.getValue() &&
5317330f729Sjoerg "non gc managed base pointer found in statepoint");
5327330f729Sjoerg }
5337330f729Sjoerg }
5347330f729Sjoerg for (const Value *V : SI.Ptrs) {
5357330f729Sjoerg auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
5367330f729Sjoerg if (Opt.hasValue()) {
5377330f729Sjoerg assert(Opt.getValue() &&
5387330f729Sjoerg "non gc managed derived pointer found in statepoint");
5397330f729Sjoerg }
5407330f729Sjoerg }
5417330f729Sjoerg assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");
5427330f729Sjoerg } else {
5437330f729Sjoerg assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
5447330f729Sjoerg assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
5457330f729Sjoerg }
5467330f729Sjoerg #endif
5477330f729Sjoerg
5487330f729Sjoerg // Figure out what lowering strategy we're going to use for each part
5497330f729Sjoerg // Note: Is is conservatively correct to lower both "live-in" and "live-out"
5507330f729Sjoerg // as "live-through". A "live-through" variable is one which is "live-in",
5517330f729Sjoerg // "live-out", and live throughout the lifetime of the call (i.e. we can find
5527330f729Sjoerg // it from any PC within the transitive callee of the statepoint). In
5537330f729Sjoerg // particular, if the callee spills callee preserved registers we may not
5547330f729Sjoerg // be able to find a value placed in that register during the call. This is
5557330f729Sjoerg // fine for live-out, but not for live-through. If we were willing to make
5567330f729Sjoerg // assumptions about the code generator producing the callee, we could
5577330f729Sjoerg // potentially allow live-through values in callee saved registers.
5587330f729Sjoerg const bool LiveInDeopt =
5597330f729Sjoerg SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
5607330f729Sjoerg
561*82d56013Sjoerg // Decide which deriver pointers will go on VRegs
562*82d56013Sjoerg unsigned MaxVRegPtrs = MaxRegistersForGCPointers.getValue();
563*82d56013Sjoerg
564*82d56013Sjoerg // Pointers used on exceptional path of invoke statepoint.
565*82d56013Sjoerg // We cannot assing them to VRegs.
566*82d56013Sjoerg SmallSet<SDValue, 8> LPadPointers;
567*82d56013Sjoerg if (!UseRegistersForGCPointersInLandingPad)
568*82d56013Sjoerg if (auto *StInvoke = dyn_cast_or_null<InvokeInst>(SI.StatepointInstr)) {
569*82d56013Sjoerg LandingPadInst *LPI = StInvoke->getLandingPadInst();
570*82d56013Sjoerg for (auto *Relocate : SI.GCRelocates)
571*82d56013Sjoerg if (Relocate->getOperand(0) == LPI) {
572*82d56013Sjoerg LPadPointers.insert(Builder.getValue(Relocate->getBasePtr()));
573*82d56013Sjoerg LPadPointers.insert(Builder.getValue(Relocate->getDerivedPtr()));
574*82d56013Sjoerg }
575*82d56013Sjoerg }
576*82d56013Sjoerg
577*82d56013Sjoerg LLVM_DEBUG(dbgs() << "Deciding how to lower GC Pointers:\n");
578*82d56013Sjoerg
579*82d56013Sjoerg // List of unique lowered GC Pointer values.
580*82d56013Sjoerg SmallSetVector<SDValue, 16> LoweredGCPtrs;
581*82d56013Sjoerg // Map lowered GC Pointer value to the index in above vector
582*82d56013Sjoerg DenseMap<SDValue, unsigned> GCPtrIndexMap;
583*82d56013Sjoerg
584*82d56013Sjoerg unsigned CurNumVRegs = 0;
585*82d56013Sjoerg
586*82d56013Sjoerg auto canPassGCPtrOnVReg = [&](SDValue SD) {
587*82d56013Sjoerg if (SD.getValueType().isVector())
588*82d56013Sjoerg return false;
589*82d56013Sjoerg if (LPadPointers.count(SD))
590*82d56013Sjoerg return false;
591*82d56013Sjoerg return !willLowerDirectly(SD);
592*82d56013Sjoerg };
593*82d56013Sjoerg
594*82d56013Sjoerg auto processGCPtr = [&](const Value *V) {
595*82d56013Sjoerg SDValue PtrSD = Builder.getValue(V);
596*82d56013Sjoerg if (!LoweredGCPtrs.insert(PtrSD))
597*82d56013Sjoerg return; // skip duplicates
598*82d56013Sjoerg GCPtrIndexMap[PtrSD] = LoweredGCPtrs.size() - 1;
599*82d56013Sjoerg
600*82d56013Sjoerg assert(!LowerAsVReg.count(PtrSD) && "must not have been seen");
601*82d56013Sjoerg if (LowerAsVReg.size() == MaxVRegPtrs)
602*82d56013Sjoerg return;
603*82d56013Sjoerg assert(V->getType()->isVectorTy() == PtrSD.getValueType().isVector() &&
604*82d56013Sjoerg "IR and SD types disagree");
605*82d56013Sjoerg if (!canPassGCPtrOnVReg(PtrSD)) {
606*82d56013Sjoerg LLVM_DEBUG(dbgs() << "direct/spill "; PtrSD.dump(&Builder.DAG));
607*82d56013Sjoerg return;
608*82d56013Sjoerg }
609*82d56013Sjoerg LLVM_DEBUG(dbgs() << "vreg "; PtrSD.dump(&Builder.DAG));
610*82d56013Sjoerg LowerAsVReg[PtrSD] = CurNumVRegs++;
611*82d56013Sjoerg };
612*82d56013Sjoerg
613*82d56013Sjoerg // Process derived pointers first to give them more chance to go on VReg.
614*82d56013Sjoerg for (const Value *V : SI.Ptrs)
615*82d56013Sjoerg processGCPtr(V);
616*82d56013Sjoerg for (const Value *V : SI.Bases)
617*82d56013Sjoerg processGCPtr(V);
618*82d56013Sjoerg
619*82d56013Sjoerg LLVM_DEBUG(dbgs() << LowerAsVReg.size() << " pointers will go in vregs\n");
620*82d56013Sjoerg
621*82d56013Sjoerg auto requireSpillSlot = [&](const Value *V) {
622*82d56013Sjoerg if (!Builder.DAG.getTargetLoweringInfo().isTypeLegal(
623*82d56013Sjoerg Builder.getValue(V).getValueType()))
624*82d56013Sjoerg return true;
625*82d56013Sjoerg if (isGCValue(V, Builder))
626*82d56013Sjoerg return !LowerAsVReg.count(Builder.getValue(V));
627*82d56013Sjoerg return !(LiveInDeopt || UseRegistersForDeoptValues);
6287330f729Sjoerg };
6297330f729Sjoerg
6307330f729Sjoerg // Before we actually start lowering (and allocating spill slots for values),
6317330f729Sjoerg // reserve any stack slots which we judge to be profitable to reuse for a
6327330f729Sjoerg // particular value. This is purely an optimization over the code below and
6337330f729Sjoerg // doesn't change semantics at all. It is important for performance that we
6347330f729Sjoerg // reserve slots for both deopt and gc values before lowering either.
6357330f729Sjoerg for (const Value *V : SI.DeoptState) {
636*82d56013Sjoerg if (requireSpillSlot(V))
6377330f729Sjoerg reservePreviousStackSlotForValue(V, Builder);
6387330f729Sjoerg }
639*82d56013Sjoerg
640*82d56013Sjoerg for (const Value *V : SI.Ptrs) {
641*82d56013Sjoerg SDValue SDV = Builder.getValue(V);
642*82d56013Sjoerg if (!LowerAsVReg.count(SDV))
643*82d56013Sjoerg reservePreviousStackSlotForValue(V, Builder);
644*82d56013Sjoerg }
645*82d56013Sjoerg
646*82d56013Sjoerg for (const Value *V : SI.Bases) {
647*82d56013Sjoerg SDValue SDV = Builder.getValue(V);
648*82d56013Sjoerg if (!LowerAsVReg.count(SDV))
649*82d56013Sjoerg reservePreviousStackSlotForValue(V, Builder);
6507330f729Sjoerg }
6517330f729Sjoerg
6527330f729Sjoerg // First, prefix the list with the number of unique values to be
6537330f729Sjoerg // lowered. Note that this is the number of *Values* not the
6547330f729Sjoerg // number of SDValues required to lower them.
6557330f729Sjoerg const int NumVMSArgs = SI.DeoptState.size();
6567330f729Sjoerg pushStackMapConstant(Ops, Builder, NumVMSArgs);
6577330f729Sjoerg
6587330f729Sjoerg // The vm state arguments are lowered in an opaque manner. We do not know
6597330f729Sjoerg // what type of values are contained within.
660*82d56013Sjoerg LLVM_DEBUG(dbgs() << "Lowering deopt state\n");
6617330f729Sjoerg for (const Value *V : SI.DeoptState) {
6627330f729Sjoerg SDValue Incoming;
6637330f729Sjoerg // If this is a function argument at a static frame index, generate it as
6647330f729Sjoerg // the frame index.
6657330f729Sjoerg if (const Argument *Arg = dyn_cast<Argument>(V)) {
6667330f729Sjoerg int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
6677330f729Sjoerg if (FI != INT_MAX)
6687330f729Sjoerg Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy());
6697330f729Sjoerg }
6707330f729Sjoerg if (!Incoming.getNode())
6717330f729Sjoerg Incoming = Builder.getValue(V);
672*82d56013Sjoerg LLVM_DEBUG(dbgs() << "Value " << *V
673*82d56013Sjoerg << " requireSpillSlot = " << requireSpillSlot(V) << "\n");
674*82d56013Sjoerg lowerIncomingStatepointValue(Incoming, requireSpillSlot(V), Ops, MemRefs,
675*82d56013Sjoerg Builder);
6767330f729Sjoerg }
6777330f729Sjoerg
678*82d56013Sjoerg // Finally, go ahead and lower all the gc arguments.
679*82d56013Sjoerg pushStackMapConstant(Ops, Builder, LoweredGCPtrs.size());
680*82d56013Sjoerg for (SDValue SDV : LoweredGCPtrs)
681*82d56013Sjoerg lowerIncomingStatepointValue(SDV, !LowerAsVReg.count(SDV), Ops, MemRefs,
682*82d56013Sjoerg Builder);
6837330f729Sjoerg
684*82d56013Sjoerg // Copy to out vector. LoweredGCPtrs will be empty after this point.
685*82d56013Sjoerg GCPtrs = LoweredGCPtrs.takeVector();
6867330f729Sjoerg
6877330f729Sjoerg // If there are any explicit spill slots passed to the statepoint, record
6887330f729Sjoerg // them, but otherwise do not do anything special. These are user provided
6897330f729Sjoerg // allocas and give control over placement to the consumer. In this case,
6907330f729Sjoerg // it is the contents of the slot which may get updated, not the pointer to
6917330f729Sjoerg // the alloca
692*82d56013Sjoerg SmallVector<SDValue, 4> Allocas;
6937330f729Sjoerg for (Value *V : SI.GCArgs) {
6947330f729Sjoerg SDValue Incoming = Builder.getValue(V);
6957330f729Sjoerg if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
6967330f729Sjoerg // This handles allocas as arguments to the statepoint
6977330f729Sjoerg assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
6987330f729Sjoerg "Incoming value is a frame index!");
699*82d56013Sjoerg Allocas.push_back(Builder.DAG.getTargetFrameIndex(
700*82d56013Sjoerg FI->getIndex(), Builder.getFrameIndexTy()));
7017330f729Sjoerg
7027330f729Sjoerg auto &MF = Builder.DAG.getMachineFunction();
7037330f729Sjoerg auto *MMO = getMachineMemOperand(MF, *FI);
7047330f729Sjoerg MemRefs.push_back(MMO);
7057330f729Sjoerg }
7067330f729Sjoerg }
707*82d56013Sjoerg pushStackMapConstant(Ops, Builder, Allocas.size());
708*82d56013Sjoerg Ops.append(Allocas.begin(), Allocas.end());
7097330f729Sjoerg
710*82d56013Sjoerg // Now construct GC base/derived map;
711*82d56013Sjoerg pushStackMapConstant(Ops, Builder, SI.Ptrs.size());
712*82d56013Sjoerg SDLoc L = Builder.getCurSDLoc();
713*82d56013Sjoerg for (unsigned i = 0; i < SI.Ptrs.size(); ++i) {
714*82d56013Sjoerg SDValue Base = Builder.getValue(SI.Bases[i]);
715*82d56013Sjoerg assert(GCPtrIndexMap.count(Base) && "base not found in index map");
716*82d56013Sjoerg Ops.push_back(
717*82d56013Sjoerg Builder.DAG.getTargetConstant(GCPtrIndexMap[Base], L, MVT::i64));
718*82d56013Sjoerg SDValue Derived = Builder.getValue(SI.Ptrs[i]);
719*82d56013Sjoerg assert(GCPtrIndexMap.count(Derived) && "derived not found in index map");
720*82d56013Sjoerg Ops.push_back(
721*82d56013Sjoerg Builder.DAG.getTargetConstant(GCPtrIndexMap[Derived], L, MVT::i64));
7227330f729Sjoerg }
7237330f729Sjoerg }
7247330f729Sjoerg
LowerAsSTATEPOINT(SelectionDAGBuilder::StatepointLoweringInfo & SI)7257330f729Sjoerg SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
7267330f729Sjoerg SelectionDAGBuilder::StatepointLoweringInfo &SI) {
7277330f729Sjoerg // The basic scheme here is that information about both the original call and
7287330f729Sjoerg // the safepoint is encoded in the CallInst. We create a temporary call and
7297330f729Sjoerg // lower it, then reverse engineer the calling sequence.
7307330f729Sjoerg
7317330f729Sjoerg NumOfStatepoints++;
7327330f729Sjoerg // Clear state
7337330f729Sjoerg StatepointLowering.startNewStatepoint(*this);
734*82d56013Sjoerg assert(SI.Bases.size() == SI.Ptrs.size());
7357330f729Sjoerg
736*82d56013Sjoerg LLVM_DEBUG(dbgs() << "Lowering statepoint " << *SI.StatepointInstr << "\n");
7377330f729Sjoerg #ifndef NDEBUG
7387330f729Sjoerg for (auto *Reloc : SI.GCRelocates)
7397330f729Sjoerg if (Reloc->getParent() == SI.StatepointInstr->getParent())
7407330f729Sjoerg StatepointLowering.scheduleRelocCall(*Reloc);
7417330f729Sjoerg #endif
7427330f729Sjoerg
7437330f729Sjoerg // Lower statepoint vmstate and gcstate arguments
744*82d56013Sjoerg
745*82d56013Sjoerg // All lowered meta args.
7467330f729Sjoerg SmallVector<SDValue, 10> LoweredMetaArgs;
747*82d56013Sjoerg // Lowered GC pointers (subset of above).
748*82d56013Sjoerg SmallVector<SDValue, 16> LoweredGCArgs;
7497330f729Sjoerg SmallVector<MachineMemOperand*, 16> MemRefs;
750*82d56013Sjoerg // Maps derived pointer SDValue to statepoint result of relocated pointer.
751*82d56013Sjoerg DenseMap<SDValue, int> LowerAsVReg;
752*82d56013Sjoerg lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, LoweredGCArgs, LowerAsVReg,
753*82d56013Sjoerg SI, *this);
7547330f729Sjoerg
7557330f729Sjoerg // Now that we've emitted the spills, we need to update the root so that the
7567330f729Sjoerg // call sequence is ordered correctly.
7577330f729Sjoerg SI.CLI.setChain(getRoot());
7587330f729Sjoerg
7597330f729Sjoerg // Get call node, we will replace it later with statepoint
7607330f729Sjoerg SDValue ReturnVal;
7617330f729Sjoerg SDNode *CallNode;
7627330f729Sjoerg std::tie(ReturnVal, CallNode) =
7637330f729Sjoerg lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
7647330f729Sjoerg
7657330f729Sjoerg // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
7667330f729Sjoerg // nodes with all the appropriate arguments and return values.
7677330f729Sjoerg
7687330f729Sjoerg // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7697330f729Sjoerg SDValue Chain = CallNode->getOperand(0);
7707330f729Sjoerg
7717330f729Sjoerg SDValue Glue;
7727330f729Sjoerg bool CallHasIncomingGlue = CallNode->getGluedNode();
7737330f729Sjoerg if (CallHasIncomingGlue) {
7747330f729Sjoerg // Glue is always last operand
7757330f729Sjoerg Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
7767330f729Sjoerg }
7777330f729Sjoerg
7787330f729Sjoerg // Build the GC_TRANSITION_START node if necessary.
7797330f729Sjoerg //
7807330f729Sjoerg // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
7817330f729Sjoerg // order in which they appear in the call to the statepoint intrinsic. If
7827330f729Sjoerg // any of the operands is a pointer-typed, that operand is immediately
7837330f729Sjoerg // followed by a SRCVALUE for the pointer that may be used during lowering
7847330f729Sjoerg // (e.g. to form MachinePointerInfo values for loads/stores).
7857330f729Sjoerg const bool IsGCTransition =
7867330f729Sjoerg (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
7877330f729Sjoerg (uint64_t)StatepointFlags::GCTransition;
7887330f729Sjoerg if (IsGCTransition) {
7897330f729Sjoerg SmallVector<SDValue, 8> TSOps;
7907330f729Sjoerg
7917330f729Sjoerg // Add chain
7927330f729Sjoerg TSOps.push_back(Chain);
7937330f729Sjoerg
7947330f729Sjoerg // Add GC transition arguments
7957330f729Sjoerg for (const Value *V : SI.GCTransitionArgs) {
7967330f729Sjoerg TSOps.push_back(getValue(V));
7977330f729Sjoerg if (V->getType()->isPointerTy())
7987330f729Sjoerg TSOps.push_back(DAG.getSrcValue(V));
7997330f729Sjoerg }
8007330f729Sjoerg
8017330f729Sjoerg // Add glue if necessary
8027330f729Sjoerg if (CallHasIncomingGlue)
8037330f729Sjoerg TSOps.push_back(Glue);
8047330f729Sjoerg
8057330f729Sjoerg SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8067330f729Sjoerg
8077330f729Sjoerg SDValue GCTransitionStart =
8087330f729Sjoerg DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
8097330f729Sjoerg
8107330f729Sjoerg Chain = GCTransitionStart.getValue(0);
8117330f729Sjoerg Glue = GCTransitionStart.getValue(1);
8127330f729Sjoerg }
8137330f729Sjoerg
8147330f729Sjoerg // TODO: Currently, all of these operands are being marked as read/write in
8157330f729Sjoerg // PrologEpilougeInserter.cpp, we should special case the VMState arguments
8167330f729Sjoerg // and flags to be read-only.
8177330f729Sjoerg SmallVector<SDValue, 40> Ops;
8187330f729Sjoerg
8197330f729Sjoerg // Add the <id> and <numBytes> constants.
8207330f729Sjoerg Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
8217330f729Sjoerg Ops.push_back(
8227330f729Sjoerg DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
8237330f729Sjoerg
8247330f729Sjoerg // Calculate and push starting position of vmstate arguments
8257330f729Sjoerg // Get number of arguments incoming directly into call node
8267330f729Sjoerg unsigned NumCallRegArgs =
8277330f729Sjoerg CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
8287330f729Sjoerg Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
8297330f729Sjoerg
8307330f729Sjoerg // Add call target
8317330f729Sjoerg SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
8327330f729Sjoerg Ops.push_back(CallTarget);
8337330f729Sjoerg
8347330f729Sjoerg // Add call arguments
8357330f729Sjoerg // Get position of register mask in the call
8367330f729Sjoerg SDNode::op_iterator RegMaskIt;
8377330f729Sjoerg if (CallHasIncomingGlue)
8387330f729Sjoerg RegMaskIt = CallNode->op_end() - 2;
8397330f729Sjoerg else
8407330f729Sjoerg RegMaskIt = CallNode->op_end() - 1;
8417330f729Sjoerg Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
8427330f729Sjoerg
8437330f729Sjoerg // Add a constant argument for the calling convention
8447330f729Sjoerg pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
8457330f729Sjoerg
8467330f729Sjoerg // Add a constant argument for the flags
8477330f729Sjoerg uint64_t Flags = SI.StatepointFlags;
8487330f729Sjoerg assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
8497330f729Sjoerg "Unknown flag used");
8507330f729Sjoerg pushStackMapConstant(Ops, *this, Flags);
8517330f729Sjoerg
8527330f729Sjoerg // Insert all vmstate and gcstate arguments
853*82d56013Sjoerg llvm::append_range(Ops, LoweredMetaArgs);
8547330f729Sjoerg
8557330f729Sjoerg // Add register mask from call node
8567330f729Sjoerg Ops.push_back(*RegMaskIt);
8577330f729Sjoerg
8587330f729Sjoerg // Add chain
8597330f729Sjoerg Ops.push_back(Chain);
8607330f729Sjoerg
8617330f729Sjoerg // Same for the glue, but we add it only if original call had it
8627330f729Sjoerg if (Glue.getNode())
8637330f729Sjoerg Ops.push_back(Glue);
8647330f729Sjoerg
8657330f729Sjoerg // Compute return values. Provide a glue output since we consume one as
8667330f729Sjoerg // input. This allows someone else to chain off us as needed.
867*82d56013Sjoerg SmallVector<EVT, 8> NodeTys;
868*82d56013Sjoerg for (auto SD : LoweredGCArgs) {
869*82d56013Sjoerg if (!LowerAsVReg.count(SD))
870*82d56013Sjoerg continue;
871*82d56013Sjoerg NodeTys.push_back(SD.getValueType());
872*82d56013Sjoerg }
873*82d56013Sjoerg LLVM_DEBUG(dbgs() << "Statepoint has " << NodeTys.size() << " results\n");
874*82d56013Sjoerg assert(NodeTys.size() == LowerAsVReg.size() && "Inconsistent GC Ptr lowering");
875*82d56013Sjoerg NodeTys.push_back(MVT::Other);
876*82d56013Sjoerg NodeTys.push_back(MVT::Glue);
8777330f729Sjoerg
878*82d56013Sjoerg unsigned NumResults = NodeTys.size();
8797330f729Sjoerg MachineSDNode *StatepointMCNode =
8807330f729Sjoerg DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
8817330f729Sjoerg DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
8827330f729Sjoerg
883*82d56013Sjoerg // For values lowered to tied-defs, create the virtual registers. Note that
884*82d56013Sjoerg // for simplicity, we *always* create a vreg even within a single block.
885*82d56013Sjoerg DenseMap<SDValue, Register> VirtRegs;
886*82d56013Sjoerg for (const auto *Relocate : SI.GCRelocates) {
887*82d56013Sjoerg Value *Derived = Relocate->getDerivedPtr();
888*82d56013Sjoerg SDValue SD = getValue(Derived);
889*82d56013Sjoerg if (!LowerAsVReg.count(SD))
890*82d56013Sjoerg continue;
891*82d56013Sjoerg
892*82d56013Sjoerg // Handle multiple gc.relocates of the same input efficiently.
893*82d56013Sjoerg if (VirtRegs.count(SD))
894*82d56013Sjoerg continue;
895*82d56013Sjoerg
896*82d56013Sjoerg SDValue Relocated = SDValue(StatepointMCNode, LowerAsVReg[SD]);
897*82d56013Sjoerg
898*82d56013Sjoerg auto *RetTy = Relocate->getType();
899*82d56013Sjoerg Register Reg = FuncInfo.CreateRegs(RetTy);
900*82d56013Sjoerg RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
901*82d56013Sjoerg DAG.getDataLayout(), Reg, RetTy, None);
902*82d56013Sjoerg SDValue Chain = DAG.getRoot();
903*82d56013Sjoerg RFV.getCopyToRegs(Relocated, DAG, getCurSDLoc(), Chain, nullptr);
904*82d56013Sjoerg PendingExports.push_back(Chain);
905*82d56013Sjoerg
906*82d56013Sjoerg VirtRegs[SD] = Reg;
907*82d56013Sjoerg }
908*82d56013Sjoerg
909*82d56013Sjoerg // Record for later use how each relocation was lowered. This is needed to
910*82d56013Sjoerg // allow later gc.relocates to mirror the lowering chosen.
911*82d56013Sjoerg const Instruction *StatepointInstr = SI.StatepointInstr;
912*82d56013Sjoerg auto &RelocationMap = FuncInfo.StatepointRelocationMaps[StatepointInstr];
913*82d56013Sjoerg for (const GCRelocateInst *Relocate : SI.GCRelocates) {
914*82d56013Sjoerg const Value *V = Relocate->getDerivedPtr();
915*82d56013Sjoerg SDValue SDV = getValue(V);
916*82d56013Sjoerg SDValue Loc = StatepointLowering.getLocation(SDV);
917*82d56013Sjoerg
918*82d56013Sjoerg RecordType Record;
919*82d56013Sjoerg if (LowerAsVReg.count(SDV)) {
920*82d56013Sjoerg Record.type = RecordType::VReg;
921*82d56013Sjoerg assert(VirtRegs.count(SDV));
922*82d56013Sjoerg Record.payload.Reg = VirtRegs[SDV];
923*82d56013Sjoerg } else if (Loc.getNode()) {
924*82d56013Sjoerg Record.type = RecordType::Spill;
925*82d56013Sjoerg Record.payload.FI = cast<FrameIndexSDNode>(Loc)->getIndex();
926*82d56013Sjoerg } else {
927*82d56013Sjoerg Record.type = RecordType::NoRelocate;
928*82d56013Sjoerg // If we didn't relocate a value, we'll essentialy end up inserting an
929*82d56013Sjoerg // additional use of the original value when lowering the gc.relocate.
930*82d56013Sjoerg // We need to make sure the value is available at the new use, which
931*82d56013Sjoerg // might be in another block.
932*82d56013Sjoerg if (Relocate->getParent() != StatepointInstr->getParent())
933*82d56013Sjoerg ExportFromCurrentBlock(V);
934*82d56013Sjoerg }
935*82d56013Sjoerg RelocationMap[V] = Record;
936*82d56013Sjoerg }
937*82d56013Sjoerg
938*82d56013Sjoerg
939*82d56013Sjoerg
9407330f729Sjoerg SDNode *SinkNode = StatepointMCNode;
9417330f729Sjoerg
9427330f729Sjoerg // Build the GC_TRANSITION_END node if necessary.
9437330f729Sjoerg //
9447330f729Sjoerg // See the comment above regarding GC_TRANSITION_START for the layout of
9457330f729Sjoerg // the operands to the GC_TRANSITION_END node.
9467330f729Sjoerg if (IsGCTransition) {
9477330f729Sjoerg SmallVector<SDValue, 8> TEOps;
9487330f729Sjoerg
9497330f729Sjoerg // Add chain
950*82d56013Sjoerg TEOps.push_back(SDValue(StatepointMCNode, NumResults - 2));
9517330f729Sjoerg
9527330f729Sjoerg // Add GC transition arguments
9537330f729Sjoerg for (const Value *V : SI.GCTransitionArgs) {
9547330f729Sjoerg TEOps.push_back(getValue(V));
9557330f729Sjoerg if (V->getType()->isPointerTy())
9567330f729Sjoerg TEOps.push_back(DAG.getSrcValue(V));
9577330f729Sjoerg }
9587330f729Sjoerg
9597330f729Sjoerg // Add glue
960*82d56013Sjoerg TEOps.push_back(SDValue(StatepointMCNode, NumResults - 1));
9617330f729Sjoerg
9627330f729Sjoerg SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9637330f729Sjoerg
9647330f729Sjoerg SDValue GCTransitionStart =
9657330f729Sjoerg DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
9667330f729Sjoerg
9677330f729Sjoerg SinkNode = GCTransitionStart.getNode();
9687330f729Sjoerg }
9697330f729Sjoerg
9707330f729Sjoerg // Replace original call
971*82d56013Sjoerg // Call: ch,glue = CALL ...
972*82d56013Sjoerg // Statepoint: [gc relocates],ch,glue = STATEPOINT ...
973*82d56013Sjoerg unsigned NumSinkValues = SinkNode->getNumValues();
974*82d56013Sjoerg SDValue StatepointValues[2] = {SDValue(SinkNode, NumSinkValues - 2),
975*82d56013Sjoerg SDValue(SinkNode, NumSinkValues - 1)};
976*82d56013Sjoerg DAG.ReplaceAllUsesWith(CallNode, StatepointValues);
9777330f729Sjoerg // Remove original call node
9787330f729Sjoerg DAG.DeleteNode(CallNode);
9797330f729Sjoerg
980*82d56013Sjoerg // Since we always emit CopyToRegs (even for local relocates), we must
981*82d56013Sjoerg // update root, so that they are emitted before any local uses.
982*82d56013Sjoerg (void)getControlRoot();
9837330f729Sjoerg
9847330f729Sjoerg // TODO: A better future implementation would be to emit a single variable
9857330f729Sjoerg // argument, variable return value STATEPOINT node here and then hookup the
9867330f729Sjoerg // return value of each gc.relocate to the respective output of the
9877330f729Sjoerg // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
9887330f729Sjoerg // to actually be possible today.
9897330f729Sjoerg
9907330f729Sjoerg return ReturnVal;
9917330f729Sjoerg }
9927330f729Sjoerg
9937330f729Sjoerg void
LowerStatepoint(const GCStatepointInst & I,const BasicBlock * EHPadBB)994*82d56013Sjoerg SelectionDAGBuilder::LowerStatepoint(const GCStatepointInst &I,
9957330f729Sjoerg const BasicBlock *EHPadBB /*= nullptr*/) {
996*82d56013Sjoerg assert(I.getCallingConv() != CallingConv::AnyReg &&
9977330f729Sjoerg "anyregcc is not supported on statepoints!");
9987330f729Sjoerg
9997330f729Sjoerg #ifndef NDEBUG
10007330f729Sjoerg // Check that the associated GCStrategy expects to encounter statepoints.
10017330f729Sjoerg assert(GFI->getStrategy().useStatepoints() &&
10027330f729Sjoerg "GCStrategy does not expect to encounter statepoints");
10037330f729Sjoerg #endif
10047330f729Sjoerg
10057330f729Sjoerg SDValue ActualCallee;
1006*82d56013Sjoerg SDValue Callee = getValue(I.getActualCalledOperand());
10077330f729Sjoerg
1008*82d56013Sjoerg if (I.getNumPatchBytes() > 0) {
10097330f729Sjoerg // If we've been asked to emit a nop sequence instead of a call instruction
10107330f729Sjoerg // for this statepoint then don't lower the call target, but use a constant
1011*82d56013Sjoerg // `undef` instead. Not lowering the call target lets statepoint clients
1012*82d56013Sjoerg // get away without providing a physical address for the symbolic call
1013*82d56013Sjoerg // target at link time.
1014*82d56013Sjoerg ActualCallee = DAG.getUNDEF(Callee.getValueType());
10157330f729Sjoerg } else {
1016*82d56013Sjoerg ActualCallee = Callee;
10177330f729Sjoerg }
10187330f729Sjoerg
10197330f729Sjoerg StatepointLoweringInfo SI(DAG);
1020*82d56013Sjoerg populateCallLoweringInfo(SI.CLI, &I, GCStatepointInst::CallArgsBeginPos,
1021*82d56013Sjoerg I.getNumCallArgs(), ActualCallee,
1022*82d56013Sjoerg I.getActualReturnType(), false /* IsPatchPoint */);
10237330f729Sjoerg
1024*82d56013Sjoerg // There may be duplication in the gc.relocate list; such as two copies of
1025*82d56013Sjoerg // each relocation on normal and exceptional path for an invoke. We only
1026*82d56013Sjoerg // need to spill once and record one copy in the stackmap, but we need to
1027*82d56013Sjoerg // reload once per gc.relocate. (Dedupping gc.relocates is trickier and best
1028*82d56013Sjoerg // handled as a CSE problem elsewhere.)
1029*82d56013Sjoerg // TODO: There a couple of major stackmap size optimizations we could do
1030*82d56013Sjoerg // here if we wished.
1031*82d56013Sjoerg // 1) If we've encountered a derived pair {B, D}, we don't need to actually
1032*82d56013Sjoerg // record {B,B} if it's seen later.
1033*82d56013Sjoerg // 2) Due to rematerialization, actual derived pointers are somewhat rare;
1034*82d56013Sjoerg // given that, we could change the format to record base pointer relocations
1035*82d56013Sjoerg // separately with half the space. This would require a format rev and a
1036*82d56013Sjoerg // fairly major rework of the STATEPOINT node though.
1037*82d56013Sjoerg SmallSet<SDValue, 8> Seen;
1038*82d56013Sjoerg for (const GCRelocateInst *Relocate : I.getGCRelocates()) {
10397330f729Sjoerg SI.GCRelocates.push_back(Relocate);
1040*82d56013Sjoerg
1041*82d56013Sjoerg SDValue DerivedSD = getValue(Relocate->getDerivedPtr());
1042*82d56013Sjoerg if (Seen.insert(DerivedSD).second) {
10437330f729Sjoerg SI.Bases.push_back(Relocate->getBasePtr());
10447330f729Sjoerg SI.Ptrs.push_back(Relocate->getDerivedPtr());
10457330f729Sjoerg }
1046*82d56013Sjoerg }
10477330f729Sjoerg
1048*82d56013Sjoerg // If we find a deopt value which isn't explicitly added, we need to
1049*82d56013Sjoerg // ensure it gets lowered such that gc cycles occurring before the
1050*82d56013Sjoerg // deoptimization event during the lifetime of the call don't invalidate
1051*82d56013Sjoerg // the pointer we're deopting with. Note that we assume that all
1052*82d56013Sjoerg // pointers passed to deopt are base pointers; relaxing that assumption
1053*82d56013Sjoerg // would require relatively large changes to how we represent relocations.
1054*82d56013Sjoerg for (Value *V : I.deopt_operands()) {
1055*82d56013Sjoerg if (!isGCValue(V, *this))
1056*82d56013Sjoerg continue;
1057*82d56013Sjoerg if (Seen.insert(getValue(V)).second) {
1058*82d56013Sjoerg SI.Bases.push_back(V);
1059*82d56013Sjoerg SI.Ptrs.push_back(V);
1060*82d56013Sjoerg }
1061*82d56013Sjoerg }
1062*82d56013Sjoerg
1063*82d56013Sjoerg SI.GCArgs = ArrayRef<const Use>(I.gc_args_begin(), I.gc_args_end());
1064*82d56013Sjoerg SI.StatepointInstr = &I;
1065*82d56013Sjoerg SI.ID = I.getID();
1066*82d56013Sjoerg
1067*82d56013Sjoerg SI.DeoptState = ArrayRef<const Use>(I.deopt_begin(), I.deopt_end());
1068*82d56013Sjoerg SI.GCTransitionArgs = ArrayRef<const Use>(I.gc_transition_args_begin(),
1069*82d56013Sjoerg I.gc_transition_args_end());
1070*82d56013Sjoerg
1071*82d56013Sjoerg SI.StatepointFlags = I.getFlags();
1072*82d56013Sjoerg SI.NumPatchBytes = I.getNumPatchBytes();
10737330f729Sjoerg SI.EHPadBB = EHPadBB;
10747330f729Sjoerg
10757330f729Sjoerg SDValue ReturnValue = LowerAsSTATEPOINT(SI);
10767330f729Sjoerg
10777330f729Sjoerg // Export the result value if needed
1078*82d56013Sjoerg const std::pair<bool, bool> GCResultLocality = I.getGCResultLocality();
1079*82d56013Sjoerg Type *RetTy = I.getActualReturnType();
1080*82d56013Sjoerg
1081*82d56013Sjoerg if (RetTy->isVoidTy() ||
1082*82d56013Sjoerg (!GCResultLocality.first && !GCResultLocality.second)) {
1083*82d56013Sjoerg // The return value is not needed, just generate a poison value.
1084*82d56013Sjoerg setValue(&I, DAG.getIntPtrConstant(-1, getCurSDLoc()));
1085*82d56013Sjoerg return;
1086*82d56013Sjoerg }
1087*82d56013Sjoerg
1088*82d56013Sjoerg if (GCResultLocality.first) {
1089*82d56013Sjoerg // Result value will be used in a same basic block. Don't export it or
1090*82d56013Sjoerg // perform any explicit register copies. The gc_result will simply grab
1091*82d56013Sjoerg // this value.
1092*82d56013Sjoerg setValue(&I, ReturnValue);
1093*82d56013Sjoerg }
1094*82d56013Sjoerg
1095*82d56013Sjoerg if (!GCResultLocality.second)
1096*82d56013Sjoerg return;
1097*82d56013Sjoerg // Result value will be used in a different basic block so we need to export
1098*82d56013Sjoerg // it now. Default exporting mechanism will not work here because statepoint
1099*82d56013Sjoerg // call has a different type than the actual call. It means that by default
1100*82d56013Sjoerg // llvm will create export register of the wrong type (always i32 in our
1101*82d56013Sjoerg // case). So instead we need to create export register with correct type
1102*82d56013Sjoerg // manually.
11037330f729Sjoerg // TODO: To eliminate this problem we can remove gc.result intrinsics
11047330f729Sjoerg // completely and make statepoint call to return a tuple.
11057330f729Sjoerg unsigned Reg = FuncInfo.CreateRegs(RetTy);
11067330f729Sjoerg RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
11077330f729Sjoerg DAG.getDataLayout(), Reg, RetTy,
1108*82d56013Sjoerg I.getCallingConv());
11097330f729Sjoerg SDValue Chain = DAG.getEntryNode();
11107330f729Sjoerg
11117330f729Sjoerg RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
11127330f729Sjoerg PendingExports.push_back(Chain);
1113*82d56013Sjoerg FuncInfo.ValueMap[&I] = Reg;
11147330f729Sjoerg }
11157330f729Sjoerg
LowerCallSiteWithDeoptBundleImpl(const CallBase * Call,SDValue Callee,const BasicBlock * EHPadBB,bool VarArgDisallowed,bool ForceVoidReturnTy)11167330f729Sjoerg void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
11177330f729Sjoerg const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
11187330f729Sjoerg bool VarArgDisallowed, bool ForceVoidReturnTy) {
11197330f729Sjoerg StatepointLoweringInfo SI(DAG);
11207330f729Sjoerg unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
11217330f729Sjoerg populateCallLoweringInfo(
11227330f729Sjoerg SI.CLI, Call, ArgBeginIndex, Call->getNumArgOperands(), Callee,
11237330f729Sjoerg ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
11247330f729Sjoerg false);
11257330f729Sjoerg if (!VarArgDisallowed)
11267330f729Sjoerg SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
11277330f729Sjoerg
11287330f729Sjoerg auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
11297330f729Sjoerg
11307330f729Sjoerg unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
11317330f729Sjoerg
11327330f729Sjoerg auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
11337330f729Sjoerg SI.ID = SD.StatepointID.getValueOr(DefaultID);
11347330f729Sjoerg SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
11357330f729Sjoerg
11367330f729Sjoerg SI.DeoptState =
11377330f729Sjoerg ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
11387330f729Sjoerg SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
11397330f729Sjoerg SI.EHPadBB = EHPadBB;
11407330f729Sjoerg
11417330f729Sjoerg // NB! The GC arguments are deliberately left empty.
11427330f729Sjoerg
11437330f729Sjoerg if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
11447330f729Sjoerg ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
11457330f729Sjoerg setValue(Call, ReturnVal);
11467330f729Sjoerg }
11477330f729Sjoerg }
11487330f729Sjoerg
LowerCallSiteWithDeoptBundle(const CallBase * Call,SDValue Callee,const BasicBlock * EHPadBB)11497330f729Sjoerg void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
11507330f729Sjoerg const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
11517330f729Sjoerg LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
11527330f729Sjoerg /* VarArgDisallowed = */ false,
11537330f729Sjoerg /* ForceVoidReturnTy = */ false);
11547330f729Sjoerg }
11557330f729Sjoerg
visitGCResult(const GCResultInst & CI)11567330f729Sjoerg void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
11577330f729Sjoerg // The result value of the gc_result is simply the result of the actual
11587330f729Sjoerg // call. We've already emitted this, so just grab the value.
1159*82d56013Sjoerg const GCStatepointInst *SI = CI.getStatepoint();
11607330f729Sjoerg
1161*82d56013Sjoerg if (SI->getParent() == CI.getParent()) {
1162*82d56013Sjoerg setValue(&CI, getValue(SI));
1163*82d56013Sjoerg return;
1164*82d56013Sjoerg }
11657330f729Sjoerg // Statepoint is in different basic block so we should have stored call
11667330f729Sjoerg // result in a virtual register.
11677330f729Sjoerg // We can not use default getValue() functionality to copy value from this
11687330f729Sjoerg // register because statepoint and actual call return types can be
11697330f729Sjoerg // different, and getValue() will use CopyFromReg of the wrong type,
11707330f729Sjoerg // which is always i32 in our case.
1171*82d56013Sjoerg Type *RetTy = SI->getActualReturnType();
1172*82d56013Sjoerg SDValue CopyFromReg = getCopyFromRegs(SI, RetTy);
11737330f729Sjoerg
11747330f729Sjoerg assert(CopyFromReg.getNode());
11757330f729Sjoerg setValue(&CI, CopyFromReg);
11767330f729Sjoerg }
11777330f729Sjoerg
visitGCRelocate(const GCRelocateInst & Relocate)11787330f729Sjoerg void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
11797330f729Sjoerg #ifndef NDEBUG
11807330f729Sjoerg // Consistency check
11817330f729Sjoerg // We skip this check for relocates not in the same basic block as their
11827330f729Sjoerg // statepoint. It would be too expensive to preserve validation info through
11837330f729Sjoerg // different basic blocks.
11847330f729Sjoerg if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
11857330f729Sjoerg StatepointLowering.relocCallVisited(Relocate);
11867330f729Sjoerg
11877330f729Sjoerg auto *Ty = Relocate.getType()->getScalarType();
11887330f729Sjoerg if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
11897330f729Sjoerg assert(*IsManaged && "Non gc managed pointer relocated!");
11907330f729Sjoerg #endif
11917330f729Sjoerg
11927330f729Sjoerg const Value *DerivedPtr = Relocate.getDerivedPtr();
1193*82d56013Sjoerg auto &RelocationMap =
1194*82d56013Sjoerg FuncInfo.StatepointRelocationMaps[Relocate.getStatepoint()];
1195*82d56013Sjoerg auto SlotIt = RelocationMap.find(DerivedPtr);
1196*82d56013Sjoerg assert(SlotIt != RelocationMap.end() && "Relocating not lowered gc value");
1197*82d56013Sjoerg const RecordType &Record = SlotIt->second;
11987330f729Sjoerg
1199*82d56013Sjoerg // If relocation was done via virtual register..
1200*82d56013Sjoerg if (Record.type == RecordType::VReg) {
1201*82d56013Sjoerg Register InReg = Record.payload.Reg;
1202*82d56013Sjoerg RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1203*82d56013Sjoerg DAG.getDataLayout(), InReg, Relocate.getType(),
1204*82d56013Sjoerg None); // This is not an ABI copy.
1205*82d56013Sjoerg // We generate copy to/from regs even for local uses, hence we must
1206*82d56013Sjoerg // chain with current root to ensure proper ordering of copies w.r.t.
1207*82d56013Sjoerg // statepoint.
1208*82d56013Sjoerg SDValue Chain = DAG.getRoot();
1209*82d56013Sjoerg SDValue Relocation = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
1210*82d56013Sjoerg Chain, nullptr, nullptr);
1211*82d56013Sjoerg setValue(&Relocate, Relocation);
12127330f729Sjoerg return;
12137330f729Sjoerg }
12147330f729Sjoerg
1215*82d56013Sjoerg if (Record.type == RecordType::Spill) {
1216*82d56013Sjoerg unsigned Index = Record.payload.FI;
12177330f729Sjoerg SDValue SpillSlot = DAG.getTargetFrameIndex(Index, getFrameIndexTy());
12187330f729Sjoerg
1219*82d56013Sjoerg // All the reloads are independent and are reading memory only modified by
1220*82d56013Sjoerg // statepoints (i.e. no other aliasing stores); informing SelectionDAG of
1221*82d56013Sjoerg // this this let's CSE kick in for free and allows reordering of
1222*82d56013Sjoerg // instructions if possible. The lowering for statepoint sets the root,
1223*82d56013Sjoerg // so this is ordering all reloads with the either
1224*82d56013Sjoerg // a) the statepoint node itself, or
1225*82d56013Sjoerg // b) the entry of the current block for an invoke statepoint.
1226*82d56013Sjoerg const SDValue Chain = DAG.getRoot(); // != Builder.getRoot()
12277330f729Sjoerg
12287330f729Sjoerg auto &MF = DAG.getMachineFunction();
12297330f729Sjoerg auto &MFI = MF.getFrameInfo();
12307330f729Sjoerg auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
1231*82d56013Sjoerg auto *LoadMMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
12327330f729Sjoerg MFI.getObjectSize(Index),
1233*82d56013Sjoerg MFI.getObjectAlign(Index));
12347330f729Sjoerg
12357330f729Sjoerg auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
12367330f729Sjoerg Relocate.getType());
12377330f729Sjoerg
1238*82d56013Sjoerg SDValue SpillLoad =
1239*82d56013Sjoerg DAG.getLoad(LoadVT, getCurSDLoc(), Chain, SpillSlot, LoadMMO);
1240*82d56013Sjoerg PendingLoads.push_back(SpillLoad.getValue(1));
12417330f729Sjoerg
12427330f729Sjoerg assert(SpillLoad.getNode());
12437330f729Sjoerg setValue(&Relocate, SpillLoad);
1244*82d56013Sjoerg return;
1245*82d56013Sjoerg }
1246*82d56013Sjoerg
1247*82d56013Sjoerg assert(Record.type == RecordType::NoRelocate);
1248*82d56013Sjoerg SDValue SD = getValue(DerivedPtr);
1249*82d56013Sjoerg
1250*82d56013Sjoerg if (SD.isUndef() && SD.getValueType().getSizeInBits() <= 64) {
1251*82d56013Sjoerg // Lowering relocate(undef) as arbitrary constant. Current constant value
1252*82d56013Sjoerg // is chosen such that it's unlikely to be a valid pointer.
1253*82d56013Sjoerg setValue(&Relocate, DAG.getTargetConstant(0xFEFEFEFE, SDLoc(SD), MVT::i64));
1254*82d56013Sjoerg return;
1255*82d56013Sjoerg }
1256*82d56013Sjoerg
1257*82d56013Sjoerg // We didn't need to spill these special cases (constants and allocas).
1258*82d56013Sjoerg // See the handling in spillIncomingValueForStatepoint for detail.
1259*82d56013Sjoerg setValue(&Relocate, SD);
12607330f729Sjoerg }
12617330f729Sjoerg
LowerDeoptimizeCall(const CallInst * CI)12627330f729Sjoerg void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
12637330f729Sjoerg const auto &TLI = DAG.getTargetLoweringInfo();
12647330f729Sjoerg SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
12657330f729Sjoerg TLI.getPointerTy(DAG.getDataLayout()));
12667330f729Sjoerg
12677330f729Sjoerg // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
12687330f729Sjoerg // call. We also do not lower the return value to any virtual register, and
12697330f729Sjoerg // change the immediately following return to a trap instruction.
12707330f729Sjoerg LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
12717330f729Sjoerg /* VarArgDisallowed = */ true,
12727330f729Sjoerg /* ForceVoidReturnTy = */ true);
12737330f729Sjoerg }
12747330f729Sjoerg
LowerDeoptimizingReturn()12757330f729Sjoerg void SelectionDAGBuilder::LowerDeoptimizingReturn() {
12767330f729Sjoerg // We do not lower the return value from llvm.deoptimize to any virtual
12777330f729Sjoerg // register, and change the immediately following return to a trap
12787330f729Sjoerg // instruction.
12797330f729Sjoerg if (DAG.getTarget().Options.TrapUnreachable)
12807330f729Sjoerg DAG.setRoot(
12817330f729Sjoerg DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
12827330f729Sjoerg }
1283