blob: 86fbc6354589aef63d635904dd8ebfd46caaf49f [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.
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000472 for (auto I = StatepointSite.vm_state_begin() + 1,
473 E = StatepointSite.vm_state_end();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000474 I != E; ++I) {
475 Value *V = *I;
476 SDValue Incoming = Builder.getValue(V);
477 reservePreviousStackSlotForValue(Incoming, Builder);
478 }
Igor Laevsky87ef5ea2015-05-12 13:12:14 +0000479 for (unsigned i = 0; i < Bases.size(); ++i) {
480 const Value *Base = Bases[i];
481 reservePreviousStackSlotForValue(Builder.getValue(Base), Builder);
482
483 const Value *Ptr = Ptrs[i];
484 reservePreviousStackSlotForValue(Builder.getValue(Ptr), Builder);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000485 }
486
487 // First, prefix the list with the number of unique values to be
488 // lowered. Note that this is the number of *Values* not the
489 // number of SDValues required to lower them.
Sanjoy Das499d7032015-05-06 02:36:26 +0000490 const int NumVMSArgs = StatepointSite.getNumTotalVMSArgs();
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000491 pushStackMapConstant(Ops, Builder, NumVMSArgs);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000492
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000493 assert(NumVMSArgs + 1 == std::distance(StatepointSite.vm_state_begin(),
494 StatepointSite.vm_state_end()));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000495
496 // The vm state arguments are lowered in an opaque manner. We do
497 // not know what type of values are contained within. We skip the
498 // first one since that happens to be the total number we lowered
499 // explicitly just above. We could have left it in the loop and
500 // not done it explicitly, but it's far easier to understand this
501 // way.
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000502 for (auto I = StatepointSite.vm_state_begin() + 1,
503 E = StatepointSite.vm_state_end();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000504 I != E; ++I) {
505 const Value *V = *I;
506 SDValue Incoming = Builder.getValue(V);
507 lowerIncomingStatepointValue(Incoming, Ops, Builder);
508 }
509
510 // Finally, go ahead and lower all the gc arguments. There's no prefixed
511 // length for this one. After lowering, we'll have the base and pointer
512 // arrays interwoven with each (lowered) base pointer immediately followed by
513 // it's (lowered) derived pointer. i.e
514 // (base[0], ptr[0], base[1], ptr[1], ...)
Igor Laevsky87ef5ea2015-05-12 13:12:14 +0000515 for (unsigned i = 0; i < Bases.size(); ++i) {
516 const Value *Base = Bases[i];
517 lowerIncomingStatepointValue(Builder.getValue(Base), Ops, Builder);
518
519 const Value *Ptr = Ptrs[i];
520 lowerIncomingStatepointValue(Builder.getValue(Ptr), Ops, Builder);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000521 }
Philip Reamesf8f09332015-03-27 04:52:48 +0000522
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000523 // If there are any explicit spill slots passed to the statepoint, record
Philip Reamesf8f09332015-03-27 04:52:48 +0000524 // them, but otherwise do not do anything special. These are user provided
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000525 // allocas and give control over placement to the consumer. In this case,
Philip Reamesf8f09332015-03-27 04:52:48 +0000526 // it is the contents of the slot which may get updated, not the pointer to
527 // the alloca
528 for (Value *V : StatepointSite.gc_args()) {
529 SDValue Incoming = Builder.getValue(V);
530 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
531 // This handles allocas as arguments to the statepoint
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000532 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
Philip Reamesf8f09332015-03-27 04:52:48 +0000533 Incoming.getValueType()));
Philip Reamesf8f09332015-03-27 04:52:48 +0000534 }
535 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000536}
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000537
Philip Reames1a1bdb22014-12-02 18:50:36 +0000538void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000539 // Check some preconditions for sanity
540 assert(isStatepoint(&CI) &&
541 "function called must be the statepoint function");
542
543 LowerStatepoint(ImmutableStatepoint(&CI));
544}
545
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000546void SelectionDAGBuilder::LowerStatepoint(
547 ImmutableStatepoint ISP, MachineBasicBlock *LandingPad /*=nullptr*/) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000548 // The basic scheme here is that information about both the original call and
549 // the safepoint is encoded in the CallInst. We create a temporary call and
550 // lower it, then reverse engineer the calling sequence.
551
Philip Reames1a1bdb22014-12-02 18:50:36 +0000552 NumOfStatepoints++;
553 // Clear state
554 StatepointLowering.startNewStatepoint(*this);
555
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000556 ImmutableCallSite CS(ISP.getCallSite());
557
Philip Reames1a1bdb22014-12-02 18:50:36 +0000558#ifndef NDEBUG
559 // Consistency check
Igor Laevsky7fc58a42015-02-20 15:28:35 +0000560 for (const User *U : CS->users()) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000561 const CallInst *Call = cast<CallInst>(U);
562 if (isGCRelocate(Call))
563 StatepointLowering.scheduleRelocCall(*Call);
564 }
565#endif
566
Philip Reames72fbe7a2014-12-02 21:01:48 +0000567#ifndef NDEBUG
568 // If this is a malformed statepoint, report it early to simplify debugging.
569 // This should catch any IR level mistake that's made when constructing or
570 // transforming statepoints.
571 ISP.verify();
Philip Reames4ac17a32015-01-07 19:07:50 +0000572
573 // Check that the associated GCStrategy expects to encounter statepoints.
574 // TODO: This if should become an assert. For now, we allow the GCStrategy
575 // to be optional for backwards compatibility. This will only last a short
576 // period (i.e. a couple of weeks).
Philip Reamese1bf2702015-03-27 05:09:33 +0000577 assert(GFI->getStrategy().useStatepoints() &&
578 "GCStrategy does not expect to encounter statepoints");
Philip Reames72fbe7a2014-12-02 21:01:48 +0000579#endif
580
Philip Reames1a1bdb22014-12-02 18:50:36 +0000581 // Lower statepoint vmstate and gcstate arguments
Sanjoy Das3fb91c02015-05-05 23:06:49 +0000582 SmallVector<SDValue, 10> LoweredMetaArgs;
583 lowerStatepointMetaArgs(LoweredMetaArgs, ISP, *this);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000584
585 // Get call node, we will replace it later with statepoint
Sanjoy Dasc6bf3e92015-05-06 02:36:20 +0000586 SDNode *CallNode =
587 lowerCallFromStatepoint(ISP, LandingPad, *this, PendingExports);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000588
Pat Gavlincc0431d2015-05-08 18:07:42 +0000589 // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
590 // nodes with all the appropriate arguments and return values.
Philip Reames1a1bdb22014-12-02 18:50:36 +0000591
592 // TODO: Currently, all of these operands are being marked as read/write in
593 // PrologEpilougeInserter.cpp, we should special case the VMState arguments
594 // and flags to be read-only.
595 SmallVector<SDValue, 40> Ops;
596
Philip Reames1a1bdb22014-12-02 18:50:36 +0000597 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
Pat Gavlincc0431d2015-05-08 18:07:42 +0000598 SDValue Chain = CallNode->getOperand(0);
599
Philip Reames1a1bdb22014-12-02 18:50:36 +0000600 SDValue Glue;
Pat Gavlincc0431d2015-05-08 18:07:42 +0000601 bool CallHasIncomingGlue = CallNode->getGluedNode();
602 if (CallHasIncomingGlue) {
Philip Reames1a1bdb22014-12-02 18:50:36 +0000603 // Glue is always last operand
604 Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
605 }
Pat Gavlincc0431d2015-05-08 18:07:42 +0000606
607 // Build the GC_TRANSITION_START node if necessary.
608 //
609 // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
610 // order in which they appear in the call to the statepoint intrinsic. If
611 // any of the operands is a pointer-typed, that operand is immediately
612 // followed by a SRCVALUE for the pointer that may be used during lowering
613 // (e.g. to form MachinePointerInfo values for loads/stores).
614 const bool IsGCTransition =
615 (ISP.getFlags() & (uint64_t)StatepointFlags::GCTransition) ==
616 (uint64_t)StatepointFlags::GCTransition;
617 if (IsGCTransition) {
618 SmallVector<SDValue, 8> TSOps;
619
620 // Add chain
621 TSOps.push_back(Chain);
622
623 // Add GC transition arguments
624 for (auto I = ISP.gc_transition_args_begin() + 1,
625 E = ISP.gc_transition_args_end();
626 I != E; ++I) {
627 TSOps.push_back(getValue(*I));
628 if ((*I)->getType()->isPointerTy())
629 TSOps.push_back(DAG.getSrcValue(*I));
630 }
631
632 // Add glue if necessary
633 if (CallHasIncomingGlue)
634 TSOps.push_back(Glue);
635
636 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
637
638 SDValue GCTransitionStart =
639 DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
640
641 Chain = GCTransitionStart.getValue(0);
642 Glue = GCTransitionStart.getValue(1);
643 }
644
645 // Calculate and push starting position of vmstate arguments
Philip Reames1a1bdb22014-12-02 18:50:36 +0000646 // Get number of arguments incoming directly into call node
647 unsigned NumCallRegArgs =
Pat Gavlincc0431d2015-05-08 18:07:42 +0000648 CallNode->getNumOperands() - (CallHasIncomingGlue ? 4 : 3);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000649 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
Philip Reames1a1bdb22014-12-02 18:50:36 +0000650
651 // Add call target
652 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
653 Ops.push_back(CallTarget);
654
655 // Add call arguments
656 // Get position of register mask in the call
657 SDNode::op_iterator RegMaskIt;
Pat Gavlincc0431d2015-05-08 18:07:42 +0000658 if (CallHasIncomingGlue)
Philip Reames1a1bdb22014-12-02 18:50:36 +0000659 RegMaskIt = CallNode->op_end() - 2;
660 else
661 RegMaskIt = CallNode->op_end() - 1;
662 Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
663
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000664 // Add a constant argument for the calling convention
665 pushStackMapConstant(Ops, *this, CS.getCallingConv());
666
667 // Add a constant argument for the flags
Pat Gavlincc0431d2015-05-08 18:07:42 +0000668 uint64_t Flags = cast<ConstantInt>(CS.getArgument(2))->getZExtValue();
669 assert(
670 ((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0)
671 && "unknown flag used");
Pat Gavlinc7dc6d6ee2015-05-12 19:50:19 +0000672 pushStackMapConstant(Ops, *this, Flags);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000673
674 // Insert all vmstate and gcstate arguments
Sanjoy Das3fb91c02015-05-05 23:06:49 +0000675 Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000676
677 // Add register mask from call node
678 Ops.push_back(*RegMaskIt);
679
680 // Add chain
Pat Gavlincc0431d2015-05-08 18:07:42 +0000681 Ops.push_back(Chain);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000682
683 // Same for the glue, but we add it only if original call had it
684 if (Glue.getNode())
685 Ops.push_back(Glue);
686
Benjamin Kramerea68a942015-02-19 15:26:17 +0000687 // Compute return values. Provide a glue output since we consume one as
688 // input. This allows someone else to chain off us as needed.
689 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000690
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000691 SDNode *StatepointMCNode =
692 DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000693
Pat Gavlincc0431d2015-05-08 18:07:42 +0000694 SDNode *SinkNode = StatepointMCNode;
695
696 // Build the GC_TRANSITION_END node if necessary.
697 //
698 // See the comment above regarding GC_TRANSITION_START for the layout of
699 // the operands to the GC_TRANSITION_END node.
700 if (IsGCTransition) {
701 SmallVector<SDValue, 8> TEOps;
702
703 // Add chain
704 TEOps.push_back(SDValue(StatepointMCNode, 0));
705
706 // Add GC transition arguments
707 for (auto I = ISP.gc_transition_args_begin() + 1,
708 E = ISP.gc_transition_args_end();
709 I != E; ++I) {
710 TEOps.push_back(getValue(*I));
711 if ((*I)->getType()->isPointerTy())
712 TEOps.push_back(DAG.getSrcValue(*I));
713 }
714
715 // Add glue
716 TEOps.push_back(SDValue(StatepointMCNode, 1));
717
718 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
719
720 SDValue GCTransitionStart =
721 DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
722
723 SinkNode = GCTransitionStart.getNode();
724 }
725
Philip Reames1a1bdb22014-12-02 18:50:36 +0000726 // Replace original call
Pat Gavlincc0431d2015-05-08 18:07:42 +0000727 DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
Philip Reames1a1bdb22014-12-02 18:50:36 +0000728 // Remove originall call node
729 DAG.DeleteNode(CallNode);
730
731 // DON'T set the root - under the assumption that it's already set past the
732 // inserted node we created.
733
734 // TODO: A better future implementation would be to emit a single variable
735 // argument, variable return value STATEPOINT node here and then hookup the
736 // return value of each gc.relocate to the respective output of the
737 // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
738 // to actually be possible today.
739}
740
741void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
742 // The result value of the gc_result is simply the result of the actual
743 // call. We've already emitted this, so just grab the value.
744 Instruction *I = cast<Instruction>(CI.getArgOperand(0));
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000745 assert(isStatepoint(I) && "first argument must be a statepoint token");
Philip Reames1a1bdb22014-12-02 18:50:36 +0000746
Igor Laevsky85f7f722015-03-10 16:26:48 +0000747 if (isa<InvokeInst>(I)) {
748 // For invokes we should have stored call result in a virtual register.
749 // We can not use default getValue() functionality to copy value from this
750 // register because statepoint and actuall call return types can be
751 // different, and getValue() will use CopyFromReg of the wrong type,
752 // which is always i32 in our case.
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000753 PointerType *CalleeType =
Sanjoy Das499d7032015-05-06 02:36:26 +0000754 cast<PointerType>(ImmutableStatepoint(I).getActualCallee()->getType());
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000755 Type *RetTy =
756 cast<FunctionType>(CalleeType->getElementType())->getReturnType();
Igor Laevsky85f7f722015-03-10 16:26:48 +0000757 SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
758
759 assert(CopyFromReg.getNode());
760 setValue(&CI, CopyFromReg);
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000761 } else {
Igor Laevsky85f7f722015-03-10 16:26:48 +0000762 setValue(&CI, getValue(I));
763 }
Philip Reames1a1bdb22014-12-02 18:50:36 +0000764}
765
766void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) {
767#ifndef NDEBUG
768 // Consistency check
769 StatepointLowering.relocCallVisited(CI);
770#endif
771
772 GCRelocateOperands relocateOpers(&CI);
Sanjoy Das499d7032015-05-06 02:36:26 +0000773 SDValue SD = getValue(relocateOpers.getDerivedPtr());
Philip Reames1a1bdb22014-12-02 18:50:36 +0000774
775 if (isa<ConstantSDNode>(SD) || isa<FrameIndexSDNode>(SD)) {
776 // We didn't need to spill these special cases (constants and allocas).
777 // See the handling in spillIncomingValueForStatepoint for detail.
778 setValue(&CI, SD);
779 return;
780 }
781
782 SDValue Loc = StatepointLowering.getRelocLocation(SD);
783 // Emit new load if we did not emit it before
784 if (!Loc.getNode()) {
785 SDValue SpillSlot = StatepointLowering.getLocation(SD);
786 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
787
788 // Be conservative: flush all pending loads
789 // TODO: Probably we can be less restrictive on this,
790 // it may allow more scheduling opprtunities
791 SDValue Chain = getRoot();
792
Pat Gavlin022c5ac2015-04-29 21:52:45 +0000793 Loc = DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
794 MachinePointerInfo::getFixedStack(FI), false, false,
795 false, 0);
Philip Reames1a1bdb22014-12-02 18:50:36 +0000796
797 StatepointLowering.setRelocLocation(SD, Loc);
798
799 // Again, be conservative, don't emit pending loads
800 DAG.setRoot(Loc.getValue(1));
801 }
802
803 assert(Loc.getNode());
804 setValue(&CI, Loc);
805}