1 //===-- 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"
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"
30 #include <algorithm>
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "statepoint-lowering"
34 
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");
40 
41 void
startNewStatepoint(SelectionDAGBuilder & Builder)42 StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
43   // Consistency check
44   assert(PendingGCRelocateCalls.empty() &&
45          "Trying to visit statepoint before finished processing previous one");
46   Locations.clear();
47   RelocLocations.clear();
48   NextSlotToAllocate = 0;
49   // Need to resize this on each safepoint - we need the two to stay in
50   // sync and the clear patterns of a SelectionDAGBuilder have no relation
51   // to FunctionLoweringInfo.
52   AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
53   for (size_t i = 0; i < AllocatedStackSlots.size(); i++) {
54     AllocatedStackSlots[i] = false;
55   }
56 }
clear()57 void StatepointLoweringState::clear() {
58   Locations.clear();
59   RelocLocations.clear();
60   AllocatedStackSlots.clear();
61   assert(PendingGCRelocateCalls.empty() &&
62          "cleared before statepoint sequence completed");
63 }
64 
65 SDValue
allocateStackSlot(EVT ValueType,SelectionDAGBuilder & Builder)66 StatepointLoweringState::allocateStackSlot(EVT ValueType,
67                                            SelectionDAGBuilder &Builder) {
68 
69   NumSlotsAllocatedForStatepoints++;
70 
71   // The basic scheme here is to first look for a previously created stack slot
72   // which is not in use (accounting for the fact arbitrary slots may already
73   // be reserved), or to create a new stack slot and use it.
74 
75   // If this doesn't succeed in 40000 iterations, something is seriously wrong
76   for (int i = 0; i < 40000; i++) {
77     assert(Builder.FuncInfo.StatepointStackSlots.size() ==
78                AllocatedStackSlots.size() &&
79            "broken invariant");
80     const size_t NumSlots = AllocatedStackSlots.size();
81     assert(NextSlotToAllocate <= NumSlots && "broken invariant");
82 
83     if (NextSlotToAllocate >= NumSlots) {
84       assert(NextSlotToAllocate == NumSlots);
85       // record stats
86       if (NumSlots + 1 > StatepointMaxSlotsRequired) {
87         StatepointMaxSlotsRequired = NumSlots + 1;
88       }
89 
90       SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
91       const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
92       Builder.FuncInfo.StatepointStackSlots.push_back(FI);
93       AllocatedStackSlots.push_back(true);
94       return SpillSlot;
95     }
96     if (!AllocatedStackSlots[NextSlotToAllocate]) {
97       const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
98       AllocatedStackSlots[NextSlotToAllocate] = true;
99       return Builder.DAG.getFrameIndex(FI, ValueType);
100     }
101     // Note: We deliberately choose to advance this only on the failing path.
102     // Doing so on the suceeding path involes a bit of complexity that caused a
103     // minor bug previously.  Unless performance shows this matters, please
104     // keep this code as simple as possible.
105     NextSlotToAllocate++;
106   }
107   llvm_unreachable("infinite loop?");
108 }
109 
110 /// Try to find existing copies of the incoming values in stack slots used for
111 /// statepoint spilling.  If we can find a spill slot for the incoming value,
112 /// mark that slot as allocated, and reuse the same slot for this safepoint.
113 /// This helps to avoid series of loads and stores that only serve to resuffle
114 /// values on the stack between calls.
reservePreviousStackSlotForValue(SDValue Incoming,SelectionDAGBuilder & Builder)115 static void reservePreviousStackSlotForValue(SDValue Incoming,
116                                              SelectionDAGBuilder &Builder) {
117 
118   if (isa<ConstantSDNode>(Incoming) || isa<FrameIndexSDNode>(Incoming)) {
119     // We won't need to spill this, so no need to check for previously
120     // allocated stack slots
121     return;
122   }
123 
124   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
125   if (Loc.getNode()) {
126     // duplicates in input
127     return;
128   }
129 
130   // Search back for the load from a stack slot pattern to find the original
131   // slot we allocated for this value.  We could extend this to deal with
132   // simple modification patterns, but simple dealing with trivial load/store
133   // sequences helps a lot already.
134   if (LoadSDNode *Load = dyn_cast<LoadSDNode>(Incoming)) {
135     if (auto *FI = dyn_cast<FrameIndexSDNode>(Load->getBasePtr())) {
136       const int Index = FI->getIndex();
137       auto Itr = std::find(Builder.FuncInfo.StatepointStackSlots.begin(),
138                            Builder.FuncInfo.StatepointStackSlots.end(), Index);
139       if (Itr == Builder.FuncInfo.StatepointStackSlots.end()) {
140         // not one of the lowering stack slots, can't reuse!
141         // TODO: Actually, we probably could reuse the stack slot if the value
142         // hasn't changed at all, but we'd need to look for intervening writes
143         return;
144       } else {
145         // This is one of our dedicated lowering slots
146         const int Offset =
147             std::distance(Builder.FuncInfo.StatepointStackSlots.begin(), Itr);
148         if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
149           // stack slot already assigned to someone else, can't use it!
150           // TODO: currently we reserve space for gc arguments after doing
151           // normal allocation for deopt arguments.  We should reserve for
152           // _all_ deopt and gc arguments, then start allocating.  This
153           // will prevent some moves being inserted when vm state changes,
154           // but gc state doesn't between two calls.
155           return;
156         }
157         // Reserve this stack slot
158         Builder.StatepointLowering.reserveStackSlot(Offset);
159       }
160 
161       // Cache this slot so we find it when going through the normal
162       // assignment loop.
163       SDValue Loc =
164           Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
165 
166       Builder.StatepointLowering.setLocation(Incoming, Loc);
167     }
168   }
169 
170   // TODO: handle case where a reloaded value flows through a phi to
171   // another safepoint.  e.g.
172   // bb1:
173   //  a' = relocated...
174   // bb2: % pred: bb1, bb3, bb4, etc.
175   //  a_phi = phi(a', ...)
176   // statepoint ... a_phi
177   // NOTE: This will require reasoning about cross basic block values.  This is
178   // decidedly non trivial and this might not be the right place to do it.  We
179   // don't really have the information we need here...
180 
181   // TODO: handle simple updates.  If a value is modified and the original
182   // value is no longer live, it would be nice to put the modified value in the
183   // same slot.  This allows folding of the memory accesses for some
184   // instructions types (like an increment).
185   // statepoint (i)
186   // i1 = i+1
187   // statepoint (i1)
188 }
189 
190 /// Remove any duplicate (as SDValues) from the derived pointer pairs.  This
191 /// is not required for correctness.  It's purpose is to reduce the size of
192 /// StackMap section.  It has no effect on the number of spill slots required
193 /// or the actual lowering.
removeDuplicatesGCPtrs(SmallVectorImpl<const Value * > & Bases,SmallVectorImpl<const Value * > & Ptrs,SmallVectorImpl<const Value * > & Relocs,SelectionDAGBuilder & Builder)194 static void removeDuplicatesGCPtrs(SmallVectorImpl<const Value *> &Bases,
195                                    SmallVectorImpl<const Value *> &Ptrs,
196                                    SmallVectorImpl<const Value *> &Relocs,
197                                    SelectionDAGBuilder &Builder) {
198 
199   // This is horribly ineffecient, but I don't care right now
200   SmallSet<SDValue, 64> Seen;
201 
202   SmallVector<const Value *, 64> NewBases, NewPtrs, NewRelocs;
203   for (size_t i = 0; i < Ptrs.size(); i++) {
204     SDValue SD = Builder.getValue(Ptrs[i]);
205     // Only add non-duplicates
206     if (Seen.count(SD) == 0) {
207       NewBases.push_back(Bases[i]);
208       NewPtrs.push_back(Ptrs[i]);
209       NewRelocs.push_back(Relocs[i]);
210     }
211     Seen.insert(SD);
212   }
213   assert(Bases.size() >= NewBases.size());
214   assert(Ptrs.size() >= NewPtrs.size());
215   assert(Relocs.size() >= NewRelocs.size());
216   Bases = NewBases;
217   Ptrs = NewPtrs;
218   Relocs = NewRelocs;
219   assert(Ptrs.size() == Bases.size());
220   assert(Ptrs.size() == Relocs.size());
221 }
222 
223 /// Extract call from statepoint, lower it and return pointer to the
224 /// call node. Also update NodeMap so that getValue(statepoint) will
225 /// reference lowered call result
lowerCallFromStatepoint(ImmutableStatepoint StatepointSite,MachineBasicBlock * LandingPad,SelectionDAGBuilder & Builder)226 static SDNode *lowerCallFromStatepoint(ImmutableStatepoint StatepointSite,
227                                        MachineBasicBlock *LandingPad,
228                                        SelectionDAGBuilder &Builder) {
229 
230   ImmutableCallSite CS(StatepointSite.getCallSite());
231 
232   // Lower the actual call itself - This is a bit of a hack, but we want to
233   // avoid modifying the actual lowering code.  This is similiar in intent to
234   // the LowerCallOperands mechanism used by PATCHPOINT, but is structured
235   // differently.  Hopefully, this is slightly more robust w.r.t. calling
236   // convention, return values, and other function attributes.
237   Value *ActualCallee = const_cast<Value *>(StatepointSite.actualCallee());
238 
239   std::vector<Value *> Args;
240   CallInst::const_op_iterator arg_begin = StatepointSite.call_args_begin();
241   CallInst::const_op_iterator arg_end = StatepointSite.call_args_end();
242   Args.insert(Args.end(), arg_begin, arg_end);
243   // TODO: remove the creation of a new instruction!  We should not be
244   // modifying the IR (even temporarily) at this point.
245   CallInst *Tmp = CallInst::Create(ActualCallee, Args);
246   Tmp->setTailCall(CS.isTailCall());
247   Tmp->setCallingConv(CS.getCallingConv());
248   Tmp->setAttributes(CS.getAttributes());
249   Builder.LowerCallTo(Tmp, Builder.getValue(ActualCallee), false, LandingPad);
250 
251   // Handle the return value of the call iff any.
252   const bool HasDef = !Tmp->getType()->isVoidTy();
253   if (HasDef) {
254     if (CS.isInvoke()) {
255       // Result value will be used in different basic block for invokes
256       // so we need to export it now. But statepoint call has a different type
257       // than the actuall call. It means that standart exporting mechanism will
258       // create register of the wrong type. So instead we need to create
259       // register with correct type and save value into it manually.
260       // TODO: To eliminate this problem we can remove gc.result intrinsics
261       //       completelly and make statepoint call to return a tuple.
262       unsigned reg = Builder.FuncInfo.CreateRegs(Tmp->getType());
263       Builder.CopyValueToVirtualRegister(Tmp, reg);
264       Builder.FuncInfo.ValueMap[CS.getInstruction()] = reg;
265     }
266     else {
267       // The value of the statepoint itself will be the value of call itself.
268       // We'll replace the actually call node shortly.  gc_result will grab
269       // this value.
270       Builder.setValue(CS.getInstruction(), Builder.getValue(Tmp));
271     }
272   } else {
273     // The token value is never used from here on, just generate a poison value
274     Builder.setValue(CS.getInstruction(), Builder.DAG.getIntPtrConstant(-1));
275   }
276   // Remove the fake entry we created so we don't have a hanging reference
277   // after we delete this node.
278   Builder.removeValue(Tmp);
279   delete Tmp;
280   Tmp = nullptr;
281 
282   // Search for the call node
283   // The following code is essentially reverse engineering X86's
284   // LowerCallTo.
285   // We are expecting DAG to have the following form:
286   // ch = eh_label (only in case of invoke statepoint)
287   //   ch, glue = callseq_start ch
288   //   ch, glue = X86::Call ch, glue
289   //   ch, glue = callseq_end ch, glue
290   // ch = eh_label ch (only in case of invoke statepoint)
291   //
292   // DAG root will be either last eh_label or callseq_end.
293 
294   SDNode *CallNode = nullptr;
295 
296   // We just emitted a call, so it should be last thing generated
297   SDValue Chain = Builder.DAG.getRoot();
298 
299   // Find closest CALLSEQ_END walking back through lowered nodes if needed
300   SDNode *CallEnd = Chain.getNode();
301   int Sanity = 0;
302   while (CallEnd->getOpcode() != ISD::CALLSEQ_END) {
303     assert(CallEnd->getNumOperands() >= 1 &&
304            CallEnd->getOperand(0).getValueType() == MVT::Other);
305 
306     CallEnd = CallEnd->getOperand(0).getNode();
307 
308     assert(Sanity < 20 && "should have found call end already");
309     Sanity++;
310   }
311   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
312          "Expected a callseq node.");
313   assert(CallEnd->getGluedNode());
314 
315   // Step back inside the CALLSEQ
316   CallNode = CallEnd->getGluedNode();
317   return CallNode;
318 }
319 
320 /// Callect all gc pointers coming into statepoint intrinsic, clean them up,
321 /// and return two arrays:
322 ///   Bases - base pointers incoming to this statepoint
323 ///   Ptrs - derived pointers incoming to this statepoint
324 ///   Relocs - the gc_relocate corresponding to each base/ptr pair
325 /// Elements of this arrays should be in one-to-one correspondence with each
326 /// other i.e Bases[i], Ptrs[i] are from the same gcrelocate call
327 static void
getIncomingStatepointGCValues(SmallVectorImpl<const Value * > & Bases,SmallVectorImpl<const Value * > & Ptrs,SmallVectorImpl<const Value * > & Relocs,ImmutableStatepoint StatepointSite,SelectionDAGBuilder & Builder)328 getIncomingStatepointGCValues(SmallVectorImpl<const Value *> &Bases,
329                               SmallVectorImpl<const Value *> &Ptrs,
330                               SmallVectorImpl<const Value *> &Relocs,
331                               ImmutableStatepoint StatepointSite,
332                               SelectionDAGBuilder &Builder) {
333   for (GCRelocateOperands relocateOpers :
334          StatepointSite.getRelocates(StatepointSite)) {
335     Relocs.push_back(relocateOpers.getUnderlyingCallSite().getInstruction());
336     Bases.push_back(relocateOpers.basePtr());
337     Ptrs.push_back(relocateOpers.derivedPtr());
338   }
339 
340   // Remove any redundant llvm::Values which map to the same SDValue as another
341   // input.  Also has the effect of removing duplicates in the original
342   // llvm::Value input list as well.  This is a useful optimization for
343   // reducing the size of the StackMap section.  It has no other impact.
344   removeDuplicatesGCPtrs(Bases, Ptrs, Relocs, Builder);
345 
346   assert(Bases.size() == Ptrs.size() && Ptrs.size() == Relocs.size());
347 }
348 
349 /// Spill a value incoming to the statepoint. It might be either part of
350 /// vmstate
351 /// or gcstate. In both cases unconditionally spill it on the stack unless it
352 /// is a null constant. Return pair with first element being frame index
353 /// containing saved value and second element with outgoing chain from the
354 /// emitted store
355 static std::pair<SDValue, SDValue>
spillIncomingStatepointValue(SDValue Incoming,SDValue Chain,SelectionDAGBuilder & Builder)356 spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
357                              SelectionDAGBuilder &Builder) {
358   SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
359 
360   // Emit new store if we didn't do it for this ptr before
361   if (!Loc.getNode()) {
362     Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
363                                                        Builder);
364     assert(isa<FrameIndexSDNode>(Loc));
365     int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
366     // We use TargetFrameIndex so that isel will not select it into LEA
367     Loc = Builder.DAG.getTargetFrameIndex(Index, Incoming.getValueType());
368 
369     // TODO: We can create TokenFactor node instead of
370     //       chaining stores one after another, this may allow
371     //       a bit more optimal scheduling for them
372     Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
373                                  MachinePointerInfo::getFixedStack(Index),
374                                  false, false, 0);
375 
376     Builder.StatepointLowering.setLocation(Incoming, Loc);
377   }
378 
379   assert(Loc.getNode());
380   return std::make_pair(Loc, Chain);
381 }
382 
383 /// Lower a single value incoming to a statepoint node.  This value can be
384 /// either a deopt value or a gc value, the handling is the same.  We special
385 /// case constants and allocas, then fall back to spilling if required.
lowerIncomingStatepointValue(SDValue Incoming,SmallVectorImpl<SDValue> & Ops,SelectionDAGBuilder & Builder)386 static void lowerIncomingStatepointValue(SDValue Incoming,
387                                          SmallVectorImpl<SDValue> &Ops,
388                                          SelectionDAGBuilder &Builder) {
389   SDValue Chain = Builder.getRoot();
390 
391   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
392     // If the original value was a constant, make sure it gets recorded as
393     // such in the stackmap.  This is required so that the consumer can
394     // parse any internal format to the deopt state.  It also handles null
395     // pointers and other constant pointers in GC states
396     Ops.push_back(
397         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
398     Ops.push_back(Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
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()));
405   } else {
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);
415     Chain = Res.second;
416   }
417 
418   Builder.DAG.setRoot(Chain);
419 }
420 
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).
lowerStatepointMetaArgs(SmallVectorImpl<SDValue> & Ops,ImmutableStatepoint StatepointSite,SelectionDAGBuilder & Builder)428 static void lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
429                                     ImmutableStatepoint StatepointSite,
430                                     SelectionDAGBuilder &Builder) {
431 
432   // Lower the deopt and gc arguments for this statepoint.  Layout will
433   // be: deopt argument length, deopt arguments.., gc arguments...
434 
435   SmallVector<const Value *, 64> Bases, Ptrs, Relocations;
436   getIncomingStatepointGCValues(Bases, Ptrs, Relocations,
437                                 StatepointSite, Builder);
438 
439 #ifndef NDEBUG
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");
451     }
452   }
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");
458     }
459   }
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");
464     }
465   }
466 #endif
467 
468 
469 
470   // Before we actually start lowering (and allocating spill slots for values),
471   // reserve any stack slots which we judge to be profitable to reuse for a
472   // particular value.  This is purely an optimization over the code below and
473   // doesn't change semantics at all.  It is important for performance that we
474   // reserve slots for both deopt and gc values before lowering either.
475   for (auto I = StatepointSite.vm_state_begin() + 1,
476             E = StatepointSite.vm_state_end();
477        I != E; ++I) {
478     Value *V = *I;
479     SDValue Incoming = Builder.getValue(V);
480     reservePreviousStackSlotForValue(Incoming, Builder);
481   }
482   for (unsigned i = 0; i < Bases.size() * 2; ++i) {
483     // Even elements will contain base, odd elements - derived ptr
484     const Value *V = i % 2 ? Bases[i / 2] : Ptrs[i / 2];
485     SDValue Incoming = Builder.getValue(V);
486     reservePreviousStackSlotForValue(Incoming, Builder);
487   }
488 
489   // First, prefix the list with the number of unique values to be
490   // lowered.  Note that this is the number of *Values* not the
491   // number of SDValues required to lower them.
492   const int NumVMSArgs = StatepointSite.numTotalVMSArgs();
493   Ops.push_back(
494       Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
495   Ops.push_back(Builder.DAG.getTargetConstant(NumVMSArgs, MVT::i64));
496 
497   assert(NumVMSArgs + 1 == std::distance(StatepointSite.vm_state_begin(),
498                                          StatepointSite.vm_state_end()));
499 
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
505   // way.
506   for (auto I = StatepointSite.vm_state_begin() + 1,
507             E = StatepointSite.vm_state_end();
508        I != E; ++I) {
509     const Value *V = *I;
510     SDValue Incoming = Builder.getValue(V);
511     lowerIncomingStatepointValue(Incoming, Ops, Builder);
512   }
513 
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);
524   }
525 
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
530   // the alloca
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()));
537 
538     }
539   }
540 }
541 
visitStatepoint(const CallInst & CI)542 void SelectionDAGBuilder::visitStatepoint(const CallInst &CI) {
543   // Check some preconditions for sanity
544   assert(isStatepoint(&CI) &&
545          "function called must be the statepoint function");
546 
547   LowerStatepoint(ImmutableStatepoint(&CI));
548 }
549 
550 void
LowerStatepoint(ImmutableStatepoint ISP,MachineBasicBlock * LandingPad)551 SelectionDAGBuilder::LowerStatepoint(ImmutableStatepoint ISP,
552                                      MachineBasicBlock *LandingPad/*=nullptr*/) {
553   // The basic scheme here is that information about both the original call and
554   // the safepoint is encoded in the CallInst.  We create a temporary call and
555   // lower it, then reverse engineer the calling sequence.
556 
557   NumOfStatepoints++;
558   // Clear state
559   StatepointLowering.startNewStatepoint(*this);
560 
561   ImmutableCallSite CS(ISP.getCallSite());
562 
563 #ifndef NDEBUG
564   // Consistency check
565   for (const User *U : CS->users()) {
566     const CallInst *Call = cast<CallInst>(U);
567     if (isGCRelocate(Call))
568       StatepointLowering.scheduleRelocCall(*Call);
569   }
570 #endif
571 
572 #ifndef NDEBUG
573   // If this is a malformed statepoint, report it early to simplify debugging.
574   // This should catch any IR level mistake that's made when constructing or
575   // transforming statepoints.
576   ISP.verify();
577 
578   // Check that the associated GCStrategy expects to encounter statepoints.
579   // TODO: This if should become an assert.  For now, we allow the GCStrategy
580   // to be optional for backwards compatibility.  This will only last a short
581   // period (i.e. a couple of weeks).
582   assert(GFI->getStrategy().useStatepoints() &&
583          "GCStrategy does not expect to encounter statepoints");
584 #endif
585 
586   // Lower statepoint vmstate and gcstate arguments
587   SmallVector<SDValue, 10> LoweredArgs;
588   lowerStatepointMetaArgs(LoweredArgs, ISP, *this);
589 
590   // Get call node, we will replace it later with statepoint
591   SDNode *CallNode = lowerCallFromStatepoint(ISP, LandingPad, *this);
592 
593   // Construct the actual STATEPOINT node with all the appropriate arguments
594   // and return values.
595 
596   // TODO: Currently, all of these operands are being marked as read/write in
597   // PrologEpilougeInserter.cpp, we should special case the VMState arguments
598   // and flags to be read-only.
599   SmallVector<SDValue, 40> Ops;
600 
601   // Calculate and push starting position of vmstate arguments
602   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
603   SDValue Glue;
604   if (CallNode->getGluedNode()) {
605     // Glue is always last operand
606     Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
607   }
608   // Get number of arguments incoming directly into call node
609   unsigned NumCallRegArgs =
610       CallNode->getNumOperands() - (Glue.getNode() ? 4 : 3);
611   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
612 
613   // Add call target
614   SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
615   Ops.push_back(CallTarget);
616 
617   // Add call arguments
618   // Get position of register mask in the call
619   SDNode::op_iterator RegMaskIt;
620   if (Glue.getNode())
621     RegMaskIt = CallNode->op_end() - 2;
622   else
623     RegMaskIt = CallNode->op_end() - 1;
624   Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
625 
626   // Add a leading constant argument with the Flags and the calling convention
627   // masked together
628   CallingConv::ID CallConv = CS.getCallingConv();
629   int Flags = cast<ConstantInt>(CS.getArgument(2))->getZExtValue();
630   assert(Flags == 0 && "not expected to be used");
631   Ops.push_back(DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
632   Ops.push_back(
633       DAG.getTargetConstant(Flags | ((unsigned)CallConv << 1), MVT::i64));
634 
635   // Insert all vmstate and gcstate arguments
636   Ops.insert(Ops.end(), LoweredArgs.begin(), LoweredArgs.end());
637 
638   // Add register mask from call node
639   Ops.push_back(*RegMaskIt);
640 
641   // Add chain
642   Ops.push_back(CallNode->getOperand(0));
643 
644   // Same for the glue, but we add it only if original call had it
645   if (Glue.getNode())
646     Ops.push_back(Glue);
647 
648   // Compute return values.  Provide a glue output since we consume one as
649   // input.  This allows someone else to chain off us as needed.
650   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
651 
652   SDNode *StatepointMCNode = DAG.getMachineNode(TargetOpcode::STATEPOINT,
653                                                 getCurSDLoc(), NodeTys, Ops);
654 
655   // Replace original call
656   DAG.ReplaceAllUsesWith(CallNode, StatepointMCNode); // This may update Root
657   // Remove originall call node
658   DAG.DeleteNode(CallNode);
659 
660   // DON'T set the root - under the assumption that it's already set past the
661   // inserted node we created.
662 
663   // TODO: A better future implementation would be to emit a single variable
664   // argument, variable return value STATEPOINT node here and then hookup the
665   // return value of each gc.relocate to the respective output of the
666   // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
667   // to actually be possible today.
668 }
669 
visitGCResult(const CallInst & CI)670 void SelectionDAGBuilder::visitGCResult(const CallInst &CI) {
671   // The result value of the gc_result is simply the result of the actual
672   // call.  We've already emitted this, so just grab the value.
673   Instruction *I = cast<Instruction>(CI.getArgOperand(0));
674   assert(isStatepoint(I) &&
675          "first argument must be a statepoint token");
676 
677   if (isa<InvokeInst>(I)) {
678     // For invokes we should have stored call result in a virtual register.
679     // We can not use default getValue() functionality to copy value from this
680     // register because statepoint and actuall call return types can be
681     // different, and getValue() will use CopyFromReg of the wrong type,
682     // which is always i32 in our case.
683     PointerType *CalleeType = cast<PointerType>(
684                                 ImmutableStatepoint(I).actualCallee()->getType());
685     Type *RetTy = cast<FunctionType>(
686                                 CalleeType->getElementType())->getReturnType();
687     SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
688 
689     assert(CopyFromReg.getNode());
690     setValue(&CI, CopyFromReg);
691   }
692   else {
693     setValue(&CI, getValue(I));
694   }
695 }
696 
visitGCRelocate(const CallInst & CI)697 void SelectionDAGBuilder::visitGCRelocate(const CallInst &CI) {
698 #ifndef NDEBUG
699   // Consistency check
700   StatepointLowering.relocCallVisited(CI);
701 #endif
702 
703   GCRelocateOperands relocateOpers(&CI);
704   SDValue SD = getValue(relocateOpers.derivedPtr());
705 
706   if (isa<ConstantSDNode>(SD) || isa<FrameIndexSDNode>(SD)) {
707     // We didn't need to spill these special cases (constants and allocas).
708     // See the handling in spillIncomingValueForStatepoint for detail.
709     setValue(&CI, SD);
710     return;
711   }
712 
713   SDValue Loc = StatepointLowering.getRelocLocation(SD);
714   // Emit new load if we did not emit it before
715   if (!Loc.getNode()) {
716     SDValue SpillSlot = StatepointLowering.getLocation(SD);
717     int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
718 
719     // Be conservative: flush all pending loads
720     // TODO: Probably we can be less restrictive on this,
721     // it may allow more scheduling opprtunities
722     SDValue Chain = getRoot();
723 
724     Loc = DAG.getLoad(SpillSlot.getValueType(), getCurSDLoc(), Chain,
725                       SpillSlot, MachinePointerInfo::getFixedStack(FI), false,
726                       false, false, 0);
727 
728     StatepointLowering.setRelocLocation(SD, Loc);
729 
730     // Again, be conservative, don't emit pending loads
731     DAG.setRoot(Loc.getValue(1));
732   }
733 
734   assert(Loc.getNode());
735   setValue(&CI, Loc);
736 }
737