1 //===-- VEISelLowering.cpp - VE 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 implements the interfaces that VE uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "VECustomDAG.h" 15 #include "VEISelLowering.h" 16 #include "MCTargetDesc/VEMCExpr.h" 17 #include "VEInstrBuilder.h" 18 #include "VEMachineFunctionInfo.h" 19 #include "VERegisterInfo.h" 20 #include "VETargetMachine.h" 21 #include "llvm/ADT/StringSwitch.h" 22 #include "llvm/CodeGen/CallingConvLower.h" 23 #include "llvm/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineFunction.h" 25 #include "llvm/CodeGen/MachineInstrBuilder.h" 26 #include "llvm/CodeGen/MachineJumpTableInfo.h" 27 #include "llvm/CodeGen/MachineModuleInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/SelectionDAG.h" 30 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 31 #include "llvm/IR/DerivedTypes.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/Module.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/KnownBits.h" 37 using namespace llvm; 38 39 #define DEBUG_TYPE "ve-lower" 40 41 //===----------------------------------------------------------------------===// 42 // Calling Convention Implementation 43 //===----------------------------------------------------------------------===// 44 45 #include "VEGenCallingConv.inc" 46 47 CCAssignFn *getReturnCC(CallingConv::ID CallConv) { 48 switch (CallConv) { 49 default: 50 return RetCC_VE_C; 51 case CallingConv::Fast: 52 return RetCC_VE_Fast; 53 } 54 } 55 56 CCAssignFn *getParamCC(CallingConv::ID CallConv, bool IsVarArg) { 57 if (IsVarArg) 58 return CC_VE2; 59 switch (CallConv) { 60 default: 61 return CC_VE_C; 62 case CallingConv::Fast: 63 return CC_VE_Fast; 64 } 65 } 66 67 bool VETargetLowering::CanLowerReturn( 68 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 69 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 70 CCAssignFn *RetCC = getReturnCC(CallConv); 71 SmallVector<CCValAssign, 16> RVLocs; 72 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 73 return CCInfo.CheckReturn(Outs, RetCC); 74 } 75 76 static const MVT AllVectorVTs[] = {MVT::v256i32, MVT::v512i32, MVT::v256i64, 77 MVT::v256f32, MVT::v512f32, MVT::v256f64}; 78 79 static const MVT AllPackedVTs[] = {MVT::v512i32, MVT::v512f32}; 80 81 void VETargetLowering::initRegisterClasses() { 82 // Set up the register classes. 83 addRegisterClass(MVT::i32, &VE::I32RegClass); 84 addRegisterClass(MVT::i64, &VE::I64RegClass); 85 addRegisterClass(MVT::f32, &VE::F32RegClass); 86 addRegisterClass(MVT::f64, &VE::I64RegClass); 87 addRegisterClass(MVT::f128, &VE::F128RegClass); 88 89 if (Subtarget->enableVPU()) { 90 for (MVT VecVT : AllVectorVTs) 91 addRegisterClass(VecVT, &VE::V64RegClass); 92 addRegisterClass(MVT::v256i1, &VE::VMRegClass); 93 addRegisterClass(MVT::v512i1, &VE::VM512RegClass); 94 } 95 } 96 97 void VETargetLowering::initSPUActions() { 98 const auto &TM = getTargetMachine(); 99 /// Load & Store { 100 101 // VE doesn't have i1 sign extending load. 102 for (MVT VT : MVT::integer_valuetypes()) { 103 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); 104 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); 105 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote); 106 setTruncStoreAction(VT, MVT::i1, Expand); 107 } 108 109 // VE doesn't have floating point extload/truncstore, so expand them. 110 for (MVT FPVT : MVT::fp_valuetypes()) { 111 for (MVT OtherFPVT : MVT::fp_valuetypes()) { 112 setLoadExtAction(ISD::EXTLOAD, FPVT, OtherFPVT, Expand); 113 setTruncStoreAction(FPVT, OtherFPVT, Expand); 114 } 115 } 116 117 // VE doesn't have fp128 load/store, so expand them in custom lower. 118 setOperationAction(ISD::LOAD, MVT::f128, Custom); 119 setOperationAction(ISD::STORE, MVT::f128, Custom); 120 121 /// } Load & Store 122 123 // Custom legalize address nodes into LO/HI parts. 124 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0)); 125 setOperationAction(ISD::BlockAddress, PtrVT, Custom); 126 setOperationAction(ISD::GlobalAddress, PtrVT, Custom); 127 setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom); 128 setOperationAction(ISD::ConstantPool, PtrVT, Custom); 129 setOperationAction(ISD::JumpTable, PtrVT, Custom); 130 131 /// VAARG handling { 132 setOperationAction(ISD::VASTART, MVT::Other, Custom); 133 // VAARG needs to be lowered to access with 8 bytes alignment. 134 setOperationAction(ISD::VAARG, MVT::Other, Custom); 135 // Use the default implementation. 136 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 137 setOperationAction(ISD::VAEND, MVT::Other, Expand); 138 /// } VAARG handling 139 140 /// Stack { 141 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom); 142 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 143 144 // Use the default implementation. 145 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 146 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 147 /// } Stack 148 149 /// Branch { 150 151 // VE doesn't have BRCOND 152 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 153 154 // BR_JT is not implemented yet. 155 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 156 157 /// } Branch 158 159 /// Int Ops { 160 for (MVT IntVT : {MVT::i32, MVT::i64}) { 161 // VE has no REM or DIVREM operations. 162 setOperationAction(ISD::UREM, IntVT, Expand); 163 setOperationAction(ISD::SREM, IntVT, Expand); 164 setOperationAction(ISD::SDIVREM, IntVT, Expand); 165 setOperationAction(ISD::UDIVREM, IntVT, Expand); 166 167 // VE has no SHL_PARTS/SRA_PARTS/SRL_PARTS operations. 168 setOperationAction(ISD::SHL_PARTS, IntVT, Expand); 169 setOperationAction(ISD::SRA_PARTS, IntVT, Expand); 170 setOperationAction(ISD::SRL_PARTS, IntVT, Expand); 171 172 // VE has no MULHU/S or U/SMUL_LOHI operations. 173 // TODO: Use MPD instruction to implement SMUL_LOHI for i32 type. 174 setOperationAction(ISD::MULHU, IntVT, Expand); 175 setOperationAction(ISD::MULHS, IntVT, Expand); 176 setOperationAction(ISD::UMUL_LOHI, IntVT, Expand); 177 setOperationAction(ISD::SMUL_LOHI, IntVT, Expand); 178 179 // VE has no CTTZ, ROTL, ROTR operations. 180 setOperationAction(ISD::CTTZ, IntVT, Expand); 181 setOperationAction(ISD::ROTL, IntVT, Expand); 182 setOperationAction(ISD::ROTR, IntVT, Expand); 183 184 // VE has 64 bits instruction which works as i64 BSWAP operation. This 185 // instruction works fine as i32 BSWAP operation with an additional 186 // parameter. Use isel patterns to lower BSWAP. 187 setOperationAction(ISD::BSWAP, IntVT, Legal); 188 189 // VE has only 64 bits instructions which work as i64 BITREVERSE/CTLZ/CTPOP 190 // operations. Use isel patterns for i64, promote for i32. 191 LegalizeAction Act = (IntVT == MVT::i32) ? Promote : Legal; 192 setOperationAction(ISD::BITREVERSE, IntVT, Act); 193 setOperationAction(ISD::CTLZ, IntVT, Act); 194 setOperationAction(ISD::CTLZ_ZERO_UNDEF, IntVT, Act); 195 setOperationAction(ISD::CTPOP, IntVT, Act); 196 197 // VE has only 64 bits instructions which work as i64 AND/OR/XOR operations. 198 // Use isel patterns for i64, promote for i32. 199 setOperationAction(ISD::AND, IntVT, Act); 200 setOperationAction(ISD::OR, IntVT, Act); 201 setOperationAction(ISD::XOR, IntVT, Act); 202 } 203 /// } Int Ops 204 205 /// Conversion { 206 // VE doesn't have instructions for fp<->uint, so expand them by llvm 207 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote); // use i64 208 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote); // use i64 209 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); 210 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); 211 212 // fp16 not supported 213 for (MVT FPVT : MVT::fp_valuetypes()) { 214 setOperationAction(ISD::FP16_TO_FP, FPVT, Expand); 215 setOperationAction(ISD::FP_TO_FP16, FPVT, Expand); 216 } 217 /// } Conversion 218 219 /// Floating-point Ops { 220 /// Note: Floating-point operations are fneg, fadd, fsub, fmul, fdiv, frem, 221 /// and fcmp. 222 223 // VE doesn't have following floating point operations. 224 for (MVT VT : MVT::fp_valuetypes()) { 225 setOperationAction(ISD::FNEG, VT, Expand); 226 setOperationAction(ISD::FREM, VT, Expand); 227 } 228 229 // VE doesn't have fdiv of f128. 230 setOperationAction(ISD::FDIV, MVT::f128, Expand); 231 232 for (MVT FPVT : {MVT::f32, MVT::f64}) { 233 // f32 and f64 uses ConstantFP. f128 uses ConstantPool. 234 setOperationAction(ISD::ConstantFP, FPVT, Legal); 235 } 236 /// } Floating-point Ops 237 238 /// Floating-point math functions { 239 240 // VE doesn't have following floating point math functions. 241 for (MVT VT : MVT::fp_valuetypes()) { 242 setOperationAction(ISD::FABS, VT, Expand); 243 setOperationAction(ISD::FCOPYSIGN, VT, Expand); 244 setOperationAction(ISD::FCOS, VT, Expand); 245 setOperationAction(ISD::FSIN, VT, Expand); 246 setOperationAction(ISD::FSQRT, VT, Expand); 247 } 248 249 /// } Floating-point math functions 250 251 /// Atomic instructions { 252 253 setMaxAtomicSizeInBitsSupported(64); 254 setMinCmpXchgSizeInBits(32); 255 setSupportsUnalignedAtomics(false); 256 257 // Use custom inserter for ATOMIC_FENCE. 258 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom); 259 260 // Other atomic instructions. 261 for (MVT VT : MVT::integer_valuetypes()) { 262 // Support i8/i16 atomic swap. 263 setOperationAction(ISD::ATOMIC_SWAP, VT, Custom); 264 265 // FIXME: Support "atmam" instructions. 266 setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Expand); 267 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Expand); 268 setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Expand); 269 setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Expand); 270 271 // VE doesn't have follwing instructions. 272 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand); 273 setOperationAction(ISD::ATOMIC_LOAD_CLR, VT, Expand); 274 setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Expand); 275 setOperationAction(ISD::ATOMIC_LOAD_NAND, VT, Expand); 276 setOperationAction(ISD::ATOMIC_LOAD_MIN, VT, Expand); 277 setOperationAction(ISD::ATOMIC_LOAD_MAX, VT, Expand); 278 setOperationAction(ISD::ATOMIC_LOAD_UMIN, VT, Expand); 279 setOperationAction(ISD::ATOMIC_LOAD_UMAX, VT, Expand); 280 } 281 282 /// } Atomic instructions 283 284 /// SJLJ instructions { 285 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); 286 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); 287 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom); 288 if (TM.Options.ExceptionModel == ExceptionHandling::SjLj) 289 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume"); 290 /// } SJLJ instructions 291 292 // Intrinsic instructions 293 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 294 } 295 296 void VETargetLowering::initVPUActions() { 297 for (MVT LegalVecVT : AllVectorVTs) { 298 setOperationAction(ISD::BUILD_VECTOR, LegalVecVT, Custom); 299 setOperationAction(ISD::INSERT_VECTOR_ELT, LegalVecVT, Legal); 300 setOperationAction(ISD::EXTRACT_VECTOR_ELT, LegalVecVT, Legal); 301 // Translate all vector instructions with legal element types to VVP_* 302 // nodes. 303 // TODO We will custom-widen into VVP_* nodes in the future. While we are 304 // buildling the infrastructure for this, we only do this for legal vector 305 // VTs. 306 #define HANDLE_VP_TO_VVP(VP_OPC, VVP_NAME) \ 307 setOperationAction(ISD::VP_OPC, LegalVecVT, Custom); 308 #define ADD_VVP_OP(VVP_NAME, ISD_NAME) \ 309 setOperationAction(ISD::ISD_NAME, LegalVecVT, Custom); 310 #include "VVPNodes.def" 311 } 312 313 for (MVT LegalPackedVT : AllPackedVTs) { 314 setOperationAction(ISD::INSERT_VECTOR_ELT, LegalPackedVT, Custom); 315 setOperationAction(ISD::EXTRACT_VECTOR_ELT, LegalPackedVT, Custom); 316 } 317 } 318 319 SDValue 320 VETargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 321 bool IsVarArg, 322 const SmallVectorImpl<ISD::OutputArg> &Outs, 323 const SmallVectorImpl<SDValue> &OutVals, 324 const SDLoc &DL, SelectionDAG &DAG) const { 325 // CCValAssign - represent the assignment of the return value to locations. 326 SmallVector<CCValAssign, 16> RVLocs; 327 328 // CCState - Info about the registers and stack slot. 329 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 330 *DAG.getContext()); 331 332 // Analyze return values. 333 CCInfo.AnalyzeReturn(Outs, getReturnCC(CallConv)); 334 335 SDValue Flag; 336 SmallVector<SDValue, 4> RetOps(1, Chain); 337 338 // Copy the result values into the output registers. 339 for (unsigned i = 0; i != RVLocs.size(); ++i) { 340 CCValAssign &VA = RVLocs[i]; 341 assert(VA.isRegLoc() && "Can only return in registers!"); 342 assert(!VA.needsCustom() && "Unexpected custom lowering"); 343 SDValue OutVal = OutVals[i]; 344 345 // Integer return values must be sign or zero extended by the callee. 346 switch (VA.getLocInfo()) { 347 case CCValAssign::Full: 348 break; 349 case CCValAssign::SExt: 350 OutVal = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), OutVal); 351 break; 352 case CCValAssign::ZExt: 353 OutVal = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), OutVal); 354 break; 355 case CCValAssign::AExt: 356 OutVal = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), OutVal); 357 break; 358 case CCValAssign::BCvt: { 359 // Convert a float return value to i64 with padding. 360 // 63 31 0 361 // +------+------+ 362 // | float| 0 | 363 // +------+------+ 364 assert(VA.getLocVT() == MVT::i64); 365 assert(VA.getValVT() == MVT::f32); 366 SDValue Undef = SDValue( 367 DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64), 0); 368 SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32); 369 OutVal = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 370 MVT::i64, Undef, OutVal, Sub_f32), 371 0); 372 break; 373 } 374 default: 375 llvm_unreachable("Unknown loc info!"); 376 } 377 378 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVal, Flag); 379 380 // Guarantee that all emitted copies are stuck together with flags. 381 Flag = Chain.getValue(1); 382 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 383 } 384 385 RetOps[0] = Chain; // Update chain. 386 387 // Add the flag if we have it. 388 if (Flag.getNode()) 389 RetOps.push_back(Flag); 390 391 return DAG.getNode(VEISD::RET_FLAG, DL, MVT::Other, RetOps); 392 } 393 394 SDValue VETargetLowering::LowerFormalArguments( 395 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 396 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 397 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 398 MachineFunction &MF = DAG.getMachineFunction(); 399 400 // Get the base offset of the incoming arguments stack space. 401 unsigned ArgsBaseOffset = Subtarget->getRsaSize(); 402 // Get the size of the preserved arguments area 403 unsigned ArgsPreserved = 64; 404 405 // Analyze arguments according to CC_VE. 406 SmallVector<CCValAssign, 16> ArgLocs; 407 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 408 *DAG.getContext()); 409 // Allocate the preserved area first. 410 CCInfo.AllocateStack(ArgsPreserved, Align(8)); 411 // We already allocated the preserved area, so the stack offset computed 412 // by CC_VE would be correct now. 413 CCInfo.AnalyzeFormalArguments(Ins, getParamCC(CallConv, false)); 414 415 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 416 CCValAssign &VA = ArgLocs[i]; 417 assert(!VA.needsCustom() && "Unexpected custom lowering"); 418 if (VA.isRegLoc()) { 419 // This argument is passed in a register. 420 // All integer register arguments are promoted by the caller to i64. 421 422 // Create a virtual register for the promoted live-in value. 423 Register VReg = 424 MF.addLiveIn(VA.getLocReg(), getRegClassFor(VA.getLocVT())); 425 SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT()); 426 427 // The caller promoted the argument, so insert an Assert?ext SDNode so we 428 // won't promote the value again in this function. 429 switch (VA.getLocInfo()) { 430 case CCValAssign::SExt: 431 Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg, 432 DAG.getValueType(VA.getValVT())); 433 break; 434 case CCValAssign::ZExt: 435 Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg, 436 DAG.getValueType(VA.getValVT())); 437 break; 438 case CCValAssign::BCvt: { 439 // Extract a float argument from i64 with padding. 440 // 63 31 0 441 // +------+------+ 442 // | float| 0 | 443 // +------+------+ 444 assert(VA.getLocVT() == MVT::i64); 445 assert(VA.getValVT() == MVT::f32); 446 SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32); 447 Arg = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 448 MVT::f32, Arg, Sub_f32), 449 0); 450 break; 451 } 452 default: 453 break; 454 } 455 456 // Truncate the register down to the argument type. 457 if (VA.isExtInLoc()) 458 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 459 460 InVals.push_back(Arg); 461 continue; 462 } 463 464 // The registers are exhausted. This argument was passed on the stack. 465 assert(VA.isMemLoc()); 466 // The CC_VE_Full/Half functions compute stack offsets relative to the 467 // beginning of the arguments area at %fp + the size of reserved area. 468 unsigned Offset = VA.getLocMemOffset() + ArgsBaseOffset; 469 unsigned ValSize = VA.getValVT().getSizeInBits() / 8; 470 471 // Adjust offset for a float argument by adding 4 since the argument is 472 // stored in 8 bytes buffer with offset like below. LLVM generates 473 // 4 bytes load instruction, so need to adjust offset here. This 474 // adjustment is required in only LowerFormalArguments. In LowerCall, 475 // a float argument is converted to i64 first, and stored as 8 bytes 476 // data, which is required by ABI, so no need for adjustment. 477 // 0 4 478 // +------+------+ 479 // | empty| float| 480 // +------+------+ 481 if (VA.getValVT() == MVT::f32) 482 Offset += 4; 483 484 int FI = MF.getFrameInfo().CreateFixedObject(ValSize, Offset, true); 485 InVals.push_back( 486 DAG.getLoad(VA.getValVT(), DL, Chain, 487 DAG.getFrameIndex(FI, getPointerTy(MF.getDataLayout())), 488 MachinePointerInfo::getFixedStack(MF, FI))); 489 } 490 491 if (!IsVarArg) 492 return Chain; 493 494 // This function takes variable arguments, some of which may have been passed 495 // in registers %s0-%s8. 496 // 497 // The va_start intrinsic needs to know the offset to the first variable 498 // argument. 499 // TODO: need to calculate offset correctly once we support f128. 500 unsigned ArgOffset = ArgLocs.size() * 8; 501 VEMachineFunctionInfo *FuncInfo = MF.getInfo<VEMachineFunctionInfo>(); 502 // Skip the reserved area at the top of stack. 503 FuncInfo->setVarArgsFrameOffset(ArgOffset + ArgsBaseOffset); 504 505 return Chain; 506 } 507 508 // FIXME? Maybe this could be a TableGen attribute on some registers and 509 // this table could be generated automatically from RegInfo. 510 Register VETargetLowering::getRegisterByName(const char *RegName, LLT VT, 511 const MachineFunction &MF) const { 512 Register Reg = StringSwitch<Register>(RegName) 513 .Case("sp", VE::SX11) // Stack pointer 514 .Case("fp", VE::SX9) // Frame pointer 515 .Case("sl", VE::SX8) // Stack limit 516 .Case("lr", VE::SX10) // Link register 517 .Case("tp", VE::SX14) // Thread pointer 518 .Case("outer", VE::SX12) // Outer regiser 519 .Case("info", VE::SX17) // Info area register 520 .Case("got", VE::SX15) // Global offset table register 521 .Case("plt", VE::SX16) // Procedure linkage table register 522 .Default(0); 523 524 if (Reg) 525 return Reg; 526 527 report_fatal_error("Invalid register name global variable"); 528 } 529 530 //===----------------------------------------------------------------------===// 531 // TargetLowering Implementation 532 //===----------------------------------------------------------------------===// 533 534 SDValue VETargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, 535 SmallVectorImpl<SDValue> &InVals) const { 536 SelectionDAG &DAG = CLI.DAG; 537 SDLoc DL = CLI.DL; 538 SDValue Chain = CLI.Chain; 539 auto PtrVT = getPointerTy(DAG.getDataLayout()); 540 541 // VE target does not yet support tail call optimization. 542 CLI.IsTailCall = false; 543 544 // Get the base offset of the outgoing arguments stack space. 545 unsigned ArgsBaseOffset = Subtarget->getRsaSize(); 546 // Get the size of the preserved arguments area 547 unsigned ArgsPreserved = 8 * 8u; 548 549 // Analyze operands of the call, assigning locations to each operand. 550 SmallVector<CCValAssign, 16> ArgLocs; 551 CCState CCInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), ArgLocs, 552 *DAG.getContext()); 553 // Allocate the preserved area first. 554 CCInfo.AllocateStack(ArgsPreserved, Align(8)); 555 // We already allocated the preserved area, so the stack offset computed 556 // by CC_VE would be correct now. 557 CCInfo.AnalyzeCallOperands(CLI.Outs, getParamCC(CLI.CallConv, false)); 558 559 // VE requires to use both register and stack for varargs or no-prototyped 560 // functions. 561 bool UseBoth = CLI.IsVarArg; 562 563 // Analyze operands again if it is required to store BOTH. 564 SmallVector<CCValAssign, 16> ArgLocs2; 565 CCState CCInfo2(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), 566 ArgLocs2, *DAG.getContext()); 567 if (UseBoth) 568 CCInfo2.AnalyzeCallOperands(CLI.Outs, getParamCC(CLI.CallConv, true)); 569 570 // Get the size of the outgoing arguments stack space requirement. 571 unsigned ArgsSize = CCInfo.getNextStackOffset(); 572 573 // Keep stack frames 16-byte aligned. 574 ArgsSize = alignTo(ArgsSize, 16); 575 576 // Adjust the stack pointer to make room for the arguments. 577 // FIXME: Use hasReservedCallFrame to avoid %sp adjustments around all calls 578 // with more than 6 arguments. 579 Chain = DAG.getCALLSEQ_START(Chain, ArgsSize, 0, DL); 580 581 // Collect the set of registers to pass to the function and their values. 582 // This will be emitted as a sequence of CopyToReg nodes glued to the call 583 // instruction. 584 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 585 586 // Collect chains from all the memory opeations that copy arguments to the 587 // stack. They must follow the stack pointer adjustment above and precede the 588 // call instruction itself. 589 SmallVector<SDValue, 8> MemOpChains; 590 591 // VE needs to get address of callee function in a register 592 // So, prepare to copy it to SX12 here. 593 594 // If the callee is a GlobalAddress node (quite common, every direct call is) 595 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it. 596 // Likewise ExternalSymbol -> TargetExternalSymbol. 597 SDValue Callee = CLI.Callee; 598 599 bool IsPICCall = isPositionIndependent(); 600 601 // PC-relative references to external symbols should go through $stub. 602 // If so, we need to prepare GlobalBaseReg first. 603 const TargetMachine &TM = DAG.getTarget(); 604 const Module *Mod = DAG.getMachineFunction().getFunction().getParent(); 605 const GlobalValue *GV = nullptr; 606 auto *CalleeG = dyn_cast<GlobalAddressSDNode>(Callee); 607 if (CalleeG) 608 GV = CalleeG->getGlobal(); 609 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV); 610 bool UsePlt = !Local; 611 MachineFunction &MF = DAG.getMachineFunction(); 612 613 // Turn GlobalAddress/ExternalSymbol node into a value node 614 // containing the address of them here. 615 if (CalleeG) { 616 if (IsPICCall) { 617 if (UsePlt) 618 Subtarget->getInstrInfo()->getGlobalBaseReg(&MF); 619 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 620 Callee = DAG.getNode(VEISD::GETFUNPLT, DL, PtrVT, Callee); 621 } else { 622 Callee = 623 makeHiLoPair(Callee, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG); 624 } 625 } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) { 626 if (IsPICCall) { 627 if (UsePlt) 628 Subtarget->getInstrInfo()->getGlobalBaseReg(&MF); 629 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT, 0); 630 Callee = DAG.getNode(VEISD::GETFUNPLT, DL, PtrVT, Callee); 631 } else { 632 Callee = 633 makeHiLoPair(Callee, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG); 634 } 635 } 636 637 RegsToPass.push_back(std::make_pair(VE::SX12, Callee)); 638 639 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 640 CCValAssign &VA = ArgLocs[i]; 641 SDValue Arg = CLI.OutVals[i]; 642 643 // Promote the value if needed. 644 switch (VA.getLocInfo()) { 645 default: 646 llvm_unreachable("Unknown location info!"); 647 case CCValAssign::Full: 648 break; 649 case CCValAssign::SExt: 650 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 651 break; 652 case CCValAssign::ZExt: 653 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 654 break; 655 case CCValAssign::AExt: 656 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 657 break; 658 case CCValAssign::BCvt: { 659 // Convert a float argument to i64 with padding. 660 // 63 31 0 661 // +------+------+ 662 // | float| 0 | 663 // +------+------+ 664 assert(VA.getLocVT() == MVT::i64); 665 assert(VA.getValVT() == MVT::f32); 666 SDValue Undef = SDValue( 667 DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64), 0); 668 SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32); 669 Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 670 MVT::i64, Undef, Arg, Sub_f32), 671 0); 672 break; 673 } 674 } 675 676 if (VA.isRegLoc()) { 677 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 678 if (!UseBoth) 679 continue; 680 VA = ArgLocs2[i]; 681 } 682 683 assert(VA.isMemLoc()); 684 685 // Create a store off the stack pointer for this argument. 686 SDValue StackPtr = DAG.getRegister(VE::SX11, PtrVT); 687 // The argument area starts at %fp/%sp + the size of reserved area. 688 SDValue PtrOff = 689 DAG.getIntPtrConstant(VA.getLocMemOffset() + ArgsBaseOffset, DL); 690 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 691 MemOpChains.push_back( 692 DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo())); 693 } 694 695 // Emit all stores, make sure they occur before the call. 696 if (!MemOpChains.empty()) 697 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 698 699 // Build a sequence of CopyToReg nodes glued together with token chain and 700 // glue operands which copy the outgoing args into registers. The InGlue is 701 // necessary since all emitted instructions must be stuck together in order 702 // to pass the live physical registers. 703 SDValue InGlue; 704 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { 705 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first, 706 RegsToPass[i].second, InGlue); 707 InGlue = Chain.getValue(1); 708 } 709 710 // Build the operands for the call instruction itself. 711 SmallVector<SDValue, 8> Ops; 712 Ops.push_back(Chain); 713 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) 714 Ops.push_back(DAG.getRegister(RegsToPass[i].first, 715 RegsToPass[i].second.getValueType())); 716 717 // Add a register mask operand representing the call-preserved registers. 718 const VERegisterInfo *TRI = Subtarget->getRegisterInfo(); 719 const uint32_t *Mask = 720 TRI->getCallPreservedMask(DAG.getMachineFunction(), CLI.CallConv); 721 assert(Mask && "Missing call preserved mask for calling convention"); 722 Ops.push_back(DAG.getRegisterMask(Mask)); 723 724 // Make sure the CopyToReg nodes are glued to the call instruction which 725 // consumes the registers. 726 if (InGlue.getNode()) 727 Ops.push_back(InGlue); 728 729 // Now the call itself. 730 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 731 Chain = DAG.getNode(VEISD::CALL, DL, NodeTys, Ops); 732 InGlue = Chain.getValue(1); 733 734 // Revert the stack pointer immediately after the call. 735 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, DL, true), 736 DAG.getIntPtrConstant(0, DL, true), InGlue, DL); 737 InGlue = Chain.getValue(1); 738 739 // Now extract the return values. This is more or less the same as 740 // LowerFormalArguments. 741 742 // Assign locations to each value returned by this call. 743 SmallVector<CCValAssign, 16> RVLocs; 744 CCState RVInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), RVLocs, 745 *DAG.getContext()); 746 747 // Set inreg flag manually for codegen generated library calls that 748 // return float. 749 if (CLI.Ins.size() == 1 && CLI.Ins[0].VT == MVT::f32 && !CLI.CB) 750 CLI.Ins[0].Flags.setInReg(); 751 752 RVInfo.AnalyzeCallResult(CLI.Ins, getReturnCC(CLI.CallConv)); 753 754 // Copy all of the result registers out of their specified physreg. 755 for (unsigned i = 0; i != RVLocs.size(); ++i) { 756 CCValAssign &VA = RVLocs[i]; 757 assert(!VA.needsCustom() && "Unexpected custom lowering"); 758 Register Reg = VA.getLocReg(); 759 760 // When returning 'inreg {i32, i32 }', two consecutive i32 arguments can 761 // reside in the same register in the high and low bits. Reuse the 762 // CopyFromReg previous node to avoid duplicate copies. 763 SDValue RV; 764 if (RegisterSDNode *SrcReg = dyn_cast<RegisterSDNode>(Chain.getOperand(1))) 765 if (SrcReg->getReg() == Reg && Chain->getOpcode() == ISD::CopyFromReg) 766 RV = Chain.getValue(0); 767 768 // But usually we'll create a new CopyFromReg for a different register. 769 if (!RV.getNode()) { 770 RV = DAG.getCopyFromReg(Chain, DL, Reg, RVLocs[i].getLocVT(), InGlue); 771 Chain = RV.getValue(1); 772 InGlue = Chain.getValue(2); 773 } 774 775 // The callee promoted the return value, so insert an Assert?ext SDNode so 776 // we won't promote the value again in this function. 777 switch (VA.getLocInfo()) { 778 case CCValAssign::SExt: 779 RV = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), RV, 780 DAG.getValueType(VA.getValVT())); 781 break; 782 case CCValAssign::ZExt: 783 RV = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), RV, 784 DAG.getValueType(VA.getValVT())); 785 break; 786 case CCValAssign::BCvt: { 787 // Extract a float return value from i64 with padding. 788 // 63 31 0 789 // +------+------+ 790 // | float| 0 | 791 // +------+------+ 792 assert(VA.getLocVT() == MVT::i64); 793 assert(VA.getValVT() == MVT::f32); 794 SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32); 795 RV = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 796 MVT::f32, RV, Sub_f32), 797 0); 798 break; 799 } 800 default: 801 break; 802 } 803 804 // Truncate the register down to the return value type. 805 if (VA.isExtInLoc()) 806 RV = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), RV); 807 808 InVals.push_back(RV); 809 } 810 811 return Chain; 812 } 813 814 bool VETargetLowering::isOffsetFoldingLegal( 815 const GlobalAddressSDNode *GA) const { 816 // VE uses 64 bit addressing, so we need multiple instructions to generate 817 // an address. Folding address with offset increases the number of 818 // instructions, so that we disable it here. Offsets will be folded in 819 // the DAG combine later if it worth to do so. 820 return false; 821 } 822 823 /// isFPImmLegal - Returns true if the target can instruction select the 824 /// specified FP immediate natively. If false, the legalizer will 825 /// materialize the FP immediate as a load from a constant pool. 826 bool VETargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 827 bool ForCodeSize) const { 828 return VT == MVT::f32 || VT == MVT::f64; 829 } 830 831 /// Determine if the target supports unaligned memory accesses. 832 /// 833 /// This function returns true if the target allows unaligned memory accesses 834 /// of the specified type in the given address space. If true, it also returns 835 /// whether the unaligned memory access is "fast" in the last argument by 836 /// reference. This is used, for example, in situations where an array 837 /// copy/move/set is converted to a sequence of store operations. Its use 838 /// helps to ensure that such replacements don't generate code that causes an 839 /// alignment error (trap) on the target machine. 840 bool VETargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 841 unsigned AddrSpace, 842 Align A, 843 MachineMemOperand::Flags, 844 bool *Fast) const { 845 if (Fast) { 846 // It's fast anytime on VE 847 *Fast = true; 848 } 849 return true; 850 } 851 852 VETargetLowering::VETargetLowering(const TargetMachine &TM, 853 const VESubtarget &STI) 854 : TargetLowering(TM), Subtarget(&STI) { 855 // Instructions which use registers as conditionals examine all the 856 // bits (as does the pseudo SELECT_CC expansion). I don't think it 857 // matters much whether it's ZeroOrOneBooleanContent, or 858 // ZeroOrNegativeOneBooleanContent, so, arbitrarily choose the 859 // former. 860 setBooleanContents(ZeroOrOneBooleanContent); 861 setBooleanVectorContents(ZeroOrOneBooleanContent); 862 863 initRegisterClasses(); 864 initSPUActions(); 865 initVPUActions(); 866 867 setStackPointerRegisterToSaveRestore(VE::SX11); 868 869 // We have target-specific dag combine patterns for the following nodes: 870 setTargetDAGCombine(ISD::TRUNCATE); 871 872 // Set function alignment to 16 bytes 873 setMinFunctionAlignment(Align(16)); 874 875 // VE stores all argument by 8 bytes alignment 876 setMinStackArgumentAlignment(Align(8)); 877 878 computeRegisterProperties(Subtarget->getRegisterInfo()); 879 } 880 881 const char *VETargetLowering::getTargetNodeName(unsigned Opcode) const { 882 #define TARGET_NODE_CASE(NAME) \ 883 case VEISD::NAME: \ 884 return "VEISD::" #NAME; 885 switch ((VEISD::NodeType)Opcode) { 886 case VEISD::FIRST_NUMBER: 887 break; 888 TARGET_NODE_CASE(CALL) 889 TARGET_NODE_CASE(EH_SJLJ_LONGJMP) 890 TARGET_NODE_CASE(EH_SJLJ_SETJMP) 891 TARGET_NODE_CASE(EH_SJLJ_SETUP_DISPATCH) 892 TARGET_NODE_CASE(GETFUNPLT) 893 TARGET_NODE_CASE(GETSTACKTOP) 894 TARGET_NODE_CASE(GETTLSADDR) 895 TARGET_NODE_CASE(GLOBAL_BASE_REG) 896 TARGET_NODE_CASE(Hi) 897 TARGET_NODE_CASE(Lo) 898 TARGET_NODE_CASE(MEMBARRIER) 899 TARGET_NODE_CASE(RET_FLAG) 900 TARGET_NODE_CASE(TS1AM) 901 TARGET_NODE_CASE(VEC_BROADCAST) 902 903 // Register the VVP_* SDNodes. 904 #define ADD_VVP_OP(VVP_NAME, ...) TARGET_NODE_CASE(VVP_NAME) 905 #include "VVPNodes.def" 906 } 907 #undef TARGET_NODE_CASE 908 return nullptr; 909 } 910 911 EVT VETargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 912 EVT VT) const { 913 return MVT::i32; 914 } 915 916 // Convert to a target node and set target flags. 917 SDValue VETargetLowering::withTargetFlags(SDValue Op, unsigned TF, 918 SelectionDAG &DAG) const { 919 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) 920 return DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(GA), 921 GA->getValueType(0), GA->getOffset(), TF); 922 923 if (const BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) 924 return DAG.getTargetBlockAddress(BA->getBlockAddress(), Op.getValueType(), 925 0, TF); 926 927 if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) 928 return DAG.getTargetConstantPool(CP->getConstVal(), CP->getValueType(0), 929 CP->getAlign(), CP->getOffset(), TF); 930 931 if (const ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) 932 return DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0), 933 TF); 934 935 if (const JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) 936 return DAG.getTargetJumpTable(JT->getIndex(), JT->getValueType(0), TF); 937 938 llvm_unreachable("Unhandled address SDNode"); 939 } 940 941 // Split Op into high and low parts according to HiTF and LoTF. 942 // Return an ADD node combining the parts. 943 SDValue VETargetLowering::makeHiLoPair(SDValue Op, unsigned HiTF, unsigned LoTF, 944 SelectionDAG &DAG) const { 945 SDLoc DL(Op); 946 EVT VT = Op.getValueType(); 947 SDValue Hi = DAG.getNode(VEISD::Hi, DL, VT, withTargetFlags(Op, HiTF, DAG)); 948 SDValue Lo = DAG.getNode(VEISD::Lo, DL, VT, withTargetFlags(Op, LoTF, DAG)); 949 return DAG.getNode(ISD::ADD, DL, VT, Hi, Lo); 950 } 951 952 // Build SDNodes for producing an address from a GlobalAddress, ConstantPool, 953 // or ExternalSymbol SDNode. 954 SDValue VETargetLowering::makeAddress(SDValue Op, SelectionDAG &DAG) const { 955 SDLoc DL(Op); 956 EVT PtrVT = Op.getValueType(); 957 958 // Handle PIC mode first. VE needs a got load for every variable! 959 if (isPositionIndependent()) { 960 auto GlobalN = dyn_cast<GlobalAddressSDNode>(Op); 961 962 if (isa<ConstantPoolSDNode>(Op) || isa<JumpTableSDNode>(Op) || 963 (GlobalN && GlobalN->getGlobal()->hasLocalLinkage())) { 964 // Create following instructions for local linkage PIC code. 965 // lea %reg, label@gotoff_lo 966 // and %reg, %reg, (32)0 967 // lea.sl %reg, label@gotoff_hi(%reg, %got) 968 SDValue HiLo = makeHiLoPair(Op, VEMCExpr::VK_VE_GOTOFF_HI32, 969 VEMCExpr::VK_VE_GOTOFF_LO32, DAG); 970 SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, PtrVT); 971 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalBase, HiLo); 972 } 973 // Create following instructions for not local linkage PIC code. 974 // lea %reg, label@got_lo 975 // and %reg, %reg, (32)0 976 // lea.sl %reg, label@got_hi(%reg) 977 // ld %reg, (%reg, %got) 978 SDValue HiLo = makeHiLoPair(Op, VEMCExpr::VK_VE_GOT_HI32, 979 VEMCExpr::VK_VE_GOT_LO32, DAG); 980 SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, PtrVT); 981 SDValue AbsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, GlobalBase, HiLo); 982 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), AbsAddr, 983 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 984 } 985 986 // This is one of the absolute code models. 987 switch (getTargetMachine().getCodeModel()) { 988 default: 989 llvm_unreachable("Unsupported absolute code model"); 990 case CodeModel::Small: 991 case CodeModel::Medium: 992 case CodeModel::Large: 993 // abs64. 994 return makeHiLoPair(Op, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG); 995 } 996 } 997 998 /// Custom Lower { 999 1000 // The mappings for emitLeading/TrailingFence for VE is designed by following 1001 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html 1002 Instruction *VETargetLowering::emitLeadingFence(IRBuilderBase &Builder, 1003 Instruction *Inst, 1004 AtomicOrdering Ord) const { 1005 switch (Ord) { 1006 case AtomicOrdering::NotAtomic: 1007 case AtomicOrdering::Unordered: 1008 llvm_unreachable("Invalid fence: unordered/non-atomic"); 1009 case AtomicOrdering::Monotonic: 1010 case AtomicOrdering::Acquire: 1011 return nullptr; // Nothing to do 1012 case AtomicOrdering::Release: 1013 case AtomicOrdering::AcquireRelease: 1014 return Builder.CreateFence(AtomicOrdering::Release); 1015 case AtomicOrdering::SequentiallyConsistent: 1016 if (!Inst->hasAtomicStore()) 1017 return nullptr; // Nothing to do 1018 return Builder.CreateFence(AtomicOrdering::SequentiallyConsistent); 1019 } 1020 llvm_unreachable("Unknown fence ordering in emitLeadingFence"); 1021 } 1022 1023 Instruction *VETargetLowering::emitTrailingFence(IRBuilderBase &Builder, 1024 Instruction *Inst, 1025 AtomicOrdering Ord) const { 1026 switch (Ord) { 1027 case AtomicOrdering::NotAtomic: 1028 case AtomicOrdering::Unordered: 1029 llvm_unreachable("Invalid fence: unordered/not-atomic"); 1030 case AtomicOrdering::Monotonic: 1031 case AtomicOrdering::Release: 1032 return nullptr; // Nothing to do 1033 case AtomicOrdering::Acquire: 1034 case AtomicOrdering::AcquireRelease: 1035 return Builder.CreateFence(AtomicOrdering::Acquire); 1036 case AtomicOrdering::SequentiallyConsistent: 1037 return Builder.CreateFence(AtomicOrdering::SequentiallyConsistent); 1038 } 1039 llvm_unreachable("Unknown fence ordering in emitTrailingFence"); 1040 } 1041 1042 SDValue VETargetLowering::lowerATOMIC_FENCE(SDValue Op, 1043 SelectionDAG &DAG) const { 1044 SDLoc DL(Op); 1045 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>( 1046 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()); 1047 SyncScope::ID FenceSSID = static_cast<SyncScope::ID>( 1048 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 1049 1050 // VE uses Release consistency, so need a fence instruction if it is a 1051 // cross-thread fence. 1052 if (FenceSSID == SyncScope::System) { 1053 switch (FenceOrdering) { 1054 case AtomicOrdering::NotAtomic: 1055 case AtomicOrdering::Unordered: 1056 case AtomicOrdering::Monotonic: 1057 // No need to generate fencem instruction here. 1058 break; 1059 case AtomicOrdering::Acquire: 1060 // Generate "fencem 2" as acquire fence. 1061 return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other, 1062 DAG.getTargetConstant(2, DL, MVT::i32), 1063 Op.getOperand(0)), 1064 0); 1065 case AtomicOrdering::Release: 1066 // Generate "fencem 1" as release fence. 1067 return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other, 1068 DAG.getTargetConstant(1, DL, MVT::i32), 1069 Op.getOperand(0)), 1070 0); 1071 case AtomicOrdering::AcquireRelease: 1072 case AtomicOrdering::SequentiallyConsistent: 1073 // Generate "fencem 3" as acq_rel and seq_cst fence. 1074 // FIXME: "fencem 3" doesn't wait for for PCIe deveices accesses, 1075 // so seq_cst may require more instruction for them. 1076 return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other, 1077 DAG.getTargetConstant(3, DL, MVT::i32), 1078 Op.getOperand(0)), 1079 0); 1080 } 1081 } 1082 1083 // MEMBARRIER is a compiler barrier; it codegens to a no-op. 1084 return DAG.getNode(VEISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0)); 1085 } 1086 1087 TargetLowering::AtomicExpansionKind 1088 VETargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 1089 // We have TS1AM implementation for i8/i16/i32/i64, so use it. 1090 if (AI->getOperation() == AtomicRMWInst::Xchg) { 1091 return AtomicExpansionKind::None; 1092 } 1093 // FIXME: Support "ATMAM" instruction for LOAD_ADD/SUB/AND/OR. 1094 1095 // Otherwise, expand it using compare and exchange instruction to not call 1096 // __sync_fetch_and_* functions. 1097 return AtomicExpansionKind::CmpXChg; 1098 } 1099 1100 static SDValue prepareTS1AM(SDValue Op, SelectionDAG &DAG, SDValue &Flag, 1101 SDValue &Bits) { 1102 SDLoc DL(Op); 1103 AtomicSDNode *N = cast<AtomicSDNode>(Op); 1104 SDValue Ptr = N->getOperand(1); 1105 SDValue Val = N->getOperand(2); 1106 EVT PtrVT = Ptr.getValueType(); 1107 bool Byte = N->getMemoryVT() == MVT::i8; 1108 // Remainder = AND Ptr, 3 1109 // Flag = 1 << Remainder ; If Byte is true (1 byte swap flag) 1110 // Flag = 3 << Remainder ; If Byte is false (2 bytes swap flag) 1111 // Bits = Remainder << 3 1112 // NewVal = Val << Bits 1113 SDValue Const3 = DAG.getConstant(3, DL, PtrVT); 1114 SDValue Remainder = DAG.getNode(ISD::AND, DL, PtrVT, {Ptr, Const3}); 1115 SDValue Mask = Byte ? DAG.getConstant(1, DL, MVT::i32) 1116 : DAG.getConstant(3, DL, MVT::i32); 1117 Flag = DAG.getNode(ISD::SHL, DL, MVT::i32, {Mask, Remainder}); 1118 Bits = DAG.getNode(ISD::SHL, DL, PtrVT, {Remainder, Const3}); 1119 return DAG.getNode(ISD::SHL, DL, Val.getValueType(), {Val, Bits}); 1120 } 1121 1122 static SDValue finalizeTS1AM(SDValue Op, SelectionDAG &DAG, SDValue Data, 1123 SDValue Bits) { 1124 SDLoc DL(Op); 1125 EVT VT = Data.getValueType(); 1126 bool Byte = cast<AtomicSDNode>(Op)->getMemoryVT() == MVT::i8; 1127 // NewData = Data >> Bits 1128 // Result = NewData & 0xff ; If Byte is true (1 byte) 1129 // Result = NewData & 0xffff ; If Byte is false (2 bytes) 1130 1131 SDValue NewData = DAG.getNode(ISD::SRL, DL, VT, Data, Bits); 1132 return DAG.getNode(ISD::AND, DL, VT, 1133 {NewData, DAG.getConstant(Byte ? 0xff : 0xffff, DL, VT)}); 1134 } 1135 1136 SDValue VETargetLowering::lowerATOMIC_SWAP(SDValue Op, 1137 SelectionDAG &DAG) const { 1138 SDLoc DL(Op); 1139 AtomicSDNode *N = cast<AtomicSDNode>(Op); 1140 1141 if (N->getMemoryVT() == MVT::i8) { 1142 // For i8, use "ts1am" 1143 // Input: 1144 // ATOMIC_SWAP Ptr, Val, Order 1145 // 1146 // Output: 1147 // Remainder = AND Ptr, 3 1148 // Flag = 1 << Remainder ; 1 byte swap flag for TS1AM inst. 1149 // Bits = Remainder << 3 1150 // NewVal = Val << Bits 1151 // 1152 // Aligned = AND Ptr, -4 1153 // Data = TS1AM Aligned, Flag, NewVal 1154 // 1155 // NewData = Data >> Bits 1156 // Result = NewData & 0xff ; 1 byte result 1157 SDValue Flag; 1158 SDValue Bits; 1159 SDValue NewVal = prepareTS1AM(Op, DAG, Flag, Bits); 1160 1161 SDValue Ptr = N->getOperand(1); 1162 SDValue Aligned = DAG.getNode(ISD::AND, DL, Ptr.getValueType(), 1163 {Ptr, DAG.getConstant(-4, DL, MVT::i64)}); 1164 SDValue TS1AM = DAG.getAtomic(VEISD::TS1AM, DL, N->getMemoryVT(), 1165 DAG.getVTList(Op.getNode()->getValueType(0), 1166 Op.getNode()->getValueType(1)), 1167 {N->getChain(), Aligned, Flag, NewVal}, 1168 N->getMemOperand()); 1169 1170 SDValue Result = finalizeTS1AM(Op, DAG, TS1AM, Bits); 1171 SDValue Chain = TS1AM.getValue(1); 1172 return DAG.getMergeValues({Result, Chain}, DL); 1173 } 1174 if (N->getMemoryVT() == MVT::i16) { 1175 // For i16, use "ts1am" 1176 SDValue Flag; 1177 SDValue Bits; 1178 SDValue NewVal = prepareTS1AM(Op, DAG, Flag, Bits); 1179 1180 SDValue Ptr = N->getOperand(1); 1181 SDValue Aligned = DAG.getNode(ISD::AND, DL, Ptr.getValueType(), 1182 {Ptr, DAG.getConstant(-4, DL, MVT::i64)}); 1183 SDValue TS1AM = DAG.getAtomic(VEISD::TS1AM, DL, N->getMemoryVT(), 1184 DAG.getVTList(Op.getNode()->getValueType(0), 1185 Op.getNode()->getValueType(1)), 1186 {N->getChain(), Aligned, Flag, NewVal}, 1187 N->getMemOperand()); 1188 1189 SDValue Result = finalizeTS1AM(Op, DAG, TS1AM, Bits); 1190 SDValue Chain = TS1AM.getValue(1); 1191 return DAG.getMergeValues({Result, Chain}, DL); 1192 } 1193 // Otherwise, let llvm legalize it. 1194 return Op; 1195 } 1196 1197 SDValue VETargetLowering::lowerGlobalAddress(SDValue Op, 1198 SelectionDAG &DAG) const { 1199 return makeAddress(Op, DAG); 1200 } 1201 1202 SDValue VETargetLowering::lowerBlockAddress(SDValue Op, 1203 SelectionDAG &DAG) const { 1204 return makeAddress(Op, DAG); 1205 } 1206 1207 SDValue VETargetLowering::lowerConstantPool(SDValue Op, 1208 SelectionDAG &DAG) const { 1209 return makeAddress(Op, DAG); 1210 } 1211 1212 SDValue 1213 VETargetLowering::lowerToTLSGeneralDynamicModel(SDValue Op, 1214 SelectionDAG &DAG) const { 1215 SDLoc DL(Op); 1216 1217 // Generate the following code: 1218 // t1: ch,glue = callseq_start t0, 0, 0 1219 // t2: i64,ch,glue = VEISD::GETTLSADDR t1, label, t1:1 1220 // t3: ch,glue = callseq_end t2, 0, 0, t2:2 1221 // t4: i64,ch,glue = CopyFromReg t3, Register:i64 $sx0, t3:1 1222 SDValue Label = withTargetFlags(Op, 0, DAG); 1223 EVT PtrVT = Op.getValueType(); 1224 1225 // Lowering the machine isd will make sure everything is in the right 1226 // location. 1227 SDValue Chain = DAG.getEntryNode(); 1228 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1229 const uint32_t *Mask = Subtarget->getRegisterInfo()->getCallPreservedMask( 1230 DAG.getMachineFunction(), CallingConv::C); 1231 Chain = DAG.getCALLSEQ_START(Chain, 64, 0, DL); 1232 SDValue Args[] = {Chain, Label, DAG.getRegisterMask(Mask), Chain.getValue(1)}; 1233 Chain = DAG.getNode(VEISD::GETTLSADDR, DL, NodeTys, Args); 1234 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(64, DL, true), 1235 DAG.getIntPtrConstant(0, DL, true), 1236 Chain.getValue(1), DL); 1237 Chain = DAG.getCopyFromReg(Chain, DL, VE::SX0, PtrVT, Chain.getValue(1)); 1238 1239 // GETTLSADDR will be codegen'ed as call. Inform MFI that function has calls. 1240 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 1241 MFI.setHasCalls(true); 1242 1243 // Also generate code to prepare a GOT register if it is PIC. 1244 if (isPositionIndependent()) { 1245 MachineFunction &MF = DAG.getMachineFunction(); 1246 Subtarget->getInstrInfo()->getGlobalBaseReg(&MF); 1247 } 1248 1249 return Chain; 1250 } 1251 1252 SDValue VETargetLowering::lowerGlobalTLSAddress(SDValue Op, 1253 SelectionDAG &DAG) const { 1254 // The current implementation of nld (2.26) doesn't allow local exec model 1255 // code described in VE-tls_v1.1.pdf (*1) as its input. Instead, we always 1256 // generate the general dynamic model code sequence. 1257 // 1258 // *1: https://www.nec.com/en/global/prod/hpc/aurora/document/VE-tls_v1.1.pdf 1259 return lowerToTLSGeneralDynamicModel(Op, DAG); 1260 } 1261 1262 SDValue VETargetLowering::lowerJumpTable(SDValue Op, SelectionDAG &DAG) const { 1263 return makeAddress(Op, DAG); 1264 } 1265 1266 // Lower a f128 load into two f64 loads. 1267 static SDValue lowerLoadF128(SDValue Op, SelectionDAG &DAG) { 1268 SDLoc DL(Op); 1269 LoadSDNode *LdNode = dyn_cast<LoadSDNode>(Op.getNode()); 1270 assert(LdNode && LdNode->getOffset().isUndef() && "Unexpected node type"); 1271 unsigned Alignment = LdNode->getAlign().value(); 1272 if (Alignment > 8) 1273 Alignment = 8; 1274 1275 SDValue Lo64 = 1276 DAG.getLoad(MVT::f64, DL, LdNode->getChain(), LdNode->getBasePtr(), 1277 LdNode->getPointerInfo(), Alignment, 1278 LdNode->isVolatile() ? MachineMemOperand::MOVolatile 1279 : MachineMemOperand::MONone); 1280 EVT AddrVT = LdNode->getBasePtr().getValueType(); 1281 SDValue HiPtr = DAG.getNode(ISD::ADD, DL, AddrVT, LdNode->getBasePtr(), 1282 DAG.getConstant(8, DL, AddrVT)); 1283 SDValue Hi64 = 1284 DAG.getLoad(MVT::f64, DL, LdNode->getChain(), HiPtr, 1285 LdNode->getPointerInfo(), Alignment, 1286 LdNode->isVolatile() ? MachineMemOperand::MOVolatile 1287 : MachineMemOperand::MONone); 1288 1289 SDValue SubRegEven = DAG.getTargetConstant(VE::sub_even, DL, MVT::i32); 1290 SDValue SubRegOdd = DAG.getTargetConstant(VE::sub_odd, DL, MVT::i32); 1291 1292 // VE stores Hi64 to 8(addr) and Lo64 to 0(addr) 1293 SDNode *InFP128 = 1294 DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f128); 1295 InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f128, 1296 SDValue(InFP128, 0), Hi64, SubRegEven); 1297 InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f128, 1298 SDValue(InFP128, 0), Lo64, SubRegOdd); 1299 SDValue OutChains[2] = {SDValue(Lo64.getNode(), 1), 1300 SDValue(Hi64.getNode(), 1)}; 1301 SDValue OutChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 1302 SDValue Ops[2] = {SDValue(InFP128, 0), OutChain}; 1303 return DAG.getMergeValues(Ops, DL); 1304 } 1305 1306 SDValue VETargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const { 1307 LoadSDNode *LdNode = cast<LoadSDNode>(Op.getNode()); 1308 1309 SDValue BasePtr = LdNode->getBasePtr(); 1310 if (isa<FrameIndexSDNode>(BasePtr.getNode())) { 1311 // Do not expand store instruction with frame index here because of 1312 // dependency problems. We expand it later in eliminateFrameIndex(). 1313 return Op; 1314 } 1315 1316 EVT MemVT = LdNode->getMemoryVT(); 1317 if (MemVT == MVT::f128) 1318 return lowerLoadF128(Op, DAG); 1319 1320 return Op; 1321 } 1322 1323 // Lower a f128 store into two f64 stores. 1324 static SDValue lowerStoreF128(SDValue Op, SelectionDAG &DAG) { 1325 SDLoc DL(Op); 1326 StoreSDNode *StNode = dyn_cast<StoreSDNode>(Op.getNode()); 1327 assert(StNode && StNode->getOffset().isUndef() && "Unexpected node type"); 1328 1329 SDValue SubRegEven = DAG.getTargetConstant(VE::sub_even, DL, MVT::i32); 1330 SDValue SubRegOdd = DAG.getTargetConstant(VE::sub_odd, DL, MVT::i32); 1331 1332 SDNode *Hi64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i64, 1333 StNode->getValue(), SubRegEven); 1334 SDNode *Lo64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i64, 1335 StNode->getValue(), SubRegOdd); 1336 1337 unsigned Alignment = StNode->getAlign().value(); 1338 if (Alignment > 8) 1339 Alignment = 8; 1340 1341 // VE stores Hi64 to 8(addr) and Lo64 to 0(addr) 1342 SDValue OutChains[2]; 1343 OutChains[0] = 1344 DAG.getStore(StNode->getChain(), DL, SDValue(Lo64, 0), 1345 StNode->getBasePtr(), MachinePointerInfo(), Alignment, 1346 StNode->isVolatile() ? MachineMemOperand::MOVolatile 1347 : MachineMemOperand::MONone); 1348 EVT AddrVT = StNode->getBasePtr().getValueType(); 1349 SDValue HiPtr = DAG.getNode(ISD::ADD, DL, AddrVT, StNode->getBasePtr(), 1350 DAG.getConstant(8, DL, AddrVT)); 1351 OutChains[1] = 1352 DAG.getStore(StNode->getChain(), DL, SDValue(Hi64, 0), HiPtr, 1353 MachinePointerInfo(), Alignment, 1354 StNode->isVolatile() ? MachineMemOperand::MOVolatile 1355 : MachineMemOperand::MONone); 1356 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 1357 } 1358 1359 SDValue VETargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const { 1360 StoreSDNode *StNode = cast<StoreSDNode>(Op.getNode()); 1361 assert(StNode && StNode->getOffset().isUndef() && "Unexpected node type"); 1362 1363 SDValue BasePtr = StNode->getBasePtr(); 1364 if (isa<FrameIndexSDNode>(BasePtr.getNode())) { 1365 // Do not expand store instruction with frame index here because of 1366 // dependency problems. We expand it later in eliminateFrameIndex(). 1367 return Op; 1368 } 1369 1370 EVT MemVT = StNode->getMemoryVT(); 1371 if (MemVT == MVT::f128) 1372 return lowerStoreF128(Op, DAG); 1373 1374 // Otherwise, ask llvm to expand it. 1375 return SDValue(); 1376 } 1377 1378 SDValue VETargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 1379 MachineFunction &MF = DAG.getMachineFunction(); 1380 VEMachineFunctionInfo *FuncInfo = MF.getInfo<VEMachineFunctionInfo>(); 1381 auto PtrVT = getPointerTy(DAG.getDataLayout()); 1382 1383 // Need frame address to find the address of VarArgsFrameIndex. 1384 MF.getFrameInfo().setFrameAddressIsTaken(true); 1385 1386 // vastart just stores the address of the VarArgsFrameIndex slot into the 1387 // memory location argument. 1388 SDLoc DL(Op); 1389 SDValue Offset = 1390 DAG.getNode(ISD::ADD, DL, PtrVT, DAG.getRegister(VE::SX9, PtrVT), 1391 DAG.getIntPtrConstant(FuncInfo->getVarArgsFrameOffset(), DL)); 1392 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 1393 return DAG.getStore(Op.getOperand(0), DL, Offset, Op.getOperand(1), 1394 MachinePointerInfo(SV)); 1395 } 1396 1397 SDValue VETargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const { 1398 SDNode *Node = Op.getNode(); 1399 EVT VT = Node->getValueType(0); 1400 SDValue InChain = Node->getOperand(0); 1401 SDValue VAListPtr = Node->getOperand(1); 1402 EVT PtrVT = VAListPtr.getValueType(); 1403 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 1404 SDLoc DL(Node); 1405 SDValue VAList = 1406 DAG.getLoad(PtrVT, DL, InChain, VAListPtr, MachinePointerInfo(SV)); 1407 SDValue Chain = VAList.getValue(1); 1408 SDValue NextPtr; 1409 1410 if (VT == MVT::f128) { 1411 // VE f128 values must be stored with 16 bytes alignment. We doesn't 1412 // know the actual alignment of VAList, so we take alignment of it 1413 // dyanmically. 1414 int Align = 16; 1415 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 1416 DAG.getConstant(Align - 1, DL, PtrVT)); 1417 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 1418 DAG.getConstant(-Align, DL, PtrVT)); 1419 // Increment the pointer, VAList, by 16 to the next vaarg. 1420 NextPtr = 1421 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(16, DL)); 1422 } else if (VT == MVT::f32) { 1423 // float --> need special handling like below. 1424 // 0 4 1425 // +------+------+ 1426 // | empty| float| 1427 // +------+------+ 1428 // Increment the pointer, VAList, by 8 to the next vaarg. 1429 NextPtr = 1430 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(8, DL)); 1431 // Then, adjust VAList. 1432 unsigned InternalOffset = 4; 1433 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 1434 DAG.getConstant(InternalOffset, DL, PtrVT)); 1435 } else { 1436 // Increment the pointer, VAList, by 8 to the next vaarg. 1437 NextPtr = 1438 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(8, DL)); 1439 } 1440 1441 // Store the incremented VAList to the legalized pointer. 1442 InChain = DAG.getStore(Chain, DL, NextPtr, VAListPtr, MachinePointerInfo(SV)); 1443 1444 // Load the actual argument out of the pointer VAList. 1445 // We can't count on greater alignment than the word size. 1446 return DAG.getLoad(VT, DL, InChain, VAList, MachinePointerInfo(), 1447 std::min(PtrVT.getSizeInBits(), VT.getSizeInBits()) / 8); 1448 } 1449 1450 SDValue VETargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op, 1451 SelectionDAG &DAG) const { 1452 // Generate following code. 1453 // (void)__llvm_grow_stack(size); 1454 // ret = GETSTACKTOP; // pseudo instruction 1455 SDLoc DL(Op); 1456 1457 // Get the inputs. 1458 SDNode *Node = Op.getNode(); 1459 SDValue Chain = Op.getOperand(0); 1460 SDValue Size = Op.getOperand(1); 1461 MaybeAlign Alignment(Op.getConstantOperandVal(2)); 1462 EVT VT = Node->getValueType(0); 1463 1464 // Chain the dynamic stack allocation so that it doesn't modify the stack 1465 // pointer when other instructions are using the stack. 1466 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 1467 1468 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering(); 1469 Align StackAlign = TFI.getStackAlign(); 1470 bool NeedsAlign = Alignment.valueOrOne() > StackAlign; 1471 1472 // Prepare arguments 1473 TargetLowering::ArgListTy Args; 1474 TargetLowering::ArgListEntry Entry; 1475 Entry.Node = Size; 1476 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 1477 Args.push_back(Entry); 1478 if (NeedsAlign) { 1479 Entry.Node = DAG.getConstant(~(Alignment->value() - 1ULL), DL, VT); 1480 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 1481 Args.push_back(Entry); 1482 } 1483 Type *RetTy = Type::getVoidTy(*DAG.getContext()); 1484 1485 EVT PtrVT = Op.getValueType(); 1486 SDValue Callee; 1487 if (NeedsAlign) { 1488 Callee = DAG.getTargetExternalSymbol("__ve_grow_stack_align", PtrVT, 0); 1489 } else { 1490 Callee = DAG.getTargetExternalSymbol("__ve_grow_stack", PtrVT, 0); 1491 } 1492 1493 TargetLowering::CallLoweringInfo CLI(DAG); 1494 CLI.setDebugLoc(DL) 1495 .setChain(Chain) 1496 .setCallee(CallingConv::PreserveAll, RetTy, Callee, std::move(Args)) 1497 .setDiscardResult(true); 1498 std::pair<SDValue, SDValue> pair = LowerCallTo(CLI); 1499 Chain = pair.second; 1500 SDValue Result = DAG.getNode(VEISD::GETSTACKTOP, DL, VT, Chain); 1501 if (NeedsAlign) { 1502 Result = DAG.getNode(ISD::ADD, DL, VT, Result, 1503 DAG.getConstant((Alignment->value() - 1ULL), DL, VT)); 1504 Result = DAG.getNode(ISD::AND, DL, VT, Result, 1505 DAG.getConstant(~(Alignment->value() - 1ULL), DL, VT)); 1506 } 1507 // Chain = Result.getValue(1); 1508 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true), 1509 DAG.getIntPtrConstant(0, DL, true), SDValue(), DL); 1510 1511 SDValue Ops[2] = {Result, Chain}; 1512 return DAG.getMergeValues(Ops, DL); 1513 } 1514 1515 SDValue VETargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, 1516 SelectionDAG &DAG) const { 1517 SDLoc DL(Op); 1518 return DAG.getNode(VEISD::EH_SJLJ_LONGJMP, DL, MVT::Other, Op.getOperand(0), 1519 Op.getOperand(1)); 1520 } 1521 1522 SDValue VETargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, 1523 SelectionDAG &DAG) const { 1524 SDLoc DL(Op); 1525 return DAG.getNode(VEISD::EH_SJLJ_SETJMP, DL, 1526 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), 1527 Op.getOperand(1)); 1528 } 1529 1530 SDValue VETargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, 1531 SelectionDAG &DAG) const { 1532 SDLoc DL(Op); 1533 return DAG.getNode(VEISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other, 1534 Op.getOperand(0)); 1535 } 1536 1537 static SDValue lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG, 1538 const VETargetLowering &TLI, 1539 const VESubtarget *Subtarget) { 1540 SDLoc DL(Op); 1541 MachineFunction &MF = DAG.getMachineFunction(); 1542 EVT PtrVT = TLI.getPointerTy(MF.getDataLayout()); 1543 1544 MachineFrameInfo &MFI = MF.getFrameInfo(); 1545 MFI.setFrameAddressIsTaken(true); 1546 1547 unsigned Depth = Op.getConstantOperandVal(0); 1548 const VERegisterInfo *RegInfo = Subtarget->getRegisterInfo(); 1549 Register FrameReg = RegInfo->getFrameRegister(MF); 1550 SDValue FrameAddr = 1551 DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, PtrVT); 1552 while (Depth--) 1553 FrameAddr = DAG.getLoad(Op.getValueType(), DL, DAG.getEntryNode(), 1554 FrameAddr, MachinePointerInfo()); 1555 return FrameAddr; 1556 } 1557 1558 static SDValue lowerRETURNADDR(SDValue Op, SelectionDAG &DAG, 1559 const VETargetLowering &TLI, 1560 const VESubtarget *Subtarget) { 1561 MachineFunction &MF = DAG.getMachineFunction(); 1562 MachineFrameInfo &MFI = MF.getFrameInfo(); 1563 MFI.setReturnAddressIsTaken(true); 1564 1565 if (TLI.verifyReturnAddressArgumentIsConstant(Op, DAG)) 1566 return SDValue(); 1567 1568 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG, TLI, Subtarget); 1569 1570 SDLoc DL(Op); 1571 EVT VT = Op.getValueType(); 1572 SDValue Offset = DAG.getConstant(8, DL, VT); 1573 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 1574 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 1575 MachinePointerInfo()); 1576 } 1577 1578 SDValue VETargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op, 1579 SelectionDAG &DAG) const { 1580 SDLoc DL(Op); 1581 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1582 switch (IntNo) { 1583 default: // Don't custom lower most intrinsics. 1584 return SDValue(); 1585 case Intrinsic::eh_sjlj_lsda: { 1586 MachineFunction &MF = DAG.getMachineFunction(); 1587 MVT VT = Op.getSimpleValueType(); 1588 const VETargetMachine *TM = 1589 static_cast<const VETargetMachine *>(&DAG.getTarget()); 1590 1591 // Create GCC_except_tableXX string. The real symbol for that will be 1592 // generated in EHStreamer::emitExceptionTable() later. So, we just 1593 // borrow it's name here. 1594 TM->getStrList()->push_back(std::string( 1595 (Twine("GCC_except_table") + Twine(MF.getFunctionNumber())).str())); 1596 SDValue Addr = 1597 DAG.getTargetExternalSymbol(TM->getStrList()->back().c_str(), VT, 0); 1598 if (isPositionIndependent()) { 1599 Addr = makeHiLoPair(Addr, VEMCExpr::VK_VE_GOTOFF_HI32, 1600 VEMCExpr::VK_VE_GOTOFF_LO32, DAG); 1601 SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, VT); 1602 return DAG.getNode(ISD::ADD, DL, VT, GlobalBase, Addr); 1603 } 1604 return makeHiLoPair(Addr, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG); 1605 } 1606 } 1607 } 1608 1609 static bool getUniqueInsertion(SDNode *N, unsigned &UniqueIdx) { 1610 if (!isa<BuildVectorSDNode>(N)) 1611 return false; 1612 const auto *BVN = cast<BuildVectorSDNode>(N); 1613 1614 // Find first non-undef insertion. 1615 unsigned Idx; 1616 for (Idx = 0; Idx < BVN->getNumOperands(); ++Idx) { 1617 auto ElemV = BVN->getOperand(Idx); 1618 if (!ElemV->isUndef()) 1619 break; 1620 } 1621 // Catch the (hypothetical) all-undef case. 1622 if (Idx == BVN->getNumOperands()) 1623 return false; 1624 // Remember insertion. 1625 UniqueIdx = Idx++; 1626 // Verify that all other insertions are undef. 1627 for (; Idx < BVN->getNumOperands(); ++Idx) { 1628 auto ElemV = BVN->getOperand(Idx); 1629 if (!ElemV->isUndef()) 1630 return false; 1631 } 1632 return true; 1633 } 1634 1635 static SDValue getSplatValue(SDNode *N) { 1636 if (auto *BuildVec = dyn_cast<BuildVectorSDNode>(N)) { 1637 return BuildVec->getSplatValue(); 1638 } 1639 return SDValue(); 1640 } 1641 1642 SDValue VETargetLowering::lowerBUILD_VECTOR(SDValue Op, 1643 SelectionDAG &DAG) const { 1644 VECustomDAG CDAG(DAG, Op); 1645 unsigned NumEls = Op.getValueType().getVectorNumElements(); 1646 MVT ElemVT = Op.getSimpleValueType().getVectorElementType(); 1647 1648 // If there is just one element, expand to INSERT_VECTOR_ELT. 1649 unsigned UniqueIdx; 1650 if (getUniqueInsertion(Op.getNode(), UniqueIdx)) { 1651 SDValue AccuV = CDAG.getUNDEF(Op.getValueType()); 1652 auto ElemV = Op->getOperand(UniqueIdx); 1653 SDValue IdxV = CDAG.getConstant(UniqueIdx, MVT::i64); 1654 return CDAG.getNode(ISD::INSERT_VECTOR_ELT, Op.getValueType(), 1655 {AccuV, ElemV, IdxV}); 1656 } 1657 1658 // Else emit a broadcast. 1659 if (SDValue ScalarV = getSplatValue(Op.getNode())) { 1660 // lower to VEC_BROADCAST 1661 MVT LegalResVT = MVT::getVectorVT(ElemVT, 256); 1662 1663 auto AVL = CDAG.getConstant(NumEls, MVT::i32); 1664 return CDAG.getBroadcast(LegalResVT, Op.getOperand(0), AVL); 1665 } 1666 1667 // Expand 1668 return SDValue(); 1669 } 1670 1671 SDValue VETargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 1672 unsigned Opcode = Op.getOpcode(); 1673 if (ISD::isVPOpcode(Opcode)) 1674 return lowerToVVP(Op, DAG); 1675 1676 switch (Opcode) { 1677 default: 1678 llvm_unreachable("Should not custom lower this!"); 1679 case ISD::ATOMIC_FENCE: 1680 return lowerATOMIC_FENCE(Op, DAG); 1681 case ISD::ATOMIC_SWAP: 1682 return lowerATOMIC_SWAP(Op, DAG); 1683 case ISD::BlockAddress: 1684 return lowerBlockAddress(Op, DAG); 1685 case ISD::ConstantPool: 1686 return lowerConstantPool(Op, DAG); 1687 case ISD::DYNAMIC_STACKALLOC: 1688 return lowerDYNAMIC_STACKALLOC(Op, DAG); 1689 case ISD::EH_SJLJ_LONGJMP: 1690 return lowerEH_SJLJ_LONGJMP(Op, DAG); 1691 case ISD::EH_SJLJ_SETJMP: 1692 return lowerEH_SJLJ_SETJMP(Op, DAG); 1693 case ISD::EH_SJLJ_SETUP_DISPATCH: 1694 return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG); 1695 case ISD::FRAMEADDR: 1696 return lowerFRAMEADDR(Op, DAG, *this, Subtarget); 1697 case ISD::GlobalAddress: 1698 return lowerGlobalAddress(Op, DAG); 1699 case ISD::GlobalTLSAddress: 1700 return lowerGlobalTLSAddress(Op, DAG); 1701 case ISD::INTRINSIC_WO_CHAIN: 1702 return lowerINTRINSIC_WO_CHAIN(Op, DAG); 1703 case ISD::JumpTable: 1704 return lowerJumpTable(Op, DAG); 1705 case ISD::LOAD: 1706 return lowerLOAD(Op, DAG); 1707 case ISD::RETURNADDR: 1708 return lowerRETURNADDR(Op, DAG, *this, Subtarget); 1709 case ISD::BUILD_VECTOR: 1710 return lowerBUILD_VECTOR(Op, DAG); 1711 case ISD::STORE: 1712 return lowerSTORE(Op, DAG); 1713 case ISD::VASTART: 1714 return lowerVASTART(Op, DAG); 1715 case ISD::VAARG: 1716 return lowerVAARG(Op, DAG); 1717 1718 case ISD::INSERT_VECTOR_ELT: 1719 return lowerINSERT_VECTOR_ELT(Op, DAG); 1720 case ISD::EXTRACT_VECTOR_ELT: 1721 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 1722 1723 #define ADD_VVP_OP(VVP_NAME, ISD_NAME) case ISD::ISD_NAME: 1724 #include "VVPNodes.def" 1725 return lowerToVVP(Op, DAG); 1726 } 1727 } 1728 /// } Custom Lower 1729 1730 void VETargetLowering::ReplaceNodeResults(SDNode *N, 1731 SmallVectorImpl<SDValue> &Results, 1732 SelectionDAG &DAG) const { 1733 switch (N->getOpcode()) { 1734 case ISD::ATOMIC_SWAP: 1735 // Let LLVM expand atomic swap instruction through LowerOperation. 1736 return; 1737 default: 1738 LLVM_DEBUG(N->dumpr(&DAG)); 1739 llvm_unreachable("Do not know how to custom type legalize this operation!"); 1740 } 1741 } 1742 1743 /// JumpTable for VE. 1744 /// 1745 /// VE cannot generate relocatable symbol in jump table. VE cannot 1746 /// generate expressions using symbols in both text segment and data 1747 /// segment like below. 1748 /// .4byte .LBB0_2-.LJTI0_0 1749 /// So, we generate offset from the top of function like below as 1750 /// a custom label. 1751 /// .4byte .LBB0_2-<function name> 1752 1753 unsigned VETargetLowering::getJumpTableEncoding() const { 1754 // Use custom label for PIC. 1755 if (isPositionIndependent()) 1756 return MachineJumpTableInfo::EK_Custom32; 1757 1758 // Otherwise, use the normal jump table encoding heuristics. 1759 return TargetLowering::getJumpTableEncoding(); 1760 } 1761 1762 const MCExpr *VETargetLowering::LowerCustomJumpTableEntry( 1763 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 1764 unsigned Uid, MCContext &Ctx) const { 1765 assert(isPositionIndependent()); 1766 1767 // Generate custom label for PIC like below. 1768 // .4bytes .LBB0_2-<function name> 1769 const auto *Value = MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 1770 MCSymbol *Sym = Ctx.getOrCreateSymbol(MBB->getParent()->getName().data()); 1771 const auto *Base = MCSymbolRefExpr::create(Sym, Ctx); 1772 return MCBinaryExpr::createSub(Value, Base, Ctx); 1773 } 1774 1775 SDValue VETargetLowering::getPICJumpTableRelocBase(SDValue Table, 1776 SelectionDAG &DAG) const { 1777 assert(isPositionIndependent()); 1778 SDLoc DL(Table); 1779 Function *Function = &DAG.getMachineFunction().getFunction(); 1780 assert(Function != nullptr); 1781 auto PtrTy = getPointerTy(DAG.getDataLayout(), Function->getAddressSpace()); 1782 1783 // In the jump table, we have following values in PIC mode. 1784 // .4bytes .LBB0_2-<function name> 1785 // We need to add this value and the address of this function to generate 1786 // .LBB0_2 label correctly under PIC mode. So, we want to generate following 1787 // instructions: 1788 // lea %reg, fun@gotoff_lo 1789 // and %reg, %reg, (32)0 1790 // lea.sl %reg, fun@gotoff_hi(%reg, %got) 1791 // In order to do so, we need to genarate correctly marked DAG node using 1792 // makeHiLoPair. 1793 SDValue Op = DAG.getGlobalAddress(Function, DL, PtrTy); 1794 SDValue HiLo = makeHiLoPair(Op, VEMCExpr::VK_VE_GOTOFF_HI32, 1795 VEMCExpr::VK_VE_GOTOFF_LO32, DAG); 1796 SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, PtrTy); 1797 return DAG.getNode(ISD::ADD, DL, PtrTy, GlobalBase, HiLo); 1798 } 1799 1800 Register VETargetLowering::prepareMBB(MachineBasicBlock &MBB, 1801 MachineBasicBlock::iterator I, 1802 MachineBasicBlock *TargetBB, 1803 const DebugLoc &DL) const { 1804 MachineFunction *MF = MBB.getParent(); 1805 MachineRegisterInfo &MRI = MF->getRegInfo(); 1806 const VEInstrInfo *TII = Subtarget->getInstrInfo(); 1807 1808 const TargetRegisterClass *RC = &VE::I64RegClass; 1809 Register Tmp1 = MRI.createVirtualRegister(RC); 1810 Register Tmp2 = MRI.createVirtualRegister(RC); 1811 Register Result = MRI.createVirtualRegister(RC); 1812 1813 if (isPositionIndependent()) { 1814 // Create following instructions for local linkage PIC code. 1815 // lea %Tmp1, TargetBB@gotoff_lo 1816 // and %Tmp2, %Tmp1, (32)0 1817 // lea.sl %Result, TargetBB@gotoff_hi(%Tmp2, %s15) ; %s15 is GOT 1818 BuildMI(MBB, I, DL, TII->get(VE::LEAzii), Tmp1) 1819 .addImm(0) 1820 .addImm(0) 1821 .addMBB(TargetBB, VEMCExpr::VK_VE_GOTOFF_LO32); 1822 BuildMI(MBB, I, DL, TII->get(VE::ANDrm), Tmp2) 1823 .addReg(Tmp1, getKillRegState(true)) 1824 .addImm(M0(32)); 1825 BuildMI(MBB, I, DL, TII->get(VE::LEASLrri), Result) 1826 .addReg(VE::SX15) 1827 .addReg(Tmp2, getKillRegState(true)) 1828 .addMBB(TargetBB, VEMCExpr::VK_VE_GOTOFF_HI32); 1829 } else { 1830 // Create following instructions for non-PIC code. 1831 // lea %Tmp1, TargetBB@lo 1832 // and %Tmp2, %Tmp1, (32)0 1833 // lea.sl %Result, TargetBB@hi(%Tmp2) 1834 BuildMI(MBB, I, DL, TII->get(VE::LEAzii), Tmp1) 1835 .addImm(0) 1836 .addImm(0) 1837 .addMBB(TargetBB, VEMCExpr::VK_VE_LO32); 1838 BuildMI(MBB, I, DL, TII->get(VE::ANDrm), Tmp2) 1839 .addReg(Tmp1, getKillRegState(true)) 1840 .addImm(M0(32)); 1841 BuildMI(MBB, I, DL, TII->get(VE::LEASLrii), Result) 1842 .addReg(Tmp2, getKillRegState(true)) 1843 .addImm(0) 1844 .addMBB(TargetBB, VEMCExpr::VK_VE_HI32); 1845 } 1846 return Result; 1847 } 1848 1849 Register VETargetLowering::prepareSymbol(MachineBasicBlock &MBB, 1850 MachineBasicBlock::iterator I, 1851 StringRef Symbol, const DebugLoc &DL, 1852 bool IsLocal = false, 1853 bool IsCall = false) const { 1854 MachineFunction *MF = MBB.getParent(); 1855 MachineRegisterInfo &MRI = MF->getRegInfo(); 1856 const VEInstrInfo *TII = Subtarget->getInstrInfo(); 1857 1858 const TargetRegisterClass *RC = &VE::I64RegClass; 1859 Register Result = MRI.createVirtualRegister(RC); 1860 1861 if (isPositionIndependent()) { 1862 if (IsCall && !IsLocal) { 1863 // Create following instructions for non-local linkage PIC code function 1864 // calls. These instructions uses IC and magic number -24, so we expand 1865 // them in VEAsmPrinter.cpp from GETFUNPLT pseudo instruction. 1866 // lea %Reg, Symbol@plt_lo(-24) 1867 // and %Reg, %Reg, (32)0 1868 // sic %s16 1869 // lea.sl %Result, Symbol@plt_hi(%Reg, %s16) ; %s16 is PLT 1870 BuildMI(MBB, I, DL, TII->get(VE::GETFUNPLT), Result) 1871 .addExternalSymbol("abort"); 1872 } else if (IsLocal) { 1873 Register Tmp1 = MRI.createVirtualRegister(RC); 1874 Register Tmp2 = MRI.createVirtualRegister(RC); 1875 // Create following instructions for local linkage PIC code. 1876 // lea %Tmp1, Symbol@gotoff_lo 1877 // and %Tmp2, %Tmp1, (32)0 1878 // lea.sl %Result, Symbol@gotoff_hi(%Tmp2, %s15) ; %s15 is GOT 1879 BuildMI(MBB, I, DL, TII->get(VE::LEAzii), Tmp1) 1880 .addImm(0) 1881 .addImm(0) 1882 .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_GOTOFF_LO32); 1883 BuildMI(MBB, I, DL, TII->get(VE::ANDrm), Tmp2) 1884 .addReg(Tmp1, getKillRegState(true)) 1885 .addImm(M0(32)); 1886 BuildMI(MBB, I, DL, TII->get(VE::LEASLrri), Result) 1887 .addReg(VE::SX15) 1888 .addReg(Tmp2, getKillRegState(true)) 1889 .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_GOTOFF_HI32); 1890 } else { 1891 Register Tmp1 = MRI.createVirtualRegister(RC); 1892 Register Tmp2 = MRI.createVirtualRegister(RC); 1893 // Create following instructions for not local linkage PIC code. 1894 // lea %Tmp1, Symbol@got_lo 1895 // and %Tmp2, %Tmp1, (32)0 1896 // lea.sl %Tmp3, Symbol@gotoff_hi(%Tmp2, %s15) ; %s15 is GOT 1897 // ld %Result, 0(%Tmp3) 1898 Register Tmp3 = MRI.createVirtualRegister(RC); 1899 BuildMI(MBB, I, DL, TII->get(VE::LEAzii), Tmp1) 1900 .addImm(0) 1901 .addImm(0) 1902 .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_GOT_LO32); 1903 BuildMI(MBB, I, DL, TII->get(VE::ANDrm), Tmp2) 1904 .addReg(Tmp1, getKillRegState(true)) 1905 .addImm(M0(32)); 1906 BuildMI(MBB, I, DL, TII->get(VE::LEASLrri), Tmp3) 1907 .addReg(VE::SX15) 1908 .addReg(Tmp2, getKillRegState(true)) 1909 .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_GOT_HI32); 1910 BuildMI(MBB, I, DL, TII->get(VE::LDrii), Result) 1911 .addReg(Tmp3, getKillRegState(true)) 1912 .addImm(0) 1913 .addImm(0); 1914 } 1915 } else { 1916 Register Tmp1 = MRI.createVirtualRegister(RC); 1917 Register Tmp2 = MRI.createVirtualRegister(RC); 1918 // Create following instructions for non-PIC code. 1919 // lea %Tmp1, Symbol@lo 1920 // and %Tmp2, %Tmp1, (32)0 1921 // lea.sl %Result, Symbol@hi(%Tmp2) 1922 BuildMI(MBB, I, DL, TII->get(VE::LEAzii), Tmp1) 1923 .addImm(0) 1924 .addImm(0) 1925 .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_LO32); 1926 BuildMI(MBB, I, DL, TII->get(VE::ANDrm), Tmp2) 1927 .addReg(Tmp1, getKillRegState(true)) 1928 .addImm(M0(32)); 1929 BuildMI(MBB, I, DL, TII->get(VE::LEASLrii), Result) 1930 .addReg(Tmp2, getKillRegState(true)) 1931 .addImm(0) 1932 .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_HI32); 1933 } 1934 return Result; 1935 } 1936 1937 void VETargetLowering::setupEntryBlockForSjLj(MachineInstr &MI, 1938 MachineBasicBlock *MBB, 1939 MachineBasicBlock *DispatchBB, 1940 int FI, int Offset) const { 1941 DebugLoc DL = MI.getDebugLoc(); 1942 const VEInstrInfo *TII = Subtarget->getInstrInfo(); 1943 1944 Register LabelReg = 1945 prepareMBB(*MBB, MachineBasicBlock::iterator(MI), DispatchBB, DL); 1946 1947 // Store an address of DispatchBB to a given jmpbuf[1] where has next IC 1948 // referenced by longjmp (throw) later. 1949 MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(VE::STrii)); 1950 addFrameReference(MIB, FI, Offset); // jmpbuf[1] 1951 MIB.addReg(LabelReg, getKillRegState(true)); 1952 } 1953 1954 MachineBasicBlock * 1955 VETargetLowering::emitEHSjLjSetJmp(MachineInstr &MI, 1956 MachineBasicBlock *MBB) const { 1957 DebugLoc DL = MI.getDebugLoc(); 1958 MachineFunction *MF = MBB->getParent(); 1959 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1960 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 1961 MachineRegisterInfo &MRI = MF->getRegInfo(); 1962 1963 const BasicBlock *BB = MBB->getBasicBlock(); 1964 MachineFunction::iterator I = ++MBB->getIterator(); 1965 1966 // Memory Reference. 1967 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(), 1968 MI.memoperands_end()); 1969 Register BufReg = MI.getOperand(1).getReg(); 1970 1971 Register DstReg; 1972 1973 DstReg = MI.getOperand(0).getReg(); 1974 const TargetRegisterClass *RC = MRI.getRegClass(DstReg); 1975 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"); 1976 (void)TRI; 1977 Register MainDestReg = MRI.createVirtualRegister(RC); 1978 Register RestoreDestReg = MRI.createVirtualRegister(RC); 1979 1980 // For `v = call @llvm.eh.sjlj.setjmp(buf)`, we generate following 1981 // instructions. SP/FP must be saved in jmpbuf before `llvm.eh.sjlj.setjmp`. 1982 // 1983 // ThisMBB: 1984 // buf[3] = %s17 iff %s17 is used as BP 1985 // buf[1] = RestoreMBB as IC after longjmp 1986 // # SjLjSetup RestoreMBB 1987 // 1988 // MainMBB: 1989 // v_main = 0 1990 // 1991 // SinkMBB: 1992 // v = phi(v_main, MainMBB, v_restore, RestoreMBB) 1993 // ... 1994 // 1995 // RestoreMBB: 1996 // %s17 = buf[3] = iff %s17 is used as BP 1997 // v_restore = 1 1998 // goto SinkMBB 1999 2000 MachineBasicBlock *ThisMBB = MBB; 2001 MachineBasicBlock *MainMBB = MF->CreateMachineBasicBlock(BB); 2002 MachineBasicBlock *SinkMBB = MF->CreateMachineBasicBlock(BB); 2003 MachineBasicBlock *RestoreMBB = MF->CreateMachineBasicBlock(BB); 2004 MF->insert(I, MainMBB); 2005 MF->insert(I, SinkMBB); 2006 MF->push_back(RestoreMBB); 2007 RestoreMBB->setHasAddressTaken(); 2008 2009 // Transfer the remainder of BB and its successor edges to SinkMBB. 2010 SinkMBB->splice(SinkMBB->begin(), MBB, 2011 std::next(MachineBasicBlock::iterator(MI)), MBB->end()); 2012 SinkMBB->transferSuccessorsAndUpdatePHIs(MBB); 2013 2014 // ThisMBB: 2015 Register LabelReg = 2016 prepareMBB(*MBB, MachineBasicBlock::iterator(MI), RestoreMBB, DL); 2017 2018 // Store BP in buf[3] iff this function is using BP. 2019 const VEFrameLowering *TFI = Subtarget->getFrameLowering(); 2020 if (TFI->hasBP(*MF)) { 2021 MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(VE::STrii)); 2022 MIB.addReg(BufReg); 2023 MIB.addImm(0); 2024 MIB.addImm(24); 2025 MIB.addReg(VE::SX17); 2026 MIB.setMemRefs(MMOs); 2027 } 2028 2029 // Store IP in buf[1]. 2030 MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(VE::STrii)); 2031 MIB.add(MI.getOperand(1)); // we can preserve the kill flags here. 2032 MIB.addImm(0); 2033 MIB.addImm(8); 2034 MIB.addReg(LabelReg, getKillRegState(true)); 2035 MIB.setMemRefs(MMOs); 2036 2037 // SP/FP are already stored in jmpbuf before `llvm.eh.sjlj.setjmp`. 2038 2039 // Insert setup. 2040 MIB = 2041 BuildMI(*ThisMBB, MI, DL, TII->get(VE::EH_SjLj_Setup)).addMBB(RestoreMBB); 2042 2043 const VERegisterInfo *RegInfo = Subtarget->getRegisterInfo(); 2044 MIB.addRegMask(RegInfo->getNoPreservedMask()); 2045 ThisMBB->addSuccessor(MainMBB); 2046 ThisMBB->addSuccessor(RestoreMBB); 2047 2048 // MainMBB: 2049 BuildMI(MainMBB, DL, TII->get(VE::LEAzii), MainDestReg) 2050 .addImm(0) 2051 .addImm(0) 2052 .addImm(0); 2053 MainMBB->addSuccessor(SinkMBB); 2054 2055 // SinkMBB: 2056 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(VE::PHI), DstReg) 2057 .addReg(MainDestReg) 2058 .addMBB(MainMBB) 2059 .addReg(RestoreDestReg) 2060 .addMBB(RestoreMBB); 2061 2062 // RestoreMBB: 2063 // Restore BP from buf[3] iff this function is using BP. The address of 2064 // buf is in SX10. 2065 // FIXME: Better to not use SX10 here 2066 if (TFI->hasBP(*MF)) { 2067 MachineInstrBuilder MIB = 2068 BuildMI(RestoreMBB, DL, TII->get(VE::LDrii), VE::SX17); 2069 MIB.addReg(VE::SX10); 2070 MIB.addImm(0); 2071 MIB.addImm(24); 2072 MIB.setMemRefs(MMOs); 2073 } 2074 BuildMI(RestoreMBB, DL, TII->get(VE::LEAzii), RestoreDestReg) 2075 .addImm(0) 2076 .addImm(0) 2077 .addImm(1); 2078 BuildMI(RestoreMBB, DL, TII->get(VE::BRCFLa_t)).addMBB(SinkMBB); 2079 RestoreMBB->addSuccessor(SinkMBB); 2080 2081 MI.eraseFromParent(); 2082 return SinkMBB; 2083 } 2084 2085 MachineBasicBlock * 2086 VETargetLowering::emitEHSjLjLongJmp(MachineInstr &MI, 2087 MachineBasicBlock *MBB) const { 2088 DebugLoc DL = MI.getDebugLoc(); 2089 MachineFunction *MF = MBB->getParent(); 2090 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2091 MachineRegisterInfo &MRI = MF->getRegInfo(); 2092 2093 // Memory Reference. 2094 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(), 2095 MI.memoperands_end()); 2096 Register BufReg = MI.getOperand(0).getReg(); 2097 2098 Register Tmp = MRI.createVirtualRegister(&VE::I64RegClass); 2099 // Since FP is only updated here but NOT referenced, it's treated as GPR. 2100 Register FP = VE::SX9; 2101 Register SP = VE::SX11; 2102 2103 MachineInstrBuilder MIB; 2104 2105 MachineBasicBlock *ThisMBB = MBB; 2106 2107 // For `call @llvm.eh.sjlj.longjmp(buf)`, we generate following instructions. 2108 // 2109 // ThisMBB: 2110 // %fp = load buf[0] 2111 // %jmp = load buf[1] 2112 // %s10 = buf ; Store an address of buf to SX10 for RestoreMBB 2113 // %sp = load buf[2] ; generated by llvm.eh.sjlj.setjmp. 2114 // jmp %jmp 2115 2116 // Reload FP. 2117 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(VE::LDrii), FP); 2118 MIB.addReg(BufReg); 2119 MIB.addImm(0); 2120 MIB.addImm(0); 2121 MIB.setMemRefs(MMOs); 2122 2123 // Reload IP. 2124 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(VE::LDrii), Tmp); 2125 MIB.addReg(BufReg); 2126 MIB.addImm(0); 2127 MIB.addImm(8); 2128 MIB.setMemRefs(MMOs); 2129 2130 // Copy BufReg to SX10 for later use in setjmp. 2131 // FIXME: Better to not use SX10 here 2132 BuildMI(*ThisMBB, MI, DL, TII->get(VE::ORri), VE::SX10) 2133 .addReg(BufReg) 2134 .addImm(0); 2135 2136 // Reload SP. 2137 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(VE::LDrii), SP); 2138 MIB.add(MI.getOperand(0)); // we can preserve the kill flags here. 2139 MIB.addImm(0); 2140 MIB.addImm(16); 2141 MIB.setMemRefs(MMOs); 2142 2143 // Jump. 2144 BuildMI(*ThisMBB, MI, DL, TII->get(VE::BCFLari_t)) 2145 .addReg(Tmp, getKillRegState(true)) 2146 .addImm(0); 2147 2148 MI.eraseFromParent(); 2149 return ThisMBB; 2150 } 2151 2152 MachineBasicBlock * 2153 VETargetLowering::emitSjLjDispatchBlock(MachineInstr &MI, 2154 MachineBasicBlock *BB) const { 2155 DebugLoc DL = MI.getDebugLoc(); 2156 MachineFunction *MF = BB->getParent(); 2157 MachineFrameInfo &MFI = MF->getFrameInfo(); 2158 MachineRegisterInfo &MRI = MF->getRegInfo(); 2159 const VEInstrInfo *TII = Subtarget->getInstrInfo(); 2160 int FI = MFI.getFunctionContextIndex(); 2161 2162 // Get a mapping of the call site numbers to all of the landing pads they're 2163 // associated with. 2164 DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad; 2165 unsigned MaxCSNum = 0; 2166 for (auto &MBB : *MF) { 2167 if (!MBB.isEHPad()) 2168 continue; 2169 2170 MCSymbol *Sym = nullptr; 2171 for (const auto &MI : MBB) { 2172 if (MI.isDebugInstr()) 2173 continue; 2174 2175 assert(MI.isEHLabel() && "expected EH_LABEL"); 2176 Sym = MI.getOperand(0).getMCSymbol(); 2177 break; 2178 } 2179 2180 if (!MF->hasCallSiteLandingPad(Sym)) 2181 continue; 2182 2183 for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) { 2184 CallSiteNumToLPad[CSI].push_back(&MBB); 2185 MaxCSNum = std::max(MaxCSNum, CSI); 2186 } 2187 } 2188 2189 // Get an ordered list of the machine basic blocks for the jump table. 2190 std::vector<MachineBasicBlock *> LPadList; 2191 SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs; 2192 LPadList.reserve(CallSiteNumToLPad.size()); 2193 2194 for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) { 2195 for (auto &LP : CallSiteNumToLPad[CSI]) { 2196 LPadList.push_back(LP); 2197 InvokeBBs.insert(LP->pred_begin(), LP->pred_end()); 2198 } 2199 } 2200 2201 assert(!LPadList.empty() && 2202 "No landing pad destinations for the dispatch jump table!"); 2203 2204 // The %fn_context is allocated like below (from --print-after=sjljehprepare): 2205 // %fn_context = alloca { i8*, i64, [4 x i64], i8*, i8*, [5 x i8*] } 2206 // 2207 // This `[5 x i8*]` is jmpbuf, so jmpbuf[1] is FI+72. 2208 // First `i64` is callsite, so callsite is FI+8. 2209 static const int OffsetIC = 72; 2210 static const int OffsetCS = 8; 2211 2212 // Create the MBBs for the dispatch code like following: 2213 // 2214 // ThisMBB: 2215 // Prepare DispatchBB address and store it to buf[1]. 2216 // ... 2217 // 2218 // DispatchBB: 2219 // %s15 = GETGOT iff isPositionIndependent 2220 // %callsite = load callsite 2221 // brgt.l.t #size of callsites, %callsite, DispContBB 2222 // 2223 // TrapBB: 2224 // Call abort. 2225 // 2226 // DispContBB: 2227 // %breg = address of jump table 2228 // %pc = load and calculate next pc from %breg and %callsite 2229 // jmp %pc 2230 2231 // Shove the dispatch's address into the return slot in the function context. 2232 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock(); 2233 DispatchBB->setIsEHPad(true); 2234 2235 // Trap BB will causes trap like `assert(0)`. 2236 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock(); 2237 DispatchBB->addSuccessor(TrapBB); 2238 2239 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock(); 2240 DispatchBB->addSuccessor(DispContBB); 2241 2242 // Insert MBBs. 2243 MF->push_back(DispatchBB); 2244 MF->push_back(DispContBB); 2245 MF->push_back(TrapBB); 2246 2247 // Insert code to call abort in the TrapBB. 2248 Register Abort = prepareSymbol(*TrapBB, TrapBB->end(), "abort", DL, 2249 /* Local */ false, /* Call */ true); 2250 BuildMI(TrapBB, DL, TII->get(VE::BSICrii), VE::SX10) 2251 .addReg(Abort, getKillRegState(true)) 2252 .addImm(0) 2253 .addImm(0); 2254 2255 // Insert code into the entry block that creates and registers the function 2256 // context. 2257 setupEntryBlockForSjLj(MI, BB, DispatchBB, FI, OffsetIC); 2258 2259 // Create the jump table and associated information 2260 unsigned JTE = getJumpTableEncoding(); 2261 MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE); 2262 unsigned MJTI = JTI->createJumpTableIndex(LPadList); 2263 2264 const VERegisterInfo &RI = TII->getRegisterInfo(); 2265 // Add a register mask with no preserved registers. This results in all 2266 // registers being marked as clobbered. 2267 BuildMI(DispatchBB, DL, TII->get(VE::NOP)) 2268 .addRegMask(RI.getNoPreservedMask()); 2269 2270 if (isPositionIndependent()) { 2271 // Force to generate GETGOT, since current implementation doesn't store GOT 2272 // register. 2273 BuildMI(DispatchBB, DL, TII->get(VE::GETGOT), VE::SX15); 2274 } 2275 2276 // IReg is used as an index in a memory operand and therefore can't be SP 2277 const TargetRegisterClass *RC = &VE::I64RegClass; 2278 Register IReg = MRI.createVirtualRegister(RC); 2279 addFrameReference(BuildMI(DispatchBB, DL, TII->get(VE::LDLZXrii), IReg), FI, 2280 OffsetCS); 2281 if (LPadList.size() < 64) { 2282 BuildMI(DispatchBB, DL, TII->get(VE::BRCFLir_t)) 2283 .addImm(VECC::CC_ILE) 2284 .addImm(LPadList.size()) 2285 .addReg(IReg) 2286 .addMBB(TrapBB); 2287 } else { 2288 assert(LPadList.size() <= 0x7FFFFFFF && "Too large Landing Pad!"); 2289 Register TmpReg = MRI.createVirtualRegister(RC); 2290 BuildMI(DispatchBB, DL, TII->get(VE::LEAzii), TmpReg) 2291 .addImm(0) 2292 .addImm(0) 2293 .addImm(LPadList.size()); 2294 BuildMI(DispatchBB, DL, TII->get(VE::BRCFLrr_t)) 2295 .addImm(VECC::CC_ILE) 2296 .addReg(TmpReg, getKillRegState(true)) 2297 .addReg(IReg) 2298 .addMBB(TrapBB); 2299 } 2300 2301 Register BReg = MRI.createVirtualRegister(RC); 2302 Register Tmp1 = MRI.createVirtualRegister(RC); 2303 Register Tmp2 = MRI.createVirtualRegister(RC); 2304 2305 if (isPositionIndependent()) { 2306 // Create following instructions for local linkage PIC code. 2307 // lea %Tmp1, .LJTI0_0@gotoff_lo 2308 // and %Tmp2, %Tmp1, (32)0 2309 // lea.sl %BReg, .LJTI0_0@gotoff_hi(%Tmp2, %s15) ; %s15 is GOT 2310 BuildMI(DispContBB, DL, TII->get(VE::LEAzii), Tmp1) 2311 .addImm(0) 2312 .addImm(0) 2313 .addJumpTableIndex(MJTI, VEMCExpr::VK_VE_GOTOFF_LO32); 2314 BuildMI(DispContBB, DL, TII->get(VE::ANDrm), Tmp2) 2315 .addReg(Tmp1, getKillRegState(true)) 2316 .addImm(M0(32)); 2317 BuildMI(DispContBB, DL, TII->get(VE::LEASLrri), BReg) 2318 .addReg(VE::SX15) 2319 .addReg(Tmp2, getKillRegState(true)) 2320 .addJumpTableIndex(MJTI, VEMCExpr::VK_VE_GOTOFF_HI32); 2321 } else { 2322 // Create following instructions for non-PIC code. 2323 // lea %Tmp1, .LJTI0_0@lo 2324 // and %Tmp2, %Tmp1, (32)0 2325 // lea.sl %BReg, .LJTI0_0@hi(%Tmp2) 2326 BuildMI(DispContBB, DL, TII->get(VE::LEAzii), Tmp1) 2327 .addImm(0) 2328 .addImm(0) 2329 .addJumpTableIndex(MJTI, VEMCExpr::VK_VE_LO32); 2330 BuildMI(DispContBB, DL, TII->get(VE::ANDrm), Tmp2) 2331 .addReg(Tmp1, getKillRegState(true)) 2332 .addImm(M0(32)); 2333 BuildMI(DispContBB, DL, TII->get(VE::LEASLrii), BReg) 2334 .addReg(Tmp2, getKillRegState(true)) 2335 .addImm(0) 2336 .addJumpTableIndex(MJTI, VEMCExpr::VK_VE_HI32); 2337 } 2338 2339 switch (JTE) { 2340 case MachineJumpTableInfo::EK_BlockAddress: { 2341 // Generate simple block address code for no-PIC model. 2342 // sll %Tmp1, %IReg, 3 2343 // lds %TReg, 0(%Tmp1, %BReg) 2344 // bcfla %TReg 2345 2346 Register TReg = MRI.createVirtualRegister(RC); 2347 Register Tmp1 = MRI.createVirtualRegister(RC); 2348 2349 BuildMI(DispContBB, DL, TII->get(VE::SLLri), Tmp1) 2350 .addReg(IReg, getKillRegState(true)) 2351 .addImm(3); 2352 BuildMI(DispContBB, DL, TII->get(VE::LDrri), TReg) 2353 .addReg(BReg, getKillRegState(true)) 2354 .addReg(Tmp1, getKillRegState(true)) 2355 .addImm(0); 2356 BuildMI(DispContBB, DL, TII->get(VE::BCFLari_t)) 2357 .addReg(TReg, getKillRegState(true)) 2358 .addImm(0); 2359 break; 2360 } 2361 case MachineJumpTableInfo::EK_Custom32: { 2362 // Generate block address code using differences from the function pointer 2363 // for PIC model. 2364 // sll %Tmp1, %IReg, 2 2365 // ldl.zx %OReg, 0(%Tmp1, %BReg) 2366 // Prepare function address in BReg2. 2367 // adds.l %TReg, %BReg2, %OReg 2368 // bcfla %TReg 2369 2370 assert(isPositionIndependent()); 2371 Register OReg = MRI.createVirtualRegister(RC); 2372 Register TReg = MRI.createVirtualRegister(RC); 2373 Register Tmp1 = MRI.createVirtualRegister(RC); 2374 2375 BuildMI(DispContBB, DL, TII->get(VE::SLLri), Tmp1) 2376 .addReg(IReg, getKillRegState(true)) 2377 .addImm(2); 2378 BuildMI(DispContBB, DL, TII->get(VE::LDLZXrri), OReg) 2379 .addReg(BReg, getKillRegState(true)) 2380 .addReg(Tmp1, getKillRegState(true)) 2381 .addImm(0); 2382 Register BReg2 = 2383 prepareSymbol(*DispContBB, DispContBB->end(), 2384 DispContBB->getParent()->getName(), DL, /* Local */ true); 2385 BuildMI(DispContBB, DL, TII->get(VE::ADDSLrr), TReg) 2386 .addReg(OReg, getKillRegState(true)) 2387 .addReg(BReg2, getKillRegState(true)); 2388 BuildMI(DispContBB, DL, TII->get(VE::BCFLari_t)) 2389 .addReg(TReg, getKillRegState(true)) 2390 .addImm(0); 2391 break; 2392 } 2393 default: 2394 llvm_unreachable("Unexpected jump table encoding"); 2395 } 2396 2397 // Add the jump table entries as successors to the MBB. 2398 SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs; 2399 for (auto &LP : LPadList) 2400 if (SeenMBBs.insert(LP).second) 2401 DispContBB->addSuccessor(LP); 2402 2403 // N.B. the order the invoke BBs are processed in doesn't matter here. 2404 SmallVector<MachineBasicBlock *, 64> MBBLPads; 2405 const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs(); 2406 for (MachineBasicBlock *MBB : InvokeBBs) { 2407 // Remove the landing pad successor from the invoke block and replace it 2408 // with the new dispatch block. 2409 // Keep a copy of Successors since it's modified inside the loop. 2410 SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(), 2411 MBB->succ_rend()); 2412 // FIXME: Avoid quadratic complexity. 2413 for (auto MBBS : Successors) { 2414 if (MBBS->isEHPad()) { 2415 MBB->removeSuccessor(MBBS); 2416 MBBLPads.push_back(MBBS); 2417 } 2418 } 2419 2420 MBB->addSuccessor(DispatchBB); 2421 2422 // Find the invoke call and mark all of the callee-saved registers as 2423 // 'implicit defined' so that they're spilled. This prevents code from 2424 // moving instructions to before the EH block, where they will never be 2425 // executed. 2426 for (auto &II : reverse(*MBB)) { 2427 if (!II.isCall()) 2428 continue; 2429 2430 DenseMap<Register, bool> DefRegs; 2431 for (auto &MOp : II.operands()) 2432 if (MOp.isReg()) 2433 DefRegs[MOp.getReg()] = true; 2434 2435 MachineInstrBuilder MIB(*MF, &II); 2436 for (unsigned RI = 0; SavedRegs[RI]; ++RI) { 2437 Register Reg = SavedRegs[RI]; 2438 if (!DefRegs[Reg]) 2439 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead); 2440 } 2441 2442 break; 2443 } 2444 } 2445 2446 // Mark all former landing pads as non-landing pads. The dispatch is the only 2447 // landing pad now. 2448 for (auto &LP : MBBLPads) 2449 LP->setIsEHPad(false); 2450 2451 // The instruction is gone now. 2452 MI.eraseFromParent(); 2453 return BB; 2454 } 2455 2456 MachineBasicBlock * 2457 VETargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 2458 MachineBasicBlock *BB) const { 2459 switch (MI.getOpcode()) { 2460 default: 2461 llvm_unreachable("Unknown Custom Instruction!"); 2462 case VE::EH_SjLj_LongJmp: 2463 return emitEHSjLjLongJmp(MI, BB); 2464 case VE::EH_SjLj_SetJmp: 2465 return emitEHSjLjSetJmp(MI, BB); 2466 case VE::EH_SjLj_Setup_Dispatch: 2467 return emitSjLjDispatchBlock(MI, BB); 2468 } 2469 } 2470 2471 static bool isI32Insn(const SDNode *User, const SDNode *N) { 2472 switch (User->getOpcode()) { 2473 default: 2474 return false; 2475 case ISD::ADD: 2476 case ISD::SUB: 2477 case ISD::MUL: 2478 case ISD::SDIV: 2479 case ISD::UDIV: 2480 case ISD::SETCC: 2481 case ISD::SMIN: 2482 case ISD::SMAX: 2483 case ISD::SHL: 2484 case ISD::SRA: 2485 case ISD::BSWAP: 2486 case ISD::SINT_TO_FP: 2487 case ISD::UINT_TO_FP: 2488 case ISD::BR_CC: 2489 case ISD::BITCAST: 2490 case ISD::ATOMIC_CMP_SWAP: 2491 case ISD::ATOMIC_SWAP: 2492 return true; 2493 case ISD::SRL: 2494 if (N->getOperand(0).getOpcode() != ISD::SRL) 2495 return true; 2496 // (srl (trunc (srl ...))) may be optimized by combining srl, so 2497 // doesn't optimize trunc now. 2498 return false; 2499 case ISD::SELECT_CC: 2500 if (User->getOperand(2).getNode() != N && 2501 User->getOperand(3).getNode() != N) 2502 return true; 2503 LLVM_FALLTHROUGH; 2504 case ISD::AND: 2505 case ISD::OR: 2506 case ISD::XOR: 2507 case ISD::SELECT: 2508 case ISD::CopyToReg: 2509 // Check all use of selections, bit operations, and copies. If all of them 2510 // are safe, optimize truncate to extract_subreg. 2511 for (const SDNode *U : User->uses()) { 2512 switch (U->getOpcode()) { 2513 default: 2514 // If the use is an instruction which treats the source operand as i32, 2515 // it is safe to avoid truncate here. 2516 if (isI32Insn(U, N)) 2517 continue; 2518 break; 2519 case ISD::ANY_EXTEND: 2520 case ISD::SIGN_EXTEND: 2521 case ISD::ZERO_EXTEND: { 2522 // Special optimizations to the combination of ext and trunc. 2523 // (ext ... (select ... (trunc ...))) is safe to avoid truncate here 2524 // since this truncate instruction clears higher 32 bits which is filled 2525 // by one of ext instructions later. 2526 assert(N->getValueType(0) == MVT::i32 && 2527 "find truncate to not i32 integer"); 2528 if (User->getOpcode() == ISD::SELECT_CC || 2529 User->getOpcode() == ISD::SELECT) 2530 continue; 2531 break; 2532 } 2533 } 2534 return false; 2535 } 2536 return true; 2537 } 2538 } 2539 2540 // Optimize TRUNCATE in DAG combining. Optimizing it in CUSTOM lower is 2541 // sometime too early. Optimizing it in DAG pattern matching in VEInstrInfo.td 2542 // is sometime too late. So, doing it at here. 2543 SDValue VETargetLowering::combineTRUNCATE(SDNode *N, 2544 DAGCombinerInfo &DCI) const { 2545 assert(N->getOpcode() == ISD::TRUNCATE && 2546 "Should be called with a TRUNCATE node"); 2547 2548 SelectionDAG &DAG = DCI.DAG; 2549 SDLoc DL(N); 2550 EVT VT = N->getValueType(0); 2551 2552 // We prefer to do this when all types are legal. 2553 if (!DCI.isAfterLegalizeDAG()) 2554 return SDValue(); 2555 2556 // Skip combine TRUNCATE atm if the operand of TRUNCATE might be a constant. 2557 if (N->getOperand(0)->getOpcode() == ISD::SELECT_CC && 2558 isa<ConstantSDNode>(N->getOperand(0)->getOperand(0)) && 2559 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 2560 return SDValue(); 2561 2562 // Check all use of this TRUNCATE. 2563 for (const SDNode *User : N->uses()) { 2564 // Make sure that we're not going to replace TRUNCATE for non i32 2565 // instructions. 2566 // 2567 // FIXME: Although we could sometimes handle this, and it does occur in 2568 // practice that one of the condition inputs to the select is also one of 2569 // the outputs, we currently can't deal with this. 2570 if (isI32Insn(User, N)) 2571 continue; 2572 2573 return SDValue(); 2574 } 2575 2576 SDValue SubI32 = DAG.getTargetConstant(VE::sub_i32, DL, MVT::i32); 2577 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, VT, 2578 N->getOperand(0), SubI32), 2579 0); 2580 } 2581 2582 SDValue VETargetLowering::PerformDAGCombine(SDNode *N, 2583 DAGCombinerInfo &DCI) const { 2584 switch (N->getOpcode()) { 2585 default: 2586 break; 2587 case ISD::TRUNCATE: 2588 return combineTRUNCATE(N, DCI); 2589 } 2590 2591 return SDValue(); 2592 } 2593 2594 //===----------------------------------------------------------------------===// 2595 // VE Inline Assembly Support 2596 //===----------------------------------------------------------------------===// 2597 2598 VETargetLowering::ConstraintType 2599 VETargetLowering::getConstraintType(StringRef Constraint) const { 2600 if (Constraint.size() == 1) { 2601 switch (Constraint[0]) { 2602 default: 2603 break; 2604 case 'v': // vector registers 2605 return C_RegisterClass; 2606 } 2607 } 2608 return TargetLowering::getConstraintType(Constraint); 2609 } 2610 2611 std::pair<unsigned, const TargetRegisterClass *> 2612 VETargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 2613 StringRef Constraint, 2614 MVT VT) const { 2615 const TargetRegisterClass *RC = nullptr; 2616 if (Constraint.size() == 1) { 2617 switch (Constraint[0]) { 2618 default: 2619 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 2620 case 'r': 2621 RC = &VE::I64RegClass; 2622 break; 2623 case 'v': 2624 RC = &VE::V64RegClass; 2625 break; 2626 } 2627 return std::make_pair(0U, RC); 2628 } 2629 2630 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 2631 } 2632 2633 //===----------------------------------------------------------------------===// 2634 // VE Target Optimization Support 2635 //===----------------------------------------------------------------------===// 2636 2637 unsigned VETargetLowering::getMinimumJumpTableEntries() const { 2638 // Specify 8 for PIC model to relieve the impact of PIC load instructions. 2639 if (isJumpTableRelative()) 2640 return 8; 2641 2642 return TargetLowering::getMinimumJumpTableEntries(); 2643 } 2644 2645 bool VETargetLowering::hasAndNot(SDValue Y) const { 2646 EVT VT = Y.getValueType(); 2647 2648 // VE doesn't have vector and not instruction. 2649 if (VT.isVector()) 2650 return false; 2651 2652 // VE allows different immediate values for X and Y where ~X & Y. 2653 // Only simm7 works for X, and only mimm works for Y on VE. However, this 2654 // function is used to check whether an immediate value is OK for and-not 2655 // instruction as both X and Y. Generating additional instruction to 2656 // retrieve an immediate value is no good since the purpose of this 2657 // function is to convert a series of 3 instructions to another series of 2658 // 3 instructions with better parallelism. Therefore, we return false 2659 // for all immediate values now. 2660 // FIXME: Change hasAndNot function to have two operands to make it work 2661 // correctly with Aurora VE. 2662 if (isa<ConstantSDNode>(Y)) 2663 return false; 2664 2665 // It's ok for generic registers. 2666 return true; 2667 } 2668 2669 SDValue VETargetLowering::lowerToVVP(SDValue Op, SelectionDAG &DAG) const { 2670 // Can we represent this as a VVP node. 2671 const unsigned Opcode = Op->getOpcode(); 2672 auto VVPOpcodeOpt = getVVPOpcode(Opcode); 2673 if (!VVPOpcodeOpt.hasValue()) 2674 return SDValue(); 2675 unsigned VVPOpcode = VVPOpcodeOpt.getValue(); 2676 const bool FromVP = ISD::isVPOpcode(Opcode); 2677 2678 // The representative and legalized vector type of this operation. 2679 VECustomDAG CDAG(DAG, Op); 2680 MVT MaskVT = MVT::v256i1; // TODO: packed mode. 2681 EVT OpVecVT = Op.getValueType(); 2682 EVT LegalVecVT = getTypeToTransformTo(*DAG.getContext(), OpVecVT); 2683 2684 SDValue AVL; 2685 SDValue Mask; 2686 2687 if (FromVP) { 2688 // All upstream VP SDNodes always have a mask and avl. 2689 auto MaskIdx = ISD::getVPMaskIdx(Opcode).getValue(); 2690 auto AVLIdx = ISD::getVPExplicitVectorLengthIdx(Opcode).getValue(); 2691 Mask = Op->getOperand(MaskIdx); 2692 AVL = Op->getOperand(AVLIdx); 2693 2694 } else { 2695 // Materialize the VL parameter. 2696 AVL = CDAG.getConstant(OpVecVT.getVectorNumElements(), MVT::i32); 2697 SDValue ConstTrue = CDAG.getConstant(1, MVT::i32); 2698 Mask = CDAG.getBroadcast(MaskVT, ConstTrue, AVL); 2699 } 2700 2701 if (isVVPBinaryOp(VVPOpcode)) { 2702 assert(LegalVecVT.isSimple()); 2703 return CDAG.getNode(VVPOpcode, LegalVecVT, 2704 {Op->getOperand(0), Op->getOperand(1), Mask, AVL}); 2705 } 2706 if (VVPOpcode == VEISD::VVP_SELECT) { 2707 auto Mask = Op->getOperand(0); 2708 auto OnTrue = Op->getOperand(1); 2709 auto OnFalse = Op->getOperand(2); 2710 return CDAG.getNode(VVPOpcode, LegalVecVT, {OnTrue, OnFalse, Mask, AVL}); 2711 } 2712 llvm_unreachable("lowerToVVP called for unexpected SDNode."); 2713 } 2714 2715 SDValue VETargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 2716 SelectionDAG &DAG) const { 2717 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 2718 MVT VT = Op.getOperand(0).getSimpleValueType(); 2719 2720 // Special treatment for packed V64 types. 2721 assert(VT == MVT::v512i32 || VT == MVT::v512f32); 2722 (void)VT; 2723 // Example of codes: 2724 // %packed_v = extractelt %vr, %idx / 2 2725 // %v = %packed_v >> (%idx % 2 * 32) 2726 // %res = %v & 0xffffffff 2727 2728 SDValue Vec = Op.getOperand(0); 2729 SDValue Idx = Op.getOperand(1); 2730 SDLoc DL(Op); 2731 SDValue Result = Op; 2732 if (false /* Idx->isConstant() */) { 2733 // TODO: optimized implementation using constant values 2734 } else { 2735 SDValue Const1 = DAG.getConstant(1, DL, MVT::i64); 2736 SDValue HalfIdx = DAG.getNode(ISD::SRL, DL, MVT::i64, {Idx, Const1}); 2737 SDValue PackedElt = 2738 SDValue(DAG.getMachineNode(VE::LVSvr, DL, MVT::i64, {Vec, HalfIdx}), 0); 2739 SDValue AndIdx = DAG.getNode(ISD::AND, DL, MVT::i64, {Idx, Const1}); 2740 SDValue Shift = DAG.getNode(ISD::XOR, DL, MVT::i64, {AndIdx, Const1}); 2741 SDValue Const5 = DAG.getConstant(5, DL, MVT::i64); 2742 Shift = DAG.getNode(ISD::SHL, DL, MVT::i64, {Shift, Const5}); 2743 PackedElt = DAG.getNode(ISD::SRL, DL, MVT::i64, {PackedElt, Shift}); 2744 SDValue Mask = DAG.getConstant(0xFFFFFFFFL, DL, MVT::i64); 2745 PackedElt = DAG.getNode(ISD::AND, DL, MVT::i64, {PackedElt, Mask}); 2746 SDValue SubI32 = DAG.getTargetConstant(VE::sub_i32, DL, MVT::i32); 2747 Result = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 2748 MVT::i32, PackedElt, SubI32), 2749 0); 2750 2751 if (Op.getSimpleValueType() == MVT::f32) { 2752 Result = DAG.getBitcast(MVT::f32, Result); 2753 } else { 2754 assert(Op.getSimpleValueType() == MVT::i32); 2755 } 2756 } 2757 return Result; 2758 } 2759 2760 SDValue VETargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 2761 SelectionDAG &DAG) const { 2762 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 2763 MVT VT = Op.getOperand(0).getSimpleValueType(); 2764 2765 // Special treatment for packed V64 types. 2766 assert(VT == MVT::v512i32 || VT == MVT::v512f32); 2767 (void)VT; 2768 // The v512i32 and v512f32 starts from upper bits (0..31). This "upper 2769 // bits" required `val << 32` from C implementation's point of view. 2770 // 2771 // Example of codes: 2772 // %packed_elt = extractelt %vr, (%idx >> 1) 2773 // %shift = ((%idx & 1) ^ 1) << 5 2774 // %packed_elt &= 0xffffffff00000000 >> shift 2775 // %packed_elt |= (zext %val) << shift 2776 // %vr = insertelt %vr, %packed_elt, (%idx >> 1) 2777 2778 SDLoc DL(Op); 2779 SDValue Vec = Op.getOperand(0); 2780 SDValue Val = Op.getOperand(1); 2781 SDValue Idx = Op.getOperand(2); 2782 if (Idx.getSimpleValueType() == MVT::i32) 2783 Idx = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Idx); 2784 if (Val.getSimpleValueType() == MVT::f32) 2785 Val = DAG.getBitcast(MVT::i32, Val); 2786 assert(Val.getSimpleValueType() == MVT::i32); 2787 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 2788 2789 SDValue Result = Op; 2790 if (false /* Idx->isConstant()*/) { 2791 // TODO: optimized implementation using constant values 2792 } else { 2793 SDValue Const1 = DAG.getConstant(1, DL, MVT::i64); 2794 SDValue HalfIdx = DAG.getNode(ISD::SRL, DL, MVT::i64, {Idx, Const1}); 2795 SDValue PackedElt = 2796 SDValue(DAG.getMachineNode(VE::LVSvr, DL, MVT::i64, {Vec, HalfIdx}), 0); 2797 SDValue AndIdx = DAG.getNode(ISD::AND, DL, MVT::i64, {Idx, Const1}); 2798 SDValue Shift = DAG.getNode(ISD::XOR, DL, MVT::i64, {AndIdx, Const1}); 2799 SDValue Const5 = DAG.getConstant(5, DL, MVT::i64); 2800 Shift = DAG.getNode(ISD::SHL, DL, MVT::i64, {Shift, Const5}); 2801 SDValue Mask = DAG.getConstant(0xFFFFFFFF00000000L, DL, MVT::i64); 2802 Mask = DAG.getNode(ISD::SRL, DL, MVT::i64, {Mask, Shift}); 2803 PackedElt = DAG.getNode(ISD::AND, DL, MVT::i64, {PackedElt, Mask}); 2804 Val = DAG.getNode(ISD::SHL, DL, MVT::i64, {Val, Shift}); 2805 PackedElt = DAG.getNode(ISD::OR, DL, MVT::i64, {PackedElt, Val}); 2806 Result = 2807 SDValue(DAG.getMachineNode(VE::LSVrr_v, DL, Vec.getSimpleValueType(), 2808 {HalfIdx, PackedElt, Vec}), 2809 0); 2810 } 2811 return Result; 2812 } 2813