1 //===-- StatepointLowering.cpp - SDAGBuilder's statepoint code -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file includes support code use by SelectionDAGBuilder when lowering a
11 // statepoint sequence in SelectionDAG IR.
13 //===----------------------------------------------------------------------===//
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"
20 #include "llvm/CodeGen/GCMetadata.h"
21 #include "llvm/CodeGen/GCStrategy.h"
22 #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"
33 #define DEBUG_TYPE "statepoint-lowering"
35 STATISTIC(NumSlotsAllocatedForStatepoints,
36 "Number of stack slots allocated for statepoints");
37 STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
38 STATISTIC(StatepointMaxSlotsRequired,
39 "Maximum number of stack slots required for a singe statepoint");
41 void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
43 assert(PendingGCRelocateCalls.empty() &&
44 "Trying to visit statepoint before finished processing previous one");
46 RelocLocations.clear();
47 NextSlotToAllocate = 0;
48 // Need to resize this on each safepoint - we need the two to stay in
49 // sync and the clear patterns of a SelectionDAGBuilder have no relation
50 // to FunctionLoweringInfo.
51 AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
52 for (size_t i = 0; i < AllocatedStackSlots.size(); i++) {
53 AllocatedStackSlots[i] = false;
56 void StatepointLoweringState::clear() {
58 RelocLocations.clear();
59 AllocatedStackSlots.clear();
60 assert(PendingGCRelocateCalls.empty() &&
61 "cleared before statepoint sequence completed");
65 StatepointLoweringState::allocateStackSlot(EVT ValueType,
66 SelectionDAGBuilder &Builder) {
68 NumSlotsAllocatedForStatepoints++;
70 // The basic scheme here is to first look for a previously created stack slot
71 // which is not in use (accounting for the fact arbitrary slots may already
72 // be reserved), or to create a new stack slot and use it.
74 // If this doesn't succeed in 40000 iterations, something is seriously wrong
75 for (int i = 0; i < 40000; i++) {
76 assert(Builder.FuncInfo.StatepointStackSlots.size() ==
77 AllocatedStackSlots.size() &&
79 const size_t NumSlots = AllocatedStackSlots.size();
80 assert(NextSlotToAllocate <= NumSlots && "broken invariant");
82 if (NextSlotToAllocate >= NumSlots) {
83 assert(NextSlotToAllocate == NumSlots);
85 if (NumSlots + 1 > StatepointMaxSlotsRequired) {
86 StatepointMaxSlotsRequired = NumSlots + 1;
89 SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
90 const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
91 Builder.FuncInfo.StatepointStackSlots.push_back(FI);
92 AllocatedStackSlots.push_back(true);
95 if (!AllocatedStackSlots[NextSlotToAllocate]) {
96 const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
97 AllocatedStackSlots[NextSlotToAllocate] = true;
98 return Builder.DAG.getFrameIndex(FI, ValueType);
100 // Note: We deliberately choose to advance this only on the failing path.
101 // Doing so on the suceeding path involes a bit of complexity that caused a
102 // minor bug previously. Unless performance shows this matters, please
103 // keep this code as simple as possible.
104 NextSlotToAllocate++;
106 llvm_unreachable("infinite loop?");
109 /// Try to find existing copies of the incoming values in stack slots used for
110 /// statepoint spilling. If we can find a spill slot for the incoming value,
111 /// mark that slot as allocated, and reuse the same slot for this safepoint.
112 /// This helps to avoid series of loads and stores that only serve to resuffle
113 /// values on the stack between calls.
114 static void reservePreviousStackSlotForValue(SDValue Incoming,
115 SelectionDAGBuilder &Builder) {
117 if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
118 // We won't need to spill this, so no need to check for previously
119 // allocated stack slots
123 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
125 // duplicates in input
129 // Search back for the load from a stack slot pattern to find the original
130 // slot we allocated for this value. We could extend this to deal with
131 // simple modification patterns, but simple dealing with trivial load/store
132 // sequences helps a lot already.
133 if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Incoming)) {
134 if (auto *FI = dyn_cast<FrameIndexSDNode>(Load->getBasePtr())) {
135 const int Index = FI->getIndex();
136 auto Itr = std::find(Builder.FuncInfo.StatepointStackSlots.begin(),
137 Builder.FuncInfo.StatepointStackSlots.end(), Index);
138 if (Itr == Builder.FuncInfo.StatepointStackSlots.end()) {
139 // not one of the lowering stack slots, can't reuse!
140 // TODO: Actually, we probably could reuse the stack slot if the value
141 // hasn't changed at all, but we'd need to look for intervening writes
144 // This is one of our dedicated lowering slots
146 std::distance(Builder.FuncInfo.StatepointStackSlots.begin(), Itr);
147 if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
148 // stack slot already assigned to someone else, can't use it!
149 // TODO: currently we reserve space for gc arguments after doing
150 // normal allocation for deopt arguments. We should reserve for
151 // _all_ deopt and gc arguments, then start allocating. This
152 // will prevent some moves being inserted when vm state changes,
153 // but gc state doesn't between two calls.
156 // Reserve this stack slot
157 Builder.StatepointLowering.reserveStackSlot(Offset);
160 // Cache this slot so we find it when going through the normal
163 Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
165 Builder.StatepointLowering.setLocation(Incoming, Loc);
169 // TODO: handle case where a reloaded value flows through a phi to
170 // another safepoint. e.g.
173 // bb2: % pred: bb1, bb3, bb4, etc.
174 // a_phi = phi(a', ...)
175 // statepoint ... a_phi
176 // NOTE: This will require reasoning about cross basic block values. This is
177 // decidedly non trivial and this might not be the right place to do it. We
178 // don't really have the information we need here...
180 // TODO: handle simple updates. If a value is modified and the original
181 // value is no longer live, it would be nice to put the modified value in the
182 // same slot. This allows folding of the memory accesses for some
183 // instructions types (like an increment).
189 /// Remove any duplicate (as SDValues) from the derived pointer pairs. This
190 /// is not required for correctness. It's purpose is to reduce the size of
191 /// StackMap section. It has no effect on the number of spill slots required
192 /// or the actual lowering.
193 static void removeDuplicatesGCPtrs(SmallVectorImpl<const Value *> &Bases,
194 SmallVectorImpl<const Value *> &Ptrs,
195 SmallVectorImpl<const Value *> &Relocs,
196 SelectionDAGBuilder &Builder) {
198 // This is horribly ineffecient, but I don't care right now
199 SmallSet<SDValue, 64> Seen;
201 SmallVector<const Value *, 64> NewBases, NewPtrs, NewRelocs;
202 for (size_t i = 0; i < Ptrs.size(); i++) {
203 SDValue SD = Builder.getValue(Ptrs[i]);
204 // Only add non-duplicates
205 if (Seen.count(SD) == 0) {
206 NewBases.push_back(Bases[i]);
207 NewPtrs.push_back(Ptrs[i]);
208 NewRelocs.push_back(Relocs[i]);
212 assert(Bases.size() >= NewBases.size());
213 assert(Ptrs.size() >= NewPtrs.size());
214 assert(Relocs.size() >= NewRelocs.size());
218 assert(Ptrs.size() == Bases.size());
219 assert(Ptrs.size() == Relocs.size());
222 /// Extract call from statepoint, lower it and return pointer to the
223 /// call node. Also update NodeMap so that getValue(statepoint) will
224 /// reference lowered call result
225 static SDNode *lowerCallFromStatepoint(ImmutableStatepoint StatepointSite,
226 MachineBasicBlock *LandingPad,
227 SelectionDAGBuilder &Builder) {
229 ImmutableCallSite CS(StatepointSite.getCallSite());
231 // Lower the actual call itself - This is a bit of a hack, but we want to
232 // avoid modifying the actual lowering code. This is similiar in intent to
233 // the LowerCallOperands mechanism used by PATCHPOINT, but is structured
234 // differently. Hopefully, this is slightly more robust w.r.t. calling
235 // convention, return values, and other function attributes.
236 Value *ActualCallee = const_cast<Value *>(StatepointSite.actualCallee());
238 std::vector<Value *> Args;
239 CallInst::const_op_iterator arg_begin = StatepointSite.call_args_begin();
240 CallInst::const_op_iterator arg_end = StatepointSite.call_args_end();
241 Args.insert(Args.end(), arg_begin, arg_end);
242 // TODO: remove the creation of a new instruction! We should not be
243 // modifying the IR (even temporarily) at this point.
244 CallInst *Tmp = CallInst::Create(ActualCallee, Args);
245 Tmp->setTailCall(CS.isTailCall());
246 Tmp->setCallingConv(CS.getCallingConv());
247 Tmp->setAttributes(CS.getAttributes());
248 Builder.LowerCallTo(Tmp, Builder.getValue(ActualCallee), false, LandingPad);
250 // Handle the return value of the call iff any.
251 const bool HasDef = !Tmp->getType()->isVoidTy();
254 // Result value will be used in different basic block for invokes
255 // so we need to export it now. But statepoint call has a different type
256 // than the actuall call. It means that standart exporting mechanism will
257 // create register of the wrong type. So instead we need to create
258 // register with correct type and save value into it manually.
259 // TODO: To eliminate this problem we can remove gc.result intrinsics
260 // completelly and make statepoint call to return a tuple.
261 unsigned reg = Builder.FuncInfo.CreateRegs(Tmp->getType());
262 Builder.CopyValueToVirtualRegister(Tmp, reg);
263 Builder.FuncInfo.ValueMap[CS.getInstruction()] = reg;
265 // The value of the statepoint itself will be the value of call itself.
266 // We'll replace the actually call node shortly. gc_result will grab
268 Builder.setValue(CS.getInstruction(), Builder.getValue(Tmp));
271 // The token value is never used from here on, just generate a poison value
272 Builder.setValue(CS.getInstruction(),
273 Builder.DAG.getIntPtrConstant(-1, Builder.getCurSDLoc()));
275 // Remove the fake entry we created so we don't have a hanging reference
276 // after we delete this node.
277 Builder.removeValue(Tmp);
281 // Search for the call node
282 // The following code is essentially reverse engineering X86's
284 // We are expecting DAG to have the following form:
285 // ch = eh_label (only in case of invoke statepoint)
286 // ch, glue = callseq_start ch
287 // ch, glue = X86::Call ch, glue
288 // ch, glue = callseq_end ch, glue
289 // ch = eh_label ch (only in case of invoke statepoint)
291 // DAG root will be either last eh_label or callseq_end.
293 SDNode *CallNode = nullptr;
295 // We just emitted a call, so it should be last thing generated
296 SDValue Chain = Builder.DAG.getRoot();
298 // Find closest CALLSEQ_END walking back through lowered nodes if needed
299 SDNode *CallEnd = Chain.getNode();
301 while (CallEnd->getOpcode() != ISD::CALLSEQ_END) {
302 assert(CallEnd->getNumOperands() >= 1 &&
303 CallEnd->getOperand(0).getValueType() == MVT::Other);
305 CallEnd = CallEnd->getOperand(0).getNode();
307 assert(Sanity < 20 && "should have found call end already");
310 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
311 "Expected a callseq node.");
312 assert(CallEnd->getGluedNode());
314 // Step back inside the CALLSEQ
315 CallNode = CallEnd->getGluedNode();
319 /// Callect all gc pointers coming into statepoint intrinsic, clean them up,
320 /// and return two arrays:
321 /// Bases - base pointers incoming to this statepoint
322 /// Ptrs - derived pointers incoming to this statepoint
323 /// Relocs - the gc_relocate corresponding to each base/ptr pair
324 /// Elements of this arrays should be in one-to-one correspondence with each
325 /// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call
326 static void getIncomingStatepointGCValues(
327 SmallVectorImpl<const Value *> &Bases, SmallVectorImpl<const Value *> &Ptrs,
328 SmallVectorImpl<const Value *> &Relocs, ImmutableStatepoint StatepointSite,
329 SelectionDAGBuilder &Builder) {
330 for (GCRelocateOperands relocateOpers :
331 StatepointSite.getRelocates(StatepointSite)) {
332 Relocs.push_back(relocateOpers.getUnderlyingCallSite().getInstruction());
333 Bases.push_back(relocateOpers.basePtr());
334 Ptrs.push_back(relocateOpers.derivedPtr());
337 // Remove any redundant llvm::Values which map to the same SDValue as another
338 // input. Also has the effect of removing duplicates in the original
339 // llvm::Value input list as well. This is a useful optimization for
340 // reducing the size of the StackMap section. It has no other impact.
341 removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder);
343 assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size());
346 /// Spill a value incoming to the statepoint. It might be either part of
348 /// or gcstate. In both cases unconditionally spill it on the stack unless it
349 /// is a null constant. Return pair with first element being frame index
350 /// containing saved value and second element with outgoing chain from the
352 static std::pair<SDValue, SDValue>
353 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
354 SelectionDAGBuilder &Builder) {
355 SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
357 // Emit new store if we didn't do it for this ptr before
358 if (!Loc.getNode()) {
359 Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
361 assert(isa<FrameIndexSDNode>(Loc));
362 int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
363 // We use TargetFrameIndex so that isel will not select it into LEA
364 Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
366 // TODO: We can create TokenFactor node instead of
367 // chaining stores one after another, this may allow
368 // a bit more optimal scheduling for them
369 Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
370 MachinePointerInfo::getFixedStack(Index),
373 Builder.StatepointLowering.setLocation(Incoming, Loc);
376 assert(Loc.getNode());
377 return std::make_pair(Loc, Chain);
380 /// Lower a single value incoming to a statepoint node. This value can be
381 /// either a deopt value or a gc value, the handling is the same. We special
382 /// case constants and allocas, then fall back to spilling if required.
383 static void lowerIncomingStatepointValue(SDValue Incoming,
384 SmallVectorImpl<SDValue> &Ops,
385 SelectionDAGBuilder &Builder) {
386 SDValue Chain = Builder.getRoot();
388 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
389 // If the original value was a constant, make sure it gets recorded as
390 // such in the stackmap. This is required so that the consumer can
391 // parse any internal format to the deopt state. It also handles null
392 // pointers and other constant pointers in GC states
393 Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp,
394 Builder.getCurSDLoc(),
396 Ops.push_back(Builder.DAG.getTargetConstant(C->getSExtValue(),
397 Builder.getCurSDLoc(),
399 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
400 // This handles allocas as arguments to the statepoint (this is only
401 // really meaningful for a deopt value. For GC, we'd be trying to
402 // relocate the address of the alloca itself?)
403 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
404 Incoming.getValueType()));
406 // Otherwise, locate a spill slot and explicitly spill it so it
407 // can be found by the runtime later. We currently do not support
408 // tracking values through callee saved registers to their eventual
409 // spill location. This would be a useful optimization, but would
410 // need to be optional since it requires a lot of complexity on the
411 // runtime side which not all would support.
412 std::pair<SDValue, SDValue> Res =
413 spillIncomingStatepointValue(Incoming, Chain, Builder);
414 Ops.push_back(Res.first);
418 Builder.DAG.setRoot(Chain);
421 /// Lower deopt state and gc pointer arguments of the statepoint. The actual
422 /// lowering is described in lowerIncomingStatepointValue. This function is
423 /// responsible for lowering everything in the right position and playing some
424 /// tricks to avoid redundant stack manipulation where possible. On
425 /// completion, 'Ops' will contain ready to use operands for machine code
426 /// statepoint. The chain nodes will have already been created and the DAG root
427 /// will be set to the last value spilled (if any were).
428 static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
429 ImmutableStatepoint StatepointSite,
430 SelectionDAGBuilder &Builder) {
432 // Lower the deopt and gc arguments for this statepoint. Layout will
433 // be: deopt argument length, deopt arguments.., gc arguments...
435 SmallVector<const Value *, 64> Bases, Ptrs, Relocations;
436 getIncomingStatepointGCValues(Bases, Ptrs, Relocations, StatepointSite,
440 // Check that each of the gc pointer and bases we've gotten out of the
441 // safepoint is something the strategy thinks might be a pointer into the GC
442 // heap. This is basically just here to help catch errors during statepoint
443 // insertion. TODO: This should actually be in the Verifier, but we can't get
444 // to the GCStrategy from there (yet).
445 GCStrategy &S = Builder.GFI->getStrategy();
446 for (const Value *V : Bases) {
447 auto Opt = S.isGCManagedPointer(V);
448 if (Opt.hasValue()) {
449 assert(Opt.getValue() &&
450 "non gc managed base pointer found in statepoint");
453 for (const Value *V : Ptrs) {
454 auto Opt = S.isGCManagedPointer(V);
455 if (Opt.hasValue()) {
456 assert(Opt.getValue() &&
457 "non gc managed derived pointer found in statepoint");
460 for (const Value *V : Relocations) {
461 auto Opt = S.isGCManagedPointer(V);
462 if (Opt.hasValue()) {
463 assert(Opt.getValue() && "non gc managed pointer relocated");
468 // Before we actually start lowering (and allocating spill slots for values),
469 // reserve any stack slots which we judge to be profitable to reuse for a
470 // particular value. This is purely an optimization over the code below and
471 // doesn't change semantics at all. It is important for performance that we
472 // reserve slots for both deopt and gc values before lowering either.
473 for (auto I = StatepointSite.vm_state_begin() + 1,
474 E = StatepointSite.vm_state_end();
477 SDValue Incoming = Builder.getValue(V);
478 reservePreviousStackSlotForValue(Incoming, Builder);
480 for (unsigned i = 0; i < Bases.size() * 2; ++i) {
481 // Even elements will contain base, odd elements - derived ptr
482 const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2];
483 SDValue Incoming = Builder.getValue(V);
484 reservePreviousStackSlotForValue(Incoming, Builder);
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.
490 const int NumVMSArgs = StatepointSite.numTotalVMSArgs();
491 Ops.push_back( Builder.DAG.getTargetConstant(StackMaps::ConstantOp,
492 Builder.getCurSDLoc(),
494 Ops.push_back(Builder.DAG.getTargetConstant(NumVMSArgs, Builder.getCurSDLoc(),
497 assert(NumVMSArgs + 1 == std::distance(StatepointSite.vm_state_begin(),
498 StatepointSite.vm_state_end()));
500 // The vm state arguments are lowered in an opaque manner. We do
501 // not know what type of values are contained within. We skip the
502 // first one since that happens to be the total number we lowered
503 // explicitly just above. We could have left it in the loop and
504 // not done it explicitly, but it's far easier to understand this
506 for (auto I = StatepointSite.vm_state_begin() + 1,
507 E = StatepointSite.vm_state_end();
510 SDValue Incoming = Builder.getValue(V);
511 lowerIncomingStatepointValue(Incoming, Ops, Builder);
514 // Finally, go ahead and lower all the gc arguments. There's no prefixed
515 // length for this one. After lowering, we'll have the base and pointer
516 // arrays interwoven with each (lowered) base pointer immediately followed by
517 // it's (lowered) derived pointer. i.e
518 // (base[0], ptr[0], base[1], ptr[1], ...)
519 for (unsigned i = 0; i < Bases.size() * 2; ++i) {
520 // Even elements will contain base, odd elements - derived ptr
521 const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2];
522 SDValue Incoming = Builder.getValue(V);
523 lowerIncomingStatepointValue(Incoming, Ops, Builder);
526 // If there are any explicit spill slots passed to the statepoint, record
527 // them, but otherwise do not do anything special. These are user provided
528 // allocas and give control over placement to the consumer. In this case,
529 // it is the contents of the slot which may get updated, not the pointer to
531 for (Value *V : StatepointSite.gc_args()) {
532 SDValue Incoming = Builder.getValue(V);
533 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
534 // This handles allocas as arguments to the statepoint
535 Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
536 Incoming.getValueType()));
541 void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
542 // Check some preconditions for sanity
543 assert(isStatepoint(&CI) &&
544 "function called must be the statepoint function");
546 LowerStatepoint(ImmutableStatepoint(&CI));
549 void SelectionDAGBuilder::LowerStatepoint(
550 ImmutableStatepoint ISP, MachineBasicBlock *LandingPad /*=nullptr*/) {
551 // The basic scheme here is that information about both the original call and
552 // the safepoint is encoded in the CallInst. We create a temporary call and
553 // lower it, then reverse engineer the calling sequence.
557 StatepointLowering.startNewStatepoint(*this);
559 ImmutableCallSite CS(ISP.getCallSite());
563 for (const User *U : CS->users()) {
564 const CallInst *Call = cast<CallInst>(U);
565 if (isGCRelocate(Call))
566 StatepointLowering.scheduleRelocCall(*Call);
571 // If this is a malformed statepoint, report it early to simplify debugging.
572 // This should catch any IR level mistake that's made when constructing or
573 // transforming statepoints.
576 // Check that the associated GCStrategy expects to encounter statepoints.
577 // TODO: This if should become an assert. For now, we allow the GCStrategy
578 // to be optional for backwards compatibility. This will only last a short
579 // period (i.e. a couple of weeks).
580 assert(GFI->getStrategy().useStatepoints() &&
581 "GCStrategy does not expect to encounter statepoints");
584 // Lower statepoint vmstate and gcstate arguments
585 SmallVector<SDValue, 10> LoweredArgs;
586 lowerStatepointMetaArgs(LoweredArgs, ISP, *this);
588 // Get call node, we will replace it later with statepoint
589 SDNode *CallNode = lowerCallFromStatepoint(ISP, LandingPad, *this);
591 // Construct the actual STATEPOINT node with all the appropriate arguments
592 // and return values.
594 // TODO: Currently, all of these operands are being marked as read/write in
595 // PrologEpilougeInserter.cpp, we should special case the VMState arguments
596 // and flags to be read-only.
597 SmallVector<SDValue, 40> Ops;
599 // Calculate and push starting position of vmstate arguments
600 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
602 if (CallNode->getGluedNode()) {
603 // Glue is always last operand
604 Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
606 // Get number of arguments incoming directly into call node
607 unsigned NumCallRegArgs =
608 CallNode->getNumOperands() - (Glue.getNode() ? 4 : 3);
609 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
612 SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
613 Ops.push_back(CallTarget);
615 // Add call arguments
616 // Get position of register mask in the call
617 SDNode::op_iterator RegMaskIt;
619 RegMaskIt = CallNode->op_end() - 2;
621 RegMaskIt = CallNode->op_end() - 1;
622 Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
624 // Add a leading constant argument with the Flags and the calling convention
626 CallingConv::ID CallConv = CS.getCallingConv();
627 int Flags = cast<ConstantInt>(CS.getArgument(2))->getZExtValue();
628 assert(Flags == 0 && "not expected to be used");
629 Ops.push_back(DAG.getTargetConstant(StackMaps::ConstantOp, getCurSDLoc(),
631 Ops.push_back(DAG.getTargetConstant(Flags | ((unsigned)CallConv << 1),
632 getCurSDLoc(), MVT::i64));
634 // Insert all vmstate and gcstate arguments
635 Ops.insert(Ops.end(), LoweredArgs.begin(), LoweredArgs.end());
637 // Add register mask from call node
638 Ops.push_back(*RegMaskIt);
641 Ops.push_back(CallNode->getOperand(0));
643 // Same for the glue, but we add it only if original call had it
647 // Compute return values. Provide a glue output since we consume one as
648 // input. This allows someone else to chain off us as needed.
649 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
651 SDNode *StatepointMCNode =
652 DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
654 // Replace original call
655 DAG.ReplaceAllUsesWith(CallNode, StatepointMCNode); // This may update Root
656 // Remove originall call node
657 DAG.DeleteNode(CallNode);
659 // DON'T set the root - under the assumption that it's already set past the
660 // inserted node we created.
662 // TODO: A better future implementation would be to emit a single variable
663 // argument, variable return value STATEPOINT node here and then hookup the
664 // return value of each gc.relocate to the respective output of the
665 // previously emitted STATEPOINT value. Unfortunately, this doesn't appear
666 // to actually be possible today.
669 void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
670 // The result value of the gc_result is simply the result of the actual
671 // call. We've already emitted this, so just grab the value.
672 Instruction *I = cast<Instruction>(CI.getArgOperand(0));
673 assert(isStatepoint(I) && "first argument must be a statepoint token");
675 if (isa<InvokeInst>(I)) {
676 // For invokes we should have stored call result in a virtual register.
677 // We can not use default getValue() functionality to copy value from this
678 // register because statepoint and actuall call return types can be
679 // different, and getValue() will use CopyFromReg of the wrong type,
680 // which is always i32 in our case.
681 PointerType *CalleeType =
682 cast<PointerType>(ImmutableStatepoint(I).actualCallee()->getType());
684 cast<FunctionType>(CalleeType->getElementType())->getReturnType();
685 SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
687 assert(CopyFromReg.getNode());
688 setValue(&CI, CopyFromReg);
690 setValue(&CI, getValue(I));
694 void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) {
697 StatepointLowering.relocCallVisited(CI);
700 GCRelocateOperands relocateOpers(&CI);
701 SDValue SD = getValue(relocateOpers.derivedPtr());
703 if (isa<ConstantSDNode>(SD) || isa<FrameIndexSDNode>(SD)) {
704 // We didn't need to spill these special cases (constants and allocas).
705 // See the handling in spillIncomingValueForStatepoint for detail.
710 SDValue Loc = StatepointLowering.getRelocLocation(SD);
711 // Emit new load if we did not emit it before
712 if (!Loc.getNode()) {
713 SDValue SpillSlot = StatepointLowering.getLocation(SD);
714 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
716 // Be conservative: flush all pending loads
717 // TODO: Probably we can be less restrictive on this,
718 // it may allow more scheduling opprtunities
719 SDValue Chain = getRoot();
721 Loc = DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain, SpillSlot,
722 MachinePointerInfo::getFixedStack(FI), false, false,
725 StatepointLowering.setRelocLocation(SD, Loc);
727 // Again, be conservative, don't emit pending loads
728 DAG.setRoot(Loc.getValue(1));
731 assert(Loc.getNode());