12cab237bSDimitry Andric //===- StatepointLowering.cpp - SDAGBuilder's statepoint code -------------===//
239d628a0SDimitry Andric //
339d628a0SDimitry Andric //                     The LLVM Compiler Infrastructure
439d628a0SDimitry Andric //
539d628a0SDimitry Andric // This file is distributed under the University of Illinois Open Source
639d628a0SDimitry Andric // License. See LICENSE.TXT for details.
739d628a0SDimitry Andric //
839d628a0SDimitry Andric //===----------------------------------------------------------------------===//
939d628a0SDimitry Andric //
1039d628a0SDimitry Andric // This file includes support code use by SelectionDAGBuilder when lowering a
1139d628a0SDimitry Andric // statepoint sequence in SelectionDAG IR.
1239d628a0SDimitry Andric //
1339d628a0SDimitry Andric //===----------------------------------------------------------------------===//
1439d628a0SDimitry Andric 
1539d628a0SDimitry Andric #include "StatepointLowering.h"
1639d628a0SDimitry Andric #include "SelectionDAGBuilder.h"
172cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
182cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
192cab237bSDimitry Andric #include "llvm/ADT/None.h"
202cab237bSDimitry Andric #include "llvm/ADT/Optional.h"
212cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
222cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
2339d628a0SDimitry Andric #include "llvm/ADT/Statistic.h"
2439d628a0SDimitry Andric #include "llvm/CodeGen/FunctionLoweringInfo.h"
25ff0cc061SDimitry Andric #include "llvm/CodeGen/GCMetadata.h"
2639d628a0SDimitry Andric #include "llvm/CodeGen/GCStrategy.h"
272cab237bSDimitry Andric #include "llvm/CodeGen/ISDOpcodes.h"
28db17bf38SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
292cab237bSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
302cab237bSDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
312cab237bSDimitry Andric #include "llvm/CodeGen/MachineValueType.h"
322cab237bSDimitry Andric #include "llvm/CodeGen/RuntimeLibcalls.h"
3339d628a0SDimitry Andric #include "llvm/CodeGen/SelectionDAG.h"
342cab237bSDimitry Andric #include "llvm/CodeGen/SelectionDAGNodes.h"
3539d628a0SDimitry Andric #include "llvm/CodeGen/StackMaps.h"
362cab237bSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
372cab237bSDimitry Andric #include "llvm/CodeGen/TargetOpcodes.h"
3839d628a0SDimitry Andric #include "llvm/IR/CallingConv.h"
392cab237bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
402cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
4139d628a0SDimitry Andric #include "llvm/IR/Instructions.h"
422cab237bSDimitry Andric #include "llvm/IR/LLVMContext.h"
4339d628a0SDimitry Andric #include "llvm/IR/Statepoint.h"
442cab237bSDimitry Andric #include "llvm/IR/Type.h"
452cab237bSDimitry Andric #include "llvm/Support/Casting.h"
462cab237bSDimitry Andric #include "llvm/Target/TargetMachine.h"
472cab237bSDimitry Andric #include "llvm/Target/TargetOptions.h"
482cab237bSDimitry Andric #include <cassert>
492cab237bSDimitry Andric #include <cstddef>
502cab237bSDimitry Andric #include <cstdint>
512cab237bSDimitry Andric #include <iterator>
522cab237bSDimitry Andric #include <tuple>
532cab237bSDimitry Andric #include <utility>
542cab237bSDimitry Andric 
5539d628a0SDimitry Andric using namespace llvm;
5639d628a0SDimitry Andric 
5739d628a0SDimitry Andric #define DEBUG_TYPE "statepoint-lowering"
5839d628a0SDimitry Andric 
5939d628a0SDimitry Andric STATISTIC(NumSlotsAllocatedForStatepoints,
6039d628a0SDimitry Andric           "Number of stack slots allocated for statepoints");
6139d628a0SDimitry Andric STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
6239d628a0SDimitry Andric STATISTIC(StatepointMaxSlotsRequired,
6339d628a0SDimitry Andric           "Maximum number of stack slots required for a singe statepoint");
6439d628a0SDimitry Andric 
65ff0cc061SDimitry Andric static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
66ff0cc061SDimitry Andric                                  SelectionDAGBuilder &Builder, uint64_t Value) {
67ff0cc061SDimitry Andric   SDLoc L = Builder.getCurSDLoc();
68ff0cc061SDimitry Andric   Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
69ff0cc061SDimitry Andric                                               MVT::i64));
70ff0cc061SDimitry Andric   Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
71ff0cc061SDimitry Andric }
72ff0cc061SDimitry Andric 
73ff0cc061SDimitry Andric void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
7439d628a0SDimitry Andric   // Consistency check
7539d628a0SDimitry Andric   assert(PendingGCRelocateCalls.empty() &&
7639d628a0SDimitry Andric          "Trying to visit statepoint before finished processing previous one");
7739d628a0SDimitry Andric   Locations.clear();
7839d628a0SDimitry Andric   NextSlotToAllocate = 0;
793ca95b02SDimitry Andric   // Need to resize this on each safepoint - we need the two to stay in sync and
803ca95b02SDimitry Andric   // the clear patterns of a SelectionDAGBuilder have no relation to
81d88c1a5aSDimitry Andric   // FunctionLoweringInfo.  Also need to ensure used bits get cleared.
82d88c1a5aSDimitry Andric   AllocatedStackSlots.clear();
8339d628a0SDimitry Andric   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
8439d628a0SDimitry Andric }
85ff0cc061SDimitry Andric 
8639d628a0SDimitry Andric void StatepointLoweringState::clear() {
8739d628a0SDimitry Andric   Locations.clear();
8839d628a0SDimitry Andric   AllocatedStackSlots.clear();
8939d628a0SDimitry Andric   assert(PendingGCRelocateCalls.empty() &&
9039d628a0SDimitry Andric          "cleared before statepoint sequence completed");
9139d628a0SDimitry Andric }
9239d628a0SDimitry Andric 
9339d628a0SDimitry Andric SDValue
9439d628a0SDimitry Andric StatepointLoweringState::allocateStackSlot(EVT ValueType,
9539d628a0SDimitry Andric                                            SelectionDAGBuilder &Builder) {
9639d628a0SDimitry Andric   NumSlotsAllocatedForStatepoints++;
97d88c1a5aSDimitry Andric   MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
9839d628a0SDimitry Andric 
992cab237bSDimitry Andric   unsigned SpillSize = ValueType.getStoreSize();
1003ca95b02SDimitry Andric   assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?");
10139d628a0SDimitry Andric 
1023ca95b02SDimitry Andric   // First look for a previously created stack slot which is not in
1033ca95b02SDimitry Andric   // use (accounting for the fact arbitrary slots may already be
1043ca95b02SDimitry Andric   // reserved), or to create a new stack slot and use it.
1053ca95b02SDimitry Andric 
10639d628a0SDimitry Andric   const size_t NumSlots = AllocatedStackSlots.size();
1073ca95b02SDimitry Andric   assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
10839d628a0SDimitry Andric 
109d88c1a5aSDimitry Andric   assert(AllocatedStackSlots.size() ==
110d88c1a5aSDimitry Andric          Builder.FuncInfo.StatepointStackSlots.size() &&
1113ca95b02SDimitry Andric          "Broken invariant");
1123ca95b02SDimitry Andric 
1133ca95b02SDimitry Andric   for (; NextSlotToAllocate < NumSlots; NextSlotToAllocate++) {
1143ca95b02SDimitry Andric     if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
1153ca95b02SDimitry Andric       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
116d88c1a5aSDimitry Andric       if (MFI.getObjectSize(FI) == SpillSize) {
1173ca95b02SDimitry Andric         AllocatedStackSlots.set(NextSlotToAllocate);
118d88c1a5aSDimitry Andric         // TODO: Is ValueType the right thing to use here?
1193ca95b02SDimitry Andric         return Builder.DAG.getFrameIndex(FI, ValueType);
12039d628a0SDimitry Andric       }
1213ca95b02SDimitry Andric     }
1223ca95b02SDimitry Andric   }
1233ca95b02SDimitry Andric 
1243ca95b02SDimitry Andric   // Couldn't find a free slot, so create a new one:
12539d628a0SDimitry Andric 
12639d628a0SDimitry Andric   SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
12739d628a0SDimitry Andric   const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
128d88c1a5aSDimitry Andric   MFI.markAsStatepointSpillSlotObjectIndex(FI);
1297d523365SDimitry Andric 
13039d628a0SDimitry Andric   Builder.FuncInfo.StatepointStackSlots.push_back(FI);
131d88c1a5aSDimitry Andric   AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
132d88c1a5aSDimitry Andric   assert(AllocatedStackSlots.size() ==
133d88c1a5aSDimitry Andric          Builder.FuncInfo.StatepointStackSlots.size() &&
134d88c1a5aSDimitry Andric          "Broken invariant");
1353ca95b02SDimitry Andric 
136d8866befSDimitry Andric   StatepointMaxSlotsRequired.updateMax(
137d8866befSDimitry Andric       Builder.FuncInfo.StatepointStackSlots.size());
1383ca95b02SDimitry Andric 
13939d628a0SDimitry Andric   return SpillSlot;
14039d628a0SDimitry Andric }
14139d628a0SDimitry Andric 
1428f0fd8f6SDimitry Andric /// Utility function for reservePreviousStackSlotForValue. Tries to find
1438f0fd8f6SDimitry Andric /// stack slot index to which we have spilled value for previous statepoints.
1448f0fd8f6SDimitry Andric /// LookUpDepth specifies maximum DFS depth this function is allowed to look.
1458f0fd8f6SDimitry Andric static Optional<int> findPreviousSpillSlot(const Value *Val,
1468f0fd8f6SDimitry Andric                                            SelectionDAGBuilder &Builder,
1478f0fd8f6SDimitry Andric                                            int LookUpDepth) {
1487d523365SDimitry Andric   // Can not look any further - give up now
1498f0fd8f6SDimitry Andric   if (LookUpDepth <= 0)
1503ca95b02SDimitry Andric     return None;
1518f0fd8f6SDimitry Andric 
1528f0fd8f6SDimitry Andric   // Spill location is known for gc relocates
1534d0b32cdSDimitry Andric   if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
1543ca95b02SDimitry Andric     const auto &SpillMap =
1553ca95b02SDimitry Andric         Builder.FuncInfo.StatepointSpillMaps[Relocate->getStatepoint()];
1568f0fd8f6SDimitry Andric 
1574d0b32cdSDimitry Andric     auto It = SpillMap.find(Relocate->getDerivedPtr());
1588f0fd8f6SDimitry Andric     if (It == SpillMap.end())
1593ca95b02SDimitry Andric       return None;
1608f0fd8f6SDimitry Andric 
1618f0fd8f6SDimitry Andric     return It->second;
1628f0fd8f6SDimitry Andric   }
1638f0fd8f6SDimitry Andric 
1648f0fd8f6SDimitry Andric   // Look through bitcast instructions.
1653ca95b02SDimitry Andric   if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
1668f0fd8f6SDimitry Andric     return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
1678f0fd8f6SDimitry Andric 
1688f0fd8f6SDimitry Andric   // Look through phi nodes
1698f0fd8f6SDimitry Andric   // All incoming values should have same known stack slot, otherwise result
1708f0fd8f6SDimitry Andric   // is unknown.
1718f0fd8f6SDimitry Andric   if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
1728f0fd8f6SDimitry Andric     Optional<int> MergedResult = None;
1738f0fd8f6SDimitry Andric 
1748f0fd8f6SDimitry Andric     for (auto &IncomingValue : Phi->incoming_values()) {
1758f0fd8f6SDimitry Andric       Optional<int> SpillSlot =
1768f0fd8f6SDimitry Andric           findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
1778f0fd8f6SDimitry Andric       if (!SpillSlot.hasValue())
1783ca95b02SDimitry Andric         return None;
1798f0fd8f6SDimitry Andric 
1808f0fd8f6SDimitry Andric       if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
1813ca95b02SDimitry Andric         return None;
1828f0fd8f6SDimitry Andric 
1838f0fd8f6SDimitry Andric       MergedResult = SpillSlot;
1848f0fd8f6SDimitry Andric     }
1858f0fd8f6SDimitry Andric     return MergedResult;
1868f0fd8f6SDimitry Andric   }
1878f0fd8f6SDimitry Andric 
1888f0fd8f6SDimitry Andric   // TODO: We can do better for PHI nodes. In cases like this:
1898f0fd8f6SDimitry Andric   //   ptr = phi(relocated_pointer, not_relocated_pointer)
1908f0fd8f6SDimitry Andric   //   statepoint(ptr)
1918f0fd8f6SDimitry Andric   // We will return that stack slot for ptr is unknown. And later we might
1928f0fd8f6SDimitry Andric   // assign different stack slots for ptr and relocated_pointer. This limits
1938f0fd8f6SDimitry Andric   // llvm's ability to remove redundant stores.
1948f0fd8f6SDimitry Andric   // Unfortunately it's hard to accomplish in current infrastructure.
1958f0fd8f6SDimitry Andric   // We use this function to eliminate spill store completely, while
1968f0fd8f6SDimitry Andric   // in example we still need to emit store, but instead of any location
1978f0fd8f6SDimitry Andric   // we need to use special "preferred" location.
1988f0fd8f6SDimitry Andric 
1998f0fd8f6SDimitry Andric   // TODO: handle simple updates.  If a value is modified and the original
2008f0fd8f6SDimitry Andric   // value is no longer live, it would be nice to put the modified value in the
2018f0fd8f6SDimitry Andric   // same slot.  This allows folding of the memory accesses for some
2028f0fd8f6SDimitry Andric   // instructions types (like an increment).
2038f0fd8f6SDimitry Andric   //   statepoint (i)
2048f0fd8f6SDimitry Andric   //   i1 = i+1
2058f0fd8f6SDimitry Andric   //   statepoint (i1)
2068f0fd8f6SDimitry Andric   // However we need to be careful for cases like this:
2078f0fd8f6SDimitry Andric   //   statepoint(i)
2088f0fd8f6SDimitry Andric   //   i1 = i+1
2098f0fd8f6SDimitry Andric   //   statepoint(i, i1)
2108f0fd8f6SDimitry Andric   // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
2118f0fd8f6SDimitry Andric   // put handling of simple modifications in this function like it's done
2128f0fd8f6SDimitry Andric   // for bitcasts we might end up reserving i's slot for 'i+1' because order in
2138f0fd8f6SDimitry Andric   // which we visit values is unspecified.
2148f0fd8f6SDimitry Andric 
2158f0fd8f6SDimitry Andric   // Don't know any information about this instruction
2163ca95b02SDimitry Andric   return None;
2178f0fd8f6SDimitry Andric }
2188f0fd8f6SDimitry Andric 
21939d628a0SDimitry Andric /// Try to find existing copies of the incoming values in stack slots used for
22039d628a0SDimitry Andric /// statepoint spilling.  If we can find a spill slot for the incoming value,
22139d628a0SDimitry Andric /// mark that slot as allocated, and reuse the same slot for this safepoint.
2227d523365SDimitry Andric /// This helps to avoid series of loads and stores that only serve to reshuffle
22339d628a0SDimitry Andric /// values on the stack between calls.
2248f0fd8f6SDimitry Andric static void reservePreviousStackSlotForValue(const Value *IncomingValue,
22539d628a0SDimitry Andric                                              SelectionDAGBuilder &Builder) {
2268f0fd8f6SDimitry Andric   SDValue Incoming = Builder.getValue(IncomingValue);
2278f0fd8f6SDimitry Andric 
22839d628a0SDimitry Andric   if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
22939d628a0SDimitry Andric     // We won't need to spill this, so no need to check for previously
23039d628a0SDimitry Andric     // allocated stack slots
23139d628a0SDimitry Andric     return;
23239d628a0SDimitry Andric   }
23339d628a0SDimitry Andric 
2348f0fd8f6SDimitry Andric   SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
2358f0fd8f6SDimitry Andric   if (OldLocation.getNode())
2363ca95b02SDimitry Andric     // Duplicates in input
23739d628a0SDimitry Andric     return;
23839d628a0SDimitry Andric 
2398f0fd8f6SDimitry Andric   const int LookUpDepth = 6;
2408f0fd8f6SDimitry Andric   Optional<int> Index =
2418f0fd8f6SDimitry Andric       findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
2428f0fd8f6SDimitry Andric   if (!Index.hasValue())
24339d628a0SDimitry Andric     return;
2448f0fd8f6SDimitry Andric 
2453ca95b02SDimitry Andric   const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
2463ca95b02SDimitry Andric 
2473ca95b02SDimitry Andric   auto SlotIt = find(StatepointSlots, *Index);
2483ca95b02SDimitry Andric   assert(SlotIt != StatepointSlots.end() &&
2493ca95b02SDimitry Andric          "Value spilled to the unknown stack slot");
2508f0fd8f6SDimitry Andric 
25139d628a0SDimitry Andric   // This is one of our dedicated lowering slots
2523ca95b02SDimitry Andric   const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
25339d628a0SDimitry Andric   if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
25439d628a0SDimitry Andric     // stack slot already assigned to someone else, can't use it!
25539d628a0SDimitry Andric     // TODO: currently we reserve space for gc arguments after doing
25639d628a0SDimitry Andric     // normal allocation for deopt arguments.  We should reserve for
25739d628a0SDimitry Andric     // _all_ deopt and gc arguments, then start allocating.  This
25839d628a0SDimitry Andric     // will prevent some moves being inserted when vm state changes,
25939d628a0SDimitry Andric     // but gc state doesn't between two calls.
26039d628a0SDimitry Andric     return;
26139d628a0SDimitry Andric   }
26239d628a0SDimitry Andric   // Reserve this stack slot
26339d628a0SDimitry Andric   Builder.StatepointLowering.reserveStackSlot(Offset);
26439d628a0SDimitry Andric 
26539d628a0SDimitry Andric   // Cache this slot so we find it when going through the normal
26639d628a0SDimitry Andric   // assignment loop.
267f37b6182SDimitry Andric   SDValue Loc =
268f37b6182SDimitry Andric       Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
26939d628a0SDimitry Andric   Builder.StatepointLowering.setLocation(Incoming, Loc);
27039d628a0SDimitry Andric }
27139d628a0SDimitry Andric 
27239d628a0SDimitry Andric /// Remove any duplicate (as SDValues) from the derived pointer pairs.  This
27339d628a0SDimitry Andric /// is not required for correctness.  It's purpose is to reduce the size of
27439d628a0SDimitry Andric /// StackMap section.  It has no effect on the number of spill slots required
27539d628a0SDimitry Andric /// or the actual lowering.
2763ca95b02SDimitry Andric static void
2773ca95b02SDimitry Andric removeDuplicateGCPtrs(SmallVectorImpl<const Value *> &Bases,
27839d628a0SDimitry Andric                       SmallVectorImpl<const Value *> &Ptrs,
2793ca95b02SDimitry Andric                       SmallVectorImpl<const GCRelocateInst *> &Relocs,
2803ca95b02SDimitry Andric                       SelectionDAGBuilder &Builder,
2813ca95b02SDimitry Andric                       FunctionLoweringInfo::StatepointSpillMap &SSM) {
2823ca95b02SDimitry Andric   DenseMap<SDValue, const Value *> Seen;
28339d628a0SDimitry Andric 
2843ca95b02SDimitry Andric   SmallVector<const Value *, 64> NewBases, NewPtrs;
2853ca95b02SDimitry Andric   SmallVector<const GCRelocateInst *, 64> NewRelocs;
2863ca95b02SDimitry Andric   for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
28739d628a0SDimitry Andric     SDValue SD = Builder.getValue(Ptrs[i]);
2883ca95b02SDimitry Andric     auto SeenIt = Seen.find(SD);
2893ca95b02SDimitry Andric 
2903ca95b02SDimitry Andric     if (SeenIt == Seen.end()) {
29139d628a0SDimitry Andric       // Only add non-duplicates
29239d628a0SDimitry Andric       NewBases.push_back(Bases[i]);
29339d628a0SDimitry Andric       NewPtrs.push_back(Ptrs[i]);
29439d628a0SDimitry Andric       NewRelocs.push_back(Relocs[i]);
2953ca95b02SDimitry Andric       Seen[SD] = Ptrs[i];
2963ca95b02SDimitry Andric     } else {
2973ca95b02SDimitry Andric       // Duplicate pointer found, note in SSM and move on:
2983ca95b02SDimitry Andric       SSM.DuplicateMap[Ptrs[i]] = SeenIt->second;
29939d628a0SDimitry Andric     }
30039d628a0SDimitry Andric   }
30139d628a0SDimitry Andric   assert(Bases.size() >= NewBases.size());
30239d628a0SDimitry Andric   assert(Ptrs.size() >= NewPtrs.size());
30339d628a0SDimitry Andric   assert(Relocs.size() >= NewRelocs.size());
30439d628a0SDimitry Andric   Bases = NewBases;
30539d628a0SDimitry Andric   Ptrs = NewPtrs;
30639d628a0SDimitry Andric   Relocs = NewRelocs;
30739d628a0SDimitry Andric   assert(Ptrs.size() == Bases.size());
30839d628a0SDimitry Andric   assert(Ptrs.size() == Relocs.size());
30939d628a0SDimitry Andric }
31039d628a0SDimitry Andric 
31139d628a0SDimitry Andric /// Extract call from statepoint, lower it and return pointer to the
31239d628a0SDimitry Andric /// call node. Also update NodeMap so that getValue(statepoint) will
31339d628a0SDimitry Andric /// reference lowered call result
3143ca95b02SDimitry Andric static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
3153ca95b02SDimitry Andric     SelectionDAGBuilder::StatepointLoweringInfo &SI,
3163ca95b02SDimitry Andric     SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
317ff0cc061SDimitry Andric   SDValue ReturnValue, CallEndVal;
3183ca95b02SDimitry Andric   std::tie(ReturnValue, CallEndVal) =
3193ca95b02SDimitry Andric       Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
320ff0cc061SDimitry Andric   SDNode *CallEnd = CallEndVal.getNode();
321ff0cc061SDimitry Andric 
322ff0cc061SDimitry Andric   // Get a call instruction from the call sequence chain.  Tail calls are not
323ff0cc061SDimitry Andric   // allowed.  The following code is essentially reverse engineering X86's
324ff0cc061SDimitry Andric   // LowerCallTo.
325ff0cc061SDimitry Andric   //
326ff0cc061SDimitry Andric   // We are expecting DAG to have the following form:
327ff0cc061SDimitry Andric   //
328ff0cc061SDimitry Andric   // ch = eh_label (only in case of invoke statepoint)
329ff0cc061SDimitry Andric   //   ch, glue = callseq_start ch
330ff0cc061SDimitry Andric   //   ch, glue = X86::Call ch, glue
331ff0cc061SDimitry Andric   //   ch, glue = callseq_end ch, glue
332ff0cc061SDimitry Andric   //   get_return_value ch, glue
333ff0cc061SDimitry Andric   //
3347d523365SDimitry Andric   // get_return_value can either be a sequence of CopyFromReg instructions
3357d523365SDimitry Andric   // to grab the return value from the return register(s), or it can be a LOAD
3367d523365SDimitry Andric   // to load a value returned by reference via a stack slot.
337ff0cc061SDimitry Andric 
3383ca95b02SDimitry Andric   bool HasDef = !SI.CLI.RetTy->isVoidTy();
3397d523365SDimitry Andric   if (HasDef) {
3407d523365SDimitry Andric     if (CallEnd->getOpcode() == ISD::LOAD)
341ff0cc061SDimitry Andric       CallEnd = CallEnd->getOperand(0).getNode();
3427d523365SDimitry Andric     else
3437d523365SDimitry Andric       while (CallEnd->getOpcode() == ISD::CopyFromReg)
3447d523365SDimitry Andric         CallEnd = CallEnd->getOperand(0).getNode();
3457d523365SDimitry Andric   }
346ff0cc061SDimitry Andric 
347ff0cc061SDimitry Andric   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
3483ca95b02SDimitry Andric   return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
34939d628a0SDimitry Andric }
35039d628a0SDimitry Andric 
35139d628a0SDimitry Andric /// Spill a value incoming to the statepoint. It might be either part of
35239d628a0SDimitry Andric /// vmstate
35339d628a0SDimitry Andric /// or gcstate. In both cases unconditionally spill it on the stack unless it
35439d628a0SDimitry Andric /// is a null constant. Return pair with first element being frame index
35539d628a0SDimitry Andric /// containing saved value and second element with outgoing chain from the
35639d628a0SDimitry Andric /// emitted store
35739d628a0SDimitry Andric static std::pair<SDValue, SDValue>
35839d628a0SDimitry Andric spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
35939d628a0SDimitry Andric                              SelectionDAGBuilder &Builder) {
36039d628a0SDimitry Andric   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
36139d628a0SDimitry Andric 
36239d628a0SDimitry Andric   // Emit new store if we didn't do it for this ptr before
36339d628a0SDimitry Andric   if (!Loc.getNode()) {
36439d628a0SDimitry Andric     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
36539d628a0SDimitry Andric                                                        Builder);
36639d628a0SDimitry Andric     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
36739d628a0SDimitry Andric     // We use TargetFrameIndex so that isel will not select it into LEA
368f37b6182SDimitry Andric     Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
36939d628a0SDimitry Andric 
37039d628a0SDimitry Andric     // TODO: We can create TokenFactor node instead of
37139d628a0SDimitry Andric     //       chaining stores one after another, this may allow
37239d628a0SDimitry Andric     //       a bit more optimal scheduling for them
3733ca95b02SDimitry Andric 
3743ca95b02SDimitry Andric #ifndef NDEBUG
3753ca95b02SDimitry Andric     // Right now we always allocate spill slots that are of the same
3763ca95b02SDimitry Andric     // size as the value we're about to spill (the size of spillee can
3773ca95b02SDimitry Andric     // vary since we spill vectors of pointers too).  At some point we
3783ca95b02SDimitry Andric     // can consider allowing spills of smaller values to larger slots
3793ca95b02SDimitry Andric     // (i.e. change the '==' in the assert below to a '>=').
380d88c1a5aSDimitry Andric     MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
381d88c1a5aSDimitry Andric     assert((MFI.getObjectSize(Index) * 8) == Incoming.getValueSizeInBits() &&
3823ca95b02SDimitry Andric            "Bad spill:  stack slot does not match!");
3833ca95b02SDimitry Andric #endif
3843ca95b02SDimitry Andric 
38539d628a0SDimitry Andric     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
3867d523365SDimitry Andric                                  MachinePointerInfo::getFixedStack(
3873ca95b02SDimitry Andric                                      Builder.DAG.getMachineFunction(), Index));
38839d628a0SDimitry Andric 
38939d628a0SDimitry Andric     Builder.StatepointLowering.setLocation(Incoming, Loc);
39039d628a0SDimitry Andric   }
39139d628a0SDimitry Andric 
39239d628a0SDimitry Andric   assert(Loc.getNode());
39339d628a0SDimitry Andric   return std::make_pair(Loc, Chain);
39439d628a0SDimitry Andric }
39539d628a0SDimitry Andric 
39639d628a0SDimitry Andric /// Lower a single value incoming to a statepoint node.  This value can be
39739d628a0SDimitry Andric /// either a deopt value or a gc value, the handling is the same.  We special
39839d628a0SDimitry Andric /// case constants and allocas, then fall back to spilling if required.
399d88c1a5aSDimitry Andric static void lowerIncomingStatepointValue(SDValue Incoming, bool LiveInOnly,
40039d628a0SDimitry Andric                                          SmallVectorImpl<SDValue> &Ops,
40139d628a0SDimitry Andric                                          SelectionDAGBuilder &Builder) {
40239d628a0SDimitry Andric   SDValue Chain = Builder.getRoot();
40339d628a0SDimitry Andric 
40439d628a0SDimitry Andric   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
40539d628a0SDimitry Andric     // If the original value was a constant, make sure it gets recorded as
40639d628a0SDimitry Andric     // such in the stackmap.  This is required so that the consumer can
40739d628a0SDimitry Andric     // parse any internal format to the deopt state.  It also handles null
408444ed5c5SDimitry Andric     // pointers and other constant pointers in GC states.  Note the constant
409444ed5c5SDimitry Andric     // vectors do not appear to actually hit this path and that anything larger
410444ed5c5SDimitry Andric     // than an i64 value (not type!) will fail asserts here.
411ff0cc061SDimitry Andric     pushStackMapConstant(Ops, Builder, C->getSExtValue());
41239d628a0SDimitry Andric   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
413ff0cc061SDimitry Andric     // This handles allocas as arguments to the statepoint (this is only
414ff0cc061SDimitry Andric     // really meaningful for a deopt value.  For GC, we'd be trying to
415ff0cc061SDimitry Andric     // relocate the address of the alloca itself?)
416f37b6182SDimitry Andric     assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
417f37b6182SDimitry Andric            "Incoming value is a frame index!");
418ff0cc061SDimitry Andric     Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
419f37b6182SDimitry Andric                                                   Builder.getFrameIndexTy()));
420d88c1a5aSDimitry Andric   } else if (LiveInOnly) {
421d88c1a5aSDimitry Andric     // If this value is live in (not live-on-return, or live-through), we can
422d88c1a5aSDimitry Andric     // treat it the same way patchpoint treats it's "live in" values.  We'll
423d88c1a5aSDimitry Andric     // end up folding some of these into stack references, but they'll be
424d88c1a5aSDimitry Andric     // handled by the register allocator.  Note that we do not have the notion
425d88c1a5aSDimitry Andric     // of a late use so these values might be placed in registers which are
426d88c1a5aSDimitry Andric     // clobbered by the call.  This is fine for live-in.
427d88c1a5aSDimitry Andric     Ops.push_back(Incoming);
42839d628a0SDimitry Andric   } else {
42939d628a0SDimitry Andric     // Otherwise, locate a spill slot and explicitly spill it so it
43039d628a0SDimitry Andric     // can be found by the runtime later.  We currently do not support
43139d628a0SDimitry Andric     // tracking values through callee saved registers to their eventual
43239d628a0SDimitry Andric     // spill location.  This would be a useful optimization, but would
43339d628a0SDimitry Andric     // need to be optional since it requires a lot of complexity on the
43439d628a0SDimitry Andric     // runtime side which not all would support.
4353ca95b02SDimitry Andric     auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
43639d628a0SDimitry Andric     Ops.push_back(Res.first);
43739d628a0SDimitry Andric     Chain = Res.second;
43839d628a0SDimitry Andric   }
43939d628a0SDimitry Andric 
44039d628a0SDimitry Andric   Builder.DAG.setRoot(Chain);
44139d628a0SDimitry Andric }
44239d628a0SDimitry Andric 
44339d628a0SDimitry Andric /// Lower deopt state and gc pointer arguments of the statepoint.  The actual
44439d628a0SDimitry Andric /// lowering is described in lowerIncomingStatepointValue.  This function is
44539d628a0SDimitry Andric /// responsible for lowering everything in the right position and playing some
44639d628a0SDimitry Andric /// tricks to avoid redundant stack manipulation where possible.  On
44739d628a0SDimitry Andric /// completion, 'Ops' will contain ready to use operands for machine code
44839d628a0SDimitry Andric /// statepoint. The chain nodes will have already been created and the DAG root
44939d628a0SDimitry Andric /// will be set to the last value spilled (if any were).
4503ca95b02SDimitry Andric static void
4513ca95b02SDimitry Andric lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
4523ca95b02SDimitry Andric                         SelectionDAGBuilder::StatepointLoweringInfo &SI,
45339d628a0SDimitry Andric                         SelectionDAGBuilder &Builder) {
4543ca95b02SDimitry Andric   // Lower the deopt and gc arguments for this statepoint.  Layout will be:
4553ca95b02SDimitry Andric   // deopt argument length, deopt arguments.., gc arguments...
45639d628a0SDimitry Andric #ifndef NDEBUG
4573ca95b02SDimitry Andric   if (auto *GFI = Builder.GFI) {
45839d628a0SDimitry Andric     // Check that each of the gc pointer and bases we've gotten out of the
459444ed5c5SDimitry Andric     // safepoint is something the strategy thinks might be a pointer (or vector
460444ed5c5SDimitry Andric     // of pointers) into the GC heap.  This is basically just here to help catch
461444ed5c5SDimitry Andric     // errors during statepoint insertion. TODO: This should actually be in the
462444ed5c5SDimitry Andric     // Verifier, but we can't get to the GCStrategy from there (yet).
4633ca95b02SDimitry Andric     GCStrategy &S = GFI->getStrategy();
4643ca95b02SDimitry Andric     for (const Value *V : SI.Bases) {
465444ed5c5SDimitry Andric       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
46639d628a0SDimitry Andric       if (Opt.hasValue()) {
46739d628a0SDimitry Andric         assert(Opt.getValue() &&
46839d628a0SDimitry Andric                "non gc managed base pointer found in statepoint");
46939d628a0SDimitry Andric       }
47039d628a0SDimitry Andric     }
4713ca95b02SDimitry Andric     for (const Value *V : SI.Ptrs) {
472444ed5c5SDimitry Andric       auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
47339d628a0SDimitry Andric       if (Opt.hasValue()) {
47439d628a0SDimitry Andric         assert(Opt.getValue() &&
47539d628a0SDimitry Andric                "non gc managed derived pointer found in statepoint");
47639d628a0SDimitry Andric       }
47739d628a0SDimitry Andric     }
478d88c1a5aSDimitry Andric     assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");
4793ca95b02SDimitry Andric   } else {
4803ca95b02SDimitry Andric     assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
4813ca95b02SDimitry Andric     assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
48239d628a0SDimitry Andric   }
48339d628a0SDimitry Andric #endif
48439d628a0SDimitry Andric 
485d88c1a5aSDimitry Andric   // Figure out what lowering strategy we're going to use for each part
486d88c1a5aSDimitry Andric   // Note: Is is conservatively correct to lower both "live-in" and "live-out"
487d88c1a5aSDimitry Andric   // as "live-through". A "live-through" variable is one which is "live-in",
488d88c1a5aSDimitry Andric   // "live-out", and live throughout the lifetime of the call (i.e. we can find
489d88c1a5aSDimitry Andric   // it from any PC within the transitive callee of the statepoint).  In
490d88c1a5aSDimitry Andric   // particular, if the callee spills callee preserved registers we may not
491d88c1a5aSDimitry Andric   // be able to find a value placed in that register during the call.  This is
492d88c1a5aSDimitry Andric   // fine for live-out, but not for live-through.  If we were willing to make
493d88c1a5aSDimitry Andric   // assumptions about the code generator producing the callee, we could
494d88c1a5aSDimitry Andric   // potentially allow live-through values in callee saved registers.
495d88c1a5aSDimitry Andric   const bool LiveInDeopt =
496d88c1a5aSDimitry Andric     SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
497d88c1a5aSDimitry Andric 
498d88c1a5aSDimitry Andric   auto isGCValue =[&](const Value *V) {
499d88c1a5aSDimitry Andric     return is_contained(SI.Ptrs, V) || is_contained(SI.Bases, V);
500d88c1a5aSDimitry Andric   };
501d88c1a5aSDimitry Andric 
50239d628a0SDimitry Andric   // Before we actually start lowering (and allocating spill slots for values),
50339d628a0SDimitry Andric   // reserve any stack slots which we judge to be profitable to reuse for a
50439d628a0SDimitry Andric   // particular value.  This is purely an optimization over the code below and
50539d628a0SDimitry Andric   // doesn't change semantics at all.  It is important for performance that we
50639d628a0SDimitry Andric   // reserve slots for both deopt and gc values before lowering either.
5073ca95b02SDimitry Andric   for (const Value *V : SI.DeoptState) {
508d88c1a5aSDimitry Andric     if (!LiveInDeopt || isGCValue(V))
5098f0fd8f6SDimitry Andric       reservePreviousStackSlotForValue(V, Builder);
51039d628a0SDimitry Andric   }
5113ca95b02SDimitry Andric   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
5123ca95b02SDimitry Andric     reservePreviousStackSlotForValue(SI.Bases[i], Builder);
5133ca95b02SDimitry Andric     reservePreviousStackSlotForValue(SI.Ptrs[i], Builder);
51439d628a0SDimitry Andric   }
51539d628a0SDimitry Andric 
51639d628a0SDimitry Andric   // First, prefix the list with the number of unique values to be
51739d628a0SDimitry Andric   // lowered.  Note that this is the number of *Values* not the
51839d628a0SDimitry Andric   // number of SDValues required to lower them.
5193ca95b02SDimitry Andric   const int NumVMSArgs = SI.DeoptState.size();
520ff0cc061SDimitry Andric   pushStackMapConstant(Ops, Builder, NumVMSArgs);
52139d628a0SDimitry Andric 
5223ca95b02SDimitry Andric   // The vm state arguments are lowered in an opaque manner.  We do not know
5233ca95b02SDimitry Andric   // what type of values are contained within.
5243ca95b02SDimitry Andric   for (const Value *V : SI.DeoptState) {
52539d628a0SDimitry Andric     SDValue Incoming = Builder.getValue(V);
526d88c1a5aSDimitry Andric     const bool LiveInValue = LiveInDeopt && !isGCValue(V);
527d88c1a5aSDimitry Andric     lowerIncomingStatepointValue(Incoming, LiveInValue, Ops, Builder);
52839d628a0SDimitry Andric   }
52939d628a0SDimitry Andric 
53039d628a0SDimitry Andric   // Finally, go ahead and lower all the gc arguments.  There's no prefixed
53139d628a0SDimitry Andric   // length for this one.  After lowering, we'll have the base and pointer
53239d628a0SDimitry Andric   // arrays interwoven with each (lowered) base pointer immediately followed by
53339d628a0SDimitry Andric   // it's (lowered) derived pointer.  i.e
53439d628a0SDimitry Andric   // (base[0], ptr[0], base[1], ptr[1], ...)
5353ca95b02SDimitry Andric   for (unsigned i = 0; i < SI.Bases.size(); ++i) {
5363ca95b02SDimitry Andric     const Value *Base = SI.Bases[i];
537d88c1a5aSDimitry Andric     lowerIncomingStatepointValue(Builder.getValue(Base), /*LiveInOnly*/ false,
538d88c1a5aSDimitry Andric                                  Ops, Builder);
539ff0cc061SDimitry Andric 
5403ca95b02SDimitry Andric     const Value *Ptr = SI.Ptrs[i];
541d88c1a5aSDimitry Andric     lowerIncomingStatepointValue(Builder.getValue(Ptr), /*LiveInOnly*/ false,
542d88c1a5aSDimitry Andric                                  Ops, Builder);
543ff0cc061SDimitry Andric   }
544ff0cc061SDimitry Andric 
545ff0cc061SDimitry Andric   // If there are any explicit spill slots passed to the statepoint, record
546ff0cc061SDimitry Andric   // them, but otherwise do not do anything special.  These are user provided
547ff0cc061SDimitry Andric   // allocas and give control over placement to the consumer.  In this case,
548ff0cc061SDimitry Andric   // it is the contents of the slot which may get updated, not the pointer to
549ff0cc061SDimitry Andric   // the alloca
5503ca95b02SDimitry Andric   for (Value *V : SI.GCArgs) {
55139d628a0SDimitry Andric     SDValue Incoming = Builder.getValue(V);
552ff0cc061SDimitry Andric     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
553ff0cc061SDimitry Andric       // This handles allocas as arguments to the statepoint
554f37b6182SDimitry Andric       assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
555f37b6182SDimitry Andric              "Incoming value is a frame index!");
556ff0cc061SDimitry Andric       Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
557f37b6182SDimitry Andric                                                     Builder.getFrameIndexTy()));
55839d628a0SDimitry Andric     }
55939d628a0SDimitry Andric   }
560ff0cc061SDimitry Andric 
561ff0cc061SDimitry Andric   // Record computed locations for all lowered values.
562ff0cc061SDimitry Andric   // This can not be embedded in lowering loops as we need to record *all*
563ff0cc061SDimitry Andric   // values, while previous loops account only values with unique SDValues.
5643ca95b02SDimitry Andric   const Instruction *StatepointInstr = SI.StatepointInstr;
5653ca95b02SDimitry Andric   auto &SpillMap = Builder.FuncInfo.StatepointSpillMaps[StatepointInstr];
566ff0cc061SDimitry Andric 
5673ca95b02SDimitry Andric   for (const GCRelocateInst *Relocate : SI.GCRelocates) {
5684d0b32cdSDimitry Andric     const Value *V = Relocate->getDerivedPtr();
569ff0cc061SDimitry Andric     SDValue SDV = Builder.getValue(V);
570ff0cc061SDimitry Andric     SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
571ff0cc061SDimitry Andric 
572ff0cc061SDimitry Andric     if (Loc.getNode()) {
5733ca95b02SDimitry Andric       SpillMap.SlotMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
574ff0cc061SDimitry Andric     } else {
575ff0cc061SDimitry Andric       // Record value as visited, but not spilled. This is case for allocas
5767d523365SDimitry Andric       // and constants. For this values we can avoid emitting spill load while
577ff0cc061SDimitry Andric       // visiting corresponding gc_relocate.
578ff0cc061SDimitry Andric       // Actually we do not need to record them in this map at all.
5797d523365SDimitry Andric       // We do this only to check that we are not relocating any unvisited
5807d523365SDimitry Andric       // value.
5813ca95b02SDimitry Andric       SpillMap.SlotMap[V] = None;
582ff0cc061SDimitry Andric 
583ff0cc061SDimitry Andric       // Default llvm mechanisms for exporting values which are used in
584ff0cc061SDimitry Andric       // different basic blocks does not work for gc relocates.
585ff0cc061SDimitry Andric       // Note that it would be incorrect to teach llvm that all relocates are
5867d523365SDimitry Andric       // uses of the corresponding values so that it would automatically
587ff0cc061SDimitry Andric       // export them. Relocates of the spilled values does not use original
588ff0cc061SDimitry Andric       // value.
5894d0b32cdSDimitry Andric       if (Relocate->getParent() != StatepointInstr->getParent())
590ff0cc061SDimitry Andric         Builder.ExportFromCurrentBlock(V);
591ff0cc061SDimitry Andric     }
592ff0cc061SDimitry Andric   }
593ff0cc061SDimitry Andric }
594ff0cc061SDimitry Andric 
5953ca95b02SDimitry Andric SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
5963ca95b02SDimitry Andric     SelectionDAGBuilder::StatepointLoweringInfo &SI) {
59739d628a0SDimitry Andric   // The basic scheme here is that information about both the original call and
59839d628a0SDimitry Andric   // the safepoint is encoded in the CallInst.  We create a temporary call and
59939d628a0SDimitry Andric   // lower it, then reverse engineer the calling sequence.
60039d628a0SDimitry Andric 
60139d628a0SDimitry Andric   NumOfStatepoints++;
60239d628a0SDimitry Andric   // Clear state
60339d628a0SDimitry Andric   StatepointLowering.startNewStatepoint(*this);
60439d628a0SDimitry Andric 
60539d628a0SDimitry Andric #ifndef NDEBUG
6063ca95b02SDimitry Andric   // We schedule gc relocates before removeDuplicateGCPtrs since we _will_
6073ca95b02SDimitry Andric   // encounter the duplicate gc relocates we elide in removeDuplicateGCPtrs.
6083ca95b02SDimitry Andric   for (auto *Reloc : SI.GCRelocates)
6093ca95b02SDimitry Andric     if (Reloc->getParent() == SI.StatepointInstr->getParent())
6103ca95b02SDimitry Andric       StatepointLowering.scheduleRelocCall(*Reloc);
61139d628a0SDimitry Andric #endif
61239d628a0SDimitry Andric 
6133ca95b02SDimitry Andric   // Remove any redundant llvm::Values which map to the same SDValue as another
6143ca95b02SDimitry Andric   // input.  Also has the effect of removing duplicates in the original
6153ca95b02SDimitry Andric   // llvm::Value input list as well.  This is a useful optimization for
6163ca95b02SDimitry Andric   // reducing the size of the StackMap section.  It has no other impact.
6173ca95b02SDimitry Andric   removeDuplicateGCPtrs(SI.Bases, SI.Ptrs, SI.GCRelocates, *this,
6183ca95b02SDimitry Andric                         FuncInfo.StatepointSpillMaps[SI.StatepointInstr]);
6193ca95b02SDimitry Andric   assert(SI.Bases.size() == SI.Ptrs.size() &&
6203ca95b02SDimitry Andric          SI.Ptrs.size() == SI.GCRelocates.size());
62139d628a0SDimitry Andric 
62239d628a0SDimitry Andric   // Lower statepoint vmstate and gcstate arguments
623ff0cc061SDimitry Andric   SmallVector<SDValue, 10> LoweredMetaArgs;
6243ca95b02SDimitry Andric   lowerStatepointMetaArgs(LoweredMetaArgs, SI, *this);
6253ca95b02SDimitry Andric 
6263ca95b02SDimitry Andric   // Now that we've emitted the spills, we need to update the root so that the
6273ca95b02SDimitry Andric   // call sequence is ordered correctly.
6283ca95b02SDimitry Andric   SI.CLI.setChain(getRoot());
62939d628a0SDimitry Andric 
63039d628a0SDimitry Andric   // Get call node, we will replace it later with statepoint
6313ca95b02SDimitry Andric   SDValue ReturnVal;
6323ca95b02SDimitry Andric   SDNode *CallNode;
6333ca95b02SDimitry Andric   std::tie(ReturnVal, CallNode) =
6343ca95b02SDimitry Andric       lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
63539d628a0SDimitry Andric 
636ff0cc061SDimitry Andric   // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
637ff0cc061SDimitry Andric   // nodes with all the appropriate arguments and return values.
638ff0cc061SDimitry Andric 
639ff0cc061SDimitry Andric   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
640ff0cc061SDimitry Andric   SDValue Chain = CallNode->getOperand(0);
641ff0cc061SDimitry Andric 
642ff0cc061SDimitry Andric   SDValue Glue;
643ff0cc061SDimitry Andric   bool CallHasIncomingGlue = CallNode->getGluedNode();
644ff0cc061SDimitry Andric   if (CallHasIncomingGlue) {
645ff0cc061SDimitry Andric     // Glue is always last operand
646ff0cc061SDimitry Andric     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
647ff0cc061SDimitry Andric   }
648ff0cc061SDimitry Andric 
649ff0cc061SDimitry Andric   // Build the GC_TRANSITION_START node if necessary.
650ff0cc061SDimitry Andric   //
651ff0cc061SDimitry Andric   // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
652ff0cc061SDimitry Andric   // order in which they appear in the call to the statepoint intrinsic. If
653ff0cc061SDimitry Andric   // any of the operands is a pointer-typed, that operand is immediately
654ff0cc061SDimitry Andric   // followed by a SRCVALUE for the pointer that may be used during lowering
655ff0cc061SDimitry Andric   // (e.g. to form MachinePointerInfo values for loads/stores).
656ff0cc061SDimitry Andric   const bool IsGCTransition =
6573ca95b02SDimitry Andric       (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
658ff0cc061SDimitry Andric       (uint64_t)StatepointFlags::GCTransition;
659ff0cc061SDimitry Andric   if (IsGCTransition) {
660ff0cc061SDimitry Andric     SmallVector<SDValue, 8> TSOps;
661ff0cc061SDimitry Andric 
662ff0cc061SDimitry Andric     // Add chain
663ff0cc061SDimitry Andric     TSOps.push_back(Chain);
664ff0cc061SDimitry Andric 
665ff0cc061SDimitry Andric     // Add GC transition arguments
6663ca95b02SDimitry Andric     for (const Value *V : SI.GCTransitionArgs) {
667ff0cc061SDimitry Andric       TSOps.push_back(getValue(V));
668ff0cc061SDimitry Andric       if (V->getType()->isPointerTy())
669ff0cc061SDimitry Andric         TSOps.push_back(DAG.getSrcValue(V));
670ff0cc061SDimitry Andric     }
671ff0cc061SDimitry Andric 
672ff0cc061SDimitry Andric     // Add glue if necessary
673ff0cc061SDimitry Andric     if (CallHasIncomingGlue)
674ff0cc061SDimitry Andric       TSOps.push_back(Glue);
675ff0cc061SDimitry Andric 
676ff0cc061SDimitry Andric     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
677ff0cc061SDimitry Andric 
678ff0cc061SDimitry Andric     SDValue GCTransitionStart =
679ff0cc061SDimitry Andric         DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
680ff0cc061SDimitry Andric 
681ff0cc061SDimitry Andric     Chain = GCTransitionStart.getValue(0);
682ff0cc061SDimitry Andric     Glue = GCTransitionStart.getValue(1);
683ff0cc061SDimitry Andric   }
68439d628a0SDimitry Andric 
68539d628a0SDimitry Andric   // TODO: Currently, all of these operands are being marked as read/write in
68639d628a0SDimitry Andric   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
68739d628a0SDimitry Andric   // and flags to be read-only.
68839d628a0SDimitry Andric   SmallVector<SDValue, 40> Ops;
68939d628a0SDimitry Andric 
690ff0cc061SDimitry Andric   // Add the <id> and <numBytes> constants.
6913ca95b02SDimitry Andric   Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
692ff0cc061SDimitry Andric   Ops.push_back(
6933ca95b02SDimitry Andric       DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
694ff0cc061SDimitry Andric 
69539d628a0SDimitry Andric   // Calculate and push starting position of vmstate arguments
69639d628a0SDimitry Andric   // Get number of arguments incoming directly into call node
69739d628a0SDimitry Andric   unsigned NumCallRegArgs =
698ff0cc061SDimitry Andric       CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
699ff0cc061SDimitry Andric   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
70039d628a0SDimitry Andric 
70139d628a0SDimitry Andric   // Add call target
70239d628a0SDimitry Andric   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
70339d628a0SDimitry Andric   Ops.push_back(CallTarget);
70439d628a0SDimitry Andric 
70539d628a0SDimitry Andric   // Add call arguments
70639d628a0SDimitry Andric   // Get position of register mask in the call
70739d628a0SDimitry Andric   SDNode::op_iterator RegMaskIt;
708ff0cc061SDimitry Andric   if (CallHasIncomingGlue)
70939d628a0SDimitry Andric     RegMaskIt = CallNode->op_end() - 2;
71039d628a0SDimitry Andric   else
71139d628a0SDimitry Andric     RegMaskIt = CallNode->op_end() - 1;
71239d628a0SDimitry Andric   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
71339d628a0SDimitry Andric 
714ff0cc061SDimitry Andric   // Add a constant argument for the calling convention
7153ca95b02SDimitry Andric   pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
716ff0cc061SDimitry Andric 
717ff0cc061SDimitry Andric   // Add a constant argument for the flags
7183ca95b02SDimitry Andric   uint64_t Flags = SI.StatepointFlags;
7193ca95b02SDimitry Andric   assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
7203ca95b02SDimitry Andric          "Unknown flag used");
721ff0cc061SDimitry Andric   pushStackMapConstant(Ops, *this, Flags);
72239d628a0SDimitry Andric 
72339d628a0SDimitry Andric   // Insert all vmstate and gcstate arguments
724ff0cc061SDimitry Andric   Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
72539d628a0SDimitry Andric 
72639d628a0SDimitry Andric   // Add register mask from call node
72739d628a0SDimitry Andric   Ops.push_back(*RegMaskIt);
72839d628a0SDimitry Andric 
72939d628a0SDimitry Andric   // Add chain
730ff0cc061SDimitry Andric   Ops.push_back(Chain);
73139d628a0SDimitry Andric 
73239d628a0SDimitry Andric   // Same for the glue, but we add it only if original call had it
73339d628a0SDimitry Andric   if (Glue.getNode())
73439d628a0SDimitry Andric     Ops.push_back(Glue);
73539d628a0SDimitry Andric 
736ff0cc061SDimitry Andric   // Compute return values.  Provide a glue output since we consume one as
737ff0cc061SDimitry Andric   // input.  This allows someone else to chain off us as needed.
738ff0cc061SDimitry Andric   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
73939d628a0SDimitry Andric 
740ff0cc061SDimitry Andric   SDNode *StatepointMCNode =
741ff0cc061SDimitry Andric       DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
742ff0cc061SDimitry Andric 
743ff0cc061SDimitry Andric   SDNode *SinkNode = StatepointMCNode;
744ff0cc061SDimitry Andric 
745ff0cc061SDimitry Andric   // Build the GC_TRANSITION_END node if necessary.
746ff0cc061SDimitry Andric   //
747ff0cc061SDimitry Andric   // See the comment above regarding GC_TRANSITION_START for the layout of
748ff0cc061SDimitry Andric   // the operands to the GC_TRANSITION_END node.
749ff0cc061SDimitry Andric   if (IsGCTransition) {
750ff0cc061SDimitry Andric     SmallVector<SDValue, 8> TEOps;
751ff0cc061SDimitry Andric 
752ff0cc061SDimitry Andric     // Add chain
753ff0cc061SDimitry Andric     TEOps.push_back(SDValue(StatepointMCNode, 0));
754ff0cc061SDimitry Andric 
755ff0cc061SDimitry Andric     // Add GC transition arguments
7563ca95b02SDimitry Andric     for (const Value *V : SI.GCTransitionArgs) {
757ff0cc061SDimitry Andric       TEOps.push_back(getValue(V));
758ff0cc061SDimitry Andric       if (V->getType()->isPointerTy())
759ff0cc061SDimitry Andric         TEOps.push_back(DAG.getSrcValue(V));
760ff0cc061SDimitry Andric     }
761ff0cc061SDimitry Andric 
762ff0cc061SDimitry Andric     // Add glue
763ff0cc061SDimitry Andric     TEOps.push_back(SDValue(StatepointMCNode, 1));
764ff0cc061SDimitry Andric 
765ff0cc061SDimitry Andric     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
766ff0cc061SDimitry Andric 
767ff0cc061SDimitry Andric     SDValue GCTransitionStart =
768ff0cc061SDimitry Andric         DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
769ff0cc061SDimitry Andric 
770ff0cc061SDimitry Andric     SinkNode = GCTransitionStart.getNode();
771ff0cc061SDimitry Andric   }
77239d628a0SDimitry Andric 
77339d628a0SDimitry Andric   // Replace original call
774ff0cc061SDimitry Andric   DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
7757d523365SDimitry Andric   // Remove original call node
77639d628a0SDimitry Andric   DAG.DeleteNode(CallNode);
77739d628a0SDimitry Andric 
77839d628a0SDimitry Andric   // DON'T set the root - under the assumption that it's already set past the
77939d628a0SDimitry Andric   // inserted node we created.
78039d628a0SDimitry Andric 
78139d628a0SDimitry Andric   // TODO: A better future implementation would be to emit a single variable
78239d628a0SDimitry Andric   // argument, variable return value STATEPOINT node here and then hookup the
78339d628a0SDimitry Andric   // return value of each gc.relocate to the respective output of the
78439d628a0SDimitry Andric   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
78539d628a0SDimitry Andric   // to actually be possible today.
7863ca95b02SDimitry Andric 
7873ca95b02SDimitry Andric   return ReturnVal;
78839d628a0SDimitry Andric }
78939d628a0SDimitry Andric 
7903ca95b02SDimitry Andric void
7913ca95b02SDimitry Andric SelectionDAGBuilder::LowerStatepoint(ImmutableStatepoint ISP,
7923ca95b02SDimitry Andric                                      const BasicBlock *EHPadBB /*= nullptr*/) {
7933ca95b02SDimitry Andric   assert(ISP.getCallSite().getCallingConv() != CallingConv::AnyReg &&
7943ca95b02SDimitry Andric          "anyregcc is not supported on statepoints!");
7953ca95b02SDimitry Andric 
7963ca95b02SDimitry Andric #ifndef NDEBUG
7973ca95b02SDimitry Andric   // If this is a malformed statepoint, report it early to simplify debugging.
7983ca95b02SDimitry Andric   // This should catch any IR level mistake that's made when constructing or
7993ca95b02SDimitry Andric   // transforming statepoints.
8003ca95b02SDimitry Andric   ISP.verify();
8013ca95b02SDimitry Andric 
8023ca95b02SDimitry Andric   // Check that the associated GCStrategy expects to encounter statepoints.
8033ca95b02SDimitry Andric   assert(GFI->getStrategy().useStatepoints() &&
8043ca95b02SDimitry Andric          "GCStrategy does not expect to encounter statepoints");
8053ca95b02SDimitry Andric #endif
8063ca95b02SDimitry Andric 
8073ca95b02SDimitry Andric   SDValue ActualCallee;
8083ca95b02SDimitry Andric 
8093ca95b02SDimitry Andric   if (ISP.getNumPatchBytes() > 0) {
8103ca95b02SDimitry Andric     // If we've been asked to emit a nop sequence instead of a call instruction
8113ca95b02SDimitry Andric     // for this statepoint then don't lower the call target, but use a constant
8123ca95b02SDimitry Andric     // `null` instead.  Not lowering the call target lets statepoint clients get
8133ca95b02SDimitry Andric     // away without providing a physical address for the symbolic call target at
8143ca95b02SDimitry Andric     // link time.
8153ca95b02SDimitry Andric 
8163ca95b02SDimitry Andric     const auto &TLI = DAG.getTargetLoweringInfo();
8173ca95b02SDimitry Andric     const auto &DL = DAG.getDataLayout();
8183ca95b02SDimitry Andric 
8193ca95b02SDimitry Andric     unsigned AS = ISP.getCalledValue()->getType()->getPointerAddressSpace();
8203ca95b02SDimitry Andric     ActualCallee = DAG.getConstant(0, getCurSDLoc(), TLI.getPointerTy(DL, AS));
8213ca95b02SDimitry Andric   } else {
8223ca95b02SDimitry Andric     ActualCallee = getValue(ISP.getCalledValue());
8233ca95b02SDimitry Andric   }
8243ca95b02SDimitry Andric 
8253ca95b02SDimitry Andric   StatepointLoweringInfo SI(DAG);
8263ca95b02SDimitry Andric   populateCallLoweringInfo(SI.CLI, ISP.getCallSite(),
8273ca95b02SDimitry Andric                            ImmutableStatepoint::CallArgsBeginPos,
8283ca95b02SDimitry Andric                            ISP.getNumCallArgs(), ActualCallee,
8293ca95b02SDimitry Andric                            ISP.getActualReturnType(), false /* IsPatchPoint */);
8303ca95b02SDimitry Andric 
8313ca95b02SDimitry Andric   for (const GCRelocateInst *Relocate : ISP.getRelocates()) {
8323ca95b02SDimitry Andric     SI.GCRelocates.push_back(Relocate);
8333ca95b02SDimitry Andric     SI.Bases.push_back(Relocate->getBasePtr());
8343ca95b02SDimitry Andric     SI.Ptrs.push_back(Relocate->getDerivedPtr());
8353ca95b02SDimitry Andric   }
8363ca95b02SDimitry Andric 
8373ca95b02SDimitry Andric   SI.GCArgs = ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
8383ca95b02SDimitry Andric   SI.StatepointInstr = ISP.getInstruction();
8393ca95b02SDimitry Andric   SI.GCTransitionArgs =
8403ca95b02SDimitry Andric       ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
8413ca95b02SDimitry Andric   SI.ID = ISP.getID();
8426d97bb29SDimitry Andric   SI.DeoptState = ArrayRef<const Use>(ISP.deopt_begin(), ISP.deopt_end());
8433ca95b02SDimitry Andric   SI.StatepointFlags = ISP.getFlags();
8443ca95b02SDimitry Andric   SI.NumPatchBytes = ISP.getNumPatchBytes();
8453ca95b02SDimitry Andric   SI.EHPadBB = EHPadBB;
8463ca95b02SDimitry Andric 
8473ca95b02SDimitry Andric   SDValue ReturnValue = LowerAsSTATEPOINT(SI);
8483ca95b02SDimitry Andric 
8493ca95b02SDimitry Andric   // Export the result value if needed
8503ca95b02SDimitry Andric   const GCResultInst *GCResult = ISP.getGCResult();
8513ca95b02SDimitry Andric   Type *RetTy = ISP.getActualReturnType();
8523ca95b02SDimitry Andric   if (!RetTy->isVoidTy() && GCResult) {
8533ca95b02SDimitry Andric     if (GCResult->getParent() != ISP.getCallSite().getParent()) {
8543ca95b02SDimitry Andric       // Result value will be used in a different basic block so we need to
8553ca95b02SDimitry Andric       // export it now.  Default exporting mechanism will not work here because
8563ca95b02SDimitry Andric       // statepoint call has a different type than the actual call. It means
8573ca95b02SDimitry Andric       // that by default llvm will create export register of the wrong type
8583ca95b02SDimitry Andric       // (always i32 in our case). So instead we need to create export register
8593ca95b02SDimitry Andric       // with correct type manually.
8603ca95b02SDimitry Andric       // TODO: To eliminate this problem we can remove gc.result intrinsics
8613ca95b02SDimitry Andric       //       completely and make statepoint call to return a tuple.
8623ca95b02SDimitry Andric       unsigned Reg = FuncInfo.CreateRegs(RetTy);
8633ca95b02SDimitry Andric       RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
864db17bf38SDimitry Andric                        DAG.getDataLayout(), Reg, RetTy, true);
8653ca95b02SDimitry Andric       SDValue Chain = DAG.getEntryNode();
8663ca95b02SDimitry Andric 
8673ca95b02SDimitry Andric       RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
8683ca95b02SDimitry Andric       PendingExports.push_back(Chain);
8693ca95b02SDimitry Andric       FuncInfo.ValueMap[ISP.getInstruction()] = Reg;
8703ca95b02SDimitry Andric     } else {
8713ca95b02SDimitry Andric       // Result value will be used in a same basic block. Don't export it or
8723ca95b02SDimitry Andric       // perform any explicit register copies.
8733ca95b02SDimitry Andric       // We'll replace the actuall call node shortly. gc_result will grab
8743ca95b02SDimitry Andric       // this value.
8753ca95b02SDimitry Andric       setValue(ISP.getInstruction(), ReturnValue);
8763ca95b02SDimitry Andric     }
8773ca95b02SDimitry Andric   } else {
8783ca95b02SDimitry Andric     // The token value is never used from here on, just generate a poison value
8793ca95b02SDimitry Andric     setValue(ISP.getInstruction(), DAG.getIntPtrConstant(-1, getCurSDLoc()));
8803ca95b02SDimitry Andric   }
8813ca95b02SDimitry Andric }
8823ca95b02SDimitry Andric 
8833ca95b02SDimitry Andric void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
8843ca95b02SDimitry Andric     ImmutableCallSite CS, SDValue Callee, const BasicBlock *EHPadBB,
8853ca95b02SDimitry Andric     bool VarArgDisallowed, bool ForceVoidReturnTy) {
8863ca95b02SDimitry Andric   StatepointLoweringInfo SI(DAG);
8873ca95b02SDimitry Andric   unsigned ArgBeginIndex = CS.arg_begin() - CS.getInstruction()->op_begin();
8883ca95b02SDimitry Andric   populateCallLoweringInfo(
8893ca95b02SDimitry Andric       SI.CLI, CS, ArgBeginIndex, CS.getNumArgOperands(), Callee,
8903ca95b02SDimitry Andric       ForceVoidReturnTy ? Type::getVoidTy(*DAG.getContext()) : CS.getType(),
8913ca95b02SDimitry Andric       false);
8923ca95b02SDimitry Andric   if (!VarArgDisallowed)
8933ca95b02SDimitry Andric     SI.CLI.IsVarArg = CS.getFunctionType()->isVarArg();
8943ca95b02SDimitry Andric 
8953ca95b02SDimitry Andric   auto DeoptBundle = *CS.getOperandBundle(LLVMContext::OB_deopt);
8963ca95b02SDimitry Andric 
8973ca95b02SDimitry Andric   unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
8983ca95b02SDimitry Andric 
8993ca95b02SDimitry Andric   auto SD = parseStatepointDirectivesFromAttrs(CS.getAttributes());
9003ca95b02SDimitry Andric   SI.ID = SD.StatepointID.getValueOr(DefaultID);
9013ca95b02SDimitry Andric   SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
9023ca95b02SDimitry Andric 
9033ca95b02SDimitry Andric   SI.DeoptState =
9043ca95b02SDimitry Andric       ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
9053ca95b02SDimitry Andric   SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
9063ca95b02SDimitry Andric   SI.EHPadBB = EHPadBB;
9073ca95b02SDimitry Andric 
9083ca95b02SDimitry Andric   // NB! The GC arguments are deliberately left empty.
9093ca95b02SDimitry Andric 
9103ca95b02SDimitry Andric   if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
9113ca95b02SDimitry Andric     const Instruction *Inst = CS.getInstruction();
9123ca95b02SDimitry Andric     ReturnVal = lowerRangeToAssertZExt(DAG, *Inst, ReturnVal);
9133ca95b02SDimitry Andric     setValue(Inst, ReturnVal);
9143ca95b02SDimitry Andric   }
9153ca95b02SDimitry Andric }
9163ca95b02SDimitry Andric 
9173ca95b02SDimitry Andric void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
9183ca95b02SDimitry Andric     ImmutableCallSite CS, SDValue Callee, const BasicBlock *EHPadBB) {
9193ca95b02SDimitry Andric   LowerCallSiteWithDeoptBundleImpl(CS, Callee, EHPadBB,
9203ca95b02SDimitry Andric                                    /* VarArgDisallowed = */ false,
9213ca95b02SDimitry Andric                                    /* ForceVoidReturnTy  = */ false);
9223ca95b02SDimitry Andric }
9233ca95b02SDimitry Andric 
9243ca95b02SDimitry Andric void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
92539d628a0SDimitry Andric   // The result value of the gc_result is simply the result of the actual
92639d628a0SDimitry Andric   // call.  We've already emitted this, so just grab the value.
9273ca95b02SDimitry Andric   const Instruction *I = CI.getStatepoint();
92839d628a0SDimitry Andric 
9297d523365SDimitry Andric   if (I->getParent() != CI.getParent()) {
9307d523365SDimitry Andric     // Statepoint is in different basic block so we should have stored call
9317d523365SDimitry Andric     // result in a virtual register.
932ff0cc061SDimitry Andric     // We can not use default getValue() functionality to copy value from this
9333ca95b02SDimitry Andric     // register because statepoint and actual call return types can be
934ff0cc061SDimitry Andric     // different, and getValue() will use CopyFromReg of the wrong type,
935ff0cc061SDimitry Andric     // which is always i32 in our case.
9363dac3a9bSDimitry Andric     PointerType *CalleeType = cast<PointerType>(
9373dac3a9bSDimitry Andric         ImmutableStatepoint(I).getCalledValue()->getType());
938ff0cc061SDimitry Andric     Type *RetTy =
939ff0cc061SDimitry Andric         cast<FunctionType>(CalleeType->getElementType())->getReturnType();
940ff0cc061SDimitry Andric     SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
941ff0cc061SDimitry Andric 
942ff0cc061SDimitry Andric     assert(CopyFromReg.getNode());
943ff0cc061SDimitry Andric     setValue(&CI, CopyFromReg);
944ff0cc061SDimitry Andric   } else {
94539d628a0SDimitry Andric     setValue(&CI, getValue(I));
94639d628a0SDimitry Andric   }
947ff0cc061SDimitry Andric }
94839d628a0SDimitry Andric 
9494d0b32cdSDimitry Andric void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
95039d628a0SDimitry Andric #ifndef NDEBUG
95139d628a0SDimitry Andric   // Consistency check
952d88c1a5aSDimitry Andric   // We skip this check for relocates not in the same basic block as their
9537d523365SDimitry Andric   // statepoint. It would be too expensive to preserve validation info through
9547d523365SDimitry Andric   // different basic blocks.
9553ca95b02SDimitry Andric   if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
9564d0b32cdSDimitry Andric     StatepointLowering.relocCallVisited(Relocate);
9573ca95b02SDimitry Andric 
9583ca95b02SDimitry Andric   auto *Ty = Relocate.getType()->getScalarType();
9593ca95b02SDimitry Andric   if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
9603ca95b02SDimitry Andric     assert(*IsManaged && "Non gc managed pointer relocated!");
96139d628a0SDimitry Andric #endif
96239d628a0SDimitry Andric 
9634d0b32cdSDimitry Andric   const Value *DerivedPtr = Relocate.getDerivedPtr();
964ff0cc061SDimitry Andric   SDValue SD = getValue(DerivedPtr);
96539d628a0SDimitry Andric 
9663ca95b02SDimitry Andric   auto &SpillMap = FuncInfo.StatepointSpillMaps[Relocate.getStatepoint()];
9673ca95b02SDimitry Andric   auto SlotIt = SpillMap.find(DerivedPtr);
9683ca95b02SDimitry Andric   assert(SlotIt != SpillMap.end() && "Relocating not lowered gc value");
9693ca95b02SDimitry Andric   Optional<int> DerivedPtrLocation = SlotIt->second;
970ff0cc061SDimitry Andric 
97139d628a0SDimitry Andric   // We didn't need to spill these special cases (constants and allocas).
97239d628a0SDimitry Andric   // See the handling in spillIncomingValueForStatepoint for detail.
973ff0cc061SDimitry Andric   if (!DerivedPtrLocation) {
9744d0b32cdSDimitry Andric     setValue(&Relocate, SD);
97539d628a0SDimitry Andric     return;
97639d628a0SDimitry Andric   }
97739d628a0SDimitry Andric 
978f37b6182SDimitry Andric   SDValue SpillSlot =
979f37b6182SDimitry Andric       DAG.getTargetFrameIndex(*DerivedPtrLocation, getFrameIndexTy());
98039d628a0SDimitry Andric 
98139d628a0SDimitry Andric   // Be conservative: flush all pending loads
98239d628a0SDimitry Andric   // TODO: Probably we can be less restrictive on this,
9837d523365SDimitry Andric   // it may allow more scheduling opportunities.
98439d628a0SDimitry Andric   SDValue Chain = getRoot();
98539d628a0SDimitry Andric 
986ff0cc061SDimitry Andric   SDValue SpillLoad =
987f37b6182SDimitry Andric       DAG.getLoad(DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
988f37b6182SDimitry Andric                                                            Relocate.getType()),
989f37b6182SDimitry Andric                   getCurSDLoc(), Chain, SpillSlot,
9907d523365SDimitry Andric                   MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
9913ca95b02SDimitry Andric                                                     *DerivedPtrLocation));
99239d628a0SDimitry Andric 
99339d628a0SDimitry Andric   // Again, be conservative, don't emit pending loads
994ff0cc061SDimitry Andric   DAG.setRoot(SpillLoad.getValue(1));
99539d628a0SDimitry Andric 
996ff0cc061SDimitry Andric   assert(SpillLoad.getNode());
9974d0b32cdSDimitry Andric   setValue(&Relocate, SpillLoad);
99839d628a0SDimitry Andric }
9993ca95b02SDimitry Andric 
10003ca95b02SDimitry Andric void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
10013ca95b02SDimitry Andric   const auto &TLI = DAG.getTargetLoweringInfo();
10023ca95b02SDimitry Andric   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
10033ca95b02SDimitry Andric                                          TLI.getPointerTy(DAG.getDataLayout()));
10043ca95b02SDimitry Andric 
10053ca95b02SDimitry Andric   // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
10063ca95b02SDimitry Andric   // call.  We also do not lower the return value to any virtual register, and
10073ca95b02SDimitry Andric   // change the immediately following return to a trap instruction.
10083ca95b02SDimitry Andric   LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
10093ca95b02SDimitry Andric                                    /* VarArgDisallowed = */ true,
10103ca95b02SDimitry Andric                                    /* ForceVoidReturnTy = */ true);
10113ca95b02SDimitry Andric }
10123ca95b02SDimitry Andric 
10133ca95b02SDimitry Andric void SelectionDAGBuilder::LowerDeoptimizingReturn() {
10143ca95b02SDimitry Andric   // We do not lower the return value from llvm.deoptimize to any virtual
10153ca95b02SDimitry Andric   // register, and change the immediately following return to a trap
10163ca95b02SDimitry Andric   // instruction.
10173ca95b02SDimitry Andric   if (DAG.getTarget().Options.TrapUnreachable)
10183ca95b02SDimitry Andric     DAG.setRoot(
10193ca95b02SDimitry Andric         DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
10203ca95b02SDimitry Andric }
1021