Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/CodeGen/SelectionDAG/StatepointLowering.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- StatepointLowering.cpp - SDAGBuilder's statepoint code -------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file includes support code use by SelectionDAGBuilder when lowering a
10
// statepoint sequence in SelectionDAG IR.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "StatepointLowering.h"
15
#include "SelectionDAGBuilder.h"
16
#include "llvm/ADT/ArrayRef.h"
17
#include "llvm/ADT/DenseMap.h"
18
#include "llvm/ADT/None.h"
19
#include "llvm/ADT/Optional.h"
20
#include "llvm/ADT/STLExtras.h"
21
#include "llvm/ADT/SmallVector.h"
22
#include "llvm/ADT/Statistic.h"
23
#include "llvm/CodeGen/FunctionLoweringInfo.h"
24
#include "llvm/CodeGen/GCMetadata.h"
25
#include "llvm/CodeGen/GCStrategy.h"
26
#include "llvm/CodeGen/ISDOpcodes.h"
27
#include "llvm/CodeGen/MachineFrameInfo.h"
28
#include "llvm/CodeGen/MachineFunction.h"
29
#include "llvm/CodeGen/MachineMemOperand.h"
30
#include "llvm/CodeGen/RuntimeLibcalls.h"
31
#include "llvm/CodeGen/SelectionDAG.h"
32
#include "llvm/CodeGen/SelectionDAGNodes.h"
33
#include "llvm/CodeGen/StackMaps.h"
34
#include "llvm/CodeGen/TargetLowering.h"
35
#include "llvm/CodeGen/TargetOpcodes.h"
36
#include "llvm/IR/CallingConv.h"
37
#include "llvm/IR/DerivedTypes.h"
38
#include "llvm/IR/Instruction.h"
39
#include "llvm/IR/Instructions.h"
40
#include "llvm/IR/LLVMContext.h"
41
#include "llvm/IR/Statepoint.h"
42
#include "llvm/IR/Type.h"
43
#include "llvm/Support/Casting.h"
44
#include "llvm/Support/MachineValueType.h"
45
#include "llvm/Target/TargetMachine.h"
46
#include "llvm/Target/TargetOptions.h"
47
#include <cassert>
48
#include <cstddef>
49
#include <cstdint>
50
#include <iterator>
51
#include <tuple>
52
#include <utility>
53
54
using namespace llvm;
55
56
#define DEBUG_TYPE "statepoint-lowering"
57
58
STATISTIC(NumSlotsAllocatedForStatepoints,
59
          "Number of stack slots allocated for statepoints");
60
STATISTIC(NumOfStatepoints, "Number of statepoint nodes encountered");
61
STATISTIC(StatepointMaxSlotsRequired,
62
          "Maximum number of stack slots required for a singe statepoint");
63
64
static void pushStackMapConstant(SmallVectorImpl<SDValue>& Ops,
65
338
                                 SelectionDAGBuilder &Builder, uint64_t Value) {
66
338
  SDLoc L = Builder.getCurSDLoc();
67
338
  Ops.push_back(Builder.DAG.getTargetConstant(StackMaps::ConstantOp, L,
68
338
                                              MVT::i64));
69
338
  Ops.push_back(Builder.DAG.getTargetConstant(Value, L, MVT::i64));
70
338
}
71
72
88
void StatepointLoweringState::startNewStatepoint(SelectionDAGBuilder &Builder) {
73
88
  // Consistency check
74
88
  assert(PendingGCRelocateCalls.empty() &&
75
88
         "Trying to visit statepoint before finished processing previous one");
76
88
  Locations.clear();
77
88
  NextSlotToAllocate = 0;
78
88
  // Need to resize this on each safepoint - we need the two to stay in sync and
79
88
  // the clear patterns of a SelectionDAGBuilder have no relation to
80
88
  // FunctionLoweringInfo.  Also need to ensure used bits get cleared.
81
88
  AllocatedStackSlots.clear();
82
88
  AllocatedStackSlots.resize(Builder.FuncInfo.StatepointStackSlots.size());
83
88
}
84
85
1.24M
void StatepointLoweringState::clear() {
86
1.24M
  Locations.clear();
87
1.24M
  AllocatedStackSlots.clear();
88
1.24M
  assert(PendingGCRelocateCalls.empty() &&
89
1.24M
         "cleared before statepoint sequence completed");
90
1.24M
}
91
92
SDValue
93
StatepointLoweringState::allocateStackSlot(EVT ValueType,
94
69
                                           SelectionDAGBuilder &Builder) {
95
69
  NumSlotsAllocatedForStatepoints++;
96
69
  MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
97
69
98
69
  unsigned SpillSize = ValueType.getStoreSize();
99
69
  assert((SpillSize * 8) == ValueType.getSizeInBits() && "Size not in bytes?");
100
69
101
69
  // First look for a previously created stack slot which is not in
102
69
  // use (accounting for the fact arbitrary slots may already be
103
69
  // reserved), or to create a new stack slot and use it.
104
69
105
69
  const size_t NumSlots = AllocatedStackSlots.size();
106
69
  assert(NextSlotToAllocate <= NumSlots && "Broken invariant");
107
69
108
69
  assert(AllocatedStackSlots.size() ==
109
69
         Builder.FuncInfo.StatepointStackSlots.size() &&
110
69
         "Broken invariant");
111
69
112
96
  for (; NextSlotToAllocate < NumSlots; 
NextSlotToAllocate++27
) {
113
38
    if (!AllocatedStackSlots.test(NextSlotToAllocate)) {
114
13
      const int FI = Builder.FuncInfo.StatepointStackSlots[NextSlotToAllocate];
115
13
      if (MFI.getObjectSize(FI) == SpillSize) {
116
11
        AllocatedStackSlots.set(NextSlotToAllocate);
117
11
        // TODO: Is ValueType the right thing to use here?
118
11
        return Builder.DAG.getFrameIndex(FI, ValueType);
119
11
      }
120
13
    }
121
38
  }
122
69
123
69
  // Couldn't find a free slot, so create a new one:
124
69
125
69
  SDValue SpillSlot = Builder.DAG.CreateStackTemporary(ValueType);
126
58
  const unsigned FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
127
58
  MFI.markAsStatepointSpillSlotObjectIndex(FI);
128
58
129
58
  Builder.FuncInfo.StatepointStackSlots.push_back(FI);
130
58
  AllocatedStackSlots.resize(AllocatedStackSlots.size()+1, true);
131
58
  assert(AllocatedStackSlots.size() ==
132
58
         Builder.FuncInfo.StatepointStackSlots.size() &&
133
58
         "Broken invariant");
134
58
135
58
  StatepointMaxSlotsRequired.updateMax(
136
58
      Builder.FuncInfo.StatepointStackSlots.size());
137
58
138
58
  return SpillSlot;
139
69
}
140
141
/// Utility function for reservePreviousStackSlotForValue. Tries to find
142
/// stack slot index to which we have spilled value for previous statepoints.
143
/// LookUpDepth specifies maximum DFS depth this function is allowed to look.
144
static Optional<int> findPreviousSpillSlot(const Value *Val,
145
                                           SelectionDAGBuilder &Builder,
146
136
                                           int LookUpDepth) {
147
136
  // Can not look any further - give up now
148
136
  if (LookUpDepth <= 0)
149
0
    return None;
150
136
151
136
  // Spill location is known for gc relocates
152
136
  if (const auto *Relocate = dyn_cast<GCRelocateInst>(Val)) {
153
9
    const auto &SpillMap =
154
9
        Builder.FuncInfo.StatepointSpillMaps[Relocate->getStatepoint()];
155
9
156
9
    auto It = SpillMap.find(Relocate->getDerivedPtr());
157
9
    if (It == SpillMap.end())
158
0
      return None;
159
9
160
9
    return It->second;
161
9
  }
162
127
163
127
  // Look through bitcast instructions.
164
127
  if (const BitCastInst *Cast = dyn_cast<BitCastInst>(Val))
165
3
    return findPreviousSpillSlot(Cast->getOperand(0), Builder, LookUpDepth - 1);
166
124
167
124
  // Look through phi nodes
168
124
  // All incoming values should have same known stack slot, otherwise result
169
124
  // is unknown.
170
124
  if (const PHINode *Phi = dyn_cast<PHINode>(Val)) {
171
0
    Optional<int> MergedResult = None;
172
0
173
0
    for (auto &IncomingValue : Phi->incoming_values()) {
174
0
      Optional<int> SpillSlot =
175
0
          findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth - 1);
176
0
      if (!SpillSlot.hasValue())
177
0
        return None;
178
0
179
0
      if (MergedResult.hasValue() && *MergedResult != *SpillSlot)
180
0
        return None;
181
0
182
0
      MergedResult = SpillSlot;
183
0
    }
184
0
    return MergedResult;
185
124
  }
186
124
187
124
  // TODO: We can do better for PHI nodes. In cases like this:
188
124
  //   ptr = phi(relocated_pointer, not_relocated_pointer)
189
124
  //   statepoint(ptr)
190
124
  // We will return that stack slot for ptr is unknown. And later we might
191
124
  // assign different stack slots for ptr and relocated_pointer. This limits
192
124
  // llvm's ability to remove redundant stores.
193
124
  // Unfortunately it's hard to accomplish in current infrastructure.
194
124
  // We use this function to eliminate spill store completely, while
195
124
  // in example we still need to emit store, but instead of any location
196
124
  // we need to use special "preferred" location.
197
124
198
124
  // TODO: handle simple updates.  If a value is modified and the original
199
124
  // value is no longer live, it would be nice to put the modified value in the
200
124
  // same slot.  This allows folding of the memory accesses for some
201
124
  // instructions types (like an increment).
202
124
  //   statepoint (i)
203
124
  //   i1 = i+1
204
124
  //   statepoint (i1)
205
124
  // However we need to be careful for cases like this:
206
124
  //   statepoint(i)
207
124
  //   i1 = i+1
208
124
  //   statepoint(i, i1)
209
124
  // Here we want to reserve spill slot for 'i', but not for 'i+1'. If we just
210
124
  // put handling of simple modifications in this function like it's done
211
124
  // for bitcasts we might end up reserving i's slot for 'i+1' because order in
212
124
  // which we visit values is unspecified.
213
124
214
124
  // Don't know any information about this instruction
215
124
  return None;
216
124
}
217
218
/// Try to find existing copies of the incoming values in stack slots used for
219
/// statepoint spilling.  If we can find a spill slot for the incoming value,
220
/// mark that slot as allocated, and reuse the same slot for this safepoint.
221
/// This helps to avoid series of loads and stores that only serve to reshuffle
222
/// values on the stack between calls.
223
static void reservePreviousStackSlotForValue(const Value *IncomingValue,
224
221
                                             SelectionDAGBuilder &Builder) {
225
221
  SDValue Incoming = Builder.getValue(IncomingValue);
226
221
227
221
  if (isa<ConstantSDNode>(Incoming) || 
isa<FrameIndexSDNode>(Incoming)147
) {
228
77
    // We won't need to spill this, so no need to check for previously
229
77
    // allocated stack slots
230
77
    return;
231
77
  }
232
144
233
144
  SDValue OldLocation = Builder.StatepointLowering.getLocation(Incoming);
234
144
  if (OldLocation.getNode())
235
11
    // Duplicates in input
236
11
    return;
237
133
238
133
  const int LookUpDepth = 6;
239
133
  Optional<int> Index =
240
133
      findPreviousSpillSlot(IncomingValue, Builder, LookUpDepth);
241
133
  if (!Index.hasValue())
242
124
    return;
243
9
244
9
  const auto &StatepointSlots = Builder.FuncInfo.StatepointStackSlots;
245
9
246
9
  auto SlotIt = find(StatepointSlots, *Index);
247
9
  assert(SlotIt != StatepointSlots.end() &&
248
9
         "Value spilled to the unknown stack slot");
249
9
250
9
  // This is one of our dedicated lowering slots
251
9
  const int Offset = std::distance(StatepointSlots.begin(), SlotIt);
252
9
  if (Builder.StatepointLowering.isStackSlotAllocated(Offset)) {
253
0
    // stack slot already assigned to someone else, can't use it!
254
0
    // TODO: currently we reserve space for gc arguments after doing
255
0
    // normal allocation for deopt arguments.  We should reserve for
256
0
    // _all_ deopt and gc arguments, then start allocating.  This
257
0
    // will prevent some moves being inserted when vm state changes,
258
0
    // but gc state doesn't between two calls.
259
0
    return;
260
0
  }
261
9
  // Reserve this stack slot
262
9
  Builder.StatepointLowering.reserveStackSlot(Offset);
263
9
264
9
  // Cache this slot so we find it when going through the normal
265
9
  // assignment loop.
266
9
  SDValue Loc =
267
9
      Builder.DAG.getTargetFrameIndex(*Index, Builder.getFrameIndexTy());
268
9
  Builder.StatepointLowering.setLocation(Incoming, Loc);
269
9
}
270
271
/// Remove any duplicate (as SDValues) from the derived pointer pairs.  This
272
/// is not required for correctness.  It's purpose is to reduce the size of
273
/// StackMap section.  It has no effect on the number of spill slots required
274
/// or the actual lowering.
275
static void
276
removeDuplicateGCPtrs(SmallVectorImpl<const Value *> &Bases,
277
                      SmallVectorImpl<const Value *> &Ptrs,
278
                      SmallVectorImpl<const GCRelocateInst *> &Relocs,
279
                      SelectionDAGBuilder &Builder,
280
88
                      FunctionLoweringInfo::StatepointSpillMap &SSM) {
281
88
  DenseMap<SDValue, const Value *> Seen;
282
88
283
88
  SmallVector<const Value *, 64> NewBases, NewPtrs;
284
88
  SmallVector<const GCRelocateInst *, 64> NewRelocs;
285
158
  for (size_t i = 0, e = Ptrs.size(); i < e; 
i++70
) {
286
70
    SDValue SD = Builder.getValue(Ptrs[i]);
287
70
    auto SeenIt = Seen.find(SD);
288
70
289
70
    if (SeenIt == Seen.end()) {
290
62
      // Only add non-duplicates
291
62
      NewBases.push_back(Bases[i]);
292
62
      NewPtrs.push_back(Ptrs[i]);
293
62
      NewRelocs.push_back(Relocs[i]);
294
62
      Seen[SD] = Ptrs[i];
295
62
    } else {
296
8
      // Duplicate pointer found, note in SSM and move on:
297
8
      SSM.DuplicateMap[Ptrs[i]] = SeenIt->second;
298
8
    }
299
70
  }
300
88
  assert(Bases.size() >= NewBases.size());
301
88
  assert(Ptrs.size() >= NewPtrs.size());
302
88
  assert(Relocs.size() >= NewRelocs.size());
303
88
  Bases = NewBases;
304
88
  Ptrs = NewPtrs;
305
88
  Relocs = NewRelocs;
306
88
  assert(Ptrs.size() == Bases.size());
307
88
  assert(Ptrs.size() == Relocs.size());
308
88
}
309
310
/// Extract call from statepoint, lower it and return pointer to the
311
/// call node. Also update NodeMap so that getValue(statepoint) will
312
/// reference lowered call result
313
static std::pair<SDValue, SDNode *> lowerCallFromStatepointLoweringInfo(
314
    SelectionDAGBuilder::StatepointLoweringInfo &SI,
315
88
    SelectionDAGBuilder &Builder, SmallVectorImpl<SDValue> &PendingExports) {
316
88
  SDValue ReturnValue, CallEndVal;
317
88
  std::tie(ReturnValue, CallEndVal) =
318
88
      Builder.lowerInvokable(SI.CLI, SI.EHPadBB);
319
88
  SDNode *CallEnd = CallEndVal.getNode();
320
88
321
88
  // Get a call instruction from the call sequence chain.  Tail calls are not
322
88
  // allowed.  The following code is essentially reverse engineering X86's
323
88
  // LowerCallTo.
324
88
  //
325
88
  // We are expecting DAG to have the following form:
326
88
  //
327
88
  // ch = eh_label (only in case of invoke statepoint)
328
88
  //   ch, glue = callseq_start ch
329
88
  //   ch, glue = X86::Call ch, glue
330
88
  //   ch, glue = callseq_end ch, glue
331
88
  //   get_return_value ch, glue
332
88
  //
333
88
  // get_return_value can either be a sequence of CopyFromReg instructions
334
88
  // to grab the return value from the return register(s), or it can be a LOAD
335
88
  // to load a value returned by reference via a stack slot.
336
88
337
88
  bool HasDef = !SI.CLI.RetTy->isVoidTy();
338
88
  if (HasDef) {
339
26
    if (CallEnd->getOpcode() == ISD::LOAD)
340
0
      CallEnd = CallEnd->getOperand(0).getNode();
341
26
    else
342
53
      
while (26
CallEnd->getOpcode() == ISD::CopyFromReg)
343
27
        CallEnd = CallEnd->getOperand(0).getNode();
344
26
  }
345
88
346
88
  assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && "expected!");
347
88
  return std::make_pair(ReturnValue, CallEnd->getOperand(0).getNode());
348
88
}
349
350
static MachineMemOperand* getMachineMemOperand(MachineFunction &MF,
351
79
                                               FrameIndexSDNode &FI) {
352
79
  auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FI.getIndex());
353
79
  auto MMOFlags = MachineMemOperand::MOStore |
354
79
    MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
355
79
  auto &MFI = MF.getFrameInfo();
356
79
  return MF.getMachineMemOperand(PtrInfo, MMOFlags, 
357
79
                                 MFI.getObjectSize(FI.getIndex()),
358
79
                                 MFI.getObjectAlignment(FI.getIndex()));
359
79
}
360
361
/// Spill a value incoming to the statepoint. It might be either part of
362
/// vmstate
363
/// or gcstate. In both cases unconditionally spill it on the stack unless it
364
/// is a null constant. Return pair with first element being frame index
365
/// containing saved value and second element with outgoing chain from the
366
/// emitted store
367
static std::tuple<SDValue, SDValue, MachineMemOperand*>
368
spillIncomingStatepointValue(SDValue Incoming, SDValue Chain,
369
142
                             SelectionDAGBuilder &Builder) {
370
142
  SDValue Loc = Builder.StatepointLowering.getLocation(Incoming);
371
142
  MachineMemOperand* MMO = nullptr;
372
142
373
142
  // Emit new store if we didn't do it for this ptr before
374
142
  if (!Loc.getNode()) {
375
69
    Loc = Builder.StatepointLowering.allocateStackSlot(Incoming.getValueType(),
376
69
                                                       Builder);
377
69
    int Index = cast<FrameIndexSDNode>(Loc)->getIndex();
378
69
    // We use TargetFrameIndex so that isel will not select it into LEA
379
69
    Loc = Builder.DAG.getTargetFrameIndex(Index, Builder.getFrameIndexTy());
380
69
381
69
    // Right now we always allocate spill slots that are of the same
382
69
    // size as the value we're about to spill (the size of spillee can
383
69
    // vary since we spill vectors of pointers too).  At some point we
384
69
    // can consider allowing spills of smaller values to larger slots
385
69
    // (i.e. change the '==' in the assert below to a '>=').
386
69
    MachineFrameInfo &MFI = Builder.DAG.getMachineFunction().getFrameInfo();
387
69
    assert((MFI.getObjectSize(Index) * 8) == Incoming.getValueSizeInBits() &&
388
69
           "Bad spill:  stack slot does not match!");
389
69
390
69
    // Note: Using the alignment of the spill slot (rather than the abi or
391
69
    // preferred alignment) is required for correctness when dealing with spill
392
69
    // slots with preferred alignments larger than frame alignment..
393
69
    auto &MF = Builder.DAG.getMachineFunction();
394
69
    auto PtrInfo = MachinePointerInfo::getFixedStack(MF, Index);
395
69
    auto *StoreMMO =
396
69
      MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore, 
397
69
                              MFI.getObjectSize(Index),
398
69
                              MFI.getObjectAlignment(Index));
399
69
    Chain = Builder.DAG.getStore(Chain, Builder.getCurSDLoc(), Incoming, Loc,
400
69
                                 StoreMMO);
401
69
402
69
    MMO = getMachineMemOperand(MF, *cast<FrameIndexSDNode>(Loc));
403
69
    
404
69
    Builder.StatepointLowering.setLocation(Incoming, Loc);
405
69
  }
406
142
407
142
  assert(Loc.getNode());
408
142
  return std::make_tuple(Loc, Chain, MMO);
409
142
}
410
411
/// Lower a single value incoming to a statepoint node.  This value can be
412
/// either a deopt value or a gc value, the handling is the same.  We special
413
/// case constants and allocas, then fall back to spilling if required.
414
static void lowerIncomingStatepointValue(SDValue Incoming, bool LiveInOnly,
415
                                         SmallVectorImpl<SDValue> &Ops,
416
                                         SmallVectorImpl<MachineMemOperand*> &MemRefs,
417
428
                                         SelectionDAGBuilder &Builder) {
418
428
  // Note: We know all of these spills are independent, but don't bother to
419
428
  // exploit that chain wise.  DAGCombine will happily do so as needed, so
420
428
  // doing it here would be a small compile time win at most.
421
428
  SDValue Chain = Builder.getRoot();
422
428
423
428
  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Incoming)) {
424
74
    // If the original value was a constant, make sure it gets recorded as
425
74
    // such in the stackmap.  This is required so that the consumer can
426
74
    // parse any internal format to the deopt state.  It also handles null
427
74
    // pointers and other constant pointers in GC states.  Note the constant
428
74
    // vectors do not appear to actually hit this path and that anything larger
429
74
    // than an i64 value (not type!) will fail asserts here.
430
74
    pushStackMapConstant(Ops, Builder, C->getSExtValue());
431
354
  } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
432
8
    // This handles allocas as arguments to the statepoint (this is only
433
8
    // really meaningful for a deopt value.  For GC, we'd be trying to
434
8
    // relocate the address of the alloca itself?)
435
8
    assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
436
8
           "Incoming value is a frame index!");
437
8
    Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
438
8
                                                  Builder.getFrameIndexTy()));
439
8
440
8
    auto &MF = Builder.DAG.getMachineFunction();
441
8
    auto *MMO = getMachineMemOperand(MF, *FI);
442
8
    MemRefs.push_back(MMO);
443
8
    
444
346
  } else if (LiveInOnly) {
445
204
    // If this value is live in (not live-on-return, or live-through), we can
446
204
    // treat it the same way patchpoint treats it's "live in" values.  We'll
447
204
    // end up folding some of these into stack references, but they'll be
448
204
    // handled by the register allocator.  Note that we do not have the notion
449
204
    // of a late use so these values might be placed in registers which are
450
204
    // clobbered by the call.  This is fine for live-in.
451
204
    Ops.push_back(Incoming);
452
204
  } else {
453
142
    // Otherwise, locate a spill slot and explicitly spill it so it
454
142
    // can be found by the runtime later.  We currently do not support
455
142
    // tracking values through callee saved registers to their eventual
456
142
    // spill location.  This would be a useful optimization, but would
457
142
    // need to be optional since it requires a lot of complexity on the
458
142
    // runtime side which not all would support.
459
142
    auto Res = spillIncomingStatepointValue(Incoming, Chain, Builder);
460
142
    Ops.push_back(std::get<0>(Res));
461
142
    if (auto *MMO = std::get<2>(Res))
462
69
      MemRefs.push_back(MMO);
463
142
    Chain = std::get<1>(Res);;
464
142
  }
465
428
466
428
  Builder.DAG.setRoot(Chain);
467
428
}
468
469
/// Lower deopt state and gc pointer arguments of the statepoint.  The actual
470
/// lowering is described in lowerIncomingStatepointValue.  This function is
471
/// responsible for lowering everything in the right position and playing some
472
/// tricks to avoid redundant stack manipulation where possible.  On
473
/// completion, 'Ops' will contain ready to use operands for machine code
474
/// statepoint. The chain nodes will have already been created and the DAG root
475
/// will be set to the last value spilled (if any were).
476
static void
477
lowerStatepointMetaArgs(SmallVectorImpl<SDValue> &Ops,
478
                        SmallVectorImpl<MachineMemOperand*> &MemRefs,                                    SelectionDAGBuilder::StatepointLoweringInfo &SI,
479
88
                        SelectionDAGBuilder &Builder) {
480
88
  // Lower the deopt and gc arguments for this statepoint.  Layout will be:
481
88
  // deopt argument length, deopt arguments.., gc arguments...
482
#ifndef NDEBUG
483
  if (auto *GFI = Builder.GFI) {
484
    // Check that each of the gc pointer and bases we've gotten out of the
485
    // safepoint is something the strategy thinks might be a pointer (or vector
486
    // of pointers) into the GC heap.  This is basically just here to help catch
487
    // errors during statepoint insertion. TODO: This should actually be in the
488
    // Verifier, but we can't get to the GCStrategy from there (yet).
489
    GCStrategy &S = GFI->getStrategy();
490
    for (const Value *V : SI.Bases) {
491
      auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
492
      if (Opt.hasValue()) {
493
        assert(Opt.getValue() &&
494
               "non gc managed base pointer found in statepoint");
495
      }
496
    }
497
    for (const Value *V : SI.Ptrs) {
498
      auto Opt = S.isGCManagedPointer(V->getType()->getScalarType());
499
      if (Opt.hasValue()) {
500
        assert(Opt.getValue() &&
501
               "non gc managed derived pointer found in statepoint");
502
      }
503
    }
504
    assert(SI.Bases.size() == SI.Ptrs.size() && "Pointer without base!");
505
  } else {
506
    assert(SI.Bases.empty() && "No gc specified, so cannot relocate pointers!");
507
    assert(SI.Ptrs.empty() && "No gc specified, so cannot relocate pointers!");
508
  }
509
#endif
510
511
88
  // Figure out what lowering strategy we're going to use for each part
512
88
  // Note: Is is conservatively correct to lower both "live-in" and "live-out"
513
88
  // as "live-through". A "live-through" variable is one which is "live-in",
514
88
  // "live-out", and live throughout the lifetime of the call (i.e. we can find
515
88
  // it from any PC within the transitive callee of the statepoint).  In
516
88
  // particular, if the callee spills callee preserved registers we may not
517
88
  // be able to find a value placed in that register during the call.  This is
518
88
  // fine for live-out, but not for live-through.  If we were willing to make
519
88
  // assumptions about the code generator producing the callee, we could
520
88
  // potentially allow live-through values in callee saved registers.
521
88
  const bool LiveInDeopt =
522
88
    SI.StatepointFlags & (uint64_t)StatepointFlags::DeoptLiveIn;
523
88
524
414
  auto isGCValue =[&](const Value *V) {
525
414
    return is_contained(SI.Ptrs, V) || is_contained(SI.Bases, V);
526
414
  };
527
88
528
88
  // Before we actually start lowering (and allocating spill slots for values),
529
88
  // reserve any stack slots which we judge to be profitable to reuse for a
530
88
  // particular value.  This is purely an optimization over the code below and
531
88
  // doesn't change semantics at all.  It is important for performance that we
532
88
  // reserve slots for both deopt and gc values before lowering either.
533
304
  for (const Value *V : SI.DeoptState) {
534
304
    if (!LiveInDeopt || 
isGCValue(V)207
)
535
97
      reservePreviousStackSlotForValue(V, Builder);
536
304
  }
537
150
  for (unsigned i = 0; i < SI.Bases.size(); 
++i62
) {
538
62
    reservePreviousStackSlotForValue(SI.Bases[i], Builder);
539
62
    reservePreviousStackSlotForValue(SI.Ptrs[i], Builder);
540
62
  }
541
88
542
88
  // First, prefix the list with the number of unique values to be
543
88
  // lowered.  Note that this is the number of *Values* not the
544
88
  // number of SDValues required to lower them.
545
88
  const int NumVMSArgs = SI.DeoptState.size();
546
88
  pushStackMapConstant(Ops, Builder, NumVMSArgs);
547
88
548
88
  // The vm state arguments are lowered in an opaque manner.  We do not know
549
88
  // what type of values are contained within.
550
304
  for (const Value *V : SI.DeoptState) {
551
304
    SDValue Incoming;
552
304
    // If this is a function argument at a static frame index, generate it as
553
304
    // the frame index.
554
304
    if (const Argument *Arg = dyn_cast<Argument>(V)) {
555
145
      int FI = Builder.FuncInfo.getArgumentFrameIndex(Arg);
556
145
      if (FI != INT_MAX)
557
145
        
Incoming = Builder.DAG.getFrameIndex(FI, Builder.getFrameIndexTy())2
;
558
145
    }
559
304
    if (!Incoming.getNode())
560
302
      Incoming = Builder.getValue(V);
561
304
    const bool LiveInValue = LiveInDeopt && 
!isGCValue(V)207
;
562
304
    lowerIncomingStatepointValue(Incoming, LiveInValue, Ops, MemRefs, Builder);
563
304
  }
564
88
565
88
  // Finally, go ahead and lower all the gc arguments.  There's no prefixed
566
88
  // length for this one.  After lowering, we'll have the base and pointer
567
88
  // arrays interwoven with each (lowered) base pointer immediately followed by
568
88
  // it's (lowered) derived pointer.  i.e
569
88
  // (base[0], ptr[0], base[1], ptr[1], ...)
570
150
  for (unsigned i = 0; i < SI.Bases.size(); 
++i62
) {
571
62
    const Value *Base = SI.Bases[i];
572
62
    lowerIncomingStatepointValue(Builder.getValue(Base), /*LiveInOnly*/ false,
573
62
                                 Ops, MemRefs, Builder);
574
62
575
62
    const Value *Ptr = SI.Ptrs[i];
576
62
    lowerIncomingStatepointValue(Builder.getValue(Ptr), /*LiveInOnly*/ false,
577
62
                                 Ops, MemRefs, Builder);
578
62
  }
579
88
580
88
  // If there are any explicit spill slots passed to the statepoint, record
581
88
  // them, but otherwise do not do anything special.  These are user provided
582
88
  // allocas and give control over placement to the consumer.  In this case,
583
88
  // it is the contents of the slot which may get updated, not the pointer to
584
88
  // the alloca
585
88
  for (Value *V : SI.GCArgs) {
586
69
    SDValue Incoming = Builder.getValue(V);
587
69
    if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Incoming)) {
588
2
      // This handles allocas as arguments to the statepoint
589
2
      assert(Incoming.getValueType() == Builder.getFrameIndexTy() &&
590
2
             "Incoming value is a frame index!");
591
2
      Ops.push_back(Builder.DAG.getTargetFrameIndex(FI->getIndex(),
592
2
                                                    Builder.getFrameIndexTy()));
593
2
594
2
      auto &MF = Builder.DAG.getMachineFunction();
595
2
      auto *MMO = getMachineMemOperand(MF, *FI);
596
2
      MemRefs.push_back(MMO);
597
2
    }
598
69
  }
599
88
600
88
  // Record computed locations for all lowered values.
601
88
  // This can not be embedded in lowering loops as we need to record *all*
602
88
  // values, while previous loops account only values with unique SDValues.
603
88
  const Instruction *StatepointInstr = SI.StatepointInstr;
604
88
  auto &SpillMap = Builder.FuncInfo.StatepointSpillMaps[StatepointInstr];
605
88
606
88
  for (const GCRelocateInst *Relocate : SI.GCRelocates) {
607
62
    const Value *V = Relocate->getDerivedPtr();
608
62
    SDValue SDV = Builder.getValue(V);
609
62
    SDValue Loc = Builder.StatepointLowering.getLocation(SDV);
610
62
611
62
    if (Loc.getNode()) {
612
55
      SpillMap.SlotMap[V] = cast<FrameIndexSDNode>(Loc)->getIndex();
613
55
    } else {
614
7
      // Record value as visited, but not spilled. This is case for allocas
615
7
      // and constants. For this values we can avoid emitting spill load while
616
7
      // visiting corresponding gc_relocate.
617
7
      // Actually we do not need to record them in this map at all.
618
7
      // We do this only to check that we are not relocating any unvisited
619
7
      // value.
620
7
      SpillMap.SlotMap[V] = None;
621
7
622
7
      // Default llvm mechanisms for exporting values which are used in
623
7
      // different basic blocks does not work for gc relocates.
624
7
      // Note that it would be incorrect to teach llvm that all relocates are
625
7
      // uses of the corresponding values so that it would automatically
626
7
      // export them. Relocates of the spilled values does not use original
627
7
      // value.
628
7
      if (Relocate->getParent() != StatepointInstr->getParent())
629
3
        Builder.ExportFromCurrentBlock(V);
630
7
    }
631
62
  }
632
88
}
633
634
SDValue SelectionDAGBuilder::LowerAsSTATEPOINT(
635
88
    SelectionDAGBuilder::StatepointLoweringInfo &SI) {
636
88
  // The basic scheme here is that information about both the original call and
637
88
  // the safepoint is encoded in the CallInst.  We create a temporary call and
638
88
  // lower it, then reverse engineer the calling sequence.
639
88
640
88
  NumOfStatepoints++;
641
88
  // Clear state
642
88
  StatepointLowering.startNewStatepoint(*this);
643
88
644
#ifndef NDEBUG
645
  // We schedule gc relocates before removeDuplicateGCPtrs since we _will_
646
  // encounter the duplicate gc relocates we elide in removeDuplicateGCPtrs.
647
  for (auto *Reloc : SI.GCRelocates)
648
    if (Reloc->getParent() == SI.StatepointInstr->getParent())
649
      StatepointLowering.scheduleRelocCall(*Reloc);
650
#endif
651
652
88
  // Remove any redundant llvm::Values which map to the same SDValue as another
653
88
  // input.  Also has the effect of removing duplicates in the original
654
88
  // llvm::Value input list as well.  This is a useful optimization for
655
88
  // reducing the size of the StackMap section.  It has no other impact.
656
88
  removeDuplicateGCPtrs(SI.Bases, SI.Ptrs, SI.GCRelocates, *this,
657
88
                        FuncInfo.StatepointSpillMaps[SI.StatepointInstr]);
658
88
  assert(SI.Bases.size() == SI.Ptrs.size() &&
659
88
         SI.Ptrs.size() == SI.GCRelocates.size());
660
88
661
88
  // Lower statepoint vmstate and gcstate arguments
662
88
  SmallVector<SDValue, 10> LoweredMetaArgs;
663
88
  SmallVector<MachineMemOperand*, 16> MemRefs;
664
88
  lowerStatepointMetaArgs(LoweredMetaArgs, MemRefs, SI, *this);
665
88
666
88
  // Now that we've emitted the spills, we need to update the root so that the
667
88
  // call sequence is ordered correctly.
668
88
  SI.CLI.setChain(getRoot());
669
88
670
88
  // Get call node, we will replace it later with statepoint
671
88
  SDValue ReturnVal;
672
88
  SDNode *CallNode;
673
88
  std::tie(ReturnVal, CallNode) =
674
88
      lowerCallFromStatepointLoweringInfo(SI, *this, PendingExports);
675
88
676
88
  // Construct the actual GC_TRANSITION_START, STATEPOINT, and GC_TRANSITION_END
677
88
  // nodes with all the appropriate arguments and return values.
678
88
679
88
  // Call Node: Chain, Target, {Args}, RegMask, [Glue]
680
88
  SDValue Chain = CallNode->getOperand(0);
681
88
682
88
  SDValue Glue;
683
88
  bool CallHasIncomingGlue = CallNode->getGluedNode();
684
88
  if (CallHasIncomingGlue) {
685
14
    // Glue is always last operand
686
14
    Glue = CallNode->getOperand(CallNode->getNumOperands() - 1);
687
14
  }
688
88
689
88
  // Build the GC_TRANSITION_START node if necessary.
690
88
  //
691
88
  // The operands to the GC_TRANSITION_{START,END} nodes are laid out in the
692
88
  // order in which they appear in the call to the statepoint intrinsic. If
693
88
  // any of the operands is a pointer-typed, that operand is immediately
694
88
  // followed by a SRCVALUE for the pointer that may be used during lowering
695
88
  // (e.g. to form MachinePointerInfo values for loads/stores).
696
88
  const bool IsGCTransition =
697
88
      (SI.StatepointFlags & (uint64_t)StatepointFlags::GCTransition) ==
698
88
      (uint64_t)StatepointFlags::GCTransition;
699
88
  if (IsGCTransition) {
700
8
    SmallVector<SDValue, 8> TSOps;
701
8
702
8
    // Add chain
703
8
    TSOps.push_back(Chain);
704
8
705
8
    // Add GC transition arguments
706
8
    for (const Value *V : SI.GCTransitionArgs) {
707
1
      TSOps.push_back(getValue(V));
708
1
      if (V->getType()->isPointerTy())
709
1
        TSOps.push_back(DAG.getSrcValue(V));
710
1
    }
711
8
712
8
    // Add glue if necessary
713
8
    if (CallHasIncomingGlue)
714
2
      TSOps.push_back(Glue);
715
8
716
8
    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
717
8
718
8
    SDValue GCTransitionStart =
719
8
        DAG.getNode(ISD::GC_TRANSITION_START, getCurSDLoc(), NodeTys, TSOps);
720
8
721
8
    Chain = GCTransitionStart.getValue(0);
722
8
    Glue = GCTransitionStart.getValue(1);
723
8
  }
724
88
725
88
  // TODO: Currently, all of these operands are being marked as read/write in
726
88
  // PrologEpilougeInserter.cpp, we should special case the VMState arguments
727
88
  // and flags to be read-only.
728
88
  SmallVector<SDValue, 40> Ops;
729
88
730
88
  // Add the <id> and <numBytes> constants.
731
88
  Ops.push_back(DAG.getTargetConstant(SI.ID, getCurSDLoc(), MVT::i64));
732
88
  Ops.push_back(
733
88
      DAG.getTargetConstant(SI.NumPatchBytes, getCurSDLoc(), MVT::i32));
734
88
735
88
  // Calculate and push starting position of vmstate arguments
736
88
  // Get number of arguments incoming directly into call node
737
88
  unsigned NumCallRegArgs =
738
88
      CallNode->getNumOperands() - (CallHasIncomingGlue ? 
414
:
374
);
739
88
  Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, getCurSDLoc(), MVT::i32));
740
88
741
88
  // Add call target
742
88
  SDValue CallTarget = SDValue(CallNode->getOperand(1).getNode(), 0);
743
88
  Ops.push_back(CallTarget);
744
88
745
88
  // Add call arguments
746
88
  // Get position of register mask in the call
747
88
  SDNode::op_iterator RegMaskIt;
748
88
  if (CallHasIncomingGlue)
749
14
    RegMaskIt = CallNode->op_end() - 2;
750
74
  else
751
74
    RegMaskIt = CallNode->op_end() - 1;
752
88
  Ops.insert(Ops.end(), CallNode->op_begin() + 2, RegMaskIt);
753
88
754
88
  // Add a constant argument for the calling convention
755
88
  pushStackMapConstant(Ops, *this, SI.CLI.CallConv);
756
88
757
88
  // Add a constant argument for the flags
758
88
  uint64_t Flags = SI.StatepointFlags;
759
88
  assert(((Flags & ~(uint64_t)StatepointFlags::MaskAll) == 0) &&
760
88
         "Unknown flag used");
761
88
  pushStackMapConstant(Ops, *this, Flags);
762
88
763
88
  // Insert all vmstate and gcstate arguments
764
88
  Ops.insert(Ops.end(), LoweredMetaArgs.begin(), LoweredMetaArgs.end());
765
88
766
88
  // Add register mask from call node
767
88
  Ops.push_back(*RegMaskIt);
768
88
769
88
  // Add chain
770
88
  Ops.push_back(Chain);
771
88
772
88
  // Same for the glue, but we add it only if original call had it
773
88
  if (Glue.getNode())
774
20
    Ops.push_back(Glue);
775
88
776
88
  // Compute return values.  Provide a glue output since we consume one as
777
88
  // input.  This allows someone else to chain off us as needed.
778
88
  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
779
88
780
88
  MachineSDNode *StatepointMCNode =
781
88
    DAG.getMachineNode(TargetOpcode::STATEPOINT, getCurSDLoc(), NodeTys, Ops);
782
88
  DAG.setNodeMemRefs(StatepointMCNode, MemRefs);
783
88
784
88
  SDNode *SinkNode = StatepointMCNode;
785
88
786
88
  // Build the GC_TRANSITION_END node if necessary.
787
88
  //
788
88
  // See the comment above regarding GC_TRANSITION_START for the layout of
789
88
  // the operands to the GC_TRANSITION_END node.
790
88
  if (IsGCTransition) {
791
8
    SmallVector<SDValue, 8> TEOps;
792
8
793
8
    // Add chain
794
8
    TEOps.push_back(SDValue(StatepointMCNode, 0));
795
8
796
8
    // Add GC transition arguments
797
8
    for (const Value *V : SI.GCTransitionArgs) {
798
1
      TEOps.push_back(getValue(V));
799
1
      if (V->getType()->isPointerTy())
800
1
        TEOps.push_back(DAG.getSrcValue(V));
801
1
    }
802
8
803
8
    // Add glue
804
8
    TEOps.push_back(SDValue(StatepointMCNode, 1));
805
8
806
8
    SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
807
8
808
8
    SDValue GCTransitionStart =
809
8
        DAG.getNode(ISD::GC_TRANSITION_END, getCurSDLoc(), NodeTys, TEOps);
810
8
811
8
    SinkNode = GCTransitionStart.getNode();
812
8
  }
813
88
814
88
  // Replace original call
815
88
  DAG.ReplaceAllUsesWith(CallNode, SinkNode); // This may update Root
816
88
  // Remove original call node
817
88
  DAG.DeleteNode(CallNode);
818
88
819
88
  // DON'T set the root - under the assumption that it's already set past the
820
88
  // inserted node we created.
821
88
822
88
  // TODO: A better future implementation would be to emit a single variable
823
88
  // argument, variable return value STATEPOINT node here and then hookup the
824
88
  // return value of each gc.relocate to the respective output of the
825
88
  // previously emitted STATEPOINT value.  Unfortunately, this doesn't appear
826
88
  // to actually be possible today.
827
88
828
88
  return ReturnVal;
829
88
}
830
831
void
832
SelectionDAGBuilder::LowerStatepoint(ImmutableStatepoint ISP,
833
83
                                     const BasicBlock *EHPadBB /*= nullptr*/) {
834
83
  assert(ISP.getCall()->getCallingConv() != CallingConv::AnyReg &&
835
83
         "anyregcc is not supported on statepoints!");
836
83
837
#ifndef NDEBUG
838
  // If this is a malformed statepoint, report it early to simplify debugging.
839
  // This should catch any IR level mistake that's made when constructing or
840
  // transforming statepoints.
841
  ISP.verify();
842
843
  // Check that the associated GCStrategy expects to encounter statepoints.
844
  assert(GFI->getStrategy().useStatepoints() &&
845
         "GCStrategy does not expect to encounter statepoints");
846
#endif
847
848
83
  SDValue ActualCallee;
849
83
850
83
  if (ISP.getNumPatchBytes() > 0) {
851
1
    // If we've been asked to emit a nop sequence instead of a call instruction
852
1
    // for this statepoint then don't lower the call target, but use a constant
853
1
    // `null` instead.  Not lowering the call target lets statepoint clients get
854
1
    // away without providing a physical address for the symbolic call target at
855
1
    // link time.
856
1
857
1
    const auto &TLI = DAG.getTargetLoweringInfo();
858
1
    const auto &DL = DAG.getDataLayout();
859
1
860
1
    unsigned AS = ISP.getCalledValue()->getType()->getPointerAddressSpace();
861
1
    ActualCallee = DAG.getConstant(0, getCurSDLoc(), TLI.getPointerTy(DL, AS));
862
82
  } else {
863
82
    ActualCallee = getValue(ISP.getCalledValue());
864
82
  }
865
83
866
83
  StatepointLoweringInfo SI(DAG);
867
83
  populateCallLoweringInfo(SI.CLI, ISP.getCall(),
868
83
                           ImmutableStatepoint::CallArgsBeginPos,
869
83
                           ISP.getNumCallArgs(), ActualCallee,
870
83
                           ISP.getActualReturnType(), false /* IsPatchPoint */);
871
83
872
83
  for (const GCRelocateInst *Relocate : ISP.getRelocates()) {
873
70
    SI.GCRelocates.push_back(Relocate);
874
70
    SI.Bases.push_back(Relocate->getBasePtr());
875
70
    SI.Ptrs.push_back(Relocate->getDerivedPtr());
876
70
  }
877
83
878
83
  SI.GCArgs = ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
879
83
  SI.StatepointInstr = ISP.getInstruction();
880
83
  SI.GCTransitionArgs =
881
83
      ArrayRef<const Use>(ISP.gc_args_begin(), ISP.gc_args_end());
882
83
  SI.ID = ISP.getID();
883
83
  SI.DeoptState = ArrayRef<const Use>(ISP.deopt_begin(), ISP.deopt_end());
884
83
  SI.StatepointFlags = ISP.getFlags();
885
83
  SI.NumPatchBytes = ISP.getNumPatchBytes();
886
83
  SI.EHPadBB = EHPadBB;
887
83
888
83
  SDValue ReturnValue = LowerAsSTATEPOINT(SI);
889
83
890
83
  // Export the result value if needed
891
83
  const GCResultInst *GCResult = ISP.getGCResult();
892
83
  Type *RetTy = ISP.getActualReturnType();
893
83
  if (!RetTy->isVoidTy() && 
GCResult26
) {
894
24
    if (GCResult->getParent() != ISP.getCall()->getParent()) {
895
2
      // Result value will be used in a different basic block so we need to
896
2
      // export it now.  Default exporting mechanism will not work here because
897
2
      // statepoint call has a different type than the actual call. It means
898
2
      // that by default llvm will create export register of the wrong type
899
2
      // (always i32 in our case). So instead we need to create export register
900
2
      // with correct type manually.
901
2
      // TODO: To eliminate this problem we can remove gc.result intrinsics
902
2
      //       completely and make statepoint call to return a tuple.
903
2
      unsigned Reg = FuncInfo.CreateRegs(RetTy);
904
2
      RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
905
2
                       DAG.getDataLayout(), Reg, RetTy,
906
2
                       ISP.getCall()->getCallingConv());
907
2
      SDValue Chain = DAG.getEntryNode();
908
2
909
2
      RFV.getCopyToRegs(ReturnValue, DAG, getCurSDLoc(), Chain, nullptr);
910
2
      PendingExports.push_back(Chain);
911
2
      FuncInfo.ValueMap[ISP.getInstruction()] = Reg;
912
22
    } else {
913
22
      // Result value will be used in a same basic block. Don't export it or
914
22
      // perform any explicit register copies.
915
22
      // We'll replace the actuall call node shortly. gc_result will grab
916
22
      // this value.
917
22
      setValue(ISP.getInstruction(), ReturnValue);
918
22
    }
919
59
  } else {
920
59
    // The token value is never used from here on, just generate a poison value
921
59
    setValue(ISP.getInstruction(), DAG.getIntPtrConstant(-1, getCurSDLoc()));
922
59
  }
923
83
}
924
925
void SelectionDAGBuilder::LowerCallSiteWithDeoptBundleImpl(
926
    const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB,
927
5
    bool VarArgDisallowed, bool ForceVoidReturnTy) {
928
5
  StatepointLoweringInfo SI(DAG);
929
5
  unsigned ArgBeginIndex = Call->arg_begin() - Call->op_begin();
930
5
  populateCallLoweringInfo(
931
5
      SI.CLI, Call, ArgBeginIndex, Call->getNumArgOperands(), Callee,
932
5
      ForceVoidReturnTy ? 
Type::getVoidTy(*DAG.getContext())0
: Call->getType(),
933
5
      false);
934
5
  if (!VarArgDisallowed)
935
5
    SI.CLI.IsVarArg = Call->getFunctionType()->isVarArg();
936
5
937
5
  auto DeoptBundle = *Call->getOperandBundle(LLVMContext::OB_deopt);
938
5
939
5
  unsigned DefaultID = StatepointDirectives::DeoptBundleStatepointID;
940
5
941
5
  auto SD = parseStatepointDirectivesFromAttrs(Call->getAttributes());
942
5
  SI.ID = SD.StatepointID.getValueOr(DefaultID);
943
5
  SI.NumPatchBytes = SD.NumPatchBytes.getValueOr(0);
944
5
945
5
  SI.DeoptState =
946
5
      ArrayRef<const Use>(DeoptBundle.Inputs.begin(), DeoptBundle.Inputs.end());
947
5
  SI.StatepointFlags = static_cast<uint64_t>(StatepointFlags::None);
948
5
  SI.EHPadBB = EHPadBB;
949
5
950
5
  // NB! The GC arguments are deliberately left empty.
951
5
952
5
  if (SDValue ReturnVal = LowerAsSTATEPOINT(SI)) {
953
0
    ReturnVal = lowerRangeToAssertZExt(DAG, *Call, ReturnVal);
954
0
    setValue(Call, ReturnVal);
955
0
  }
956
5
}
957
958
void SelectionDAGBuilder::LowerCallSiteWithDeoptBundle(
959
5
    const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB) {
960
5
  LowerCallSiteWithDeoptBundleImpl(Call, Callee, EHPadBB,
961
5
                                   /* VarArgDisallowed = */ false,
962
5
                                   /* ForceVoidReturnTy  = */ false);
963
5
}
964
965
24
void SelectionDAGBuilder::visitGCResult(const GCResultInst &CI) {
966
24
  // The result value of the gc_result is simply the result of the actual
967
24
  // call.  We've already emitted this, so just grab the value.
968
24
  const Instruction *I = CI.getStatepoint();
969
24
970
24
  if (I->getParent() != CI.getParent()) {
971
2
    // Statepoint is in different basic block so we should have stored call
972
2
    // result in a virtual register.
973
2
    // We can not use default getValue() functionality to copy value from this
974
2
    // register because statepoint and actual call return types can be
975
2
    // different, and getValue() will use CopyFromReg of the wrong type,
976
2
    // which is always i32 in our case.
977
2
    PointerType *CalleeType = cast<PointerType>(
978
2
        ImmutableStatepoint(I).getCalledValue()->getType());
979
2
    Type *RetTy =
980
2
        cast<FunctionType>(CalleeType->getElementType())->getReturnType();
981
2
    SDValue CopyFromReg = getCopyFromRegs(I, RetTy);
982
2
983
2
    assert(CopyFromReg.getNode());
984
2
    setValue(&CI, CopyFromReg);
985
22
  } else {
986
22
    setValue(&CI, getValue(I));
987
22
  }
988
24
}
989
990
69
void SelectionDAGBuilder::visitGCRelocate(const GCRelocateInst &Relocate) {
991
#ifndef NDEBUG
992
  // Consistency check
993
  // We skip this check for relocates not in the same basic block as their
994
  // statepoint. It would be too expensive to preserve validation info through
995
  // different basic blocks.
996
  if (Relocate.getStatepoint()->getParent() == Relocate.getParent())
997
    StatepointLowering.relocCallVisited(Relocate);
998
999
  auto *Ty = Relocate.getType()->getScalarType();
1000
  if (auto IsManaged = GFI->getStrategy().isGCManagedPointer(Ty))
1001
    assert(*IsManaged && "Non gc managed pointer relocated!");
1002
#endif
1003
1004
69
  const Value *DerivedPtr = Relocate.getDerivedPtr();
1005
69
  SDValue SD = getValue(DerivedPtr);
1006
69
1007
69
  auto &SpillMap = FuncInfo.StatepointSpillMaps[Relocate.getStatepoint()];
1008
69
  auto SlotIt = SpillMap.find(DerivedPtr);
1009
69
  assert(SlotIt != SpillMap.end() && "Relocating not lowered gc value");
1010
69
  Optional<int> DerivedPtrLocation = SlotIt->second;
1011
69
1012
69
  // We didn't need to spill these special cases (constants and allocas).
1013
69
  // See the handling in spillIncomingValueForStatepoint for detail.
1014
69
  if (!DerivedPtrLocation) {
1015
8
    setValue(&Relocate, SD);
1016
8
    return;
1017
8
  }
1018
61
1019
61
  SDValue SpillSlot =
1020
61
    DAG.getTargetFrameIndex(*DerivedPtrLocation, getFrameIndexTy());
1021
61
1022
61
  // Note: We know all of these reloads are independent, but don't bother to
1023
61
  // exploit that chain wise.  DAGCombine will happily do so as needed, so
1024
61
  // doing it here would be a small compile time win at most.
1025
61
  SDValue Chain = getRoot();
1026
61
1027
61
  SDValue SpillLoad =
1028
61
      DAG.getLoad(DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
1029
61
                                                           Relocate.getType()),
1030
61
                  getCurSDLoc(), Chain, SpillSlot,
1031
61
                  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
1032
61
                                                    *DerivedPtrLocation));
1033
61
1034
61
  DAG.setRoot(SpillLoad.getValue(1));
1035
61
1036
61
  assert(SpillLoad.getNode());
1037
61
  setValue(&Relocate, SpillLoad);
1038
61
}
1039
1040
0
void SelectionDAGBuilder::LowerDeoptimizeCall(const CallInst *CI) {
1041
0
  const auto &TLI = DAG.getTargetLoweringInfo();
1042
0
  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(RTLIB::DEOPTIMIZE),
1043
0
                                         TLI.getPointerTy(DAG.getDataLayout()));
1044
0
1045
0
  // We don't lower calls to __llvm_deoptimize as varargs, but as a regular
1046
0
  // call.  We also do not lower the return value to any virtual register, and
1047
0
  // change the immediately following return to a trap instruction.
1048
0
  LowerCallSiteWithDeoptBundleImpl(CI, Callee, /* EHPadBB = */ nullptr,
1049
0
                                   /* VarArgDisallowed = */ true,
1050
0
                                   /* ForceVoidReturnTy = */ true);
1051
0
}
1052
1053
0
void SelectionDAGBuilder::LowerDeoptimizingReturn() {
1054
0
  // We do not lower the return value from llvm.deoptimize to any virtual
1055
0
  // register, and change the immediately following return to a trap
1056
0
  // instruction.
1057
0
  if (DAG.getTarget().Options.TrapUnreachable)
1058
0
    DAG.setRoot(
1059
0
        DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
1060
0
}