blob: 19048d2c20b2b90e9399bf6db8f609e67e6241bb [file] [log] [blame]
Philip Reames1a1bdb22014-12-02 18:50:36 +00001//===-- StatepointLowering.cpp - SDAGBuilder's statepoint code -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file includes support code use by SelectionDAGBuilder when lowering a
11// statepoint sequence in SelectionDAG IR.
12//
13//===----------------------------------------------------------------------===//
14
15#include "StatepointLowering.h"
16#include "SelectionDAGBuilder.h"
17#include "llvm/ADT/SmallSet.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/CodeGen/FunctionLoweringInfo.h"
Chandler Carruth71f308a2015-02-13 09:09:03 +000020#include "llvm/CodeGen/GCMetadata.h"
Philip Reames56a03932015-01-26 18:26:35 +000021#include "llvm/CodeGen/GCStrategy.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000022#include "llvm/CodeGen/SelectionDAG.h"
23#include "llvm/CodeGen/StackMaps.h"
24#include "llvm/IR/CallingConv.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Statepoint.h"
29#include "llvm/Target/TargetLowering.h"
30#include <algorithm>
31using namespace llvm;
32
33#define DEBUG_TYPE "statepoint-lowering"
34
35STATISTIC(NumSlotsAllocatedForStatepoints,
36 "Number of stack slots allocated for statepoints");
37STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
38STATISTIC(StatepointMaxSlotsRequired,
39 "Maximum number of stack slots required for a singe statepoint");
40
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +000041static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
42 SelectionDAGBuilder &Builder, uint64_t Value) {
43 SDLoc L = Builder.getCurSDLoc();
44 Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
45 MVT::i64));
46 Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
47}
48
Pat Gavlin022c5ac2015-04-29 21:52:45 +000049void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
Philip Reames1a1bdb22014-12-02 18:50:36 +000050 // Consistency check
51 assert(PendingGCRelocateCalls.empty() &&
52 "Trying to visit statepoint before finished processing previous one");
53 Locations.clear();
54 RelocLocations.clear();
55 NextSlotToAllocate = 0;
56 // Need to resize this on each safepoint - we need the two to stay in
57 // sync and the clear patterns of a SelectionDAGBuilder have no relation
58 // to FunctionLoweringInfo.
59 AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
60 for (size_t i = 0; i < AllocatedStackSlots.size(); i++) {
61 AllocatedStackSlots[i] = false;
62 }
63}
64void StatepointLoweringState::clear() {
65 Locations.clear();
66 RelocLocations.clear();
67 AllocatedStackSlots.clear();
68 assert(PendingGCRelocateCalls.empty() &&
69 "cleared before statepoint sequence completed");
70}
71
72SDValue
73StatepointLoweringState::allocateStackSlot(EVT ValueType,
74 SelectionDAGBuilder &Builder) {
75
76 NumSlotsAllocatedForStatepoints++;
77
78 // The basic scheme here is to first look for a previously created stack slot
79 // which is not in use (accounting for the fact arbitrary slots may already
80 // be reserved), or to create a new stack slot and use it.
81
82 // If this doesn't succeed in 40000 iterations, something is seriously wrong
83 for (int i = 0; i < 40000; i++) {
84 assert(Builder.FuncInfo.StatepointStackSlots.size() ==
85 AllocatedStackSlots.size() &&
86 "broken invariant");
87 const size_t NumSlots = AllocatedStackSlots.size();
88 assert(NextSlotToAllocate <= NumSlots && "broken invariant");
89
90 if (NextSlotToAllocate >= NumSlots) {
91 assert(NextSlotToAllocate == NumSlots);
92 // record stats
93 if (NumSlots + 1 > StatepointMaxSlotsRequired) {
94 StatepointMaxSlotsRequired = NumSlots + 1;
95 }
96
97 SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
98 const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
99 Builder.FuncInfo.StatepointStackSlots.push_back(FI);
100 AllocatedStackSlots.push_back(true);
101 return SpillSlot;
102 }
103 if (!AllocatedStackSlots[NextSlotToAllocate]) {
104 const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
105 AllocatedStackSlots[NextSlotToAllocate] = true;
106 return Builder.DAG.getFrameIndex(FI, ValueType);
107 }
108 // Note: We deliberately choose to advance this only on the failing path.
109 // Doing so on the suceeding path involes a bit of complexity that caused a
110 // minor bug previously. Unless performance shows this matters, please
111 // keep this code as simple as possible.
112 NextSlotToAllocate++;
113 }
114 llvm_unreachable("infinite loop?");
115}
116
117/// Try to find existing copies of the incoming values in stack slots used for
118/// statepoint spilling. If we can find a spill slot for the incoming value,
119/// mark that slot as allocated, and reuse the same slot for this safepoint.
120/// This helps to avoid series of loads and stores that only serve to resuffle
121/// values on the stack between calls.
122static void reservePreviousStackSlotForValue(SDValue Incoming,
123 SelectionDAGBuilder &Builder) {
124
125 if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
126 // We won't need to spill this, so no need to check for previously
127 // allocated stack slots
128 return;
129 }
130
131 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
132 if (Loc.getNode()) {
133 // duplicates in input
134 return;
135 }
136
137 // Search back for the load from a stack slot pattern to find the original
138 // slot we allocated for this value. We could extend this to deal with
139 // simple modification patterns, but simple dealing with trivial load/store
140 // sequences helps a lot already.
141 if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Incoming)) {
142 if (auto *FI = dyn_cast<FrameIndexSDNode>(Load->getBasePtr())) {
143 const int Index = FI->getIndex();
144 auto Itr = std::find(Builder.FuncInfo.StatepointStackSlots.begin(),
145 Builder.FuncInfo.StatepointStackSlots.end(), Index);
146 if (Itr == Builder.FuncInfo.StatepointStackSlots.end()) {
147 // not one of the lowering stack slots, can't reuse!
148 // TODO: Actually, we probably could reuse the stack slot if the value
149 // hasn't changed at all, but we'd need to look for intervening writes
150 return;
151 } else {
152 // This is one of our dedicated lowering slots
153 const int Offset =
154 std::distance(Builder.FuncInfo.StatepointStackSlots.begin(), Itr);
155 if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
156 // stack slot already assigned to someone else, can't use it!
157 // TODO: currently we reserve space for gc arguments after doing
158 // normal allocation for deopt arguments. We should reserve for
159 // _all_ deopt and gc arguments, then start allocating. This
160 // will prevent some moves being inserted when vm state changes,
161 // but gc state doesn't between two calls.
162 return;
163 }
164 // Reserve this stack slot
165 Builder.StatepointLowering.reserveStackSlot(Offset);
166 }
167
168 // Cache this slot so we find it when going through the normal
169 // assignment loop.
170 SDValue Loc =
171 Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
172
173 Builder.StatepointLowering.setLocation(Incoming, Loc);
174 }
175 }
176
177 // TODO: handle case where a reloaded value flows through a phi to
178 // another safepoint. e.g.
179 // bb1:
180 // a' = relocated...
181 // bb2: % pred: bb1, bb3, bb4, etc.
182 // a_phi = phi(a', ...)
183 // statepoint ... a_phi
184 // NOTE: This will require reasoning about cross basic block values. This is
185 // decidedly non trivial and this might not be the right place to do it. We
186 // don't really have the information we need here...
187
188 // TODO: handle simple updates. If a value is modified and the original
189 // value is no longer live, it would be nice to put the modified value in the
190 // same slot. This allows folding of the memory accesses for some
191 // instructions types (like an increment).
192 // statepoint (i)
193 // i1 = i+1
194 // statepoint (i1)
195}
196
197/// Remove any duplicate (as SDValues) from the derived pointer pairs. This
198/// is not required for correctness. It's purpose is to reduce the size of
199/// StackMap section. It has no effect on the number of spill slots required
200/// or the actual lowering.
201static void removeDuplicatesGCPtrs(SmallVectorImpl<const Value *> &Bases,
202 SmallVectorImpl<const Value *> &Ptrs,
203 SmallVectorImpl<const Value *> &Relocs,
204 SelectionDAGBuilder &Builder) {
205
206 // This is horribly ineffecient, but I don't care right now
207 SmallSet<SDValue, 64> Seen;
208
209 SmallVector<const Value *, 64> NewBases, NewPtrs, NewRelocs;
210 for (size_t i = 0; i < Ptrs.size(); i++) {
211 SDValue SD = Builder.getValue(Ptrs[i]);
212 // Only add non-duplicates
213 if (Seen.count(SD) == 0) {
214 NewBases.push_back(Bases[i]);
215 NewPtrs.push_back(Ptrs[i]);
216 NewRelocs.push_back(Relocs[i]);
217 }
218 Seen.insert(SD);
219 }
220 assert(Bases.size() >= NewBases.size());
221 assert(Ptrs.size() >= NewPtrs.size());
222 assert(Relocs.size() >= NewRelocs.size());
223 Bases = NewBases;
224 Ptrs = NewPtrs;
225 Relocs = NewRelocs;
226 assert(Ptrs.size() == Bases.size());
227 assert(Ptrs.size() == Relocs.size());
228}
229
230/// Extract call from statepoint, lower it and return pointer to the
231/// call node. Also update NodeMap so that getValue(statepoint) will
232/// reference lowered call result
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000233static SDNode *
234lowerCallFromStatepoint(ImmutableStatepoint ISP, MachineBasicBlock *LandingPad,
235 SelectionDAGBuilder &Builder,
236 SmallVectorImpl<SDValue> &PendingExports) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000237
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000238 ImmutableCallSite CS(ISP.getCallSite());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000239
Sanjoy Das499d7032015-05-06 02:36:26 +0000240 SDValue ActualCallee = Builder.getValue(ISP.getActualCallee());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000241
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000242 // Handle immediate and symbolic callees.
243 if (auto *ConstCallee = dyn_cast<ConstantSDNode>(ActualCallee.getNode()))
244 ActualCallee = Builder.DAG.getIntPtrConstant(ConstCallee->getZExtValue(),
245 Builder.getCurSDLoc(),
246 /*isTarget=*/true);
247 else if (auto *SymbolicCallee =
248 dyn_cast<GlobalAddressSDNode>(ActualCallee.getNode()))
249 ActualCallee = Builder.DAG.getTargetGlobalAddress(
250 SymbolicCallee->getGlobal(), SDLoc(SymbolicCallee),
251 SymbolicCallee->getValueType(0));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000252
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000253 assert(CS.getCallingConv() != CallingConv::AnyReg &&
254 "anyregcc is not supported on statepoints!");
255
Sanjoy Das499d7032015-05-06 02:36:26 +0000256 Type *DefTy = ISP.getActualReturnType();
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000257 bool HasDef = !DefTy->isVoidTy();
258
259 SDValue ReturnValue, CallEndVal;
260 std::tie(ReturnValue, CallEndVal) = Builder.lowerCallOperands(
Sanjoy Das4bfb4722015-05-06 02:36:31 +0000261 ISP.getCallSite(), ImmutableStatepoint::CallArgsBeginPos,
262 ISP.getNumCallArgs(), ActualCallee, DefTy, LandingPad,
263 false /* IsPatchPoint */);
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000264
265 SDNode *CallEnd = CallEndVal.getNode();
266
267 // Get a call instruction from the call sequence chain. Tail calls are not
268 // allowed. The following code is essentially reverse engineering X86's
269 // LowerCallTo.
270 //
271 // We are expecting DAG to have the following form:
272 //
273 // ch = eh_label (only in case of invoke statepoint)
274 // ch, glue = callseq_start ch
275 // ch, glue = X86::Call ch, glue
276 // ch, glue = callseq_end ch, glue
277 // get_return_value ch, glue
278 //
279 // get_return_value can either be a CopyFromReg to grab the return value from
280 // %RAX, or it can be a LOAD to load a value returned by reference via a stack
281 // slot.
282
283 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg ||
284 CallEnd->getOpcode() == ISD::LOAD))
285 CallEnd = CallEnd->getOperand(0).getNode();
286
287 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
288
Philip Reames1a1bdb22014-12-02 18:50:36 +0000289 if (HasDef) {
Igor Laevsky85f7f722015-03-10 16:26:48 +0000290 if (CS.isInvoke()) {
291 // Result value will be used in different basic block for invokes
292 // so we need to export it now. But statepoint call has a different type
293 // than the actuall call. It means that standart exporting mechanism will
294 // create register of the wrong type. So instead we need to create
295 // register with correct type and save value into it manually.
296 // TODO: To eliminate this problem we can remove gc.result intrinsics
297 // completelly and make statepoint call to return a tuple.
Sanjoy Das499d7032015-05-06 02:36:26 +0000298 unsigned Reg = Builder.FuncInfo.CreateRegs(ISP.getActualReturnType());
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000299 RegsForValue RFV(*Builder.DAG.getContext(),
300 Builder.DAG.getTargetLoweringInfo(), Reg,
Sanjoy Das499d7032015-05-06 02:36:26 +0000301 ISP.getActualReturnType());
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000302 SDValue Chain = Builder.DAG.getEntryNode();
303
304 RFV.getCopyToRegs(ReturnValue, Builder.DAG, Builder.getCurSDLoc(), Chain,
305 nullptr);
306 PendingExports.push_back(Chain);
307 Builder.FuncInfo.ValueMap[CS.getInstruction()] = Reg;
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000308 } else {
Igor Laevsky85f7f722015-03-10 16:26:48 +0000309 // The value of the statepoint itself will be the value of call itself.
310 // We'll replace the actually call node shortly. gc_result will grab
311 // this value.
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000312 Builder.setValue(CS.getInstruction(), ReturnValue);
Igor Laevsky85f7f722015-03-10 16:26:48 +0000313 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000314 } else {
315 // The token value is never used from here on, just generate a poison value
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000316 Builder.setValue(CS.getInstruction(),
317 Builder.DAG.getIntPtrConstant(-1, Builder.getCurSDLoc()));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000318 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000319
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000320 return CallEnd->getOperand(0).getNode();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000321}
322
323/// Callect all gc pointers coming into statepoint intrinsic, clean them up,
324/// and return two arrays:
325/// Bases - base pointers incoming to this statepoint
326/// Ptrs - derived pointers incoming to this statepoint
327/// Relocs - the gc_relocate corresponding to each base/ptr pair
328/// Elements of this arrays should be in one-to-one correspondence with each
329/// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000330static void getIncomingStatepointGCValues(
331 SmallVectorImpl<const Value *> &Bases, SmallVectorImpl<const Value *> &Ptrs,
332 SmallVectorImpl<const Value *> &Relocs, ImmutableStatepoint StatepointSite,
333 SelectionDAGBuilder &Builder) {
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000334 for (GCRelocateOperands relocateOpers :
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000335 StatepointSite.getRelocates(StatepointSite)) {
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000336 Relocs.push_back(relocateOpers.getUnderlyingCallSite().getInstruction());
Sanjoy Das499d7032015-05-06 02:36:26 +0000337 Bases.push_back(relocateOpers.getBasePtr());
338 Ptrs.push_back(relocateOpers.getDerivedPtr());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000339 }
340
341 // Remove any redundant llvm::Values which map to the same SDValue as another
342 // input. Also has the effect of removing duplicates in the original
343 // llvm::Value input list as well. This is a useful optimization for
344 // reducing the size of the StackMap section. It has no other impact.
345 removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder);
346
347 assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size());
348}
349
350/// Spill a value incoming to the statepoint. It might be either part of
351/// vmstate
352/// or gcstate. In both cases unconditionally spill it on the stack unless it
353/// is a null constant. Return pair with first element being frame index
354/// containing saved value and second element with outgoing chain from the
355/// emitted store
356static std::pair<SDValue, SDValue>
357spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
358 SelectionDAGBuilder &Builder) {
359 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
360
361 // Emit new store if we didn't do it for this ptr before
362 if (!Loc.getNode()) {
363 Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
364 Builder);
365 assert(isa<FrameIndexSDNode>(Loc));
366 int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
367 // We use TargetFrameIndex so that isel will not select it into LEA
368 Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
369
370 // TODO: We can create TokenFactor node instead of
371 // chaining stores one after another, this may allow
372 // a bit more optimal scheduling for them
373 Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
374 MachinePointerInfo::getFixedStack(Index),
375 false, false, 0);
376
377 Builder.StatepointLowering.setLocation(Incoming, Loc);
378 }
379
380 assert(Loc.getNode());
381 return std::make_pair(Loc, Chain);
382}
383
384/// Lower a single value incoming to a statepoint node. This value can be
385/// either a deopt value or a gc value, the handling is the same. We special
386/// case constants and allocas, then fall back to spilling if required.
387static void lowerIncomingStatepointValue(SDValue Incoming,
388 SmallVectorImpl<SDValue> &Ops,
389 SelectionDAGBuilder &Builder) {
390 SDValue Chain = Builder.getRoot();
391
392 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
393 // If the original value was a constant, make sure it gets recorded as
394 // such in the stackmap. This is required so that the consumer can
395 // parse any internal format to the deopt state. It also handles null
396 // pointers and other constant pointers in GC states
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000397 pushStackMapConstant(Ops, Builder, C->getSExtValue());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000398 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
Philip Reamesf8f09332015-03-27 04:52:48 +0000399 // This handles allocas as arguments to the statepoint (this is only
400 // really meaningful for a deopt value. For GC, we'd be trying to
401 // relocate the address of the alloca itself?)
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000402 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
Philip Reamesf8f09332015-03-27 04:52:48 +0000403 Incoming.getValueType()));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000404 } else {
405 // Otherwise, locate a spill slot and explicitly spill it so it
406 // can be found by the runtime later. We currently do not support
407 // tracking values through callee saved registers to their eventual
408 // spill location. This would be a useful optimization, but would
409 // need to be optional since it requires a lot of complexity on the
410 // runtime side which not all would support.
411 std::pair<SDValue, SDValue> Res =
412 spillIncomingStatepointValue(Incoming, Chain, Builder);
413 Ops.push_back(Res.first);
414 Chain = Res.second;
415 }
416
417 Builder.DAG.setRoot(Chain);
418}
419
420/// Lower deopt state and gc pointer arguments of the statepoint. The actual
421/// lowering is described in lowerIncomingStatepointValue. This function is
422/// responsible for lowering everything in the right position and playing some
423/// tricks to avoid redundant stack manipulation where possible. On
424/// completion, 'Ops' will contain ready to use operands for machine code
425/// statepoint. The chain nodes will have already been created and the DAG root
426/// will be set to the last value spilled (if any were).
427static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000428 ImmutableStatepoint StatepointSite,
Philip Reames1a1bdb22014-12-02 18:50:36 +0000429 SelectionDAGBuilder &Builder) {
430
431 // Lower the deopt and gc arguments for this statepoint. Layout will
432 // be: deopt argument length, deopt arguments.., gc arguments...
433
434 SmallVector<const Value *, 64> Bases, Ptrs, Relocations;
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000435 getIncomingStatepointGCValues(Bases, Ptrs, Relocations, StatepointSite,
436 Builder);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000437
Philip Reames4ac17a32015-01-07 19:07:50 +0000438#ifndef NDEBUG
439 // Check that each of the gc pointer and bases we've gotten out of the
440 // safepoint is something the strategy thinks might be a pointer into the GC
441 // heap. This is basically just here to help catch errors during statepoint
442 // insertion. TODO: This should actually be in the Verifier, but we can't get
443 // to the GCStrategy from there (yet).
Philip Reamese1bf2702015-03-27 05:09:33 +0000444 GCStrategy &S = Builder.GFI->getStrategy();
445 for (const Value *V : Bases) {
446 auto Opt = S.isGCManagedPointer(V);
447 if (Opt.hasValue()) {
448 assert(Opt.getValue() &&
449 "non gc managed base pointer found in statepoint");
Philip Reames4ac17a32015-01-07 19:07:50 +0000450 }
Philip Reamese1bf2702015-03-27 05:09:33 +0000451 }
452 for (const Value *V : Ptrs) {
453 auto Opt = S.isGCManagedPointer(V);
454 if (Opt.hasValue()) {
455 assert(Opt.getValue() &&
456 "non gc managed derived pointer found in statepoint");
Philip Reames4ac17a32015-01-07 19:07:50 +0000457 }
Philip Reamese1bf2702015-03-27 05:09:33 +0000458 }
459 for (const Value *V : Relocations) {
460 auto Opt = S.isGCManagedPointer(V);
461 if (Opt.hasValue()) {
462 assert(Opt.getValue() && "non gc managed pointer relocated");
Philip Reames4ac17a32015-01-07 19:07:50 +0000463 }
464 }
465#endif
466
Philip Reames1a1bdb22014-12-02 18:50:36 +0000467 // Before we actually start lowering (and allocating spill slots for values),
468 // reserve any stack slots which we judge to be profitable to reuse for a
469 // particular value. This is purely an optimization over the code below and
470 // doesn't change semantics at all. It is important for performance that we
471 // reserve slots for both deopt and gc values before lowering either.
Pat Gavlin08d70272015-05-12 21:33:48 +0000472 for (const Value *V : StatepointSite.vm_state_args()) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000473 SDValue Incoming = Builder.getValue(V);
474 reservePreviousStackSlotForValue(Incoming, Builder);
475 }
Igor Laevsky87ef5ea2015-05-12 13:12:14 +0000476 for (unsigned i = 0; i < Bases.size(); ++i) {
477 const Value *Base = Bases[i];
478 reservePreviousStackSlotForValue(Builder.getValue(Base), Builder);
479
480 const Value *Ptr = Ptrs[i];
481 reservePreviousStackSlotForValue(Builder.getValue(Ptr), Builder);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000482 }
483
484 // First, prefix the list with the number of unique values to be
485 // lowered. Note that this is the number of *Values* not the
486 // number of SDValues required to lower them.
Sanjoy Das499d7032015-05-06 02:36:26 +0000487 const int NumVMSArgs = StatepointSite.getNumTotalVMSArgs();
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000488 pushStackMapConstant(Ops, Builder, NumVMSArgs);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000489
Pat Gavlin08d70272015-05-12 21:33:48 +0000490 assert(NumVMSArgs == std::distance(StatepointSite.vm_state_begin(),
491 StatepointSite.vm_state_end()));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000492
493 // The vm state arguments are lowered in an opaque manner. We do
494 // not know what type of values are contained within. We skip the
495 // first one since that happens to be the total number we lowered
496 // explicitly just above. We could have left it in the loop and
497 // not done it explicitly, but it's far easier to understand this
498 // way.
Pat Gavlin08d70272015-05-12 21:33:48 +0000499 for (const Value *V : StatepointSite.vm_state_args()) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000500 SDValue Incoming = Builder.getValue(V);
501 lowerIncomingStatepointValue(Incoming, Ops, Builder);
502 }
503
504 // Finally, go ahead and lower all the gc arguments. There's no prefixed
505 // length for this one. After lowering, we'll have the base and pointer
506 // arrays interwoven with each (lowered) base pointer immediately followed by
507 // it's (lowered) derived pointer. i.e
508 // (base[0], ptr[0], base[1], ptr[1], ...)
Igor Laevsky87ef5ea2015-05-12 13:12:14 +0000509 for (unsigned i = 0; i < Bases.size(); ++i) {
510 const Value *Base = Bases[i];
511 lowerIncomingStatepointValue(Builder.getValue(Base), Ops, Builder);
512
513 const Value *Ptr = Ptrs[i];
514 lowerIncomingStatepointValue(Builder.getValue(Ptr), Ops, Builder);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000515 }
Philip Reamesf8f09332015-03-27 04:52:48 +0000516
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000517 // If there are any explicit spill slots passed to the statepoint, record
Philip Reamesf8f09332015-03-27 04:52:48 +0000518 // them, but otherwise do not do anything special. These are user provided
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000519 // allocas and give control over placement to the consumer. In this case,
Philip Reamesf8f09332015-03-27 04:52:48 +0000520 // it is the contents of the slot which may get updated, not the pointer to
521 // the alloca
522 for (Value *V : StatepointSite.gc_args()) {
523 SDValue Incoming = Builder.getValue(V);
524 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
525 // This handles allocas as arguments to the statepoint
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000526 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
Philip Reamesf8f09332015-03-27 04:52:48 +0000527 Incoming.getValueType()));
Philip Reamesf8f09332015-03-27 04:52:48 +0000528 }
529 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000530}
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000531
Philip Reames1a1bdb22014-12-02 18:50:36 +0000532void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000533 // Check some preconditions for sanity
534 assert(isStatepoint(&CI) &&
535 "function called must be the statepoint function");
536
537 LowerStatepoint(ImmutableStatepoint(&CI));
538}
539
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000540void SelectionDAGBuilder::LowerStatepoint(
541 ImmutableStatepoint ISP, MachineBasicBlock *LandingPad /*=nullptr*/) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000542 // The basic scheme here is that information about both the original call and
543 // the safepoint is encoded in the CallInst. We create a temporary call and
544 // lower it, then reverse engineer the calling sequence.
545
Philip Reames1a1bdb22014-12-02 18:50:36 +0000546 NumOfStatepoints++;
547 // Clear state
548 StatepointLowering.startNewStatepoint(*this);
549
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000550 ImmutableCallSite CS(ISP.getCallSite());
551
Philip Reames1a1bdb22014-12-02 18:50:36 +0000552#ifndef NDEBUG
553 // Consistency check
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000554 for (const User *U : CS->users()) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000555 const CallInst *Call = cast<CallInst>(U);
556 if (isGCRelocate(Call))
557 StatepointLowering.scheduleRelocCall(*Call);
558 }
559#endif
560
Philip Reames72fbe7a2014-12-02 21:01:48 +0000561#ifndef NDEBUG
562 // If this is a malformed statepoint, report it early to simplify debugging.
563 // This should catch any IR level mistake that's made when constructing or
564 // transforming statepoints.
565 ISP.verify();
Philip Reames4ac17a32015-01-07 19:07:50 +0000566
567 // Check that the associated GCStrategy expects to encounter statepoints.
Philip Reamese1bf2702015-03-27 05:09:33 +0000568 assert(GFI->getStrategy().useStatepoints() &&
569 "GCStrategy does not expect to encounter statepoints");
Philip Reames72fbe7a2014-12-02 21:01:48 +0000570#endif
571
Philip Reames1a1bdb22014-12-02 18:50:36 +0000572 // Lower statepoint vmstate and gcstate arguments
Sanjoy Das3fb91c02015-05-05 23:06:49 +0000573 SmallVector<SDValue, 10> LoweredMetaArgs;
574 lowerStatepointMetaArgs(LoweredMetaArgs, ISP, *this);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000575
576 // Get call node, we will replace it later with statepoint
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000577 SDNode *CallNode =
578 lowerCallFromStatepoint(ISP, LandingPad, *this, PendingExports);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000579
Pat Gavlincc0431d2015-05-08 18:07:42 +0000580 // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
581 // nodes with all the appropriate arguments and return values.
Philip Reames1a1bdb22014-12-02 18:50:36 +0000582
Philip Reames1a1bdb22014-12-02 18:50:36 +0000583 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
Pat Gavlincc0431d2015-05-08 18:07:42 +0000584 SDValue Chain = CallNode->getOperand(0);
585
Philip Reames1a1bdb22014-12-02 18:50:36 +0000586 SDValue Glue;
Pat Gavlincc0431d2015-05-08 18:07:42 +0000587 bool CallHasIncomingGlue = CallNode->getGluedNode();
588 if (CallHasIncomingGlue) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000589 // Glue is always last operand
590 Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
591 }
Pat Gavlincc0431d2015-05-08 18:07:42 +0000592
593 // Build the GC_TRANSITION_START node if necessary.
594 //
595 // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
596 // order in which they appear in the call to the statepoint intrinsic. If
597 // any of the operands is a pointer-typed, that operand is immediately
598 // followed by a SRCVALUE for the pointer that may be used during lowering
599 // (e.g. to form MachinePointerInfo values for loads/stores).
600 const bool IsGCTransition =
601 (ISP.getFlags() & (uint64_t)StatepointFlags::GCTransition) ==
602 (uint64_t)StatepointFlags::GCTransition;
603 if (IsGCTransition) {
604 SmallVector<SDValue, 8> TSOps;
605
606 // Add chain
607 TSOps.push_back(Chain);
608
609 // Add GC transition arguments
Pat Gavlin08d70272015-05-12 21:33:48 +0000610 for (const Value *V : ISP.gc_transition_args()) {
611 TSOps.push_back(getValue(V));
612 if (V->getType()->isPointerTy())
613 TSOps.push_back(DAG.getSrcValue(V));
Pat Gavlincc0431d2015-05-08 18:07:42 +0000614 }
615
616 // Add glue if necessary
617 if (CallHasIncomingGlue)
618 TSOps.push_back(Glue);
619
620 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
621
622 SDValue GCTransitionStart =
623 DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
624
625 Chain = GCTransitionStart.getValue(0);
626 Glue = GCTransitionStart.getValue(1);
627 }
628
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +0000629 // TODO: Currently, all of these operands are being marked as read/write in
630 // PrologEpilougeInserter.cpp, we should special case the VMState arguments
631 // and flags to be read-only.
632 SmallVector<SDValue, 40> Ops;
633
634 // Add the <id> and <numBytes> constants.
635 Ops.push_back(DAG.getTargetConstant(ISP.getID(), getCurSDLoc(), MVT::i64));
636 Ops.push_back(
637 DAG.getTargetConstant(ISP.getNumPatchBytes(), getCurSDLoc(), MVT::i32));
638
Pat Gavlincc0431d2015-05-08 18:07:42 +0000639 // Calculate and push starting position of vmstate arguments
Philip Reames1a1bdb22014-12-02 18:50:36 +0000640 // Get number of arguments incoming directly into call node
641 unsigned NumCallRegArgs =
Pat Gavlincc0431d2015-05-08 18:07:42 +0000642 CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000643 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000644
645 // Add call target
646 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
647 Ops.push_back(CallTarget);
648
649 // Add call arguments
650 // Get position of register mask in the call
651 SDNode::op_iterator RegMaskIt;
Pat Gavlincc0431d2015-05-08 18:07:42 +0000652 if (CallHasIncomingGlue)
Philip Reames1a1bdb22014-12-02 18:50:36 +0000653 RegMaskIt = CallNode->op_end() - 2;
654 else
655 RegMaskIt = CallNode->op_end() - 1;
656 Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
657
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000658 // Add a constant argument for the calling convention
659 pushStackMapConstant(Ops, *this, CS.getCallingConv());
660
661 // Add a constant argument for the flags
Sanjoy Dasa1d39ba2015-05-12 23:52:24 +0000662 uint64_t Flags = ISP.getFlags();
Pat Gavlincc0431d2015-05-08 18:07:42 +0000663 assert(
664 ((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0)
665 && "unknown flag used");
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000666 pushStackMapConstant(Ops, *this, Flags);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000667
668 // Insert all vmstate and gcstate arguments
Sanjoy Das3fb91c02015-05-05 23:06:49 +0000669 Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000670
671 // Add register mask from call node
672 Ops.push_back(*RegMaskIt);
673
674 // Add chain
Pat Gavlincc0431d2015-05-08 18:07:42 +0000675 Ops.push_back(Chain);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000676
677 // Same for the glue, but we add it only if original call had it
678 if (Glue.getNode())
679 Ops.push_back(Glue);
680
Benjamin Kramerea68a942015-02-19 15:26:17 +0000681 // Compute return values. Provide a glue output since we consume one as
682 // input. This allows someone else to chain off us as needed.
683 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000684
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000685 SDNode *StatepointMCNode =
686 DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000687
Pat Gavlincc0431d2015-05-08 18:07:42 +0000688 SDNode *SinkNode = StatepointMCNode;
689
690 // Build the GC_TRANSITION_END node if necessary.
691 //
692 // See the comment above regarding GC_TRANSITION_START for the layout of
693 // the operands to the GC_TRANSITION_END node.
694 if (IsGCTransition) {
695 SmallVector<SDValue, 8> TEOps;
696
697 // Add chain
698 TEOps.push_back(SDValue(StatepointMCNode, 0));
699
700 // Add GC transition arguments
Pat Gavlin08d70272015-05-12 21:33:48 +0000701 for (const Value *V : ISP.gc_transition_args()) {
702 TEOps.push_back(getValue(V));
703 if (V->getType()->isPointerTy())
704 TEOps.push_back(DAG.getSrcValue(V));
Pat Gavlincc0431d2015-05-08 18:07:42 +0000705 }
706
707 // Add glue
708 TEOps.push_back(SDValue(StatepointMCNode, 1));
709
710 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
711
712 SDValue GCTransitionStart =
713 DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
714
715 SinkNode = GCTransitionStart.getNode();
716 }
717
Philip Reames1a1bdb22014-12-02 18:50:36 +0000718 // Replace original call
Pat Gavlincc0431d2015-05-08 18:07:42 +0000719 DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
Philip Reames1a1bdb22014-12-02 18:50:36 +0000720 // Remove originall call node
721 DAG.DeleteNode(CallNode);
722
723 // DON'T set the root - under the assumption that it's already set past the
724 // inserted node we created.
725
726 // TODO: A better future implementation would be to emit a single variable
727 // argument, variable return value STATEPOINT node here and then hookup the
728 // return value of each gc.relocate to the respective output of the
729 // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
730 // to actually be possible today.
731}
732
733void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
734 // The result value of the gc_result is simply the result of the actual
735 // call. We've already emitted this, so just grab the value.
736 Instruction *I = cast<Instruction>(CI.getArgOperand(0));
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000737 assert(isStatepoint(I) && "first argument must be a statepoint token");
Philip Reames1a1bdb22014-12-02 18:50:36 +0000738
Igor Laevsky85f7f722015-03-10 16:26:48 +0000739 if (isa<InvokeInst>(I)) {
740 // For invokes we should have stored call result in a virtual register.
741 // We can not use default getValue() functionality to copy value from this
742 // register because statepoint and actuall call return types can be
743 // different, and getValue() will use CopyFromReg of the wrong type,
744 // which is always i32 in our case.
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000745 PointerType *CalleeType =
Sanjoy Das499d7032015-05-06 02:36:26 +0000746 cast<PointerType>(ImmutableStatepoint(I).getActualCallee()->getType());
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000747 Type *RetTy =
748 cast<FunctionType>(CalleeType->getElementType())->getReturnType();
Igor Laevsky85f7f722015-03-10 16:26:48 +0000749 SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
750
751 assert(CopyFromReg.getNode());
752 setValue(&CI, CopyFromReg);
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000753 } else {
Igor Laevsky85f7f722015-03-10 16:26:48 +0000754 setValue(&CI, getValue(I));
755 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000756}
757
758void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) {
759#ifndef NDEBUG
760 // Consistency check
761 StatepointLowering.relocCallVisited(CI);
762#endif
763
764 GCRelocateOperands relocateOpers(&CI);
Sanjoy Das499d7032015-05-06 02:36:26 +0000765 SDValue SD = getValue(relocateOpers.getDerivedPtr());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000766
767 if (isa<ConstantSDNode>(SD) || isa<FrameIndexSDNode>(SD)) {
768 // We didn't need to spill these special cases (constants and allocas).
769 // See the handling in spillIncomingValueForStatepoint for detail.
770 setValue(&CI, SD);
771 return;
772 }
773
774 SDValue Loc = StatepointLowering.getRelocLocation(SD);
775 // Emit new load if we did not emit it before
776 if (!Loc.getNode()) {
777 SDValue SpillSlot = StatepointLowering.getLocation(SD);
778 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
779
780 // Be conservative: flush all pending loads
781 // TODO: Probably we can be less restrictive on this,
782 // it may allow more scheduling opprtunities
783 SDValue Chain = getRoot();
784
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000785 Loc = DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
786 MachinePointerInfo::getFixedStack(FI), false, false,
787 false, 0);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000788
789 StatepointLowering.setRelocLocation(SD, Loc);
790
791 // Again, be conservative, don't emit pending loads
792 DAG.setRoot(Loc.getValue(1));
793 }
794
795 assert(Loc.getNode());
796 setValue(&CI, Loc);
797}