xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- StatepointLowering.cpp - SDAGBuilder's statepoint code -------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file includes support code use by SelectionDAGBuilder when lowering a
100b57cec5SDimitry Andric // statepoint sequence in SelectionDAG IR.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "StatepointLowering.h"
150b57cec5SDimitry Andric #include "SelectionDAGBuilder.h"
160b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
170b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
1881ad6265SDimitry Andric #include "llvm/ADT/SetVector.h"
1981ad6265SDimitry Andric #include "llvm/ADT/SmallBitVector.h"
205ffd83dbSDimitry Andric #include "llvm/ADT/SmallSet.h"
2181ad6265SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/FunctionLoweringInfo.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/GCMetadata.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/ISDOpcodes.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
29*0fca6ea1SDimitry Andric #include "llvm/CodeGen/RuntimeLibcallUtil.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAG.h"
3181ad6265SDimitry Andric #include "llvm/CodeGen/SelectionDAGNodes.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/StackMaps.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
35*0fca6ea1SDimitry Andric #include "llvm/CodeGenTypes/MachineValueType.h"
360b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
370b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
38fe6060f1SDimitry Andric #include "llvm/IR/GCStrategy.h"
390b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
400b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
410b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
420b57cec5SDimitry Andric #include "llvm/IR/Statepoint.h"
430b57cec5SDimitry Andric #include "llvm/IR/Type.h"
440b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
455ffd83dbSDimitry Andric #include "llvm/Support/CommandLine.h"
460b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
470b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
480b57cec5SDimitry Andric #include <cassert>
490b57cec5SDimitry Andric #include <cstddef>
500b57cec5SDimitry Andric #include <cstdint>
510b57cec5SDimitry Andric #include <iterator>
520b57cec5SDimitry Andric #include <tuple>
530b57cec5SDimitry Andric #include <utility>
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric using namespace llvm;
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric #define DEBUG_TYPE "statepoint-lowering"
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric STATISTIC(NumSlotsAllocatedForStatepoints,
600b57cec5SDimitry Andric           "Number of stack slots allocated for statepoints");
610b57cec5SDimitry Andric STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
620b57cec5SDimitry Andric STATISTIC(StatepointMaxSlotsRequired,
630b57cec5SDimitry Andric           "Maximum number of stack slots required for a singe statepoint");
640b57cec5SDimitry Andric 
655f757f3fSDimitry Andric static cl::opt<bool> UseRegistersForDeoptValues(
665ffd83dbSDimitry Andric     "use-registers-for-deopt-values", cl::Hidden, cl::init(false),
675ffd83dbSDimitry Andric     cl::desc("Allow using registers for non pointer deopt args"));
685ffd83dbSDimitry Andric 
695f757f3fSDimitry Andric static cl::opt<bool> UseRegistersForGCPointersInLandingPad(
70e8d8bef9SDimitry Andric     "use-registers-for-gc-values-in-landing-pad", cl::Hidden, cl::init(false),
71e8d8bef9SDimitry Andric     cl::desc("Allow using registers for gc pointer in landing pad"));
72e8d8bef9SDimitry Andric 
735f757f3fSDimitry Andric static cl::opt<unsigned> MaxRegistersForGCPointers(
74e8d8bef9SDimitry Andric     "max-registers-for-gc-values", cl::Hidden, cl::init(0),
75e8d8bef9SDimitry Andric     cl::desc("Max number of VRegs allowed to pass GC pointer meta args in"));
76e8d8bef9SDimitry Andric 
77e8d8bef9SDimitry Andric typedef FunctionLoweringInfo::StatepointRelocationRecord RecordType;
78e8d8bef9SDimitry Andric 
790b57cec5SDimitry Andric static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
800b57cec5SDimitry Andric                                  SelectionDAGBuilder &Builder, uint64_t Value) {
810b57cec5SDimitry Andric   SDLoc L = Builder.getCurSDLoc();
820b57cec5SDimitry Andric   Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
830b57cec5SDimitry Andric                                               MVT::i64));
840b57cec5SDimitry Andric   Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
850b57cec5SDimitry Andric }
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
880b57cec5SDimitry Andric   // Consistency check
890b57cec5SDimitry Andric   assert(PendingGCRelocateCalls.empty() &&
900b57cec5SDimitry Andric          "Trying to visit statepoint before finished processing previous one");
910b57cec5SDimitry Andric   Locations.clear();
920b57cec5SDimitry Andric   NextSlotToAllocate = 0;
930b57cec5SDimitry Andric   // Need to resize this on each safepoint - we need the two to stay in sync and
940b57cec5SDimitry Andric   // the clear patterns of a SelectionDAGBuilder have no relation to
950b57cec5SDimitry Andric   // FunctionLoweringInfo.  Also need to ensure used bits get cleared.
960b57cec5SDimitry Andric   AllocatedStackSlots.clear();
970b57cec5SDimitry Andric   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
980b57cec5SDimitry Andric }
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric void StatepointLoweringState::clear() {
1010b57cec5SDimitry Andric   Locations.clear();
1020b57cec5SDimitry Andric   AllocatedStackSlots.clear();
1030b57cec5SDimitry Andric   assert(PendingGCRelocateCalls.empty() &&
1040b57cec5SDimitry Andric          "cleared before statepoint sequence completed");
1050b57cec5SDimitry Andric }
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric SDValue
1080b57cec5SDimitry Andric StatepointLoweringState::allocateStackSlot(EVT ValueType,
1090b57cec5SDimitry Andric                                            SelectionDAGBuilder &Builder) {
1100b57cec5SDimitry Andric   NumSlotsAllocatedForStatepoints++;
1110b57cec5SDimitry Andric   MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric   unsigned SpillSize = ValueType.getStoreSize();
114fe6060f1SDimitry Andric   assert((SpillSize * 8) ==
115fe6060f1SDimitry Andric              (-8u & (7 + ValueType.getSizeInBits())) && // Round up modulo 8.
116fe6060f1SDimitry Andric          "Size not in bytes?");
1170b57cec5SDimitry Andric 
1180b57cec5SDimitry Andric   // First look for a previously created stack slot which is not in
1190b57cec5SDimitry Andric   // use (accounting for the fact arbitrary slots may already be
1200b57cec5SDimitry Andric   // reserved), or to create a new stack slot and use it.
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric   const size_t NumSlots = AllocatedStackSlots.size();
1230b57cec5SDimitry Andric   assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   assert(AllocatedStackSlots.size() ==
1260b57cec5SDimitry Andric          Builder.FuncInfo.StatepointStackSlots.size() &&
1270b57cec5SDimitry Andric          "Broken invariant");
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric   for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
1300b57cec5SDimitry Andric     if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
1310b57cec5SDimitry Andric       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
1320b57cec5SDimitry Andric       if (MFI.getObjectSize(FI) == SpillSize) {
1330b57cec5SDimitry Andric         AllocatedStackSlots.set(NextSlotToAllocate);
1340b57cec5SDimitry Andric         // TODO: Is ValueType the right thing to use here?
1350b57cec5SDimitry Andric         return Builder.DAG.getFrameIndex(FI, ValueType);
1360b57cec5SDimitry Andric       }
1370b57cec5SDimitry Andric     }
1380b57cec5SDimitry Andric   }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric   // Couldn't find a free slot, so create a new one:
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
1430b57cec5SDimitry Andric   const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1440b57cec5SDimitry Andric   MFI.markAsStatepointSpillSlotObjectIndex(FI);
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric   Builder.FuncInfo.StatepointStackSlots.push_back(FI);
1470b57cec5SDimitry Andric   AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
1480b57cec5SDimitry Andric   assert(AllocatedStackSlots.size() ==
1490b57cec5SDimitry Andric          Builder.FuncInfo.StatepointStackSlots.size() &&
1500b57cec5SDimitry Andric          "Broken invariant");
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   StatepointMaxSlotsRequired.updateMax(
1530b57cec5SDimitry Andric       Builder.FuncInfo.StatepointStackSlots.size());
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric   return SpillSlot;
1560b57cec5SDimitry Andric }
1570b57cec5SDimitry Andric 
1580b57cec5SDimitry Andric /// Utility function for reservePreviousStackSlotForValue. Tries to find
1590b57cec5SDimitry Andric /// stack slot index to which we have spilled value for previous statepoints.
1600b57cec5SDimitry Andric /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
161bdd1243dSDimitry Andric static std::optional<int> findPreviousSpillSlot(const Value *Val,
1620b57cec5SDimitry Andric                                                 SelectionDAGBuilder &Builder,
1630b57cec5SDimitry Andric                                                 int LookUpDepth) {
1640b57cec5SDimitry Andric   // Can not look any further - give up now
1650b57cec5SDimitry Andric   if (LookUpDepth <= 0)
166bdd1243dSDimitry Andric     return std::nullopt;
1670b57cec5SDimitry Andric 
1680b57cec5SDimitry Andric   // Spill location is known for gc relocates
1690b57cec5SDimitry Andric   if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
170fcaf7f86SDimitry Andric     const Value *Statepoint = Relocate->getStatepoint();
171fcaf7f86SDimitry Andric     assert((isa<GCStatepointInst>(Statepoint) || isa<UndefValue>(Statepoint)) &&
172fcaf7f86SDimitry Andric            "GetStatepoint must return one of two types");
173fcaf7f86SDimitry Andric     if (isa<UndefValue>(Statepoint))
174bdd1243dSDimitry Andric       return std::nullopt;
175fcaf7f86SDimitry Andric 
176fcaf7f86SDimitry Andric     const auto &RelocationMap = Builder.FuncInfo.StatepointRelocationMaps
177fcaf7f86SDimitry Andric                                     [cast<GCStatepointInst>(Statepoint)];
1780b57cec5SDimitry Andric 
17981ad6265SDimitry Andric     auto It = RelocationMap.find(Relocate);
180e8d8bef9SDimitry Andric     if (It == RelocationMap.end())
181bdd1243dSDimitry Andric       return std::nullopt;
1820b57cec5SDimitry Andric 
183e8d8bef9SDimitry Andric     auto &Record = It->second;
184e8d8bef9SDimitry Andric     if (Record.type != RecordType::Spill)
185bdd1243dSDimitry Andric       return std::nullopt;
186e8d8bef9SDimitry Andric 
187e8d8bef9SDimitry Andric     return Record.payload.FI;
1880b57cec5SDimitry Andric   }
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   // Look through bitcast instructions.
1910b57cec5SDimitry Andric   if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
1920b57cec5SDimitry Andric     return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   // Look through phi nodes
1950b57cec5SDimitry Andric   // All incoming values should have same known stack slot, otherwise result
1960b57cec5SDimitry Andric   // is unknown.
1970b57cec5SDimitry Andric   if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
198bdd1243dSDimitry Andric     std::optional<int> MergedResult;
1990b57cec5SDimitry Andric 
200fcaf7f86SDimitry Andric     for (const auto &IncomingValue : Phi->incoming_values()) {
201bdd1243dSDimitry Andric       std::optional<int> SpillSlot =
2020b57cec5SDimitry Andric           findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
20381ad6265SDimitry Andric       if (!SpillSlot)
204bdd1243dSDimitry Andric         return std::nullopt;
2050b57cec5SDimitry Andric 
20681ad6265SDimitry Andric       if (MergedResult && *MergedResult != *SpillSlot)
207bdd1243dSDimitry Andric         return std::nullopt;
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric       MergedResult = SpillSlot;
2100b57cec5SDimitry Andric     }
2110b57cec5SDimitry Andric     return MergedResult;
2120b57cec5SDimitry Andric   }
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric   // TODO: We can do better for PHI nodes. In cases like this:
2150b57cec5SDimitry Andric   //   ptr = phi(relocated_pointer, not_relocated_pointer)
2160b57cec5SDimitry Andric   //   statepoint(ptr)
2170b57cec5SDimitry Andric   // We will return that stack slot for ptr is unknown. And later we might
2180b57cec5SDimitry Andric   // assign different stack slots for ptr and relocated_pointer. This limits
2190b57cec5SDimitry Andric   // llvm's ability to remove redundant stores.
2200b57cec5SDimitry Andric   // Unfortunately it's hard to accomplish in current infrastructure.
2210b57cec5SDimitry Andric   // We use this function to eliminate spill store completely, while
2220b57cec5SDimitry Andric   // in example we still need to emit store, but instead of any location
2230b57cec5SDimitry Andric   // we need to use special "preferred" location.
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric   // TODO: handle simple updates.  If a value is modified and the original
2260b57cec5SDimitry Andric   // value is no longer live, it would be nice to put the modified value in the
2270b57cec5SDimitry Andric   // same slot.  This allows folding of the memory accesses for some
2280b57cec5SDimitry Andric   // instructions types (like an increment).
2290b57cec5SDimitry Andric   //   statepoint (i)
2300b57cec5SDimitry Andric   //   i1 = i+1
2310b57cec5SDimitry Andric   //   statepoint (i1)
2320b57cec5SDimitry Andric   // However we need to be careful for cases like this:
2330b57cec5SDimitry Andric   //   statepoint(i)
2340b57cec5SDimitry Andric   //   i1 = i+1
2350b57cec5SDimitry Andric   //   statepoint(i, i1)
2360b57cec5SDimitry Andric   // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
2370b57cec5SDimitry Andric   // put handling of simple modifications in this function like it's done
2380b57cec5SDimitry Andric   // for bitcasts we might end up reserving i's slot for 'i+1' because order in
2390b57cec5SDimitry Andric   // which we visit values is unspecified.
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   // Don't know any information about this instruction
242bdd1243dSDimitry Andric   return std::nullopt;
2430b57cec5SDimitry Andric }
2440b57cec5SDimitry Andric 
2455ffd83dbSDimitry Andric /// Return true if-and-only-if the given SDValue can be lowered as either a
2465ffd83dbSDimitry Andric /// constant argument or a stack reference.  The key point is that the value
2475ffd83dbSDimitry Andric /// doesn't need to be spilled or tracked as a vreg use.
2485ffd83dbSDimitry Andric static bool willLowerDirectly(SDValue Incoming) {
2495ffd83dbSDimitry Andric   // We are making an unchecked assumption that the frame size <= 2^16 as that
2505ffd83dbSDimitry Andric   // is the largest offset which can be encoded in the stackmap format.
2515ffd83dbSDimitry Andric   if (isa<FrameIndexSDNode>(Incoming))
2525ffd83dbSDimitry Andric     return true;
2535ffd83dbSDimitry Andric 
2545ffd83dbSDimitry Andric   // The largest constant describeable in the StackMap format is 64 bits.
2555ffd83dbSDimitry Andric   // Potential Optimization:  Constants values are sign extended by consumer,
2565ffd83dbSDimitry Andric   // and thus there are many constants of static type > 64 bits whose value
2575ffd83dbSDimitry Andric   // happens to be sext(Con64) and could thus be lowered directly.
2585ffd83dbSDimitry Andric   if (Incoming.getValueType().getSizeInBits() > 64)
2595ffd83dbSDimitry Andric     return false;
2605ffd83dbSDimitry Andric 
26106c3fb27SDimitry Andric   return isIntOrFPConstant(Incoming) || Incoming.isUndef();
2625ffd83dbSDimitry Andric }
2635ffd83dbSDimitry Andric 
2640b57cec5SDimitry Andric /// Try to find existing copies of the incoming values in stack slots used for
2650b57cec5SDimitry Andric /// statepoint spilling.  If we can find a spill slot for the incoming value,
2660b57cec5SDimitry Andric /// mark that slot as allocated, and reuse the same slot for this safepoint.
2670b57cec5SDimitry Andric /// This helps to avoid series of loads and stores that only serve to reshuffle
2680b57cec5SDimitry Andric /// values on the stack between calls.
2690b57cec5SDimitry Andric static void reservePreviousStackSlotForValue(const Value *IncomingValue,
2700b57cec5SDimitry Andric                                              SelectionDAGBuilder &Builder) {
2710b57cec5SDimitry Andric   SDValue Incoming = Builder.getValue(IncomingValue);
2720b57cec5SDimitry Andric 
2735ffd83dbSDimitry Andric   // If we won't spill this, we don't need to check for previously allocated
2745ffd83dbSDimitry Andric   // stack slots.
2755ffd83dbSDimitry Andric   if (willLowerDirectly(Incoming))
2760b57cec5SDimitry Andric     return;
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric   SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
2790b57cec5SDimitry Andric   if (OldLocation.getNode())
2800b57cec5SDimitry Andric     // Duplicates in input
2810b57cec5SDimitry Andric     return;
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   const int LookUpDepth = 6;
284bdd1243dSDimitry Andric   std::optional<int> Index =
2850b57cec5SDimitry Andric       findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
28681ad6265SDimitry Andric   if (!Index)
2870b57cec5SDimitry Andric     return;
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric   const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   auto SlotIt = find(StatepointSlots, *Index);
2920b57cec5SDimitry Andric   assert(SlotIt != StatepointSlots.end() &&
2930b57cec5SDimitry Andric          "Value spilled to the unknown stack slot");
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric   // This is one of our dedicated lowering slots
2960b57cec5SDimitry Andric   const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
2970b57cec5SDimitry Andric   if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
2980b57cec5SDimitry Andric     // stack slot already assigned to someone else, can't use it!
2990b57cec5SDimitry Andric     // TODO: currently we reserve space for gc arguments after doing
3000b57cec5SDimitry Andric     // normal allocation for deopt arguments.  We should reserve for
3010b57cec5SDimitry Andric     // _all_ deopt and gc arguments, then start allocating.  This
3020b57cec5SDimitry Andric     // will prevent some moves being inserted when vm state changes,
3030b57cec5SDimitry Andric     // but gc state doesn't between two calls.
3040b57cec5SDimitry Andric     return;
3050b57cec5SDimitry Andric   }
3060b57cec5SDimitry Andric   // Reserve this stack slot
3070b57cec5SDimitry Andric   Builder.StatepointLowering.reserveStackSlot(Offset);
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric   // Cache this slot so we find it when going through the normal
3100b57cec5SDimitry Andric   // assignment loop.
3110b57cec5SDimitry Andric   SDValue Loc =
3120b57cec5SDimitry Andric       Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
3130b57cec5SDimitry Andric   Builder.StatepointLowering.setLocation(Incoming, Loc);
3140b57cec5SDimitry Andric }
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric /// Extract call from statepoint, lower it and return pointer to the
3170b57cec5SDimitry Andric /// call node. Also update NodeMap so that getValue(statepoint) will
3180b57cec5SDimitry Andric /// reference lowered call result
3190b57cec5SDimitry Andric static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
3200b57cec5SDimitry Andric     SelectionDAGBuilder::StatepointLoweringInfo &SI,
321bdd1243dSDimitry Andric     SelectionDAGBuilder &Builder) {
3220b57cec5SDimitry Andric   SDValue ReturnValue, CallEndVal;
3230b57cec5SDimitry Andric   std::tie(ReturnValue, CallEndVal) =
3240b57cec5SDimitry Andric       Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
3250b57cec5SDimitry Andric   SDNode *CallEnd = CallEndVal.getNode();
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   // Get a call instruction from the call sequence chain.  Tail calls are not
3280b57cec5SDimitry Andric   // allowed.  The following code is essentially reverse engineering X86's
3290b57cec5SDimitry Andric   // LowerCallTo.
3300b57cec5SDimitry Andric   //
3310b57cec5SDimitry Andric   // We are expecting DAG to have the following form:
3320b57cec5SDimitry Andric   //
3330b57cec5SDimitry Andric   // ch = eh_label (only in case of invoke statepoint)
3340b57cec5SDimitry Andric   //   ch, glue = callseq_start ch
3350b57cec5SDimitry Andric   //   ch, glue = X86::Call ch, glue
3360b57cec5SDimitry Andric   //   ch, glue = callseq_end ch, glue
3370b57cec5SDimitry Andric   //   get_return_value ch, glue
3380b57cec5SDimitry Andric   //
3390b57cec5SDimitry Andric   // get_return_value can either be a sequence of CopyFromReg instructions
3400b57cec5SDimitry Andric   // to grab the return value from the return register(s), or it can be a LOAD
3410b57cec5SDimitry Andric   // to load a value returned by reference via a stack slot.
3420b57cec5SDimitry Andric 
343*0fca6ea1SDimitry Andric   if (CallEnd->getOpcode() == ISD::EH_LABEL)
344*0fca6ea1SDimitry Andric     CallEnd = CallEnd->getOperand(0).getNode();
345*0fca6ea1SDimitry Andric 
3460b57cec5SDimitry Andric   bool HasDef = !SI.CLI.RetTy->isVoidTy();
3470b57cec5SDimitry Andric   if (HasDef) {
3480b57cec5SDimitry Andric     if (CallEnd->getOpcode() == ISD::LOAD)
3490b57cec5SDimitry Andric       CallEnd = CallEnd->getOperand(0).getNode();
3500b57cec5SDimitry Andric     else
3510b57cec5SDimitry Andric       while (CallEnd->getOpcode() == ISD::CopyFromReg)
3520b57cec5SDimitry Andric         CallEnd = CallEnd->getOperand(0).getNode();
3530b57cec5SDimitry Andric   }
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
3560b57cec5SDimitry Andric   return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
3570b57cec5SDimitry Andric }
3580b57cec5SDimitry Andric 
3590b57cec5SDimitry Andric static MachineMemOperand* getMachineMemOperand(MachineFunction &MF,
3600b57cec5SDimitry Andric                                                FrameIndexSDNode &FI) {
3610b57cec5SDimitry Andric   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
3620b57cec5SDimitry Andric   auto MMOFlags = MachineMemOperand::MOStore |
3630b57cec5SDimitry Andric     MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
3640b57cec5SDimitry Andric   auto &MFI = MF.getFrameInfo();
3650b57cec5SDimitry Andric   return MF.getMachineMemOperand(PtrInfo, MMOFlags,
3660b57cec5SDimitry Andric                                  MFI.getObjectSize(FI.getIndex()),
3675ffd83dbSDimitry Andric                                  MFI.getObjectAlign(FI.getIndex()));
3680b57cec5SDimitry Andric }
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric /// Spill a value incoming to the statepoint. It might be either part of
3710b57cec5SDimitry Andric /// vmstate
3720b57cec5SDimitry Andric /// or gcstate. In both cases unconditionally spill it on the stack unless it
3730b57cec5SDimitry Andric /// is a null constant. Return pair with first element being frame index
3740b57cec5SDimitry Andric /// containing saved value and second element with outgoing chain from the
3750b57cec5SDimitry Andric /// emitted store
3760b57cec5SDimitry Andric static std::tuple<SDValue, SDValue, MachineMemOperand*>
3770b57cec5SDimitry Andric spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
3780b57cec5SDimitry Andric                              SelectionDAGBuilder &Builder) {
3790b57cec5SDimitry Andric   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
3800b57cec5SDimitry Andric   MachineMemOperand* MMO = nullptr;
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric   // Emit new store if we didn't do it for this ptr before
3830b57cec5SDimitry Andric   if (!Loc.getNode()) {
3840b57cec5SDimitry Andric     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
3850b57cec5SDimitry Andric                                                        Builder);
3860b57cec5SDimitry Andric     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
3870b57cec5SDimitry Andric     // We use TargetFrameIndex so that isel will not select it into LEA
3880b57cec5SDimitry Andric     Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric     // Right now we always allocate spill slots that are of the same
3910b57cec5SDimitry Andric     // size as the value we're about to spill (the size of spillee can
3920b57cec5SDimitry Andric     // vary since we spill vectors of pointers too).  At some point we
3930b57cec5SDimitry Andric     // can consider allowing spills of smaller values to larger slots
3940b57cec5SDimitry Andric     // (i.e. change the '==' in the assert below to a '>=').
3950b57cec5SDimitry Andric     MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
396480093f4SDimitry Andric     assert((MFI.getObjectSize(Index) * 8) ==
397fe6060f1SDimitry Andric                (-8 & (7 + // Round up modulo 8.
398fe6060f1SDimitry Andric                       (int64_t)Incoming.getValueSizeInBits())) &&
3990b57cec5SDimitry Andric            "Bad spill:  stack slot does not match!");
4000b57cec5SDimitry Andric 
4018bcb0991SDimitry Andric     // Note: Using the alignment of the spill slot (rather than the abi or
4028bcb0991SDimitry Andric     // preferred alignment) is required for correctness when dealing with spill
4038bcb0991SDimitry Andric     // slots with preferred alignments larger than frame alignment..
4040b57cec5SDimitry Andric     auto &MF = Builder.DAG.getMachineFunction();
4050b57cec5SDimitry Andric     auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
4065ffd83dbSDimitry Andric     auto *StoreMMO = MF.getMachineMemOperand(
4075ffd83dbSDimitry Andric         PtrInfo, MachineMemOperand::MOStore, MFI.getObjectSize(Index),
4085ffd83dbSDimitry Andric         MFI.getObjectAlign(Index));
4090b57cec5SDimitry Andric     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
4108bcb0991SDimitry Andric                                  StoreMMO);
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric     MMO = getMachineMemOperand(MF, *cast<FrameIndexSDNode>(Loc));
4130b57cec5SDimitry Andric 
4140b57cec5SDimitry Andric     Builder.StatepointLowering.setLocation(Incoming, Loc);
4150b57cec5SDimitry Andric   }
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric   assert(Loc.getNode());
4180b57cec5SDimitry Andric   return std::make_tuple(Loc, Chain, MMO);
4190b57cec5SDimitry Andric }
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric /// Lower a single value incoming to a statepoint node.  This value can be
4220b57cec5SDimitry Andric /// either a deopt value or a gc value, the handling is the same.  We special
4230b57cec5SDimitry Andric /// case constants and allocas, then fall back to spilling if required.
4245ffd83dbSDimitry Andric static void
4255ffd83dbSDimitry Andric lowerIncomingStatepointValue(SDValue Incoming, bool RequireSpillSlot,
4260b57cec5SDimitry Andric                              SmallVectorImpl<SDValue> &Ops,
4270b57cec5SDimitry Andric                              SmallVectorImpl<MachineMemOperand *> &MemRefs,
4280b57cec5SDimitry Andric                              SelectionDAGBuilder &Builder) {
4290b57cec5SDimitry Andric 
4305ffd83dbSDimitry Andric   if (willLowerDirectly(Incoming)) {
4315ffd83dbSDimitry Andric     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
4320b57cec5SDimitry Andric       // This handles allocas as arguments to the statepoint (this is only
4330b57cec5SDimitry Andric       // really meaningful for a deopt value.  For GC, we'd be trying to
4340b57cec5SDimitry Andric       // relocate the address of the alloca itself?)
4350b57cec5SDimitry Andric       assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
4360b57cec5SDimitry Andric              "Incoming value is a frame index!");
4370b57cec5SDimitry Andric       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
4380b57cec5SDimitry Andric                                                     Builder.getFrameIndexTy()));
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric       auto &MF = Builder.DAG.getMachineFunction();
4410b57cec5SDimitry Andric       auto *MMO = getMachineMemOperand(MF, *FI);
4420b57cec5SDimitry Andric       MemRefs.push_back(MMO);
4435ffd83dbSDimitry Andric       return;
4445ffd83dbSDimitry Andric     }
4450b57cec5SDimitry Andric 
4465ffd83dbSDimitry Andric     assert(Incoming.getValueType().getSizeInBits() <= 64);
4475ffd83dbSDimitry Andric 
4485ffd83dbSDimitry Andric     if (Incoming.isUndef()) {
4495ffd83dbSDimitry Andric       // Put an easily recognized constant that's unlikely to be a valid
4505ffd83dbSDimitry Andric       // value so that uses of undef by the consumer of the stackmap is
4515ffd83dbSDimitry Andric       // easily recognized. This is legal since the compiler is always
4525ffd83dbSDimitry Andric       // allowed to chose an arbitrary value for undef.
4535ffd83dbSDimitry Andric       pushStackMapConstant(Ops, Builder, 0xFEFEFEFE);
4545ffd83dbSDimitry Andric       return;
4555ffd83dbSDimitry Andric     }
4565ffd83dbSDimitry Andric 
4575ffd83dbSDimitry Andric     // If the original value was a constant, make sure it gets recorded as
4585ffd83dbSDimitry Andric     // such in the stackmap.  This is required so that the consumer can
4595ffd83dbSDimitry Andric     // parse any internal format to the deopt state.  It also handles null
4605ffd83dbSDimitry Andric     // pointers and other constant pointers in GC states.
4615ffd83dbSDimitry Andric     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
4625ffd83dbSDimitry Andric       pushStackMapConstant(Ops, Builder, C->getSExtValue());
4635ffd83dbSDimitry Andric       return;
4645ffd83dbSDimitry Andric     } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Incoming)) {
4655ffd83dbSDimitry Andric       pushStackMapConstant(Ops, Builder,
4665ffd83dbSDimitry Andric                            C->getValueAPF().bitcastToAPInt().getZExtValue());
4675ffd83dbSDimitry Andric       return;
4685ffd83dbSDimitry Andric     }
4695ffd83dbSDimitry Andric 
4705ffd83dbSDimitry Andric     llvm_unreachable("unhandled direct lowering case");
4715ffd83dbSDimitry Andric   }
4725ffd83dbSDimitry Andric 
4735ffd83dbSDimitry Andric 
4745ffd83dbSDimitry Andric 
4755ffd83dbSDimitry Andric   if (!RequireSpillSlot) {
4760b57cec5SDimitry Andric     // If this value is live in (not live-on-return, or live-through), we can
4770b57cec5SDimitry Andric     // treat it the same way patchpoint treats it's "live in" values.  We'll
4780b57cec5SDimitry Andric     // end up folding some of these into stack references, but they'll be
4790b57cec5SDimitry Andric     // handled by the register allocator.  Note that we do not have the notion
4800b57cec5SDimitry Andric     // of a late use so these values might be placed in registers which are
4815ffd83dbSDimitry Andric     // clobbered by the call.  This is fine for live-in. For live-through
4825ffd83dbSDimitry Andric     // fix-up pass should be executed to force spilling of such registers.
4830b57cec5SDimitry Andric     Ops.push_back(Incoming);
4840b57cec5SDimitry Andric   } else {
4855ffd83dbSDimitry Andric     // Otherwise, locate a spill slot and explicitly spill it so it can be
4865ffd83dbSDimitry Andric     // found by the runtime later.  Note: We know all of these spills are
4875ffd83dbSDimitry Andric     // independent, but don't bother to exploit that chain wise.  DAGCombine
4885ffd83dbSDimitry Andric     // will happily do so as needed, so doing it here would be a small compile
4895ffd83dbSDimitry Andric     // time win at most.
4905ffd83dbSDimitry Andric     SDValue Chain = Builder.getRoot();
4910b57cec5SDimitry Andric     auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
4920b57cec5SDimitry Andric     Ops.push_back(std::get<0>(Res));
4930b57cec5SDimitry Andric     if (auto *MMO = std::get<2>(Res))
4940b57cec5SDimitry Andric       MemRefs.push_back(MMO);
49506c3fb27SDimitry Andric     Chain = std::get<1>(Res);
4965ffd83dbSDimitry Andric     Builder.DAG.setRoot(Chain);
4970b57cec5SDimitry Andric   }
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric }
5000b57cec5SDimitry Andric 
501fe6060f1SDimitry Andric /// Return true if value V represents the GC value. The behavior is conservative
502fe6060f1SDimitry Andric /// in case it is not sure that value is not GC the function returns true.
503fe6060f1SDimitry Andric static bool isGCValue(const Value *V, SelectionDAGBuilder &Builder) {
504fe6060f1SDimitry Andric   auto *Ty = V->getType();
505fe6060f1SDimitry Andric   if (!Ty->isPtrOrPtrVectorTy())
506fe6060f1SDimitry Andric     return false;
507fe6060f1SDimitry Andric   if (auto *GFI = Builder.GFI)
508fe6060f1SDimitry Andric     if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
509fe6060f1SDimitry Andric       return *IsManaged;
510fe6060f1SDimitry Andric   return true; // conservative
511fe6060f1SDimitry Andric }
512fe6060f1SDimitry Andric 
5130b57cec5SDimitry Andric /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
5140b57cec5SDimitry Andric /// lowering is described in lowerIncomingStatepointValue.  This function is
5150b57cec5SDimitry Andric /// responsible for lowering everything in the right position and playing some
5160b57cec5SDimitry Andric /// tricks to avoid redundant stack manipulation where possible.  On
5170b57cec5SDimitry Andric /// completion, 'Ops' will contain ready to use operands for machine code
5180b57cec5SDimitry Andric /// statepoint. The chain nodes will have already been created and the DAG root
5190b57cec5SDimitry Andric /// will be set to the last value spilled (if any were).
5200b57cec5SDimitry Andric static void
5210b57cec5SDimitry Andric lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
522e8d8bef9SDimitry Andric                         SmallVectorImpl<MachineMemOperand *> &MemRefs,
523e8d8bef9SDimitry Andric                         SmallVectorImpl<SDValue> &GCPtrs,
524e8d8bef9SDimitry Andric                         DenseMap<SDValue, int> &LowerAsVReg,
525e8d8bef9SDimitry Andric                         SelectionDAGBuilder::StatepointLoweringInfo &SI,
5260b57cec5SDimitry Andric                         SelectionDAGBuilder &Builder) {
5270b57cec5SDimitry Andric   // Lower the deopt and gc arguments for this statepoint.  Layout will be:
5280b57cec5SDimitry Andric   // deopt argument length, deopt arguments.., gc arguments...
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric   // Figure out what lowering strategy we're going to use for each part
5315f757f3fSDimitry Andric   // Note: It is conservatively correct to lower both "live-in" and "live-out"
5320b57cec5SDimitry Andric   // as "live-through". A "live-through" variable is one which is "live-in",
5330b57cec5SDimitry Andric   // "live-out", and live throughout the lifetime of the call (i.e. we can find
5340b57cec5SDimitry Andric   // it from any PC within the transitive callee of the statepoint).  In
5350b57cec5SDimitry Andric   // particular, if the callee spills callee preserved registers we may not
5360b57cec5SDimitry Andric   // be able to find a value placed in that register during the call.  This is
5370b57cec5SDimitry Andric   // fine for live-out, but not for live-through.  If we were willing to make
5380b57cec5SDimitry Andric   // assumptions about the code generator producing the callee, we could
5390b57cec5SDimitry Andric   // potentially allow live-through values in callee saved registers.
5400b57cec5SDimitry Andric   const bool LiveInDeopt =
5410b57cec5SDimitry Andric     SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
5420b57cec5SDimitry Andric 
543e8d8bef9SDimitry Andric   // Decide which deriver pointers will go on VRegs
544e8d8bef9SDimitry Andric   unsigned MaxVRegPtrs = MaxRegistersForGCPointers.getValue();
545e8d8bef9SDimitry Andric 
546e8d8bef9SDimitry Andric   // Pointers used on exceptional path of invoke statepoint.
547e8d8bef9SDimitry Andric   // We cannot assing them to VRegs.
548e8d8bef9SDimitry Andric   SmallSet<SDValue, 8> LPadPointers;
549e8d8bef9SDimitry Andric   if (!UseRegistersForGCPointersInLandingPad)
550fcaf7f86SDimitry Andric     if (const auto *StInvoke =
551fcaf7f86SDimitry Andric             dyn_cast_or_null<InvokeInst>(SI.StatepointInstr)) {
552e8d8bef9SDimitry Andric       LandingPadInst *LPI = StInvoke->getLandingPadInst();
553fcaf7f86SDimitry Andric       for (const auto *Relocate : SI.GCRelocates)
554e8d8bef9SDimitry Andric         if (Relocate->getOperand(0) == LPI) {
555e8d8bef9SDimitry Andric           LPadPointers.insert(Builder.getValue(Relocate->getBasePtr()));
556e8d8bef9SDimitry Andric           LPadPointers.insert(Builder.getValue(Relocate->getDerivedPtr()));
557e8d8bef9SDimitry Andric         }
558e8d8bef9SDimitry Andric     }
559e8d8bef9SDimitry Andric 
560e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Deciding how to lower GC Pointers:\n");
561e8d8bef9SDimitry Andric 
562e8d8bef9SDimitry Andric   // List of unique lowered GC Pointer values.
563e8d8bef9SDimitry Andric   SmallSetVector<SDValue, 16> LoweredGCPtrs;
564e8d8bef9SDimitry Andric   // Map lowered GC Pointer value to the index in above vector
565e8d8bef9SDimitry Andric   DenseMap<SDValue, unsigned> GCPtrIndexMap;
566e8d8bef9SDimitry Andric 
567e8d8bef9SDimitry Andric   unsigned CurNumVRegs = 0;
568e8d8bef9SDimitry Andric 
569e8d8bef9SDimitry Andric   auto canPassGCPtrOnVReg = [&](SDValue SD) {
570e8d8bef9SDimitry Andric     if (SD.getValueType().isVector())
571e8d8bef9SDimitry Andric       return false;
572e8d8bef9SDimitry Andric     if (LPadPointers.count(SD))
573e8d8bef9SDimitry Andric       return false;
574e8d8bef9SDimitry Andric     return !willLowerDirectly(SD);
575e8d8bef9SDimitry Andric   };
576e8d8bef9SDimitry Andric 
577e8d8bef9SDimitry Andric   auto processGCPtr = [&](const Value *V) {
578e8d8bef9SDimitry Andric     SDValue PtrSD = Builder.getValue(V);
579e8d8bef9SDimitry Andric     if (!LoweredGCPtrs.insert(PtrSD))
580e8d8bef9SDimitry Andric       return; // skip duplicates
581e8d8bef9SDimitry Andric     GCPtrIndexMap[PtrSD] = LoweredGCPtrs.size() - 1;
582e8d8bef9SDimitry Andric 
583e8d8bef9SDimitry Andric     assert(!LowerAsVReg.count(PtrSD) && "must not have been seen");
584e8d8bef9SDimitry Andric     if (LowerAsVReg.size() == MaxVRegPtrs)
585e8d8bef9SDimitry Andric       return;
586e8d8bef9SDimitry Andric     assert(V->getType()->isVectorTy() == PtrSD.getValueType().isVector() &&
587e8d8bef9SDimitry Andric            "IR and SD types disagree");
588e8d8bef9SDimitry Andric     if (!canPassGCPtrOnVReg(PtrSD)) {
589e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "direct/spill "; PtrSD.dump(&Builder.DAG));
590e8d8bef9SDimitry Andric       return;
591e8d8bef9SDimitry Andric     }
592e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "vreg "; PtrSD.dump(&Builder.DAG));
593e8d8bef9SDimitry Andric     LowerAsVReg[PtrSD] = CurNumVRegs++;
594e8d8bef9SDimitry Andric   };
595e8d8bef9SDimitry Andric 
596e8d8bef9SDimitry Andric   // Process derived pointers first to give them more chance to go on VReg.
597e8d8bef9SDimitry Andric   for (const Value *V : SI.Ptrs)
598e8d8bef9SDimitry Andric     processGCPtr(V);
599e8d8bef9SDimitry Andric   for (const Value *V : SI.Bases)
600e8d8bef9SDimitry Andric     processGCPtr(V);
601e8d8bef9SDimitry Andric 
602e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << LowerAsVReg.size() << " pointers will go in vregs\n");
603e8d8bef9SDimitry Andric 
6045ffd83dbSDimitry Andric   auto requireSpillSlot = [&](const Value *V) {
605fe6060f1SDimitry Andric     if (!Builder.DAG.getTargetLoweringInfo().isTypeLegal(
606fe6060f1SDimitry Andric              Builder.getValue(V).getValueType()))
607fe6060f1SDimitry Andric       return true;
608fe6060f1SDimitry Andric     if (isGCValue(V, Builder))
609e8d8bef9SDimitry Andric       return !LowerAsVReg.count(Builder.getValue(V));
610e8d8bef9SDimitry Andric     return !(LiveInDeopt || UseRegistersForDeoptValues);
6110b57cec5SDimitry Andric   };
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   // Before we actually start lowering (and allocating spill slots for values),
6140b57cec5SDimitry Andric   // reserve any stack slots which we judge to be profitable to reuse for a
6150b57cec5SDimitry Andric   // particular value.  This is purely an optimization over the code below and
6160b57cec5SDimitry Andric   // doesn't change semantics at all.  It is important for performance that we
6170b57cec5SDimitry Andric   // reserve slots for both deopt and gc values before lowering either.
6180b57cec5SDimitry Andric   for (const Value *V : SI.DeoptState) {
6195ffd83dbSDimitry Andric     if (requireSpillSlot(V))
6200b57cec5SDimitry Andric       reservePreviousStackSlotForValue(V, Builder);
6210b57cec5SDimitry Andric   }
622e8d8bef9SDimitry Andric 
623e8d8bef9SDimitry Andric   for (const Value *V : SI.Ptrs) {
624e8d8bef9SDimitry Andric     SDValue SDV = Builder.getValue(V);
625e8d8bef9SDimitry Andric     if (!LowerAsVReg.count(SDV))
626e8d8bef9SDimitry Andric       reservePreviousStackSlotForValue(V, Builder);
627e8d8bef9SDimitry Andric   }
628e8d8bef9SDimitry Andric 
629e8d8bef9SDimitry Andric   for (const Value *V : SI.Bases) {
630e8d8bef9SDimitry Andric     SDValue SDV = Builder.getValue(V);
631e8d8bef9SDimitry Andric     if (!LowerAsVReg.count(SDV))
632e8d8bef9SDimitry Andric       reservePreviousStackSlotForValue(V, Builder);
6330b57cec5SDimitry Andric   }
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric   // First, prefix the list with the number of unique values to be
6360b57cec5SDimitry Andric   // lowered.  Note that this is the number of *Values* not the
6370b57cec5SDimitry Andric   // number of SDValues required to lower them.
6380b57cec5SDimitry Andric   const int NumVMSArgs = SI.DeoptState.size();
6390b57cec5SDimitry Andric   pushStackMapConstant(Ops, Builder, NumVMSArgs);
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   // The vm state arguments are lowered in an opaque manner.  We do not know
6420b57cec5SDimitry Andric   // what type of values are contained within.
643e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Lowering deopt state\n");
6440b57cec5SDimitry Andric   for (const Value *V : SI.DeoptState) {
6450b57cec5SDimitry Andric     SDValue Incoming;
6460b57cec5SDimitry Andric     // If this is a function argument at a static frame index, generate it as
6470b57cec5SDimitry Andric     // the frame index.
6480b57cec5SDimitry Andric     if (const Argument *Arg = dyn_cast<Argument>(V)) {
6490b57cec5SDimitry Andric       int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
6500b57cec5SDimitry Andric       if (FI != INT_MAX)
6510b57cec5SDimitry Andric         Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy());
6520b57cec5SDimitry Andric     }
6530b57cec5SDimitry Andric     if (!Incoming.getNode())
6540b57cec5SDimitry Andric       Incoming = Builder.getValue(V);
655e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Value " << *V
656e8d8bef9SDimitry Andric                       << " requireSpillSlot = " << requireSpillSlot(V) << "\n");
6575ffd83dbSDimitry Andric     lowerIncomingStatepointValue(Incoming, requireSpillSlot(V), Ops, MemRefs,
6585ffd83dbSDimitry Andric                                  Builder);
6590b57cec5SDimitry Andric   }
6600b57cec5SDimitry Andric 
661e8d8bef9SDimitry Andric   // Finally, go ahead and lower all the gc arguments.
662e8d8bef9SDimitry Andric   pushStackMapConstant(Ops, Builder, LoweredGCPtrs.size());
663e8d8bef9SDimitry Andric   for (SDValue SDV : LoweredGCPtrs)
664e8d8bef9SDimitry Andric     lowerIncomingStatepointValue(SDV, !LowerAsVReg.count(SDV), Ops, MemRefs,
6655ffd83dbSDimitry Andric                                  Builder);
6660b57cec5SDimitry Andric 
667e8d8bef9SDimitry Andric   // Copy to out vector. LoweredGCPtrs will be empty after this point.
668e8d8bef9SDimitry Andric   GCPtrs = LoweredGCPtrs.takeVector();
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   // If there are any explicit spill slots passed to the statepoint, record
6710b57cec5SDimitry Andric   // them, but otherwise do not do anything special.  These are user provided
6720b57cec5SDimitry Andric   // allocas and give control over placement to the consumer.  In this case,
6730b57cec5SDimitry Andric   // it is the contents of the slot which may get updated, not the pointer to
6740b57cec5SDimitry Andric   // the alloca
675e8d8bef9SDimitry Andric   SmallVector<SDValue, 4> Allocas;
6760b57cec5SDimitry Andric   for (Value *V : SI.GCArgs) {
6770b57cec5SDimitry Andric     SDValue Incoming = Builder.getValue(V);
6780b57cec5SDimitry Andric     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
6790b57cec5SDimitry Andric       // This handles allocas as arguments to the statepoint
6800b57cec5SDimitry Andric       assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
6810b57cec5SDimitry Andric              "Incoming value is a frame index!");
682e8d8bef9SDimitry Andric       Allocas.push_back(Builder.DAG.getTargetFrameIndex(
683e8d8bef9SDimitry Andric           FI->getIndex(), Builder.getFrameIndexTy()));
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric       auto &MF = Builder.DAG.getMachineFunction();
6860b57cec5SDimitry Andric       auto *MMO = getMachineMemOperand(MF, *FI);
6870b57cec5SDimitry Andric       MemRefs.push_back(MMO);
6880b57cec5SDimitry Andric     }
6890b57cec5SDimitry Andric   }
690e8d8bef9SDimitry Andric   pushStackMapConstant(Ops, Builder, Allocas.size());
691e8d8bef9SDimitry Andric   Ops.append(Allocas.begin(), Allocas.end());
6920b57cec5SDimitry Andric 
693e8d8bef9SDimitry Andric   // Now construct GC base/derived map;
694e8d8bef9SDimitry Andric   pushStackMapConstant(Ops, Builder, SI.Ptrs.size());
695e8d8bef9SDimitry Andric   SDLoc L = Builder.getCurSDLoc();
696e8d8bef9SDimitry Andric   for (unsigned i = 0; i < SI.Ptrs.size(); ++i) {
697e8d8bef9SDimitry Andric     SDValue Base = Builder.getValue(SI.Bases[i]);
698e8d8bef9SDimitry Andric     assert(GCPtrIndexMap.count(Base) && "base not found in index map");
699e8d8bef9SDimitry Andric     Ops.push_back(
700e8d8bef9SDimitry Andric         Builder.DAG.getTargetConstant(GCPtrIndexMap[Base], L, MVT::i64));
701e8d8bef9SDimitry Andric     SDValue Derived = Builder.getValue(SI.Ptrs[i]);
702e8d8bef9SDimitry Andric     assert(GCPtrIndexMap.count(Derived) && "derived not found in index map");
703e8d8bef9SDimitry Andric     Ops.push_back(
704e8d8bef9SDimitry Andric         Builder.DAG.getTargetConstant(GCPtrIndexMap[Derived], L, MVT::i64));
7050b57cec5SDimitry Andric   }
7060b57cec5SDimitry Andric }
7070b57cec5SDimitry Andric 
7080b57cec5SDimitry Andric SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
7090b57cec5SDimitry Andric     SelectionDAGBuilder::StatepointLoweringInfo &SI) {
7100b57cec5SDimitry Andric   // The basic scheme here is that information about both the original call and
7110b57cec5SDimitry Andric   // the safepoint is encoded in the CallInst.  We create a temporary call and
7120b57cec5SDimitry Andric   // lower it, then reverse engineer the calling sequence.
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric   NumOfStatepoints++;
7150b57cec5SDimitry Andric   // Clear state
7160b57cec5SDimitry Andric   StatepointLowering.startNewStatepoint(*this);
717bdd1243dSDimitry Andric   assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");
718bdd1243dSDimitry Andric   assert((GFI || SI.Bases.empty()) &&
719bdd1243dSDimitry Andric          "No gc specified, so cannot relocate pointers!");
7200b57cec5SDimitry Andric 
7215f757f3fSDimitry Andric   LLVM_DEBUG(if (SI.StatepointInstr) dbgs()
7225f757f3fSDimitry Andric              << "Lowering statepoint " << *SI.StatepointInstr << "\n");
7230b57cec5SDimitry Andric #ifndef NDEBUG
724fcaf7f86SDimitry Andric   for (const auto *Reloc : SI.GCRelocates)
7250b57cec5SDimitry Andric     if (Reloc->getParent() == SI.StatepointInstr->getParent())
7260b57cec5SDimitry Andric       StatepointLowering.scheduleRelocCall(*Reloc);
7270b57cec5SDimitry Andric #endif
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric   // Lower statepoint vmstate and gcstate arguments
730e8d8bef9SDimitry Andric 
731e8d8bef9SDimitry Andric   // All lowered meta args.
7320b57cec5SDimitry Andric   SmallVector<SDValue, 10> LoweredMetaArgs;
733e8d8bef9SDimitry Andric   // Lowered GC pointers (subset of above).
734e8d8bef9SDimitry Andric   SmallVector<SDValue, 16> LoweredGCArgs;
7350b57cec5SDimitry Andric   SmallVector<MachineMemOperand*, 16> MemRefs;
736e8d8bef9SDimitry Andric   // Maps derived pointer SDValue to statepoint result of relocated pointer.
737e8d8bef9SDimitry Andric   DenseMap<SDValue, int> LowerAsVReg;
738e8d8bef9SDimitry Andric   lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, LoweredGCArgs, LowerAsVReg,
739e8d8bef9SDimitry Andric                           SI, *this);
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric   // Now that we've emitted the spills, we need to update the root so that the
7420b57cec5SDimitry Andric   // call sequence is ordered correctly.
7430b57cec5SDimitry Andric   SI.CLI.setChain(getRoot());
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   // Get call node, we will replace it later with statepoint
7460b57cec5SDimitry Andric   SDValue ReturnVal;
7470b57cec5SDimitry Andric   SDNode *CallNode;
748bdd1243dSDimitry Andric   std::tie(ReturnVal, CallNode) = lowerCallFromStatepointLoweringInfo(SI, *this);
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
7510b57cec5SDimitry Andric   // nodes with all the appropriate arguments and return values.
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7540b57cec5SDimitry Andric   SDValue Chain = CallNode->getOperand(0);
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric   SDValue Glue;
7570b57cec5SDimitry Andric   bool CallHasIncomingGlue = CallNode->getGluedNode();
7580b57cec5SDimitry Andric   if (CallHasIncomingGlue) {
7590b57cec5SDimitry Andric     // Glue is always last operand
7600b57cec5SDimitry Andric     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
7610b57cec5SDimitry Andric   }
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric   // Build the GC_TRANSITION_START node if necessary.
7640b57cec5SDimitry Andric   //
7650b57cec5SDimitry Andric   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
7660b57cec5SDimitry Andric   // order in which they appear in the call to the statepoint intrinsic. If
7670b57cec5SDimitry Andric   // any of the operands is a pointer-typed, that operand is immediately
7680b57cec5SDimitry Andric   // followed by a SRCVALUE for the pointer that may be used during lowering
7690b57cec5SDimitry Andric   // (e.g. to form MachinePointerInfo values for loads/stores).
7700b57cec5SDimitry Andric   const bool IsGCTransition =
7710b57cec5SDimitry Andric       (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
7720b57cec5SDimitry Andric       (uint64_t)StatepointFlags::GCTransition;
7730b57cec5SDimitry Andric   if (IsGCTransition) {
7740b57cec5SDimitry Andric     SmallVector<SDValue, 8> TSOps;
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric     // Add chain
7770b57cec5SDimitry Andric     TSOps.push_back(Chain);
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric     // Add GC transition arguments
7800b57cec5SDimitry Andric     for (const Value *V : SI.GCTransitionArgs) {
7810b57cec5SDimitry Andric       TSOps.push_back(getValue(V));
7820b57cec5SDimitry Andric       if (V->getType()->isPointerTy())
7830b57cec5SDimitry Andric         TSOps.push_back(DAG.getSrcValue(V));
7840b57cec5SDimitry Andric     }
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric     // Add glue if necessary
7870b57cec5SDimitry Andric     if (CallHasIncomingGlue)
7880b57cec5SDimitry Andric       TSOps.push_back(Glue);
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric     SDValue GCTransitionStart =
7930b57cec5SDimitry Andric         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
7940b57cec5SDimitry Andric 
7950b57cec5SDimitry Andric     Chain = GCTransitionStart.getValue(0);
7960b57cec5SDimitry Andric     Glue = GCTransitionStart.getValue(1);
7970b57cec5SDimitry Andric   }
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric   // TODO: Currently, all of these operands are being marked as read/write in
8000b57cec5SDimitry Andric   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
8010b57cec5SDimitry Andric   // and flags to be read-only.
8020b57cec5SDimitry Andric   SmallVector<SDValue, 40> Ops;
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric   // Add the <id> and <numBytes> constants.
8050b57cec5SDimitry Andric   Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
8060b57cec5SDimitry Andric   Ops.push_back(
8070b57cec5SDimitry Andric       DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric   // Calculate and push starting position of vmstate arguments
8100b57cec5SDimitry Andric   // Get number of arguments incoming directly into call node
8110b57cec5SDimitry Andric   unsigned NumCallRegArgs =
8120b57cec5SDimitry Andric       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
8130b57cec5SDimitry Andric   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric   // Add call target
8160b57cec5SDimitry Andric   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
8170b57cec5SDimitry Andric   Ops.push_back(CallTarget);
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   // Add call arguments
8200b57cec5SDimitry Andric   // Get position of register mask in the call
8210b57cec5SDimitry Andric   SDNode::op_iterator RegMaskIt;
8220b57cec5SDimitry Andric   if (CallHasIncomingGlue)
8230b57cec5SDimitry Andric     RegMaskIt = CallNode->op_end() - 2;
8240b57cec5SDimitry Andric   else
8250b57cec5SDimitry Andric     RegMaskIt = CallNode->op_end() - 1;
8260b57cec5SDimitry Andric   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   // Add a constant argument for the calling convention
8290b57cec5SDimitry Andric   pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   // Add a constant argument for the flags
8320b57cec5SDimitry Andric   uint64_t Flags = SI.StatepointFlags;
8330b57cec5SDimitry Andric   assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
8340b57cec5SDimitry Andric          "Unknown flag used");
8350b57cec5SDimitry Andric   pushStackMapConstant(Ops, *this, Flags);
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric   // Insert all vmstate and gcstate arguments
838e8d8bef9SDimitry Andric   llvm::append_range(Ops, LoweredMetaArgs);
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric   // Add register mask from call node
8410b57cec5SDimitry Andric   Ops.push_back(*RegMaskIt);
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric   // Add chain
8440b57cec5SDimitry Andric   Ops.push_back(Chain);
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   // Same for the glue, but we add it only if original call had it
8470b57cec5SDimitry Andric   if (Glue.getNode())
8480b57cec5SDimitry Andric     Ops.push_back(Glue);
8490b57cec5SDimitry Andric 
8500b57cec5SDimitry Andric   // Compute return values.  Provide a glue output since we consume one as
8510b57cec5SDimitry Andric   // input.  This allows someone else to chain off us as needed.
852e8d8bef9SDimitry Andric   SmallVector<EVT, 8> NodeTys;
853e8d8bef9SDimitry Andric   for (auto SD : LoweredGCArgs) {
854e8d8bef9SDimitry Andric     if (!LowerAsVReg.count(SD))
855e8d8bef9SDimitry Andric       continue;
856e8d8bef9SDimitry Andric     NodeTys.push_back(SD.getValueType());
857e8d8bef9SDimitry Andric   }
858e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Statepoint has " << NodeTys.size() << " results\n");
859e8d8bef9SDimitry Andric   assert(NodeTys.size() == LowerAsVReg.size() && "Inconsistent GC Ptr lowering");
860e8d8bef9SDimitry Andric   NodeTys.push_back(MVT::Other);
861e8d8bef9SDimitry Andric   NodeTys.push_back(MVT::Glue);
8620b57cec5SDimitry Andric 
863e8d8bef9SDimitry Andric   unsigned NumResults = NodeTys.size();
8640b57cec5SDimitry Andric   MachineSDNode *StatepointMCNode =
8650b57cec5SDimitry Andric     DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
8660b57cec5SDimitry Andric   DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
8670b57cec5SDimitry Andric 
86881ad6265SDimitry Andric   // For values lowered to tied-defs, create the virtual registers if used
86981ad6265SDimitry Andric   // in other blocks. For local gc.relocate record appropriate statepoint
87081ad6265SDimitry Andric   // result in StatepointLoweringState.
871e8d8bef9SDimitry Andric   DenseMap<SDValue, Register> VirtRegs;
872e8d8bef9SDimitry Andric   for (const auto *Relocate : SI.GCRelocates) {
873e8d8bef9SDimitry Andric     Value *Derived = Relocate->getDerivedPtr();
874e8d8bef9SDimitry Andric     SDValue SD = getValue(Derived);
875e8d8bef9SDimitry Andric     if (!LowerAsVReg.count(SD))
876e8d8bef9SDimitry Andric       continue;
877e8d8bef9SDimitry Andric 
87881ad6265SDimitry Andric     SDValue Relocated = SDValue(StatepointMCNode, LowerAsVReg[SD]);
87981ad6265SDimitry Andric 
88081ad6265SDimitry Andric     // Handle local relocate. Note that different relocates might
88181ad6265SDimitry Andric     // map to the same SDValue.
88281ad6265SDimitry Andric     if (SI.StatepointInstr->getParent() == Relocate->getParent()) {
88381ad6265SDimitry Andric       SDValue Res = StatepointLowering.getLocation(SD);
88481ad6265SDimitry Andric       if (Res)
88581ad6265SDimitry Andric         assert(Res == Relocated);
88681ad6265SDimitry Andric       else
88781ad6265SDimitry Andric         StatepointLowering.setLocation(SD, Relocated);
88881ad6265SDimitry Andric       continue;
88981ad6265SDimitry Andric     }
89081ad6265SDimitry Andric 
891e8d8bef9SDimitry Andric     // Handle multiple gc.relocates of the same input efficiently.
892e8d8bef9SDimitry Andric     if (VirtRegs.count(SD))
893e8d8bef9SDimitry Andric       continue;
894e8d8bef9SDimitry Andric 
895e8d8bef9SDimitry Andric     auto *RetTy = Relocate->getType();
896e8d8bef9SDimitry Andric     Register Reg = FuncInfo.CreateRegs(RetTy);
897e8d8bef9SDimitry Andric     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
898bdd1243dSDimitry Andric                      DAG.getDataLayout(), Reg, RetTy, std::nullopt);
899e8d8bef9SDimitry Andric     SDValue Chain = DAG.getRoot();
900e8d8bef9SDimitry Andric     RFV.getCopyToRegs(Relocated, DAG, getCurSDLoc(), Chain, nullptr);
901e8d8bef9SDimitry Andric     PendingExports.push_back(Chain);
902e8d8bef9SDimitry Andric 
903e8d8bef9SDimitry Andric     VirtRegs[SD] = Reg;
904e8d8bef9SDimitry Andric   }
905e8d8bef9SDimitry Andric 
906e8d8bef9SDimitry Andric   // Record for later use how each relocation was lowered.  This is needed to
907e8d8bef9SDimitry Andric   // allow later gc.relocates to mirror the lowering chosen.
908e8d8bef9SDimitry Andric   const Instruction *StatepointInstr = SI.StatepointInstr;
909e8d8bef9SDimitry Andric   auto &RelocationMap = FuncInfo.StatepointRelocationMaps[StatepointInstr];
910e8d8bef9SDimitry Andric   for (const GCRelocateInst *Relocate : SI.GCRelocates) {
911e8d8bef9SDimitry Andric     const Value *V = Relocate->getDerivedPtr();
912e8d8bef9SDimitry Andric     SDValue SDV = getValue(V);
913e8d8bef9SDimitry Andric     SDValue Loc = StatepointLowering.getLocation(SDV);
914e8d8bef9SDimitry Andric 
91581ad6265SDimitry Andric     bool IsLocal = (Relocate->getParent() == StatepointInstr->getParent());
91681ad6265SDimitry Andric 
917e8d8bef9SDimitry Andric     RecordType Record;
91881ad6265SDimitry Andric     if (IsLocal && LowerAsVReg.count(SDV)) {
91981ad6265SDimitry Andric       // Result is already stored in StatepointLowering
92081ad6265SDimitry Andric       Record.type = RecordType::SDValueNode;
92181ad6265SDimitry Andric     } else if (LowerAsVReg.count(SDV)) {
922e8d8bef9SDimitry Andric       Record.type = RecordType::VReg;
923e8d8bef9SDimitry Andric       assert(VirtRegs.count(SDV));
924e8d8bef9SDimitry Andric       Record.payload.Reg = VirtRegs[SDV];
925e8d8bef9SDimitry Andric     } else if (Loc.getNode()) {
926e8d8bef9SDimitry Andric       Record.type = RecordType::Spill;
927e8d8bef9SDimitry Andric       Record.payload.FI = cast<FrameIndexSDNode>(Loc)->getIndex();
928e8d8bef9SDimitry Andric     } else {
929e8d8bef9SDimitry Andric       Record.type = RecordType::NoRelocate;
930e8d8bef9SDimitry Andric       // If we didn't relocate a value, we'll essentialy end up inserting an
931e8d8bef9SDimitry Andric       // additional use of the original value when lowering the gc.relocate.
932e8d8bef9SDimitry Andric       // We need to make sure the value is available at the new use, which
933e8d8bef9SDimitry Andric       // might be in another block.
934e8d8bef9SDimitry Andric       if (Relocate->getParent() != StatepointInstr->getParent())
935e8d8bef9SDimitry Andric         ExportFromCurrentBlock(V);
936e8d8bef9SDimitry Andric     }
93781ad6265SDimitry Andric     RelocationMap[Relocate] = Record;
938e8d8bef9SDimitry Andric   }
939e8d8bef9SDimitry Andric 
940e8d8bef9SDimitry Andric 
941e8d8bef9SDimitry Andric 
9420b57cec5SDimitry Andric   SDNode *SinkNode = StatepointMCNode;
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric   // Build the GC_TRANSITION_END node if necessary.
9450b57cec5SDimitry Andric   //
9460b57cec5SDimitry Andric   // See the comment above regarding GC_TRANSITION_START for the layout of
9470b57cec5SDimitry Andric   // the operands to the GC_TRANSITION_END node.
9480b57cec5SDimitry Andric   if (IsGCTransition) {
9490b57cec5SDimitry Andric     SmallVector<SDValue, 8> TEOps;
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric     // Add chain
952e8d8bef9SDimitry Andric     TEOps.push_back(SDValue(StatepointMCNode, NumResults - 2));
9530b57cec5SDimitry Andric 
9540b57cec5SDimitry Andric     // Add GC transition arguments
9550b57cec5SDimitry Andric     for (const Value *V : SI.GCTransitionArgs) {
9560b57cec5SDimitry Andric       TEOps.push_back(getValue(V));
9570b57cec5SDimitry Andric       if (V->getType()->isPointerTy())
9580b57cec5SDimitry Andric         TEOps.push_back(DAG.getSrcValue(V));
9590b57cec5SDimitry Andric     }
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric     // Add glue
962e8d8bef9SDimitry Andric     TEOps.push_back(SDValue(StatepointMCNode, NumResults - 1));
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric     SDValue GCTransitionStart =
9670b57cec5SDimitry Andric         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric     SinkNode = GCTransitionStart.getNode();
9700b57cec5SDimitry Andric   }
9710b57cec5SDimitry Andric 
9720b57cec5SDimitry Andric   // Replace original call
973e8d8bef9SDimitry Andric   // Call: ch,glue = CALL ...
974e8d8bef9SDimitry Andric   // Statepoint: [gc relocates],ch,glue = STATEPOINT ...
975e8d8bef9SDimitry Andric   unsigned NumSinkValues = SinkNode->getNumValues();
976e8d8bef9SDimitry Andric   SDValue StatepointValues[2] = {SDValue(SinkNode, NumSinkValues - 2),
977e8d8bef9SDimitry Andric                                  SDValue(SinkNode, NumSinkValues - 1)};
978e8d8bef9SDimitry Andric   DAG.ReplaceAllUsesWith(CallNode, StatepointValues);
9790b57cec5SDimitry Andric   // Remove original call node
9800b57cec5SDimitry Andric   DAG.DeleteNode(CallNode);
9810b57cec5SDimitry Andric 
982e8d8bef9SDimitry Andric   // Since we always emit CopyToRegs (even for local relocates), we must
983e8d8bef9SDimitry Andric   // update root, so that they are emitted before any local uses.
984e8d8bef9SDimitry Andric   (void)getControlRoot();
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric   // TODO: A better future implementation would be to emit a single variable
9870b57cec5SDimitry Andric   // argument, variable return value STATEPOINT node here and then hookup the
9880b57cec5SDimitry Andric   // return value of each gc.relocate to the respective output of the
9890b57cec5SDimitry Andric   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
9900b57cec5SDimitry Andric   // to actually be possible today.
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric   return ReturnVal;
9930b57cec5SDimitry Andric }
9940b57cec5SDimitry Andric 
9951fd87a68SDimitry Andric /// Return two gc.results if present.  First result is a block local
9961fd87a68SDimitry Andric /// gc.result, second result is a non-block local gc.result.  Corresponding
9971fd87a68SDimitry Andric /// entry will be nullptr if not present.
9981fd87a68SDimitry Andric static std::pair<const GCResultInst*, const GCResultInst*>
9991fd87a68SDimitry Andric getGCResultLocality(const GCStatepointInst &S) {
10001fd87a68SDimitry Andric   std::pair<const GCResultInst *, const GCResultInst*> Res(nullptr, nullptr);
1001fcaf7f86SDimitry Andric   for (const auto *U : S.users()) {
10021fd87a68SDimitry Andric     auto *GRI = dyn_cast<GCResultInst>(U);
10031fd87a68SDimitry Andric     if (!GRI)
10041fd87a68SDimitry Andric       continue;
10051fd87a68SDimitry Andric     if (GRI->getParent() == S.getParent())
10061fd87a68SDimitry Andric       Res.first = GRI;
10071fd87a68SDimitry Andric     else
10081fd87a68SDimitry Andric       Res.second = GRI;
10091fd87a68SDimitry Andric   }
10101fd87a68SDimitry Andric   return Res;
10111fd87a68SDimitry Andric }
10121fd87a68SDimitry Andric 
10130b57cec5SDimitry Andric void
10145ffd83dbSDimitry Andric SelectionDAGBuilder::LowerStatepoint(const GCStatepointInst &I,
10150b57cec5SDimitry Andric                                      const BasicBlock *EHPadBB /*= nullptr*/) {
10165ffd83dbSDimitry Andric   assert(I.getCallingConv() != CallingConv::AnyReg &&
10170b57cec5SDimitry Andric          "anyregcc is not supported on statepoints!");
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric #ifndef NDEBUG
10200b57cec5SDimitry Andric   // Check that the associated GCStrategy expects to encounter statepoints.
10210b57cec5SDimitry Andric   assert(GFI->getStrategy().useStatepoints() &&
10220b57cec5SDimitry Andric          "GCStrategy does not expect to encounter statepoints");
10230b57cec5SDimitry Andric #endif
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric   SDValue ActualCallee;
10265ffd83dbSDimitry Andric   SDValue Callee = getValue(I.getActualCalledOperand());
10270b57cec5SDimitry Andric 
10285ffd83dbSDimitry Andric   if (I.getNumPatchBytes() > 0) {
10290b57cec5SDimitry Andric     // If we've been asked to emit a nop sequence instead of a call instruction
10300b57cec5SDimitry Andric     // for this statepoint then don't lower the call target, but use a constant
10315ffd83dbSDimitry Andric     // `undef` instead.  Not lowering the call target lets statepoint clients
10325ffd83dbSDimitry Andric     // get away without providing a physical address for the symbolic call
10335ffd83dbSDimitry Andric     // target at link time.
10345ffd83dbSDimitry Andric     ActualCallee = DAG.getUNDEF(Callee.getValueType());
10350b57cec5SDimitry Andric   } else {
10365ffd83dbSDimitry Andric     ActualCallee = Callee;
10370b57cec5SDimitry Andric   }
10380b57cec5SDimitry Andric 
10395f757f3fSDimitry Andric   const auto GCResultLocality = getGCResultLocality(I);
10405f757f3fSDimitry Andric   AttributeSet retAttrs;
10415f757f3fSDimitry Andric   if (GCResultLocality.first)
10425f757f3fSDimitry Andric     retAttrs = GCResultLocality.first->getAttributes().getRetAttrs();
10435f757f3fSDimitry Andric 
10440b57cec5SDimitry Andric   StatepointLoweringInfo SI(DAG);
10455ffd83dbSDimitry Andric   populateCallLoweringInfo(SI.CLI, &I, GCStatepointInst::CallArgsBeginPos,
10465ffd83dbSDimitry Andric                            I.getNumCallArgs(), ActualCallee,
10475f757f3fSDimitry Andric                            I.getActualReturnType(), retAttrs,
10485f757f3fSDimitry Andric                            /*IsPatchPoint=*/false);
10490b57cec5SDimitry Andric 
10505ffd83dbSDimitry Andric   // There may be duplication in the gc.relocate list; such as two copies of
10515ffd83dbSDimitry Andric   // each relocation on normal and exceptional path for an invoke.  We only
10525ffd83dbSDimitry Andric   // need to spill once and record one copy in the stackmap, but we need to
10535ffd83dbSDimitry Andric   // reload once per gc.relocate.  (Dedupping gc.relocates is trickier and best
10545ffd83dbSDimitry Andric   // handled as a CSE problem elsewhere.)
10555ffd83dbSDimitry Andric   // TODO: There a couple of major stackmap size optimizations we could do
10565ffd83dbSDimitry Andric   // here if we wished.
10575ffd83dbSDimitry Andric   // 1) If we've encountered a derived pair {B, D}, we don't need to actually
10585ffd83dbSDimitry Andric   // record {B,B} if it's seen later.
10595ffd83dbSDimitry Andric   // 2) Due to rematerialization, actual derived pointers are somewhat rare;
10605ffd83dbSDimitry Andric   // given that, we could change the format to record base pointer relocations
10615ffd83dbSDimitry Andric   // separately with half the space. This would require a format rev and a
10625ffd83dbSDimitry Andric   // fairly major rework of the STATEPOINT node though.
10635ffd83dbSDimitry Andric   SmallSet<SDValue, 8> Seen;
10645ffd83dbSDimitry Andric   for (const GCRelocateInst *Relocate : I.getGCRelocates()) {
10650b57cec5SDimitry Andric     SI.GCRelocates.push_back(Relocate);
10665ffd83dbSDimitry Andric 
10675ffd83dbSDimitry Andric     SDValue DerivedSD = getValue(Relocate->getDerivedPtr());
10685ffd83dbSDimitry Andric     if (Seen.insert(DerivedSD).second) {
10690b57cec5SDimitry Andric       SI.Bases.push_back(Relocate->getBasePtr());
10700b57cec5SDimitry Andric       SI.Ptrs.push_back(Relocate->getDerivedPtr());
10710b57cec5SDimitry Andric     }
10725ffd83dbSDimitry Andric   }
10730b57cec5SDimitry Andric 
1074fe6060f1SDimitry Andric   // If we find a deopt value which isn't explicitly added, we need to
1075fe6060f1SDimitry Andric   // ensure it gets lowered such that gc cycles occurring before the
1076fe6060f1SDimitry Andric   // deoptimization event during the lifetime of the call don't invalidate
1077fe6060f1SDimitry Andric   // the pointer we're deopting with.  Note that we assume that all
1078fe6060f1SDimitry Andric   // pointers passed to deopt are base pointers; relaxing that assumption
1079fe6060f1SDimitry Andric   // would require relatively large changes to how we represent relocations.
1080fe6060f1SDimitry Andric   for (Value *V : I.deopt_operands()) {
1081fe6060f1SDimitry Andric     if (!isGCValue(V, *this))
1082fe6060f1SDimitry Andric       continue;
1083fe6060f1SDimitry Andric     if (Seen.insert(getValue(V)).second) {
1084fe6060f1SDimitry Andric       SI.Bases.push_back(V);
1085fe6060f1SDimitry Andric       SI.Ptrs.push_back(V);
1086fe6060f1SDimitry Andric     }
1087fe6060f1SDimitry Andric   }
1088fe6060f1SDimitry Andric 
10895ffd83dbSDimitry Andric   SI.GCArgs = ArrayRef<const Use>(I.gc_args_begin(), I.gc_args_end());
10905ffd83dbSDimitry Andric   SI.StatepointInstr = &I;
10915ffd83dbSDimitry Andric   SI.ID = I.getID();
10925ffd83dbSDimitry Andric 
10935ffd83dbSDimitry Andric   SI.DeoptState = ArrayRef<const Use>(I.deopt_begin(), I.deopt_end());
10945ffd83dbSDimitry Andric   SI.GCTransitionArgs = ArrayRef<const Use>(I.gc_transition_args_begin(),
10955ffd83dbSDimitry Andric                                             I.gc_transition_args_end());
10965ffd83dbSDimitry Andric 
10975ffd83dbSDimitry Andric   SI.StatepointFlags = I.getFlags();
10985ffd83dbSDimitry Andric   SI.NumPatchBytes = I.getNumPatchBytes();
10990b57cec5SDimitry Andric   SI.EHPadBB = EHPadBB;
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   SDValue ReturnValue = LowerAsSTATEPOINT(SI);
11020b57cec5SDimitry Andric 
11030b57cec5SDimitry Andric   // Export the result value if needed
11041fd87a68SDimitry Andric   if (!GCResultLocality.first && !GCResultLocality.second) {
11055ffd83dbSDimitry Andric     // The return value is not needed, just generate a poison value.
11061fd87a68SDimitry Andric     // Note: This covers the void return case.
11075ffd83dbSDimitry Andric     setValue(&I, DAG.getIntPtrConstant(-1, getCurSDLoc()));
11085ffd83dbSDimitry Andric     return;
11095ffd83dbSDimitry Andric   }
11105ffd83dbSDimitry Andric 
1111fe6060f1SDimitry Andric   if (GCResultLocality.first) {
11125ffd83dbSDimitry Andric     // Result value will be used in a same basic block. Don't export it or
11135ffd83dbSDimitry Andric     // perform any explicit register copies. The gc_result will simply grab
11145ffd83dbSDimitry Andric     // this value.
11155ffd83dbSDimitry Andric     setValue(&I, ReturnValue);
11165ffd83dbSDimitry Andric   }
11175ffd83dbSDimitry Andric 
1118fe6060f1SDimitry Andric   if (!GCResultLocality.second)
1119fe6060f1SDimitry Andric     return;
11205ffd83dbSDimitry Andric   // Result value will be used in a different basic block so we need to export
11215ffd83dbSDimitry Andric   // it now.  Default exporting mechanism will not work here because statepoint
11225ffd83dbSDimitry Andric   // call has a different type than the actual call. It means that by default
11235ffd83dbSDimitry Andric   // llvm will create export register of the wrong type (always i32 in our
11245ffd83dbSDimitry Andric   // case). So instead we need to create export register with correct type
11255ffd83dbSDimitry Andric   // manually.
11260b57cec5SDimitry Andric   // TODO: To eliminate this problem we can remove gc.result intrinsics
11270b57cec5SDimitry Andric   //       completely and make statepoint call to return a tuple.
11281fd87a68SDimitry Andric   Type *RetTy = GCResultLocality.second->getType();
1129bdd1243dSDimitry Andric   Register Reg = FuncInfo.CreateRegs(RetTy);
11300b57cec5SDimitry Andric   RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
11310b57cec5SDimitry Andric                    DAG.getDataLayout(), Reg, RetTy,
11325ffd83dbSDimitry Andric                    I.getCallingConv());
11330b57cec5SDimitry Andric   SDValue Chain = DAG.getEntryNode();
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric   RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
11360b57cec5SDimitry Andric   PendingExports.push_back(Chain);
11375ffd83dbSDimitry Andric   FuncInfo.ValueMap[&I] = Reg;
11380b57cec5SDimitry Andric }
11390b57cec5SDimitry Andric 
11400b57cec5SDimitry Andric void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
11410b57cec5SDimitry Andric     const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
11420b57cec5SDimitry Andric     bool VarArgDisallowed, bool ForceVoidReturnTy) {
11430b57cec5SDimitry Andric   StatepointLoweringInfo SI(DAG);
11440b57cec5SDimitry Andric   unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
11450b57cec5SDimitry Andric   populateCallLoweringInfo(
1146349cc55cSDimitry Andric       SI.CLI, Call, ArgBeginIndex, Call->arg_size(), Callee,
11470b57cec5SDimitry Andric       ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : Call->getType(),
11485f757f3fSDimitry Andric       Call->getAttributes().getRetAttrs(), /*IsPatchPoint=*/false);
11490b57cec5SDimitry Andric   if (!VarArgDisallowed)
11500b57cec5SDimitry Andric     SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
11510b57cec5SDimitry Andric 
11520b57cec5SDimitry Andric   auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric   unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric   auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
115781ad6265SDimitry Andric   SI.ID = SD.StatepointID.value_or(DefaultID);
115881ad6265SDimitry Andric   SI.NumPatchBytes = SD.NumPatchBytes.value_or(0);
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric   SI.DeoptState =
11610b57cec5SDimitry Andric       ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
11620b57cec5SDimitry Andric   SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
11630b57cec5SDimitry Andric   SI.EHPadBB = EHPadBB;
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric   // NB! The GC arguments are deliberately left empty.
11660b57cec5SDimitry Andric 
11675f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "Lowering call with deopt bundle " << *Call << "\n");
11680b57cec5SDimitry Andric   if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
11690b57cec5SDimitry Andric     ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
11700b57cec5SDimitry Andric     setValue(Call, ReturnVal);
11710b57cec5SDimitry Andric   }
11720b57cec5SDimitry Andric }
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
11750b57cec5SDimitry Andric     const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
11760b57cec5SDimitry Andric   LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
11770b57cec5SDimitry Andric                                    /* VarArgDisallowed = */ false,
11780b57cec5SDimitry Andric                                    /* ForceVoidReturnTy  = */ false);
11790b57cec5SDimitry Andric }
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
11820b57cec5SDimitry Andric   // The result value of the gc_result is simply the result of the actual
11830b57cec5SDimitry Andric   // call.  We've already emitted this, so just grab the value.
1184fcaf7f86SDimitry Andric   const Value *SI = CI.getStatepoint();
1185fcaf7f86SDimitry Andric   assert((isa<GCStatepointInst>(SI) || isa<UndefValue>(SI)) &&
1186fcaf7f86SDimitry Andric          "GetStatepoint must return one of two types");
1187fcaf7f86SDimitry Andric   if (isa<UndefValue>(SI))
1188fcaf7f86SDimitry Andric     return;
11890b57cec5SDimitry Andric 
1190fcaf7f86SDimitry Andric   if (cast<GCStatepointInst>(SI)->getParent() == CI.getParent()) {
11915ffd83dbSDimitry Andric     setValue(&CI, getValue(SI));
11925ffd83dbSDimitry Andric     return;
11935ffd83dbSDimitry Andric   }
11940b57cec5SDimitry Andric   // Statepoint is in different basic block so we should have stored call
11950b57cec5SDimitry Andric   // result in a virtual register.
11960b57cec5SDimitry Andric   // We can not use default getValue() functionality to copy value from this
11970b57cec5SDimitry Andric   // register because statepoint and actual call return types can be
11980b57cec5SDimitry Andric   // different, and getValue() will use CopyFromReg of the wrong type,
11990b57cec5SDimitry Andric   // which is always i32 in our case.
12001fd87a68SDimitry Andric   Type *RetTy = CI.getType();
12015ffd83dbSDimitry Andric   SDValue CopyFromReg = getCopyFromRegs(SI, RetTy);
12020b57cec5SDimitry Andric 
12030b57cec5SDimitry Andric   assert(CopyFromReg.getNode());
12040b57cec5SDimitry Andric   setValue(&CI, CopyFromReg);
12050b57cec5SDimitry Andric }
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
1208fcaf7f86SDimitry Andric   const Value *Statepoint = Relocate.getStatepoint();
12090b57cec5SDimitry Andric #ifndef NDEBUG
12100b57cec5SDimitry Andric   // Consistency check
12110b57cec5SDimitry Andric   // We skip this check for relocates not in the same basic block as their
12120b57cec5SDimitry Andric   // statepoint. It would be too expensive to preserve validation info through
12130b57cec5SDimitry Andric   // different basic blocks.
1214fcaf7f86SDimitry Andric   assert((isa<GCStatepointInst>(Statepoint) || isa<UndefValue>(Statepoint)) &&
1215fcaf7f86SDimitry Andric          "GetStatepoint must return one of two types");
1216fcaf7f86SDimitry Andric   if (isa<UndefValue>(Statepoint))
1217fcaf7f86SDimitry Andric     return;
1218fcaf7f86SDimitry Andric 
1219fcaf7f86SDimitry Andric   if (cast<GCStatepointInst>(Statepoint)->getParent() == Relocate.getParent())
12200b57cec5SDimitry Andric     StatepointLowering.relocCallVisited(Relocate);
12210b57cec5SDimitry Andric #endif
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   const Value *DerivedPtr = Relocate.getDerivedPtr();
1224e8d8bef9SDimitry Andric   auto &RelocationMap =
1225fcaf7f86SDimitry Andric       FuncInfo.StatepointRelocationMaps[cast<GCStatepointInst>(Statepoint)];
122681ad6265SDimitry Andric   auto SlotIt = RelocationMap.find(&Relocate);
1227e8d8bef9SDimitry Andric   assert(SlotIt != RelocationMap.end() && "Relocating not lowered gc value");
1228e8d8bef9SDimitry Andric   const RecordType &Record = SlotIt->second;
1229e8d8bef9SDimitry Andric 
1230e8d8bef9SDimitry Andric   // If relocation was done via virtual register..
123181ad6265SDimitry Andric   if (Record.type == RecordType::SDValueNode) {
1232fcaf7f86SDimitry Andric     assert(cast<GCStatepointInst>(Statepoint)->getParent() ==
1233fcaf7f86SDimitry Andric                Relocate.getParent() &&
123481ad6265SDimitry Andric            "Nonlocal gc.relocate mapped via SDValue");
123581ad6265SDimitry Andric     SDValue SDV = StatepointLowering.getLocation(getValue(DerivedPtr));
123681ad6265SDimitry Andric     assert(SDV.getNode() && "empty SDValue");
123781ad6265SDimitry Andric     setValue(&Relocate, SDV);
123881ad6265SDimitry Andric     return;
123981ad6265SDimitry Andric   }
1240e8d8bef9SDimitry Andric   if (Record.type == RecordType::VReg) {
1241e8d8bef9SDimitry Andric     Register InReg = Record.payload.Reg;
1242e8d8bef9SDimitry Andric     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1243e8d8bef9SDimitry Andric                      DAG.getDataLayout(), InReg, Relocate.getType(),
1244bdd1243dSDimitry Andric                      std::nullopt); // This is not an ABI copy.
1245e8d8bef9SDimitry Andric     // We generate copy to/from regs even for local uses, hence we must
1246e8d8bef9SDimitry Andric     // chain with current root to ensure proper ordering of copies w.r.t.
1247e8d8bef9SDimitry Andric     // statepoint.
1248e8d8bef9SDimitry Andric     SDValue Chain = DAG.getRoot();
1249e8d8bef9SDimitry Andric     SDValue Relocation = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
1250e8d8bef9SDimitry Andric                                              Chain, nullptr, nullptr);
1251e8d8bef9SDimitry Andric     setValue(&Relocate, Relocation);
1252e8d8bef9SDimitry Andric     return;
1253e8d8bef9SDimitry Andric   }
1254e8d8bef9SDimitry Andric 
1255fe6060f1SDimitry Andric   if (Record.type == RecordType::Spill) {
1256fe6060f1SDimitry Andric     unsigned Index = Record.payload.FI;
12578bcb0991SDimitry Andric     SDValue SpillSlot = DAG.getTargetFrameIndex(Index, getFrameIndexTy());
12580b57cec5SDimitry Andric 
12595ffd83dbSDimitry Andric     // All the reloads are independent and are reading memory only modified by
12605ffd83dbSDimitry Andric     // statepoints (i.e. no other aliasing stores); informing SelectionDAG of
126106c3fb27SDimitry Andric     // this lets CSE kick in for free and allows reordering of
1262fe6060f1SDimitry Andric     // instructions if possible.  The lowering for statepoint sets the root,
1263fe6060f1SDimitry Andric     // so this is ordering all reloads with the either
1264fe6060f1SDimitry Andric     // a) the statepoint node itself, or
1265fe6060f1SDimitry Andric     // b) the entry of the current block for an invoke statepoint.
12665ffd83dbSDimitry Andric     const SDValue Chain = DAG.getRoot(); // != Builder.getRoot()
12670b57cec5SDimitry Andric 
12688bcb0991SDimitry Andric     auto &MF = DAG.getMachineFunction();
12698bcb0991SDimitry Andric     auto &MFI = MF.getFrameInfo();
12708bcb0991SDimitry Andric     auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
12715ffd83dbSDimitry Andric     auto *LoadMMO = MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
12728bcb0991SDimitry Andric                                             MFI.getObjectSize(Index),
12735ffd83dbSDimitry Andric                                             MFI.getObjectAlign(Index));
12748bcb0991SDimitry Andric 
12758bcb0991SDimitry Andric     auto LoadVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
12768bcb0991SDimitry Andric                                                            Relocate.getType());
12778bcb0991SDimitry Andric 
1278fe6060f1SDimitry Andric     SDValue SpillLoad =
1279fe6060f1SDimitry Andric         DAG.getLoad(LoadVT, getCurSDLoc(), Chain, SpillSlot, LoadMMO);
12805ffd83dbSDimitry Andric     PendingLoads.push_back(SpillLoad.getValue(1));
12810b57cec5SDimitry Andric 
12820b57cec5SDimitry Andric     assert(SpillLoad.getNode());
12830b57cec5SDimitry Andric     setValue(&Relocate, SpillLoad);
1284fe6060f1SDimitry Andric     return;
1285fe6060f1SDimitry Andric   }
1286fe6060f1SDimitry Andric 
1287fe6060f1SDimitry Andric   assert(Record.type == RecordType::NoRelocate);
1288fe6060f1SDimitry Andric   SDValue SD = getValue(DerivedPtr);
1289fe6060f1SDimitry Andric 
1290fe6060f1SDimitry Andric   if (SD.isUndef() && SD.getValueType().getSizeInBits() <= 64) {
1291fe6060f1SDimitry Andric     // Lowering relocate(undef) as arbitrary constant. Current constant value
1292fe6060f1SDimitry Andric     // is chosen such that it's unlikely to be a valid pointer.
1293*0fca6ea1SDimitry Andric     setValue(&Relocate, DAG.getConstant(0xFEFEFEFE, SDLoc(SD), MVT::i64));
1294fe6060f1SDimitry Andric     return;
1295fe6060f1SDimitry Andric   }
1296fe6060f1SDimitry Andric 
1297fe6060f1SDimitry Andric   // We didn't need to spill these special cases (constants and allocas).
1298fe6060f1SDimitry Andric   // See the handling in spillIncomingValueForStatepoint for detail.
1299fe6060f1SDimitry Andric   setValue(&Relocate, SD);
13000b57cec5SDimitry Andric }
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
13030b57cec5SDimitry Andric   const auto &TLI = DAG.getTargetLoweringInfo();
13040b57cec5SDimitry Andric   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
13050b57cec5SDimitry Andric                                          TLI.getPointerTy(DAG.getDataLayout()));
13060b57cec5SDimitry Andric 
13070b57cec5SDimitry Andric   // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
13080b57cec5SDimitry Andric   // call.  We also do not lower the return value to any virtual register, and
13090b57cec5SDimitry Andric   // change the immediately following return to a trap instruction.
13100b57cec5SDimitry Andric   LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
13110b57cec5SDimitry Andric                                    /* VarArgDisallowed = */ true,
13120b57cec5SDimitry Andric                                    /* ForceVoidReturnTy = */ true);
13130b57cec5SDimitry Andric }
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric void SelectionDAGBuilder::LowerDeoptimizingReturn() {
13160b57cec5SDimitry Andric   // We do not lower the return value from llvm.deoptimize to any virtual
13170b57cec5SDimitry Andric   // register, and change the immediately following return to a trap
13180b57cec5SDimitry Andric   // instruction.
13190b57cec5SDimitry Andric   if (DAG.getTarget().Options.TrapUnreachable)
13200b57cec5SDimitry Andric     DAG.setRoot(
13210b57cec5SDimitry Andric         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
13220b57cec5SDimitry Andric }
1323