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