Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Target/BPF/BPFISelLowering.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- BPFISelLowering.cpp - BPF DAG Lowering Implementation  ------------===//
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 defines the interfaces that BPF uses to lower LLVM code into a
10
// selection DAG.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "BPFISelLowering.h"
15
#include "BPF.h"
16
#include "BPFSubtarget.h"
17
#include "BPFTargetMachine.h"
18
#include "llvm/CodeGen/CallingConvLower.h"
19
#include "llvm/CodeGen/MachineFrameInfo.h"
20
#include "llvm/CodeGen/MachineFunction.h"
21
#include "llvm/CodeGen/MachineInstrBuilder.h"
22
#include "llvm/CodeGen/MachineRegisterInfo.h"
23
#include "llvm/CodeGen/SelectionDAGISel.h"
24
#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25
#include "llvm/CodeGen/ValueTypes.h"
26
#include "llvm/IR/DiagnosticInfo.h"
27
#include "llvm/IR/DiagnosticPrinter.h"
28
#include "llvm/Support/Debug.h"
29
#include "llvm/Support/ErrorHandling.h"
30
#include "llvm/Support/raw_ostream.h"
31
using namespace llvm;
32
33
#define DEBUG_TYPE "bpf-lower"
34
35
static cl::opt<bool> BPFExpandMemcpyInOrder("bpf-expand-memcpy-in-order",
36
  cl::Hidden, cl::init(false),
37
  cl::desc("Expand memcpy into load/store pairs in order"));
38
39
6
static void fail(const SDLoc &DL, SelectionDAG &DAG, const Twine &Msg) {
40
6
  MachineFunction &MF = DAG.getMachineFunction();
41
6
  DAG.getContext()->diagnose(
42
6
      DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
43
6
}
44
45
static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg,
46
2
                 SDValue Val) {
47
2
  MachineFunction &MF = DAG.getMachineFunction();
48
2
  std::string Str;
49
2
  raw_string_ostream OS(Str);
50
2
  OS << Msg;
51
2
  Val->print(OS);
52
2
  OS.flush();
53
2
  DAG.getContext()->diagnose(
54
2
      DiagnosticInfoUnsupported(MF.getFunction(), Str, DL.getDebugLoc()));
55
2
}
56
57
BPFTargetLowering::BPFTargetLowering(const TargetMachine &TM,
58
                                     const BPFSubtarget &STI)
59
212
    : TargetLowering(TM) {
60
212
61
212
  // Set up the register classes.
62
212
  addRegisterClass(MVT::i64, &BPF::GPRRegClass);
63
212
  if (STI.getHasAlu32())
64
8
    addRegisterClass(MVT::i32, &BPF::GPR32RegClass);
65
212
66
212
  // Compute derived properties from the register classes
67
212
  computeRegisterProperties(STI.getRegisterInfo());
68
212
69
212
  setStackPointerRegisterToSaveRestore(BPF::R11);
70
212
71
212
  setOperationAction(ISD::BR_CC, MVT::i64, Custom);
72
212
  setOperationAction(ISD::BR_JT, MVT::Other, Expand);
73
212
  setOperationAction(ISD::BRIND, MVT::Other, Expand);
74
212
  setOperationAction(ISD::BRCOND, MVT::Other, Expand);
75
212
76
212
  setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
77
212
78
212
  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
79
212
  setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
80
212
  setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
81
212
82
424
  for (auto VT : { MVT::i32, MVT::i64 }) {
83
424
    if (VT == MVT::i32 && 
!STI.getHasAlu32()212
)
84
204
      continue;
85
220
86
220
    setOperationAction(ISD::SDIVREM, VT, Expand);
87
220
    setOperationAction(ISD::UDIVREM, VT, Expand);
88
220
    setOperationAction(ISD::SREM, VT, Expand);
89
220
    setOperationAction(ISD::UREM, VT, Expand);
90
220
    setOperationAction(ISD::MULHU, VT, Expand);
91
220
    setOperationAction(ISD::MULHS, VT, Expand);
92
220
    setOperationAction(ISD::UMUL_LOHI, VT, Expand);
93
220
    setOperationAction(ISD::SMUL_LOHI, VT, Expand);
94
220
    setOperationAction(ISD::ROTR, VT, Expand);
95
220
    setOperationAction(ISD::ROTL, VT, Expand);
96
220
    setOperationAction(ISD::SHL_PARTS, VT, Expand);
97
220
    setOperationAction(ISD::SRL_PARTS, VT, Expand);
98
220
    setOperationAction(ISD::SRA_PARTS, VT, Expand);
99
220
    setOperationAction(ISD::CTPOP, VT, Expand);
100
220
101
220
    setOperationAction(ISD::SETCC, VT, Expand);
102
220
    setOperationAction(ISD::SELECT, VT, Expand);
103
220
    setOperationAction(ISD::SELECT_CC, VT, Custom);
104
220
  }
105
212
106
212
  if (STI.getHasAlu32()) {
107
8
    setOperationAction(ISD::BSWAP, MVT::i32, Promote);
108
8
    setOperationAction(ISD::BR_CC, MVT::i32,
109
8
                       STI.getHasJmp32() ? 
Custom0
: Promote);
110
8
  }
111
212
112
212
  setOperationAction(ISD::CTTZ, MVT::i64, Custom);
113
212
  setOperationAction(ISD::CTLZ, MVT::i64, Custom);
114
212
  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Custom);
115
212
  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
116
212
117
212
  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
118
212
  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
119
212
  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
120
212
  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Expand);
121
212
122
212
  // Extended load operations for i1 types must be promoted
123
1.27k
  for (MVT VT : MVT::integer_valuetypes()) {
124
1.27k
    setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
125
1.27k
    setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
126
1.27k
    setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
127
1.27k
128
1.27k
    setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
129
1.27k
    setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Expand);
130
1.27k
    setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
131
1.27k
  }
132
212
133
212
  setBooleanContents(ZeroOrOneBooleanContent);
134
212
135
212
  // Function alignments (log2)
136
212
  setMinFunctionAlignment(3);
137
212
  setPrefFunctionAlignment(3);
138
212
139
212
  if (BPFExpandMemcpyInOrder) {
140
2
    // LLVM generic code will try to expand memcpy into load/store pairs at this
141
2
    // stage which is before quite a few IR optimization passes, therefore the
142
2
    // loads and stores could potentially be moved apart from each other which
143
2
    // will cause trouble to memcpy pattern matcher inside kernel eBPF JIT
144
2
    // compilers.
145
2
    //
146
2
    // When -bpf-expand-memcpy-in-order specified, we want to defer the expand
147
2
    // of memcpy to later stage in IR optimization pipeline so those load/store
148
2
    // pairs won't be touched and could be kept in order. Hence, we set
149
2
    // MaxStoresPerMem* to zero to disable the generic getMemcpyLoadsAndStores
150
2
    // code path, and ask LLVM to use target expander EmitTargetCodeForMemcpy.
151
2
    MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 0;
152
2
    MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 0;
153
2
    MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 0;
154
210
  } else {
155
210
    // inline memcpy() for kernel to see explicit copy
156
210
    unsigned CommonMaxStores =
157
210
      STI.getSelectionDAGInfo()->getCommonMaxStoresPerMemFunc();
158
210
159
210
    MaxStoresPerMemset = MaxStoresPerMemsetOptSize = CommonMaxStores;
160
210
    MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = CommonMaxStores;
161
210
    MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = CommonMaxStores;
162
210
  }
163
212
164
212
  // CPU/Feature control
165
212
  HasAlu32 = STI.getHasAlu32();
166
212
  HasJmp32 = STI.getHasJmp32();
167
212
  HasJmpExt = STI.getHasJmpExt();
168
212
}
169
170
90
bool BPFTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
171
90
  return false;
172
90
}
173
174
std::pair<unsigned, const TargetRegisterClass *>
175
BPFTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
176
                                                StringRef Constraint,
177
19
                                                MVT VT) const {
178
19
  if (Constraint.size() == 1)
179
19
    // GCC Constraint Letters
180
19
    switch (Constraint[0]) {
181
19
    case 'r': // GENERAL_REGS
182
10
      return std::make_pair(0U, &BPF::GPRRegClass);
183
19
    default:
184
9
      break;
185
9
    }
186
9
187
9
  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
188
9
}
189
190
234
SDValue BPFTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
191
234
  switch (Op.getOpcode()) {
192
234
  case ISD::BR_CC:
193
57
    return LowerBR_CC(Op, DAG);
194
234
  case ISD::GlobalAddress:
195
128
    return LowerGlobalAddress(Op, DAG);
196
234
  case ISD::SELECT_CC:
197
49
    return LowerSELECT_CC(Op, DAG);
198
234
  default:
199
0
    llvm_unreachable("unimplemented operand");
200
234
  }
201
234
}
202
203
// Calling Convention Implementation
204
#include "BPFGenCallingConv.inc"
205
206
SDValue BPFTargetLowering::LowerFormalArguments(
207
    SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
208
    const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
209
285
    SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
210
285
  switch (CallConv) {
211
285
  default:
212
0
    report_fatal_error("Unsupported calling convention");
213
285
  case CallingConv::C:
214
285
  case CallingConv::Fast:
215
285
    break;
216
285
  }
217
285
218
285
  MachineFunction &MF = DAG.getMachineFunction();
219
285
  MachineRegisterInfo &RegInfo = MF.getRegInfo();
220
285
221
285
  // Assign locations to all of the incoming arguments.
222
285
  SmallVector<CCValAssign, 16> ArgLocs;
223
285
  CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
224
285
  CCInfo.AnalyzeFormalArguments(Ins, getHasAlu32() ? 
CC_BPF3246
:
CC_BPF64239
);
225
285
226
412
  for (auto &VA : ArgLocs) {
227
412
    if (VA.isRegLoc()) {
228
411
      // Arguments passed in registers
229
411
      EVT RegVT = VA.getLocVT();
230
411
      MVT::SimpleValueType SimpleTy = RegVT.getSimpleVT().SimpleTy;
231
411
      switch (SimpleTy) {
232
411
      default: {
233
0
        errs() << "LowerFormalArguments Unhandled argument type: "
234
0
               << RegVT.getEVTString() << '\n';
235
0
        llvm_unreachable(0);
236
411
      }
237
411
      case MVT::i32:
238
411
      case MVT::i64:
239
411
        unsigned VReg = RegInfo.createVirtualRegister(SimpleTy == MVT::i64 ?
240
355
                                                      &BPF::GPRRegClass :
241
411
                                                      
&BPF::GPR32RegClass56
);
242
411
        RegInfo.addLiveIn(VA.getLocReg(), VReg);
243
411
        SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, RegVT);
244
411
245
411
        // If this is an value that has been promoted to wider types, insert an
246
411
        // assert[sz]ext to capture this, then truncate to the right size.
247
411
        if (VA.getLocInfo() == CCValAssign::SExt)
248
0
          ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
249
0
                                 DAG.getValueType(VA.getValVT()));
250
411
        else if (VA.getLocInfo() == CCValAssign::ZExt)
251
0
          ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
252
0
                                 DAG.getValueType(VA.getValVT()));
253
411
254
411
        if (VA.getLocInfo() != CCValAssign::Full)
255
0
          ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
256
411
257
411
        InVals.push_back(ArgValue);
258
411
259
411
  break;
260
1
      }
261
1
    } else {
262
1
      fail(DL, DAG, "defined with too many args");
263
1
      InVals.push_back(DAG.getConstant(0, DL, VA.getLocVT()));
264
1
    }
265
412
  }
266
285
267
285
  if (IsVarArg || 
MF.getFunction().hasStructRetAttr()284
) {
268
1
    fail(DL, DAG, "functions with VarArgs or StructRet are not supported");
269
1
  }
270
285
271
285
  return Chain;
272
285
}
273
274
const unsigned BPFTargetLowering::MaxArgs = 5;
275
276
SDValue BPFTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
277
59
                                     SmallVectorImpl<SDValue> &InVals) const {
278
59
  SelectionDAG &DAG = CLI.DAG;
279
59
  auto &Outs = CLI.Outs;
280
59
  auto &OutVals = CLI.OutVals;
281
59
  auto &Ins = CLI.Ins;
282
59
  SDValue Chain = CLI.Chain;
283
59
  SDValue Callee = CLI.Callee;
284
59
  bool &IsTailCall = CLI.IsTailCall;
285
59
  CallingConv::ID CallConv = CLI.CallConv;
286
59
  bool IsVarArg = CLI.IsVarArg;
287
59
  MachineFunction &MF = DAG.getMachineFunction();
288
59
289
59
  // BPF target does not support tail call optimization.
290
59
  IsTailCall = false;
291
59
292
59
  switch (CallConv) {
293
59
  default:
294
0
    report_fatal_error("Unsupported calling convention");
295
59
  case CallingConv::Fast:
296
59
  case CallingConv::C:
297
59
    break;
298
59
  }
299
59
300
59
  // Analyze operands of the call, assigning locations to each operand.
301
59
  SmallVector<CCValAssign, 16> ArgLocs;
302
59
  CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
303
59
304
59
  CCInfo.AnalyzeCallOperands(Outs, getHasAlu32() ? 
CC_BPF321
:
CC_BPF6458
);
305
59
306
59
  unsigned NumBytes = CCInfo.getNextStackOffset();
307
59
308
59
  if (Outs.size() > MaxArgs)
309
1
    fail(CLI.DL, DAG, "too many args to ", Callee);
310
59
311
125
  for (auto &Arg : Outs) {
312
125
    ISD::ArgFlagsTy Flags = Arg.Flags;
313
125
    if (!Flags.isByVal())
314
124
      continue;
315
1
316
1
    fail(CLI.DL, DAG, "pass by value not supported ", Callee);
317
1
  }
318
59
319
59
  auto PtrVT = getPointerTy(MF.getDataLayout());
320
59
  Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
321
59
322
59
  SmallVector<std::pair<unsigned, SDValue>, MaxArgs> RegsToPass;
323
59
324
59
  // Walk arg assignments
325
59
  for (unsigned i = 0,
326
59
                e = std::min(static_cast<unsigned>(ArgLocs.size()), MaxArgs);
327
183
       i != e; 
++i124
) {
328
124
    CCValAssign &VA = ArgLocs[i];
329
124
    SDValue Arg = OutVals[i];
330
124
331
124
    // Promote the value if needed.
332
124
    switch (VA.getLocInfo()) {
333
124
    default:
334
0
      llvm_unreachable("Unknown loc info");
335
124
    case CCValAssign::Full:
336
124
      break;
337
124
    case CCValAssign::SExt:
338
0
      Arg = DAG.getNode(ISD::SIGN_EXTEND, CLI.DL, VA.getLocVT(), Arg);
339
0
      break;
340
124
    case CCValAssign::ZExt:
341
0
      Arg = DAG.getNode(ISD::ZERO_EXTEND, CLI.DL, VA.getLocVT(), Arg);
342
0
      break;
343
124
    case CCValAssign::AExt:
344
0
      Arg = DAG.getNode(ISD::ANY_EXTEND, CLI.DL, VA.getLocVT(), Arg);
345
0
      break;
346
124
    }
347
124
348
124
    // Push arguments into RegsToPass vector
349
124
    if (VA.isRegLoc())
350
124
      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
351
124
    else
352
124
      
llvm_unreachable0
("call arg pass bug");
353
124
  }
354
59
355
59
  SDValue InFlag;
356
59
357
59
  // Build a sequence of copy-to-reg nodes chained together with token chain and
358
59
  // flag operands which copy the outgoing args into registers.  The InFlag in
359
59
  // necessary since all emitted instructions must be stuck together.
360
124
  for (auto &Reg : RegsToPass) {
361
124
    Chain = DAG.getCopyToReg(Chain, CLI.DL, Reg.first, Reg.second, InFlag);
362
124
    InFlag = Chain.getValue(1);
363
124
  }
364
59
365
59
  // If the callee is a GlobalAddress node (quite common, every direct call is)
366
59
  // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
367
59
  // Likewise ExternalSymbol -> TargetExternalSymbol.
368
59
  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
369
34
    Callee = DAG.getTargetGlobalAddress(G->getGlobal(), CLI.DL, PtrVT,
370
34
                                        G->getOffset(), 0);
371
34
  } else 
if (ExternalSymbolSDNode *25
E25
= dyn_cast<ExternalSymbolSDNode>(Callee)) {
372
1
    Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT, 0);
373
1
    fail(CLI.DL, DAG, Twine("A call to built-in function '"
374
1
                            + StringRef(E->getSymbol())
375
1
                            + "' is not supported."));
376
1
  }
377
59
378
59
  // Returns a chain & a flag for retval copy to use.
379
59
  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
380
59
  SmallVector<SDValue, 8> Ops;
381
59
  Ops.push_back(Chain);
382
59
  Ops.push_back(Callee);
383
59
384
59
  // Add argument registers to the end of the list so that they are
385
59
  // known live into the call.
386
59
  for (auto &Reg : RegsToPass)
387
124
    Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
388
59
389
59
  if (InFlag.getNode())
390
53
    Ops.push_back(InFlag);
391
59
392
59
  Chain = DAG.getNode(BPFISD::CALL, CLI.DL, NodeTys, Ops);
393
59
  InFlag = Chain.getValue(1);
394
59
395
59
  // Create the CALLSEQ_END node.
396
59
  Chain = DAG.getCALLSEQ_END(
397
59
      Chain, DAG.getConstant(NumBytes, CLI.DL, PtrVT, true),
398
59
      DAG.getConstant(0, CLI.DL, PtrVT, true), InFlag, CLI.DL);
399
59
  InFlag = Chain.getValue(1);
400
59
401
59
  // Handle result values, copying them out of physregs into vregs that we
402
59
  // return.
403
59
  return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, CLI.DL, DAG,
404
59
                         InVals);
405
59
}
406
407
SDValue
408
BPFTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
409
                               bool IsVarArg,
410
                               const SmallVectorImpl<ISD::OutputArg> &Outs,
411
                               const SmallVectorImpl<SDValue> &OutVals,
412
286
                               const SDLoc &DL, SelectionDAG &DAG) const {
413
286
  unsigned Opc = BPFISD::RET_FLAG;
414
286
415
286
  // CCValAssign - represent the assignment of the return value to a location
416
286
  SmallVector<CCValAssign, 16> RVLocs;
417
286
  MachineFunction &MF = DAG.getMachineFunction();
418
286
419
286
  // CCState - Info about the registers and stack slot.
420
286
  CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
421
286
422
286
  if (MF.getFunction().getReturnType()->isAggregateType()) {
423
2
    fail(DL, DAG, "only integer returns supported");
424
2
    return DAG.getNode(Opc, DL, MVT::Other, Chain);
425
2
  }
426
284
427
284
  // Analize return values.
428
284
  CCInfo.AnalyzeReturn(Outs, getHasAlu32() ? 
RetCC_BPF3246
:
RetCC_BPF64238
);
429
284
430
284
  SDValue Flag;
431
284
  SmallVector<SDValue, 4> RetOps(1, Chain);
432
284
433
284
  // Copy the result values into the output registers.
434
521
  for (unsigned i = 0; i != RVLocs.size(); 
++i237
) {
435
237
    CCValAssign &VA = RVLocs[i];
436
237
    assert(VA.isRegLoc() && "Can only return in registers!");
437
237
438
237
    Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVals[i], Flag);
439
237
440
237
    // Guarantee that all emitted copies are stuck together,
441
237
    // avoiding something bad.
442
237
    Flag = Chain.getValue(1);
443
237
    RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
444
237
  }
445
284
446
284
  RetOps[0] = Chain; // Update chain.
447
284
448
284
  // Add the flag if we have it.
449
284
  if (Flag.getNode())
450
237
    RetOps.push_back(Flag);
451
284
452
284
  return DAG.getNode(Opc, DL, MVT::Other, RetOps);
453
284
}
454
455
SDValue BPFTargetLowering::LowerCallResult(
456
    SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
457
    const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
458
59
    SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
459
59
460
59
  MachineFunction &MF = DAG.getMachineFunction();
461
59
  // Assign locations to each value returned by this call.
462
59
  SmallVector<CCValAssign, 16> RVLocs;
463
59
  CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
464
59
465
59
  if (Ins.size() >= 2) {
466
1
    fail(DL, DAG, "only small returns supported");
467
3
    for (unsigned i = 0, e = Ins.size(); i != e; 
++i2
)
468
2
      InVals.push_back(DAG.getConstant(0, DL, Ins[i].VT));
469
1
    return DAG.getCopyFromReg(Chain, DL, 1, Ins[0].VT, InFlag).getValue(1);
470
1
  }
471
58
472
58
  CCInfo.AnalyzeCallResult(Ins, getHasAlu32() ? 
RetCC_BPF321
:
RetCC_BPF6457
);
473
58
474
58
  // Copy all of the result registers out of their specified physreg.
475
58
  for (auto &Val : RVLocs) {
476
34
    Chain = DAG.getCopyFromReg(Chain, DL, Val.getLocReg(),
477
34
                               Val.getValVT(), InFlag).getValue(1);
478
34
    InFlag = Chain.getValue(2);
479
34
    InVals.push_back(Chain.getValue(0));
480
34
  }
481
58
482
58
  return Chain;
483
58
}
484
485
87
static void NegateCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
486
87
  switch (CC) {
487
87
  default:
488
76
    break;
489
87
  case ISD::SETULT:
490
11
  case ISD::SETULE:
491
11
  case ISD::SETLT:
492
11
  case ISD::SETLE:
493
11
    CC = ISD::getSetCCSwappedOperands(CC);
494
11
    std::swap(LHS, RHS);
495
11
    break;
496
87
  }
497
87
}
498
499
57
SDValue BPFTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
500
57
  SDValue Chain = Op.getOperand(0);
501
57
  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
502
57
  SDValue LHS = Op.getOperand(2);
503
57
  SDValue RHS = Op.getOperand(3);
504
57
  SDValue Dest = Op.getOperand(4);
505
57
  SDLoc DL(Op);
506
57
507
57
  if (!getHasJmpExt())
508
57
    NegateCC(LHS, RHS, CC);
509
57
510
57
  return DAG.getNode(BPFISD::BR_CC, DL, Op.getValueType(), Chain, LHS, RHS,
511
57
                     DAG.getConstant(CC, DL, LHS.getValueType()), Dest);
512
57
}
513
514
49
SDValue BPFTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
515
49
  SDValue LHS = Op.getOperand(0);
516
49
  SDValue RHS = Op.getOperand(1);
517
49
  SDValue TrueV = Op.getOperand(2);
518
49
  SDValue FalseV = Op.getOperand(3);
519
49
  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
520
49
  SDLoc DL(Op);
521
49
522
49
  if (!getHasJmpExt())
523
30
    NegateCC(LHS, RHS, CC);
524
49
525
49
  SDValue TargetCC = DAG.getConstant(CC, DL, LHS.getValueType());
526
49
  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
527
49
  SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
528
49
529
49
  return DAG.getNode(BPFISD::SELECT_CC, DL, VTs, Ops);
530
49
}
531
532
0
const char *BPFTargetLowering::getTargetNodeName(unsigned Opcode) const {
533
0
  switch ((BPFISD::NodeType)Opcode) {
534
0
  case BPFISD::FIRST_NUMBER:
535
0
    break;
536
0
  case BPFISD::RET_FLAG:
537
0
    return "BPFISD::RET_FLAG";
538
0
  case BPFISD::CALL:
539
0
    return "BPFISD::CALL";
540
0
  case BPFISD::SELECT_CC:
541
0
    return "BPFISD::SELECT_CC";
542
0
  case BPFISD::BR_CC:
543
0
    return "BPFISD::BR_CC";
544
0
  case BPFISD::Wrapper:
545
0
    return "BPFISD::Wrapper";
546
0
  case BPFISD::MEMCPY:
547
0
    return "BPFISD::MEMCPY";
548
0
  }
549
0
  return nullptr;
550
0
}
551
552
SDValue BPFTargetLowering::LowerGlobalAddress(SDValue Op,
553
128
                                              SelectionDAG &DAG) const {
554
128
  auto N = cast<GlobalAddressSDNode>(Op);
555
128
  assert(N->getOffset() == 0 && "Invalid offset for global address");
556
128
557
128
  SDLoc DL(Op);
558
128
  const GlobalValue *GV = N->getGlobal();
559
128
  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i64);
560
128
561
128
  return DAG.getNode(BPFISD::Wrapper, DL, MVT::i64, GA);
562
128
}
563
564
unsigned
565
BPFTargetLowering::EmitSubregExt(MachineInstr &MI, MachineBasicBlock *BB,
566
11
                                 unsigned Reg, bool isSigned) const {
567
11
  const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
568
11
  const TargetRegisterClass *RC = getRegClassFor(MVT::i64);
569
11
  int RShiftOp = isSigned ? 
BPF::SRA_ri2
:
BPF::SRL_ri9
;
570
11
  MachineFunction *F = BB->getParent();
571
11
  DebugLoc DL = MI.getDebugLoc();
572
11
573
11
  MachineRegisterInfo &RegInfo = F->getRegInfo();
574
11
  unsigned PromotedReg0 = RegInfo.createVirtualRegister(RC);
575
11
  unsigned PromotedReg1 = RegInfo.createVirtualRegister(RC);
576
11
  unsigned PromotedReg2 = RegInfo.createVirtualRegister(RC);
577
11
  BuildMI(BB, DL, TII.get(BPF::MOV_32_64), PromotedReg0).addReg(Reg);
578
11
  BuildMI(BB, DL, TII.get(BPF::SLL_ri), PromotedReg1)
579
11
    .addReg(PromotedReg0).addImm(32);
580
11
  BuildMI(BB, DL, TII.get(RShiftOp), PromotedReg2)
581
11
    .addReg(PromotedReg1).addImm(32);
582
11
583
11
  return PromotedReg2;
584
11
}
585
586
MachineBasicBlock *
587
BPFTargetLowering::EmitInstrWithCustomInserterMemcpy(MachineInstr &MI,
588
                                                     MachineBasicBlock *BB)
589
8
                                                     const {
590
8
  MachineFunction *MF = MI.getParent()->getParent();
591
8
  MachineRegisterInfo &MRI = MF->getRegInfo();
592
8
  MachineInstrBuilder MIB(*MF, MI);
593
8
  unsigned ScratchReg;
594
8
595
8
  // This function does custom insertion during lowering BPFISD::MEMCPY which
596
8
  // only has two register operands from memcpy semantics, the copy source
597
8
  // address and the copy destination address.
598
8
  //
599
8
  // Because we will expand BPFISD::MEMCPY into load/store pairs, we will need
600
8
  // a third scratch register to serve as the destination register of load and
601
8
  // source register of store.
602
8
  //
603
8
  // The scratch register here is with the Define | Dead | EarlyClobber flags.
604
8
  // The EarlyClobber flag has the semantic property that the operand it is
605
8
  // attached to is clobbered before the rest of the inputs are read. Hence it
606
8
  // must be unique among the operands to the instruction. The Define flag is
607
8
  // needed to coerce the machine verifier that an Undef value isn't a problem
608
8
  // as we anyway is loading memory into it. The Dead flag is needed as the
609
8
  // value in scratch isn't supposed to be used by any other instruction.
610
8
  ScratchReg = MRI.createVirtualRegister(&BPF::GPRRegClass);
611
8
  MIB.addReg(ScratchReg,
612
8
             RegState::Define | RegState::Dead | RegState::EarlyClobber);
613
8
614
8
  return BB;
615
8
}
616
617
MachineBasicBlock *
618
BPFTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
619
57
                                               MachineBasicBlock *BB) const {
620
57
  const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
621
57
  DebugLoc DL = MI.getDebugLoc();
622
57
  unsigned Opc = MI.getOpcode();
623
57
  bool isSelectRROp = (Opc == BPF::Select ||
624
57
                       
Opc == BPF::Select_64_3230
||
625
57
                       
Opc == BPF::Select_3229
||
626
57
                       
Opc == BPF::Select_32_6428
);
627
57
628
57
  bool isMemcpyOp = Opc == BPF::MEMCPY;
629
57
630
#ifndef NDEBUG
631
  bool isSelectRIOp = (Opc == BPF::Select_Ri ||
632
                       Opc == BPF::Select_Ri_64_32 ||
633
                       Opc == BPF::Select_Ri_32 ||
634
                       Opc == BPF::Select_Ri_32_64);
635
636
637
  assert((isSelectRROp || isSelectRIOp || isMemcpyOp) &&
638
         "Unexpected instr type to insert");
639
#endif
640
641
57
  if (isMemcpyOp)
642
8
    return EmitInstrWithCustomInserterMemcpy(MI, BB);
643
49
644
49
  bool is32BitCmp = (Opc == BPF::Select_32 ||
645
49
                     
Opc == BPF::Select_32_6448
||
646
49
                     
Opc == BPF::Select_Ri_3245
||
647
49
                     
Opc == BPF::Select_Ri_32_6443
);
648
49
649
49
  // To "insert" a SELECT instruction, we actually have to insert the diamond
650
49
  // control-flow pattern.  The incoming instruction knows the destination vreg
651
49
  // to set, the condition code register to branch on, the true/false values to
652
49
  // select between, and a branch opcode to use.
653
49
  const BasicBlock *LLVM_BB = BB->getBasicBlock();
654
49
  MachineFunction::iterator I = ++BB->getIterator();
655
49
656
49
  // ThisMBB:
657
49
  // ...
658
49
  //  TrueVal = ...
659
49
  //  jmp_XX r1, r2 goto Copy1MBB
660
49
  //  fallthrough --> Copy0MBB
661
49
  MachineBasicBlock *ThisMBB = BB;
662
49
  MachineFunction *F = BB->getParent();
663
49
  MachineBasicBlock *Copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
664
49
  MachineBasicBlock *Copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
665
49
666
49
  F->insert(I, Copy0MBB);
667
49
  F->insert(I, Copy1MBB);
668
49
  // Update machine-CFG edges by transferring all successors of the current
669
49
  // block to the new block which will contain the Phi node for the select.
670
49
  Copy1MBB->splice(Copy1MBB->begin(), BB,
671
49
                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
672
49
  Copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
673
49
  // Next, add the true and fallthrough blocks as its successors.
674
49
  BB->addSuccessor(Copy0MBB);
675
49
  BB->addSuccessor(Copy1MBB);
676
49
677
49
  // Insert Branch if Flag
678
49
  int CC = MI.getOperand(3).getImm();
679
49
  int NewCC;
680
49
  switch (CC) {
681
49
#define SET_NEWCC(X, Y) \
682
49
  case ISD::X: \
683
49
    if (is32BitCmp && 
HasJmp327
) \
684
49
      
NewCC = isSelectRROp ? 0
BPF::Y0
##_rr_32 :
BPF::Y0
##_ri_32; \
685
49
    else \
686
49
      NewCC = isSelectRROp ? 
BPF::Y32
##_rr :
BPF::Y17
##_ri; \
687
49
    break
688
49
  
SET_NEWCC9
(SETGT, JSGT);
689
49
  
SET_NEWCC10
(SETUGT, JUGT);
690
49
  
SET_NEWCC3
(SETGE, JSGE);
691
49
  
SET_NEWCC3
(SETUGE, JUGE);
692
49
  
SET_NEWCC11
(SETEQ, JEQ);
693
49
  
SET_NEWCC7
(SETNE, JNE);
694
49
  
SET_NEWCC2
(SETLT, JSLT);
695
49
  
SET_NEWCC2
(SETULT, JULT);
696
49
  
SET_NEWCC1
(SETLE, JSLE);
697
49
  
SET_NEWCC1
(SETULE, JULE);
698
49
  default:
699
0
    report_fatal_error("unimplemented select CondCode " + Twine(CC));
700
49
  }
701
49
702
49
  unsigned LHS = MI.getOperand(1).getReg();
703
49
  bool isSignedCmp = (CC == ISD::SETGT ||
704
49
                      
CC == ISD::SETGE40
||
705
49
                      
CC == ISD::SETLT37
||
706
49
                      
CC == ISD::SETLE35
);
707
49
708
49
  // eBPF at the moment only has 64-bit comparison. Any 32-bit comparison need
709
49
  // to be promoted, however if the 32-bit comparison operands are destination
710
49
  // registers then they are implicitly zero-extended already, there is no
711
49
  // need of explicit zero-extend sequence for them.
712
49
  //
713
49
  // We simply do extension for all situations in this method, but we will
714
49
  // try to remove those unnecessary in BPFMIPeephole pass.
715
49
  if (is32BitCmp && 
!HasJmp327
)
716
7
    LHS = EmitSubregExt(MI, BB, LHS, isSignedCmp);
717
49
718
49
  if (isSelectRROp) {
719
32
    unsigned RHS = MI.getOperand(2).getReg();
720
32
721
32
    if (is32BitCmp && 
!HasJmp324
)
722
4
      RHS = EmitSubregExt(MI, BB, RHS, isSignedCmp);
723
32
724
32
    BuildMI(BB, DL, TII.get(NewCC)).addReg(LHS).addReg(RHS).addMBB(Copy1MBB);
725
32
  } else {
726
17
    int64_t imm32 = MI.getOperand(2).getImm();
727
17
    // sanity check before we build J*_ri instruction.
728
17
    assert (isInt<32>(imm32));
729
17
    BuildMI(BB, DL, TII.get(NewCC))
730
17
        .addReg(LHS).addImm(imm32).addMBB(Copy1MBB);
731
17
  }
732
49
733
49
  // Copy0MBB:
734
49
  //  %FalseValue = ...
735
49
  //  # fallthrough to Copy1MBB
736
49
  BB = Copy0MBB;
737
49
738
49
  // Update machine-CFG edges
739
49
  BB->addSuccessor(Copy1MBB);
740
49
741
49
  // Copy1MBB:
742
49
  //  %Result = phi [ %FalseValue, Copy0MBB ], [ %TrueValue, ThisMBB ]
743
49
  // ...
744
49
  BB = Copy1MBB;
745
49
  BuildMI(*BB, BB->begin(), DL, TII.get(BPF::PHI), MI.getOperand(0).getReg())
746
49
      .addReg(MI.getOperand(5).getReg())
747
49
      .addMBB(Copy0MBB)
748
49
      .addReg(MI.getOperand(4).getReg())
749
49
      .addMBB(ThisMBB);
750
49
751
49
  MI.eraseFromParent(); // The pseudo instruction is gone now.
752
49
  return BB;
753
49
}
754
755
EVT BPFTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
756
267
                                          EVT VT) const {
757
267
  return getHasAlu32() ? 
MVT::i3224
:
MVT::i64243
;
758
267
}
759
760
MVT BPFTargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
761
665
                                              EVT VT) const {
762
665
  return (getHasAlu32() && 
VT == MVT::i3222
) ?
MVT::i3220
:
MVT::i64645
;
763
665
}